@warlock.js/grimoire 5.63.0 → 5.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/esm/book/build.d.mts.map +1 -1
  3. package/esm/book/build.mjs +24 -2
  4. package/esm/book/build.mjs.map +1 -1
  5. package/esm/check/check-grimoire.d.mts.map +1 -1
  6. package/esm/check/check-grimoire.mjs +11 -1
  7. package/esm/check/check-grimoire.mjs.map +1 -1
  8. package/esm/check/rules/api-snapshot.mjs +39 -0
  9. package/esm/check/rules/api-snapshot.mjs.map +1 -0
  10. package/esm/check/rules/code-rules.mjs +45 -0
  11. package/esm/check/rules/code-rules.mjs.map +1 -0
  12. package/esm/check/rules/drift.mjs +54 -0
  13. package/esm/check/rules/drift.mjs.map +1 -0
  14. package/esm/check/rules/focused-tests.mjs +39 -0
  15. package/esm/check/rules/focused-tests.mjs.map +1 -0
  16. package/esm/check/rules/shows.mjs +52 -0
  17. package/esm/check/rules/shows.mjs.map +1 -0
  18. package/esm/codes/codes.d.mts +48 -0
  19. package/esm/codes/codes.d.mts.map +1 -1
  20. package/esm/codes/codes.mjs +26 -1
  21. package/esm/codes/codes.mjs.map +1 -1
  22. package/esm/contracts/adapter.d.mts +6 -0
  23. package/esm/contracts/adapter.d.mts.map +1 -1
  24. package/esm/contracts/guard.d.mts +104 -0
  25. package/esm/contracts/guard.d.mts.map +1 -0
  26. package/esm/contracts/index.mjs +5 -0
  27. package/esm/contracts/matrix.d.mts +75 -0
  28. package/esm/contracts/matrix.d.mts.map +1 -0
  29. package/esm/contracts/scry.d.mts +21 -0
  30. package/esm/contracts/scry.d.mts.map +1 -1
  31. package/esm/contracts/settings.d.mts +71 -0
  32. package/esm/contracts/settings.d.mts.map +1 -0
  33. package/esm/contracts/settings.mjs +67 -0
  34. package/esm/contracts/settings.mjs.map +1 -0
  35. package/esm/contracts/shots.d.mts +146 -0
  36. package/esm/contracts/shots.d.mts.map +1 -0
  37. package/esm/contracts/snapshot.d.mts +10 -0
  38. package/esm/contracts/snapshot.d.mts.map +1 -1
  39. package/esm/contracts/written.d.mts +13 -0
  40. package/esm/contracts/written.d.mts.map +1 -1
  41. package/esm/contracts/written.mjs +7 -1
  42. package/esm/contracts/written.mjs.map +1 -1
  43. package/esm/devtools/approvals.mjs +59 -0
  44. package/esm/devtools/approvals.mjs.map +1 -0
  45. package/esm/devtools/data.mjs +2 -0
  46. package/esm/devtools/data.mjs.map +1 -1
  47. package/esm/devtools/graphs.mjs +13 -3
  48. package/esm/devtools/graphs.mjs.map +1 -1
  49. package/esm/devtools/index.d.mts.map +1 -1
  50. package/esm/devtools/index.mjs +32 -2
  51. package/esm/devtools/index.mjs.map +1 -1
  52. package/esm/devtools/matrix.mjs +207 -0
  53. package/esm/devtools/matrix.mjs.map +1 -0
  54. package/esm/devtools/product-map.d.mts.map +1 -1
  55. package/esm/devtools/product-map.mjs +87 -1
  56. package/esm/devtools/product-map.mjs.map +1 -1
  57. package/esm/devtools/site.d.mts.map +1 -1
  58. package/esm/devtools/site.mjs +12 -3
  59. package/esm/devtools/site.mjs.map +1 -1
  60. package/esm/devtools/snapshot-source.mjs +5 -1
  61. package/esm/devtools/snapshot-source.mjs.map +1 -1
  62. package/esm/git/index.d.mts +20 -0
  63. package/esm/git/index.d.mts.map +1 -0
  64. package/esm/git/index.mjs +280 -0
  65. package/esm/git/index.mjs.map +1 -0
  66. package/esm/guard/api.mjs +70 -0
  67. package/esm/guard/api.mjs.map +1 -0
  68. package/esm/guard/assertions.mjs +18 -0
  69. package/esm/guard/assertions.mjs.map +1 -0
  70. package/esm/guard/collect.mjs +139 -0
  71. package/esm/guard/collect.mjs.map +1 -0
  72. package/esm/guard/format.mjs +27 -0
  73. package/esm/guard/format.mjs.map +1 -0
  74. package/esm/guard/glob.mjs +79 -0
  75. package/esm/guard/glob.mjs.map +1 -0
  76. package/esm/guard/index.mjs +9 -0
  77. package/esm/guard/rules.mjs +310 -0
  78. package/esm/guard/rules.mjs.map +1 -0
  79. package/esm/guard/scope.mjs +95 -0
  80. package/esm/guard/scope.mjs.map +1 -0
  81. package/esm/index.d.mts +10 -3
  82. package/esm/index.mjs +6 -2
  83. package/esm/paths/index.d.mts +15 -1
  84. package/esm/paths/index.d.mts.map +1 -1
  85. package/esm/paths/index.mjs +27 -3
  86. package/esm/paths/index.mjs.map +1 -1
  87. package/esm/proves/index.mjs +2 -1
  88. package/esm/proves/scan-proofs.mjs +1 -1
  89. package/esm/proves/scan-proofs.mjs.map +1 -1
  90. package/esm/proves/scan-shows.d.mts +21 -0
  91. package/esm/proves/scan-shows.d.mts.map +1 -0
  92. package/esm/proves/scan-shows.mjs +168 -0
  93. package/esm/proves/scan-shows.mjs.map +1 -0
  94. package/esm/releases/index.d.mts.map +1 -1
  95. package/esm/releases/index.mjs +5 -3
  96. package/esm/releases/index.mjs.map +1 -1
  97. package/esm/releases/stamp.mjs +121 -0
  98. package/esm/releases/stamp.mjs.map +1 -0
  99. package/esm/rules/focused.mjs +26 -0
  100. package/esm/rules/focused.mjs.map +1 -0
  101. package/esm/rules/index.mjs +88 -0
  102. package/esm/rules/index.mjs.map +1 -0
  103. package/esm/rules/logical-css.mjs +112 -0
  104. package/esm/rules/logical-css.mjs.map +1 -0
  105. package/esm/rules/no-js-imports.mjs +22 -0
  106. package/esm/rules/no-js-imports.mjs.map +1 -0
  107. package/esm/rules/scan.mjs +196 -0
  108. package/esm/rules/scan.mjs.map +1 -0
  109. package/esm/rules/specific-errors.mjs +51 -0
  110. package/esm/rules/specific-errors.mjs.map +1 -0
  111. package/esm/rules/type-discriminator.mjs +27 -0
  112. package/esm/rules/type-discriminator.mjs.map +1 -0
  113. package/esm/scry/also-changes.mjs +106 -0
  114. package/esm/scry/also-changes.mjs.map +1 -0
  115. package/esm/scry/format.d.mts.map +1 -1
  116. package/esm/scry/format.mjs +22 -0
  117. package/esm/scry/format.mjs.map +1 -1
  118. package/esm/scry/query.d.mts.map +1 -1
  119. package/esm/scry/query.mjs +7 -2
  120. package/esm/scry/query.mjs.map +1 -1
  121. package/esm/scry/search.d.mts.map +1 -1
  122. package/esm/scry/search.mjs +43 -11
  123. package/esm/scry/search.mjs.map +1 -1
  124. package/esm/shots/approve.mjs +195 -0
  125. package/esm/shots/approve.mjs.map +1 -0
  126. package/esm/shots/drift.mjs +174 -0
  127. package/esm/shots/drift.mjs.map +1 -0
  128. package/esm/shots/png.mjs +166 -0
  129. package/esm/shots/png.mjs.map +1 -0
  130. package/esm/shots/state.mjs +43 -0
  131. package/esm/shots/state.mjs.map +1 -0
  132. package/esm/shots/store.mjs +66 -0
  133. package/esm/shots/store.mjs.map +1 -0
  134. package/esm/shots/touched.mjs +38 -0
  135. package/esm/shots/touched.mjs.map +1 -0
  136. package/esm/warlock/adapter.d.mts.map +1 -1
  137. package/esm/warlock/adapter.mjs +15 -2
  138. package/esm/warlock/adapter.mjs.map +1 -1
  139. package/esm/warlock/api-command.mjs +41 -0
  140. package/esm/warlock/api-command.mjs.map +1 -0
  141. package/esm/warlock/approve-command.mjs +80 -0
  142. package/esm/warlock/approve-command.mjs.map +1 -0
  143. package/esm/warlock/commands.d.mts +1 -1
  144. package/esm/warlock/commands.d.mts.map +1 -1
  145. package/esm/warlock/commands.mjs +61 -8
  146. package/esm/warlock/commands.mjs.map +1 -1
  147. package/esm/warlock/guard-command.mjs +116 -0
  148. package/esm/warlock/guard-command.mjs.map +1 -0
  149. package/esm/warlock/index.d.mts +2 -1
  150. package/esm/warlock/index.mjs +2 -1
  151. package/esm/warlock/languages.mjs +75 -0
  152. package/esm/warlock/languages.mjs.map +1 -0
  153. package/esm/warlock/mcp-tools.mjs +2 -2
  154. package/esm/warlock/mcp-tools.mjs.map +1 -1
  155. package/esm/warlock/release-command.mjs +65 -0
  156. package/esm/warlock/release-command.mjs.map +1 -0
  157. package/esm/warlock/shows.d.mts +35 -0
  158. package/esm/warlock/shows.d.mts.map +1 -0
  159. package/esm/warlock/shows.mjs +195 -0
  160. package/esm/warlock/shows.mjs.map +1 -0
  161. package/esm/workspace/cache.mjs +4 -1
  162. package/esm/workspace/cache.mjs.map +1 -1
  163. package/esm/workspace/derived.mjs +11 -6
  164. package/esm/workspace/derived.mjs.map +1 -1
  165. package/esm/workspace/index.d.mts.map +1 -1
  166. package/esm/workspace/index.mjs +8 -1
  167. package/esm/workspace/index.mjs.map +1 -1
  168. package/esm/workspace/stored.mjs +4 -1
  169. package/esm/workspace/stored.mjs.map +1 -1
  170. package/esm/written/features.mjs +21 -5
  171. package/esm/written/features.mjs.map +1 -1
  172. package/esm/written/index.mjs +2 -1
  173. package/esm/written/parse-grimoire.d.mts.map +1 -1
  174. package/esm/written/parse-grimoire.mjs +16 -3
  175. package/esm/written/parse-grimoire.mjs.map +1 -1
  176. package/esm/written/settings.d.mts +11 -0
  177. package/esm/written/settings.d.mts.map +1 -0
  178. package/esm/written/settings.mjs +88 -0
  179. package/esm/written/settings.mjs.map +1 -0
  180. package/llms-full.txt +276 -39
  181. package/llms.txt +2 -0
  182. package/package.json +3 -3
  183. package/skills/backfill-a-grimoire/SKILL.md +4 -0
  184. package/skills/describe-an-app/SKILL.md +4 -1
  185. package/skills/guard-a-change/SKILL.md +85 -0
  186. package/skills/index.md +7 -3
  187. package/skills/record-a-change/SKILL.md +52 -16
  188. package/skills/review-a-change/SKILL.md +53 -0
  189. package/skills/use-the-grimoire/SKILL.md +21 -18
  190. package/skills/write-a-feature/SKILL.md +42 -1
  191. package/ui/grimoire-view.js +756 -40
  192. package/ui/grimoire.css +303 -28
  193. package/ui/product-map.css +43 -7
  194. package/ui/product-map.js +212 -37
@@ -0,0 +1,168 @@
1
+ import { createFinding } from "../codes/index.mjs";
2
+ import { toPosixPath } from "../paths/index.mjs";
3
+ import { withoutBlockComments } from "./scan-proofs.mjs";
4
+ import path from "node:path";
5
+ import { readFile } from "node:fs/promises";
6
+
7
+ //#region ../../packages/grimoire/src/proves/scan-shows.ts
8
+ const READ_CONCURRENCY = 32;
9
+ /** A `// @shows …` line comment on its own line; group 1 is the rest of the line. */
10
+ const SHOWS_LINE = /^\s*\/\/\s*@shows\b(.*)$/;
11
+ /** A `// @shows` comment after code on the same line. */
12
+ const TRAILING_SHOWS = /\S.*\/\/\s*@shows\b/;
13
+ /** The rest of a well-formed line: ` <feature>/<flow> AC-<n>`. */
14
+ const SHOWS_TARGET = /^\s+([a-z0-9]+(?:-[a-z0-9]+)*)\/([a-z0-9]+(?:-[a-z0-9]+)*)\s+(AC-\d+)\s*$/;
15
+ /** The start of a `shows(` call: `shows(`, `await shows(`, `grimoire.shows(`. */
16
+ const SHOWS_CALL = /^(?:await\s+)?(?:[A-Za-z_$][\w$]*\s*\.\s*)?shows\s*\(/;
17
+ /** The first string argument after the first argument (`context`). */
18
+ const CALL_REF = /^[^,]*,\s*(["'`])([^"'`]*)\1/;
19
+ /** How many lines a call's first arguments may span. */
20
+ const CALL_LOOKAHEAD = 6;
21
+ /** The criteria of every flow of a written grimoire. */
22
+ function knownCriteria(written) {
23
+ const known = /* @__PURE__ */ new Map();
24
+ for (const feature of written.features) for (const flow of feature.flows) known.set(flow.ref, new Set(flow.criteria.map((criterion) => criterion.id)));
25
+ return known;
26
+ }
27
+ /** Read the `@shows` lines of one test file's content. Pure. */
28
+ function scanShowsInText(text, file, known) {
29
+ const testFile = toPosixPath(file);
30
+ const code = withoutBlockComments(text.split(/\r?\n/));
31
+ const findings = [];
32
+ const shows = [];
33
+ let pending = null;
34
+ const settle = (callLine) => {
35
+ if (pending === null) return;
36
+ const { feature, flow, criterion, line } = pending;
37
+ const ref = `${feature}/${flow}`;
38
+ const at = {
39
+ file: testFile,
40
+ line,
41
+ column: null
42
+ };
43
+ pending = null;
44
+ if (known !== void 0) {
45
+ const criteria = known.get(ref);
46
+ if (criteria === void 0 || !criteria.has(criterion)) {
47
+ findings.push(createFinding({
48
+ code: "GR4014",
49
+ message: criteria === void 0 ? `"@shows ${ref} ${criterion}" names a flow that does not exist` : `"@shows ${ref} ${criterion}" names a criterion the flow does not have`,
50
+ at,
51
+ feature,
52
+ flow: ref
53
+ }));
54
+ return;
55
+ }
56
+ }
57
+ let call = null;
58
+ if (callLine !== null) {
59
+ const named = callRef(code, callLine - 1);
60
+ if (named === `${ref} ${criterion}`) call = { line: callLine };
61
+ else findings.push(createFinding({
62
+ code: "GR4013",
63
+ message: named === null ? `"@shows ${ref} ${criterion}" is not directly above a shows() call that names "${ref} ${criterion}"` : `"@shows ${ref} ${criterion}" is above a shows() call that names ${JSON.stringify(named)}`,
64
+ at,
65
+ feature,
66
+ flow: ref
67
+ }));
68
+ } else findings.push(createFinding({
69
+ code: "GR4013",
70
+ message: `"@shows ${ref} ${criterion}" is not directly above a shows() call`,
71
+ at,
72
+ feature,
73
+ flow: ref
74
+ }));
75
+ shows.push({
76
+ feature,
77
+ flow,
78
+ ref,
79
+ criterion,
80
+ call,
81
+ at
82
+ });
83
+ };
84
+ code.forEach((content, index) => {
85
+ const lineNumber = index + 1;
86
+ const match = SHOWS_LINE.exec(content);
87
+ if (match) {
88
+ settle(null);
89
+ const target = SHOWS_TARGET.exec(match[1] ?? "");
90
+ if (target) pending = {
91
+ feature: target[1] ?? "",
92
+ flow: target[2] ?? "",
93
+ criterion: target[3] ?? "",
94
+ line: lineNumber
95
+ };
96
+ else findings.push(malformed(testFile, lineNumber, content));
97
+ return;
98
+ }
99
+ const trimmed = content.trim();
100
+ if (trimmed === "" || trimmed.startsWith("//")) return;
101
+ if (TRAILING_SHOWS.test(content)) findings.push(malformed(testFile, lineNumber, content));
102
+ settle(SHOWS_CALL.test(trimmed) ? lineNumber : null);
103
+ });
104
+ settle(null);
105
+ return {
106
+ shows,
107
+ findings
108
+ };
109
+ }
110
+ /**
111
+ * Read the `@shows` lines of every test file. Files that cannot be read are
112
+ * skipped. Lines and findings come out in file order, then line order.
113
+ *
114
+ * @param root Absolute project root.
115
+ * @param testFiles Project-relative test files (`BookFacts.tests`).
116
+ * @param written The written grimoire; with it, a line naming no flow or criterion is `GR4014`.
117
+ */
118
+ async function scanShows(root, testFiles, written) {
119
+ const files = [...new Set(testFiles.map(toPosixPath))].sort();
120
+ const known = written === void 0 ? void 0 : knownCriteria(written);
121
+ const results = new Array(files.length);
122
+ let next = 0;
123
+ const worker = async () => {
124
+ while (next < files.length) {
125
+ const index = next++;
126
+ const file = files[index] ?? "";
127
+ try {
128
+ const content = await readFile(path.join(root, ...file.split("/")), "utf8");
129
+ results[index] = content.includes("@shows") ? scanShowsInText(content, file, known) : {
130
+ shows: [],
131
+ findings: []
132
+ };
133
+ } catch {
134
+ results[index] = {
135
+ shows: [],
136
+ findings: []
137
+ };
138
+ }
139
+ }
140
+ };
141
+ await Promise.all(Array.from({ length: Math.min(READ_CONCURRENCY, files.length) }, worker));
142
+ return {
143
+ shows: results.flatMap((result) => result.shows),
144
+ findings: results.flatMap((result) => result.findings)
145
+ };
146
+ }
147
+ /** The ref string the `shows(` call that starts at `code[start]` names, or `null`. */
148
+ function callRef(code, start) {
149
+ const joined = code.slice(start, start + CALL_LOOKAHEAD).join("\n").trim();
150
+ const open = SHOWS_CALL.exec(joined);
151
+ if (!open) return null;
152
+ return CALL_REF.exec(joined.slice(open[0].length))?.[2] ?? null;
153
+ }
154
+ function malformed(file, line, content) {
155
+ return createFinding({
156
+ code: "GR4013",
157
+ message: `"${content.trim()}" is not "// @shows <feature>/<flow> AC-<n>" on its own line`,
158
+ at: {
159
+ file,
160
+ line,
161
+ column: null
162
+ }
163
+ });
164
+ }
165
+
166
+ //#endregion
167
+ export { knownCriteria, scanShows, scanShowsInText };
168
+ //# sourceMappingURL=scan-shows.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan-shows.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/proves/scan-shows.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createFinding } from \"../codes\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { ShowsLine } from \"../contracts/shots\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { toPosixPath } from \"../paths\";\nimport { withoutBlockComments } from \"./scan-proofs\";\n\n/** What a scan returns. */\nexport type ScanShowsResult = {\n shows: ShowsLine[];\n /** `GR4013` (wrong form, no matching `shows()` call) and `GR4014` (names no flow or criterion). */\n findings: GrimoireFinding[];\n};\n\n/** The criteria each flow has, by `<feature>/<flow>`; the scanner reports `GR4014` for a line outside it. */\nexport type KnownCriteria = ReadonlyMap<string, ReadonlySet<string>>;\n\nconst READ_CONCURRENCY = 32;\n\n/** A `// @shows …` line comment on its own line; group 1 is the rest of the line. */\nconst SHOWS_LINE = /^\\s*\\/\\/\\s*@shows\\b(.*)$/;\n/** A `// @shows` comment after code on the same line. */\nconst TRAILING_SHOWS = /\\S.*\\/\\/\\s*@shows\\b/;\n/** The rest of a well-formed line: ` <feature>/<flow> AC-<n>`. */\nconst SHOWS_TARGET = /^\\s+([a-z0-9]+(?:-[a-z0-9]+)*)\\/([a-z0-9]+(?:-[a-z0-9]+)*)\\s+(AC-\\d+)\\s*$/;\n/** The start of a `shows(` call: `shows(`, `await shows(`, `grimoire.shows(`. */\nconst SHOWS_CALL = /^(?:await\\s+)?(?:[A-Za-z_$][\\w$]*\\s*\\.\\s*)?shows\\s*\\(/;\n/** The first string argument after the first argument (`context`). */\nconst CALL_REF = /^[^,]*,\\s*([\"'`])([^\"'`]*)\\1/;\n/** How many lines a call's first arguments may span. */\nconst CALL_LOOKAHEAD = 6;\n\n/** The criteria of every flow of a written grimoire. */\nexport function knownCriteria(written: WrittenGrimoire): KnownCriteria {\n const known = new Map<string, Set<string>>();\n\n for (const feature of written.features) {\n for (const flow of feature.flows) {\n known.set(flow.ref, new Set(flow.criteria.map((criterion) => criterion.id)));\n }\n }\n\n return known;\n}\n\n/** Read the `@shows` lines of one test file's content. Pure. */\nexport function scanShowsInText(\n text: string,\n file: string,\n known?: KnownCriteria,\n): ScanShowsResult {\n const testFile = toPosixPath(file);\n const code = withoutBlockComments(text.split(/\\r?\\n/));\n const findings: GrimoireFinding[] = [];\n const shows: ShowsLine[] = [];\n let pending: { feature: string; flow: string; criterion: string; line: number } | null = null;\n\n const settle = (callLine: number | null): void => {\n if (pending === null) return;\n\n const { feature, flow, criterion, line } = pending;\n const ref = `${feature}/${flow}`;\n const at = { file: testFile, line, column: null };\n\n pending = null;\n\n if (known !== undefined) {\n const criteria = known.get(ref);\n\n if (criteria === undefined || !criteria.has(criterion)) {\n findings.push(\n createFinding({\n code: \"GR4014\",\n message:\n criteria === undefined\n ? `\"@shows ${ref} ${criterion}\" names a flow that does not exist`\n : `\"@shows ${ref} ${criterion}\" names a criterion the flow does not have`,\n at,\n feature,\n flow: ref,\n }),\n );\n\n return;\n }\n }\n\n let call: { line: number } | null = null;\n\n if (callLine !== null) {\n const named = callRef(code, callLine - 1);\n\n if (named === `${ref} ${criterion}`) call = { line: callLine };\n else {\n findings.push(\n createFinding({\n code: \"GR4013\",\n message:\n named === null\n ? `\"@shows ${ref} ${criterion}\" is not directly above a shows() call that names \"${ref} ${criterion}\"`\n : `\"@shows ${ref} ${criterion}\" is above a shows() call that names ${JSON.stringify(named)}`,\n at,\n feature,\n flow: ref,\n }),\n );\n }\n } else {\n findings.push(\n createFinding({\n code: \"GR4013\",\n message: `\"@shows ${ref} ${criterion}\" is not directly above a shows() call`,\n at,\n feature,\n flow: ref,\n }),\n );\n }\n\n shows.push({ feature, flow, ref, criterion, call, at });\n };\n\n code.forEach((content, index) => {\n const lineNumber = index + 1;\n const match = SHOWS_LINE.exec(content);\n\n if (match) {\n // A second line stacked above the same call: the first has no call of its own.\n settle(null);\n\n const target = SHOWS_TARGET.exec(match[1] ?? \"\");\n\n if (target) {\n pending = {\n feature: target[1] ?? \"\",\n flow: target[2] ?? \"\",\n criterion: target[3] ?? \"\",\n line: lineNumber,\n };\n } else {\n findings.push(malformed(testFile, lineNumber, content));\n }\n\n return;\n }\n\n const trimmed = content.trim();\n\n if (trimmed === \"\" || trimmed.startsWith(\"//\")) return;\n\n if (TRAILING_SHOWS.test(content)) findings.push(malformed(testFile, lineNumber, content));\n\n settle(SHOWS_CALL.test(trimmed) ? lineNumber : null);\n });\n\n settle(null);\n\n return { shows, findings };\n}\n\n/**\n * Read the `@shows` lines of every test file. Files that cannot be read are\n * skipped. Lines and findings come out in file order, then line order.\n *\n * @param root Absolute project root.\n * @param testFiles Project-relative test files (`BookFacts.tests`).\n * @param written The written grimoire; with it, a line naming no flow or criterion is `GR4014`.\n */\nexport async function scanShows(\n root: string,\n testFiles: readonly string[],\n written?: WrittenGrimoire,\n): Promise<ScanShowsResult> {\n const files = [...new Set(testFiles.map(toPosixPath))].sort();\n const known = written === undefined ? undefined : knownCriteria(written);\n const results: ScanShowsResult[] = new Array(files.length);\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < files.length) {\n const index = next++;\n const file = files[index] ?? \"\";\n\n try {\n const content = await readFile(path.join(root, ...file.split(\"/\")), \"utf8\");\n\n // Most test files never mention it; skip the line scan for them.\n results[index] = content.includes(\"@shows\")\n ? scanShowsInText(content, file, known)\n : { shows: [], findings: [] };\n } catch {\n results[index] = { shows: [], findings: [] };\n }\n }\n };\n\n await Promise.all(Array.from({ length: Math.min(READ_CONCURRENCY, files.length) }, worker));\n\n return {\n shows: results.flatMap((result) => result.shows),\n findings: results.flatMap((result) => result.findings),\n };\n}\n\n/** The ref string the `shows(` call that starts at `code[start]` names, or `null`. */\nfunction callRef(code: readonly string[], start: number): string | null {\n const joined = code\n .slice(start, start + CALL_LOOKAHEAD)\n .join(\"\\n\")\n .trim();\n const open = SHOWS_CALL.exec(joined);\n\n if (!open) return null;\n\n return CALL_REF.exec(joined.slice(open[0].length))?.[2] ?? null;\n}\n\nfunction malformed(file: string, line: number, content: string): GrimoireFinding {\n return createFinding({\n code: \"GR4013\",\n message: `\"${content.trim()}\" is not \"// @shows <feature>/<flow> AC-<n>\" on its own line`,\n at: { file, line, column: null },\n });\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,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,SAAS,iBAAiB,kBAAkB;;wBA0C3D,oBAAoB,YAAY;;;;;;;;;wBAiC1B,aACpB,cACA,SAAS,iBACT,kBACC,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/releases/index.ts"],"mappings":";;;;YA0BY,sBAAsB;;EAEhC,YAAY;;;;;;;;;wBA0DE,eAAe,SAAS,iBAAiB,kBAAkB;;wBA0C3D,oBAAoB,YAAY;;;;;;;;;wBAiC1B,aACpB,cACA,SAAS,iBACT,kBACC,QAAQ"}
@@ -1,6 +1,7 @@
1
1
  import { COLLECTED_END_MARKER, COLLECTED_START_MARKER } from "../contracts/written.mjs";
2
2
  import { GrimoireError, createFinding } from "../codes/index.mjs";
3
3
  import { releaseFilePath } from "../paths/index.mjs";
4
+ import { applyStamp, planStamp } from "./stamp.mjs";
4
5
  import path from "node:path";
5
6
  import { readFile, writeFile } from "node:fs/promises";
6
7
 
@@ -9,8 +10,9 @@ import { readFile, writeFile } from "node:fs/promises";
9
10
  * Releases: collecting the changelog entries the agent stamped with a release
10
11
  * into `grimoire/releases/<release>.md`, and the GR6001–GR6003 rules.
11
12
  *
12
- * Warlock never edits a feature changelog or the agent's brief. It writes only
13
- * the text between the collected-list markers of the release file.
13
+ * Collecting never edits a feature changelog or the agent's brief: it writes only
14
+ * the text between the collected-list markers of the release file. Stamping
15
+ * (`stamp.ts`, only on `--stamp`) is the one edit Warlock makes to written files.
14
16
  */
15
17
  function findRelease(written, release) {
16
18
  return written.releases.find((item) => item.release.value === release);
@@ -153,5 +155,5 @@ function checkReleases(snapshot) {
153
155
  }
154
156
 
155
157
  //#endregion
156
- export { checkReleases, collectRelease, renderCollectedList, unreleasedEntries, writeRelease };
158
+ export { applyStamp, checkReleases, collectRelease, planStamp, renderCollectedList, unreleasedEntries, writeRelease };
157
159
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/releases/index.ts"],"sourcesContent":["/**\n * Releases: collecting the changelog entries the agent stamped with a release\n * into `grimoire/releases/<release>.md`, and the GR6001–GR6003 rules.\n *\n * Warlock never edits a feature changelog or the agent's brief. It writes only\n * the text between the collected-list markers of the release file.\n */\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { GrimoireError, createFinding } from \"../codes\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { ReleaseCollection, ReleaseEntry, WriteReleaseResult } from \"../contracts/releases\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport {\n COLLECTED_END_MARKER,\n COLLECTED_START_MARKER,\n type WrittenChangelogEntry,\n type WrittenGrimoire,\n type WrittenRelease,\n} from \"../contracts/written\";\nimport { releaseFilePath } from \"../paths\";\n\n/** What `writeRelease()` returns: the contract result plus the entries it left out. */\nexport type WriteReleaseOutcome = WriteReleaseResult & {\n /** Entries still under `## Unreleased`; not collected. */\n unreleased: ReleaseEntry[];\n};\n\nfunction findRelease(written: WrittenGrimoire, release: string): WrittenRelease | undefined {\n return written.releases.find((item) => item.release.value === release);\n}\n\nfunction toReleaseEntry(entry: WrittenChangelogEntry, state: ReleaseEntry[\"state\"]): ReleaseEntry {\n return {\n feature: entry.feature,\n version: entry.version.value,\n word: entry.word,\n flow: entry.flow,\n criteria: [...entry.criteria],\n text: entry.text,\n state,\n source: entry.at,\n };\n}\n\n/** Compare two `<whole>.<decimal>` versions, newest first. */\nfunction compareVersionsDescending(a: string, b: string): number {\n const [aWhole = 0, aDecimal = 0] = a.split(\".\").map(Number);\n const [bWhole = 0, bDecimal = 0] = b.split(\".\").map(Number);\n\n return bWhole - aWhole || bDecimal - aDecimal;\n}\n\nfunction sortEntries(entries: ReleaseEntry[]): ReleaseEntry[] {\n // `sort` is stable, so equal versions keep their changelog order.\n return entries.sort(\n (a, b) => a.feature.localeCompare(b.feature) || compareVersionsDescending(a.version, b.version),\n );\n}\n\n/**\n * The entries still under `## Unreleased` in every feature changelog. They are\n * not part of any release until the agent stamps them.\n */\nexport function unreleasedEntries(written: WrittenGrimoire): ReleaseEntry[] {\n const entries: ReleaseEntry[] = [];\n\n for (const feature of written.features) {\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null) entries.push(toReleaseEntry(entry, \"unreleased\"));\n }\n }\n\n return sortEntries(entries);\n}\n\n/**\n * The entries a release lists: the entries the agent stamped with that release\n * (under `## <release> (<date>)`). Entries under `## Unreleased` are never\n * collected. Throws a `GrimoireError` with `GR9005` when\n * `grimoire/releases/<release>.md` does not exist, has no `release` and\n * `date`, or has no brief.\n */\nexport function collectRelease(written: WrittenGrimoire, release: string): ReleaseCollection {\n const file = findRelease(written, release);\n\n if (!file || file.release.value === \"\" || file.date.value === \"\") {\n throw new GrimoireError(\n \"GR9005\",\n `${releaseFilePath(release)} does not exist or has no release and date. Write the brief first, with \\`release\\` and \\`date\\` in the front matter.`,\n );\n }\n\n if (file.brief.trim() === \"\") {\n throw new GrimoireError(\n \"GR9005\",\n `${file.file} has no brief yet. Write the brief under the heading, then run the command again.`,\n );\n }\n\n const entries: ReleaseEntry[] = [];\n\n for (const feature of written.features) {\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === release) entries.push(toReleaseEntry(entry, \"stamped\"));\n }\n }\n\n return { release, date: file.date.value, entries: sortEntries(entries) };\n}\n\nfunction entryLine(entry: {\n version: string;\n word: string;\n flow: string | null;\n criteria: string[];\n text: string;\n}): string {\n const flow = entry.flow === null ? \"\" : `${entry.flow}: `;\n const criteria = entry.criteria.length > 0 ? ` (${entry.criteria.join(\", \")})` : \"\";\n\n return `- ${entry.version} ${entry.word} ${flow}${entry.text}${criteria}`;\n}\n\n/** The Markdown between (and including) the collected-list markers. Pure. */\nexport function renderCollectedList(collection: ReleaseCollection): string {\n const lines: string[] = [COLLECTED_START_MARKER];\n\n if (collection.entries.length === 0) {\n lines.push(\"No feature changes.\");\n } else {\n lines.push(\"## Changes\");\n\n let current: string | null = null;\n\n for (const entry of collection.entries) {\n if (entry.feature !== current) {\n current = entry.feature;\n lines.push(\"\", `### ${entry.feature}`);\n }\n\n lines.push(entryLine(entry));\n }\n }\n\n lines.push(COLLECTED_END_MARKER);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Collect the release and write the list into its file: replaces the text\n * between the markers, or appends the markers and the list at the end. Never\n * touches any other file or any text outside the markers. Refuses (`GR9005`)\n * when the agent has not written the release file and its brief.\n *\n * @param root Absolute project root.\n */\nexport async function writeRelease(\n root: string,\n written: WrittenGrimoire,\n release: string,\n): Promise<WriteReleaseOutcome> {\n const collection = collectRelease(written, release);\n const file = findRelease(written, release)?.file ?? releaseFilePath(release);\n const absolute = path.join(root, ...file.split(\"/\"));\n const current = await readFile(absolute, \"utf8\");\n const eol = current.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const list = renderCollectedList(collection).split(\"\\n\").join(eol);\n const start = current.indexOf(COLLECTED_START_MARKER);\n const end = current.indexOf(COLLECTED_END_MARKER);\n\n let next: string;\n\n if (start === -1 && end === -1) {\n const base = current.replace(/\\s+$/, \"\");\n\n next = `${base}${eol}${eol}${list}${eol}`;\n } else if (\n start === -1 ||\n end === -1 ||\n end < start ||\n current.indexOf(COLLECTED_START_MARKER, start + 1) !== -1 ||\n current.indexOf(COLLECTED_END_MARKER, end + 1) !== -1\n ) {\n throw new GrimoireError(\n \"GR1024\",\n `${file} has broken collected-list markers. Keep one start marker followed by one end marker, or remove both.`,\n );\n } else {\n next = current.slice(0, start) + list + current.slice(end + COLLECTED_END_MARKER.length);\n }\n\n const changed = next !== current;\n\n if (changed) await writeFile(absolute, next);\n\n return { file, collection, changed, unreleased: unreleasedEntries(written) };\n}\n\nfunction sameEntry(\n listed: { feature: string; version: string; word: string; flow: string | null; text: string },\n entry: WrittenChangelogEntry,\n): boolean {\n return (\n listed.feature === entry.feature &&\n listed.version === entry.version.value &&\n listed.word === entry.word &&\n listed.flow === entry.flow &&\n listed.text === entry.text\n );\n}\n\n/** The GR6001–GR6003 rules. Read-only. */\nexport function checkReleases(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const { written } = snapshot;\n const findings: GrimoireFinding[] = [];\n\n // GR6001: a listed entry with no matching entry stamped with this release.\n for (const file of written.releases) {\n for (const listed of file.collected?.entries ?? []) {\n const changelog = written.features.find(\n (feature) => feature.id === listed.feature,\n )?.changelog;\n const stamped = (changelog?.entries ?? []).some(\n (entry) =>\n entry.release === file.release.value && entry.date !== null && sameEntry(listed, entry),\n );\n\n if (!stamped) {\n findings.push(\n createFinding({\n code: \"GR6001\",\n message: `release ${file.release.value} lists \"${listed.feature} ${listed.version} ${listed.word}: ${listed.text}\", but no entry in that changelog is stamped with ${file.release.value} and a date`,\n at: listed.at,\n feature: listed.feature,\n file: file.file,\n }),\n );\n }\n }\n }\n\n // GR6002 and GR6003: a changelog release section needs its release file and date.\n for (const feature of written.features) {\n for (const section of feature.changelog?.sections ?? []) {\n if (section.release === null) continue;\n\n const file = findRelease(written, section.release);\n\n if (!file) {\n findings.push(\n createFinding({\n code: \"GR6002\",\n message: `${feature.id} changelog has a section for release ${section.release}, but ${releaseFilePath(section.release)} does not exist`,\n at: section.at,\n feature: feature.id,\n file: section.at.file,\n }),\n );\n } else if (section.date !== null && section.date !== file.date.value) {\n findings.push(\n createFinding({\n code: \"GR6003\",\n message: `${feature.id} changelog dates release ${section.release} ${section.date}, but ${file.file} says ${file.date.value}`,\n at: section.at,\n feature: feature.id,\n file: section.at.file,\n }),\n );\n }\n }\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,SAAS,YAAY,SAA0B,SAA6C;CAC1F,OAAO,QAAQ,SAAS,MAAM,SAAS,KAAK,QAAQ,UAAU,OAAO;AACvE;AAEA,SAAS,eAAe,OAA8B,OAA4C;CAChG,OAAO;EACL,SAAS,MAAM;EACf,SAAS,MAAM,QAAQ;EACvB,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,UAAU,CAAC,GAAG,MA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AAQ,UAC5B,KAAK,MAAM,WAAW,QAAQ,WAAW,YAAY,CAAC,GAAG;EACvD,IAAI,QAAQ,YAAY,MAAM;EAE9B,MAAM,OAAO,YAAY,SAAS,QAAQ,OAAO;EAEjD,IAAI,CAAC,MACH,SAAS,KACP,cAAc;GACZ,MAAM;GACN,SAAS,GAAG,QAAQ,GAAG,uCAAuC,QAAQ,QAAQ,QAAQ,gBAAgB,QAAQ,OAAO,EAAE;GACvH,IAAI,QAAQ;GACZ,SAAS,QAAQ;GACjB,MAAM,QAAQ,GAAG;EACnB,CAAC,CACH;OACK,IAAI,QAAQ,SAAS,QAAQ,QAAQ,SAAS,KAAK,KAAK,OAC7D,SAAS,KACP,cAAc;GACZ,MAAM;GACN,SAAS,GAAG,QAAQ,GAAG,2BAA2B,QAAQ,QAAQ,GAAG,QAAQ,KAAK,QAAQ,KAAK,KAAK,QAAQ,KAAK,KAAK;GACtH,IAAI,QAAQ;GACZ,SAAS,QAAQ;GACjB,MAAM,QAAQ,GAAG;EACnB,CAAC,CACH;CAEJ;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/releases/index.ts"],"sourcesContent":["/**\n * Releases: collecting the changelog entries the agent stamped with a release\n * into `grimoire/releases/<release>.md`, and the GR6001–GR6003 rules.\n *\n * Collecting never edits a feature changelog or the agent's brief: it writes only\n * the text between the collected-list markers of the release file. Stamping\n * (`stamp.ts`, only on `--stamp`) is the one edit Warlock makes to written files.\n */\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { GrimoireError, createFinding } from \"../codes\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type { ReleaseCollection, ReleaseEntry, WriteReleaseResult } from \"../contracts/releases\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport {\n COLLECTED_END_MARKER,\n COLLECTED_START_MARKER,\n type WrittenChangelogEntry,\n type WrittenGrimoire,\n type WrittenRelease,\n} from \"../contracts/written\";\nimport { releaseFilePath } from \"../paths\";\n\nexport { applyStamp, planStamp, type StampInput, type StampPlan } from \"./stamp\";\n\n/** What `writeRelease()` returns: the contract result plus the entries it left out. */\nexport type WriteReleaseOutcome = WriteReleaseResult & {\n /** Entries still under `## Unreleased`; not collected. */\n unreleased: ReleaseEntry[];\n};\n\nfunction findRelease(written: WrittenGrimoire, release: string): WrittenRelease | undefined {\n return written.releases.find((item) => item.release.value === release);\n}\n\nfunction toReleaseEntry(entry: WrittenChangelogEntry, state: ReleaseEntry[\"state\"]): ReleaseEntry {\n return {\n feature: entry.feature,\n version: entry.version.value,\n word: entry.word,\n flow: entry.flow,\n criteria: [...entry.criteria],\n text: entry.text,\n state,\n source: entry.at,\n };\n}\n\n/** Compare two `<whole>.<decimal>` versions, newest first. */\nfunction compareVersionsDescending(a: string, b: string): number {\n const [aWhole = 0, aDecimal = 0] = a.split(\".\").map(Number);\n const [bWhole = 0, bDecimal = 0] = b.split(\".\").map(Number);\n\n return bWhole - aWhole || bDecimal - aDecimal;\n}\n\nfunction sortEntries(entries: ReleaseEntry[]): ReleaseEntry[] {\n // `sort` is stable, so equal versions keep their changelog order.\n return entries.sort(\n (a, b) => a.feature.localeCompare(b.feature) || compareVersionsDescending(a.version, b.version),\n );\n}\n\n/**\n * The entries still under `## Unreleased` in every feature changelog. They are\n * not part of any release until the agent stamps them.\n */\nexport function unreleasedEntries(written: WrittenGrimoire): ReleaseEntry[] {\n const entries: ReleaseEntry[] = [];\n\n for (const feature of written.features) {\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === null) entries.push(toReleaseEntry(entry, \"unreleased\"));\n }\n }\n\n return sortEntries(entries);\n}\n\n/**\n * The entries a release lists: the entries the agent stamped with that release\n * (under `## <release> (<date>)`). Entries under `## Unreleased` are never\n * collected. Throws a `GrimoireError` with `GR9005` when\n * `grimoire/releases/<release>.md` does not exist, has no `release` and\n * `date`, or has no brief.\n */\nexport function collectRelease(written: WrittenGrimoire, release: string): ReleaseCollection {\n const file = findRelease(written, release);\n\n if (!file || file.release.value === \"\" || file.date.value === \"\") {\n throw new GrimoireError(\n \"GR9005\",\n `${releaseFilePath(release)} does not exist or has no release and date. Write the brief first, with \\`release\\` and \\`date\\` in the front matter.`,\n );\n }\n\n if (file.brief.trim() === \"\") {\n throw new GrimoireError(\n \"GR9005\",\n `${file.file} has no brief yet. Write the brief under the heading, then run the command again.`,\n );\n }\n\n const entries: ReleaseEntry[] = [];\n\n for (const feature of written.features) {\n for (const entry of feature.changelog?.entries ?? []) {\n if (entry.release === release) entries.push(toReleaseEntry(entry, \"stamped\"));\n }\n }\n\n return { release, date: file.date.value, entries: sortEntries(entries) };\n}\n\nfunction entryLine(entry: {\n version: string;\n word: string;\n flow: string | null;\n criteria: string[];\n text: string;\n}): string {\n const flow = entry.flow === null ? \"\" : `${entry.flow}: `;\n const criteria = entry.criteria.length > 0 ? ` (${entry.criteria.join(\", \")})` : \"\";\n\n return `- ${entry.version} ${entry.word} ${flow}${entry.text}${criteria}`;\n}\n\n/** The Markdown between (and including) the collected-list markers. Pure. */\nexport function renderCollectedList(collection: ReleaseCollection): string {\n const lines: string[] = [COLLECTED_START_MARKER];\n\n if (collection.entries.length === 0) {\n lines.push(\"No feature changes.\");\n } else {\n lines.push(\"## Changes\");\n\n let current: string | null = null;\n\n for (const entry of collection.entries) {\n if (entry.feature !== current) {\n current = entry.feature;\n lines.push(\"\", `### ${entry.feature}`);\n }\n\n lines.push(entryLine(entry));\n }\n }\n\n lines.push(COLLECTED_END_MARKER);\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Collect the release and write the list into its file: replaces the text\n * between the markers, or appends the markers and the list at the end. Never\n * touches any other file or any text outside the markers. Refuses (`GR9005`)\n * when the agent has not written the release file and its brief.\n *\n * @param root Absolute project root.\n */\nexport async function writeRelease(\n root: string,\n written: WrittenGrimoire,\n release: string,\n): Promise<WriteReleaseOutcome> {\n const collection = collectRelease(written, release);\n const file = findRelease(written, release)?.file ?? releaseFilePath(release);\n const absolute = path.join(root, ...file.split(\"/\"));\n const current = await readFile(absolute, \"utf8\");\n const eol = current.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const list = renderCollectedList(collection).split(\"\\n\").join(eol);\n const start = current.indexOf(COLLECTED_START_MARKER);\n const end = current.indexOf(COLLECTED_END_MARKER);\n\n let next: string;\n\n if (start === -1 && end === -1) {\n const base = current.replace(/\\s+$/, \"\");\n\n next = `${base}${eol}${eol}${list}${eol}`;\n } else if (\n start === -1 ||\n end === -1 ||\n end < start ||\n current.indexOf(COLLECTED_START_MARKER, start + 1) !== -1 ||\n current.indexOf(COLLECTED_END_MARKER, end + 1) !== -1\n ) {\n throw new GrimoireError(\n \"GR1024\",\n `${file} has broken collected-list markers. Keep one start marker followed by one end marker, or remove both.`,\n );\n } else {\n next = current.slice(0, start) + list + current.slice(end + COLLECTED_END_MARKER.length);\n }\n\n const changed = next !== current;\n\n if (changed) await writeFile(absolute, next);\n\n return { file, collection, changed, unreleased: unreleasedEntries(written) };\n}\n\nfunction sameEntry(\n listed: { feature: string; version: string; word: string; flow: string | null; text: string },\n entry: WrittenChangelogEntry,\n): boolean {\n return (\n listed.feature === entry.feature &&\n listed.version === entry.version.value &&\n listed.word === entry.word &&\n listed.flow === entry.flow &&\n listed.text === entry.text\n );\n}\n\n/** The GR6001–GR6003 rules. Read-only. */\nexport function checkReleases(snapshot: GrimoireSnapshot): GrimoireFinding[] {\n const { written } = snapshot;\n const findings: GrimoireFinding[] = [];\n\n // GR6001: a listed entry with no matching entry stamped with this release.\n for (const file of written.releases) {\n for (const listed of file.collected?.entries ?? []) {\n const changelog = written.features.find(\n (feature) => feature.id === listed.feature,\n )?.changelog;\n const stamped = (changelog?.entries ?? []).some(\n (entry) =>\n entry.release === file.release.value && entry.date !== null && sameEntry(listed, entry),\n );\n\n if (!stamped) {\n findings.push(\n createFinding({\n code: \"GR6001\",\n message: `release ${file.release.value} lists \"${listed.feature} ${listed.version} ${listed.word}: ${listed.text}\", but no entry in that changelog is stamped with ${file.release.value} and a date`,\n at: listed.at,\n feature: listed.feature,\n file: file.file,\n }),\n );\n }\n }\n }\n\n // GR6002 and GR6003: a changelog release section needs its release file and date.\n for (const feature of written.features) {\n for (const section of feature.changelog?.sections ?? []) {\n if (section.release === null) continue;\n\n const file = findRelease(written, section.release);\n\n if (!file) {\n findings.push(\n createFinding({\n code: \"GR6002\",\n message: `${feature.id} changelog has a section for release ${section.release}, but ${releaseFilePath(section.release)} does not exist`,\n at: section.at,\n feature: feature.id,\n file: section.at.file,\n }),\n );\n } else if (section.date !== null && section.date !== file.date.value) {\n findings.push(\n createFinding({\n code: \"GR6003\",\n message: `${feature.id} changelog dates release ${section.release} ${section.date}, but ${file.file} says ${file.date.value}`,\n at: section.at,\n feature: feature.id,\n file: section.at.file,\n }),\n );\n }\n }\n }\n\n return findings;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,SAAS,YAAY,SAA0B,SAA6C;CAC1F,OAAO,QAAQ,SAAS,MAAM,SAAS,KAAK,QAAQ,UAAU,OAAO;AACvE;AAEA,SAAS,eAAe,OAA8B,OAA4C;CAChG,OAAO;EACL,SAAS,MAAM;EACf,SAAS,MAAM,QAAQ;EACvB,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,UAAU,CAAC,GAAG,MAAM,QAAQ;EAC5B,MAAM,MAAM;EACZ;EACA,QAAQ,MAAM;CAChB;AACF;;AAGA,SAAS,0BAA0B,GAAW,GAAmB;CAC/D,MAAM,CAAC,SAAS,GAAG,WAAW,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC1D,MAAM,CAAC,SAAS,GAAG,WAAW,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAE1D,OAAO,SAAS,UAAU,WAAW;AACvC;AAEA,SAAS,YAAY,SAAyC;CAE5D,OAAO,QAAQ,MACZ,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,KAAK,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,KAAK,OAC7D,SAAS,KACP,cAAc;GACZ,MAAM;GACN,SAAS,GAAG,QAAQ,GAAG,2BAA2B,QAAQ,QAAQ,GAAG,QAAQ,KAAK,QAAQ,KAAK,KAAK,QAAQ,KAAK,KAAK;GACtH,IAAI,QAAQ;GACZ,SAAS,QAAQ;GACjB,MAAM,QAAQ,GAAG;EACnB,CAAC,CACH;CAEJ;CAGF,OAAO;AACT"}
@@ -0,0 +1,121 @@
1
+ import { GrimoireError } from "../codes/index.mjs";
2
+ import { releaseFilePath } from "../paths/index.mjs";
3
+ import { isDate } from "../written/fields.mjs";
4
+ import path from "node:path";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+
7
+ //#region ../../packages/grimoire/src/releases/stamp.ts
8
+ /**
9
+ * Release stamping (`warlock grimoire release --stamp`): moves the entries under
10
+ * `## Unreleased` of each feature changelog under `## <version> (<date>)` and
11
+ * writes the release file when it is missing. It is the one edit Warlock makes to
12
+ * written files, and only on request.
13
+ *
14
+ * `planStamp()` is pure (text in, text out). `applyStamp()` is the thin writer.
15
+ */
16
+ const UNRELEASED = /^##[ \t]+unreleased[ \t]*$/i;
17
+ /** A section heading of a feature changelog: level 2 only (`### Added` stays inside its section). */
18
+ const HEADING = /^##[ \t]/;
19
+ /** A release section heading, the way the changelog parser reads it. */
20
+ const RELEASE_HEADING = /^##[ \t]+(\S+)[ \t]+\((.+)\)$/;
21
+ function refuse(message) {
22
+ throw new GrimoireError("GR9006", message);
23
+ }
24
+ /** "a", "a and b", "a, b and c". */
25
+ function listOf(items) {
26
+ if (items.length <= 1) return items.join("");
27
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
28
+ }
29
+ /**
30
+ * The new text of one changelog: the `## Unreleased` heading line stays as the
31
+ * (now empty) unreleased section, and `## <version> (<date>)` and a blank line
32
+ * follow it. When the changelog already has a section for the version (same date),
33
+ * the unreleased lines move to the top of that section instead.
34
+ */
35
+ function stampText(text, file, version, date, hasSection) {
36
+ const lines = text.split("\n");
37
+ const cr = (line) => line.endsWith("\r") ? "\r" : "";
38
+ const start = lines.findIndex((line) => UNRELEASED.test(line.trimEnd()));
39
+ if (start === -1) refuse(`${file} has no "## Unreleased" heading to stamp.`);
40
+ const heading = `## ${version} (${date})`;
41
+ if (!hasSection) {
42
+ const fresh = lines[start] ?? "";
43
+ lines.splice(start, 1, fresh, cr(fresh), `${heading}${cr(fresh)}`);
44
+ return lines.join("\n");
45
+ }
46
+ let end = start + 1;
47
+ while (end < lines.length && !HEADING.test(lines[end] ?? "")) end++;
48
+ const body = lines.slice(start + 1, end);
49
+ while (body.length > 0 && (body[body.length - 1] ?? "").trim() === "") body.pop();
50
+ while (body.length > 0 && (body[0] ?? "").trim() === "") body.shift();
51
+ const out = [
52
+ ...lines.slice(0, start + 1),
53
+ cr(lines[start] ?? ""),
54
+ ...lines.slice(end)
55
+ ];
56
+ const at = out.findIndex((line) => {
57
+ const match = RELEASE_HEADING.exec(line.trimEnd());
58
+ return match !== null && match[1] === version && match[2]?.trim() === date;
59
+ });
60
+ if (at === -1) refuse(`${file} has no "${heading}" heading to stamp.`);
61
+ out.splice(at + 1, 0, ...body);
62
+ return out.join("\n");
63
+ }
64
+ /** Plan a stamp: the new changelog texts and the release file to create. Pure. */
65
+ function planStamp(input) {
66
+ const { version, date, written, texts } = input;
67
+ if (!isDate(date)) refuse(`The release date must be yyyy-mm-dd (got ${JSON.stringify(date)}).`);
68
+ const changelogs = [];
69
+ const titles = [];
70
+ for (const feature of written.features) {
71
+ const changelog = feature.changelog;
72
+ if (changelog === null || !changelog.entries.some((entry) => entry.release === null)) continue;
73
+ const same = changelog.sections.find((section) => section.release === version);
74
+ if (same !== void 0 && same.date !== date) refuse(`${changelog.file} already has a section for ${version} dated ${same.date ?? ""}, not ${date}. Use that date, or correct the heading.`);
75
+ const text = texts[changelog.file];
76
+ if (text === void 0) refuse(`The text of ${changelog.file} was not given.`);
77
+ changelogs.push({
78
+ feature: feature.id,
79
+ file: changelog.file,
80
+ text: stampText(text, changelog.file, version, date, same !== void 0)
81
+ });
82
+ titles.push(feature.readme?.title.value ?? feature.id);
83
+ }
84
+ const file = releaseFilePath(version);
85
+ const exists = written.releases.some((item) => item.release.value === version);
86
+ const brief = titles.length === 0 ? "No feature changes in this release." : `Changes to ${listOf(titles)}.`;
87
+ return {
88
+ version,
89
+ date,
90
+ changelogs,
91
+ release: exists ? null : {
92
+ file,
93
+ text: `---\nrelease: ${version}\ndate: ${date}\n---\n\n# Release ${version}\n\n${brief}\n`
94
+ }
95
+ };
96
+ }
97
+ /** Read the changelogs, plan the stamp and write it. Returns the plan. */
98
+ async function applyStamp(root, written, version, date) {
99
+ const texts = {};
100
+ for (const feature of written.features) {
101
+ const file = feature.changelog?.file;
102
+ if (file !== void 0) texts[file] = await readFile(path.join(root, ...file.split("/")), "utf8");
103
+ }
104
+ const plan = planStamp({
105
+ version,
106
+ date,
107
+ written,
108
+ texts
109
+ });
110
+ for (const item of plan.changelogs) await writeFile(path.join(root, ...item.file.split("/")), item.text);
111
+ if (plan.release !== null) {
112
+ const absolute = path.join(root, ...plan.release.file.split("/"));
113
+ await mkdir(path.dirname(absolute), { recursive: true });
114
+ await writeFile(absolute, plan.release.text);
115
+ }
116
+ return plan;
117
+ }
118
+
119
+ //#endregion
120
+ export { applyStamp, planStamp };
121
+ //# sourceMappingURL=stamp.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stamp.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/releases/stamp.ts"],"sourcesContent":["/**\n * Release stamping (`warlock grimoire release --stamp`): moves the entries under\n * `## Unreleased` of each feature changelog under `## <version> (<date>)` and\n * writes the release file when it is missing. It is the one edit Warlock makes to\n * written files, and only on request.\n *\n * `planStamp()` is pure (text in, text out). `applyStamp()` is the thin writer.\n */\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { GrimoireError } from \"../codes\";\nimport type { WrittenGrimoire } from \"../contracts/written\";\nimport { releaseFilePath } from \"../paths\";\nimport { isDate } from \"../written/fields\";\n\nconst UNRELEASED = /^##[ \\t]+unreleased[ \\t]*$/i;\n/** A section heading of a feature changelog: level 2 only (`### Added` stays inside its section). */\nconst HEADING = /^##[ \\t]/;\n/** A release section heading, the way the changelog parser reads it. */\nconst RELEASE_HEADING = /^##[ \\t]+(\\S+)[ \\t]+\\((.+)\\)$/;\n\nexport type StampInput = {\n /** The release name, such as `1.4.0`. */\n version: string;\n /** `yyyy-mm-dd`. */\n date: string;\n written: WrittenGrimoire;\n /** The text of each feature changelog by project-relative path (at least the ones with unreleased entries). */\n texts: Readonly<Record<string, string>>;\n};\n\nexport type StampPlan = {\n version: string;\n date: string;\n /** Changelogs that change, with their new text. */\n changelogs: { feature: string; file: string; text: string }[];\n /** The release file to create, or `null` when it exists. */\n release: { file: string; text: string } | null;\n};\n\nfunction refuse(message: string): never {\n throw new GrimoireError(\"GR9006\", message);\n}\n\n/** \"a\", \"a and b\", \"a, b and c\". */\nfunction listOf(items: string[]): string {\n if (items.length <= 1) return items.join(\"\");\n\n return `${items.slice(0, -1).join(\", \")} and ${items[items.length - 1]}`;\n}\n\n/**\n * The new text of one changelog: the `## Unreleased` heading line stays as the\n * (now empty) unreleased section, and `## <version> (<date>)` and a blank line\n * follow it. When the changelog already has a section for the version (same date),\n * the unreleased lines move to the top of that section instead.\n */\nfunction stampText(\n text: string,\n file: string,\n version: string,\n date: string,\n hasSection: boolean,\n): string {\n const lines = text.split(\"\\n\");\n const cr = (line: string): string => (line.endsWith(\"\\r\") ? \"\\r\" : \"\");\n const start = lines.findIndex((line) => UNRELEASED.test(line.trimEnd()));\n\n if (start === -1) refuse(`${file} has no \"## Unreleased\" heading to stamp.`);\n\n const heading = `## ${version} (${date})`;\n\n if (!hasSection) {\n const fresh = lines[start] ?? \"\";\n\n lines.splice(start, 1, fresh, cr(fresh), `${heading}${cr(fresh)}`);\n\n return lines.join(\"\\n\");\n }\n\n // The version already has a section: move the unreleased lines to the top of it.\n let end = start + 1;\n\n while (end < lines.length && !HEADING.test(lines[end] ?? \"\")) end++;\n\n const body = lines.slice(start + 1, end);\n\n while (body.length > 0 && (body[body.length - 1] ?? \"\").trim() === \"\") body.pop();\n while (body.length > 0 && (body[0] ?? \"\").trim() === \"\") body.shift();\n\n const out = [...lines.slice(0, start + 1), cr(lines[start] ?? \"\"), ...lines.slice(end)];\n const at = out.findIndex((line) => {\n const match = RELEASE_HEADING.exec(line.trimEnd());\n\n return match !== null && match[1] === version && match[2]?.trim() === date;\n });\n\n if (at === -1) refuse(`${file} has no \"${heading}\" heading to stamp.`);\n\n out.splice(at + 1, 0, ...body);\n\n return out.join(\"\\n\");\n}\n\n/** Plan a stamp: the new changelog texts and the release file to create. Pure. */\nexport function planStamp(input: StampInput): StampPlan {\n const { version, date, written, texts } = input;\n\n if (!isDate(date)) refuse(`The release date must be yyyy-mm-dd (got ${JSON.stringify(date)}).`);\n\n const changelogs: StampPlan[\"changelogs\"] = [];\n const titles: string[] = [];\n\n for (const feature of written.features) {\n const changelog = feature.changelog;\n\n if (changelog === null || !changelog.entries.some((entry) => entry.release === null)) continue;\n\n const same = changelog.sections.find((section) => section.release === version);\n\n if (same !== undefined && same.date !== date) {\n refuse(\n `${changelog.file} already has a section for ${version} dated ${same.date ?? \"\"}, not ${date}. Use that date, or correct the heading.`,\n );\n }\n\n const text = texts[changelog.file];\n\n if (text === undefined) refuse(`The text of ${changelog.file} was not given.`);\n\n changelogs.push({\n feature: feature.id,\n file: changelog.file,\n text: stampText(text, changelog.file, version, date, same !== undefined),\n });\n titles.push(feature.readme?.title.value ?? feature.id);\n }\n\n const file = releaseFilePath(version);\n const exists = written.releases.some((item) => item.release.value === version);\n const brief =\n titles.length === 0 ? \"No feature changes in this release.\" : `Changes to ${listOf(titles)}.`;\n\n return {\n version,\n date,\n changelogs,\n release: exists\n ? null\n : {\n file,\n text: `---\\nrelease: ${version}\\ndate: ${date}\\n---\\n\\n# Release ${version}\\n\\n${brief}\\n`,\n },\n };\n}\n\n/** Read the changelogs, plan the stamp and write it. Returns the plan. */\nexport async function applyStamp(\n root: string,\n written: WrittenGrimoire,\n version: string,\n date: string,\n): Promise<StampPlan> {\n const texts: Record<string, string> = {};\n\n for (const feature of written.features) {\n const file = feature.changelog?.file;\n\n if (file !== undefined) {\n texts[file] = await readFile(path.join(root, ...file.split(\"/\")), \"utf8\");\n }\n }\n\n const plan = planStamp({ version, date, written, texts });\n\n for (const item of plan.changelogs) {\n await writeFile(path.join(root, ...item.file.split(\"/\")), item.text);\n }\n\n if (plan.release !== null) {\n const absolute = path.join(root, ...plan.release.file.split(\"/\"));\n\n await mkdir(path.dirname(absolute), { recursive: true });\n await writeFile(absolute, plan.release.text);\n }\n\n return plan;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAM,aAAa;;AAEnB,MAAM,UAAU;;AAEhB,MAAM,kBAAkB;AAqBxB,SAAS,OAAO,SAAwB;CACtC,MAAM,IAAI,cAAc,UAAU,OAAO;AAC3C;;AAGA,SAAS,OAAO,OAAyB;CACvC,IAAI,MAAM,UAAU,GAAG,OAAO,MAAM,KAAK,EAAE;CAE3C,OAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,MAAM,MAAM,SAAS;AACtE;;;;;;;AAQA,SAAS,UACP,MACA,MACA,SACA,MACA,YACQ;CACR,MAAM,QAAQ,KAAK,MAAM,IAAI;CAC7B,MAAM,MAAM,SAA0B,KAAK,SAAS,IAAI,IAAI,OAAO;CACnE,MAAM,QAAQ,MAAM,WAAW,SAAS,WAAW,KAAK,KAAK,QAAQ,CAAC,CAAC;CAEvE,IAAI,UAAU,IAAI,OAAO,GAAG,KAAK,0CAA0C;CAE3E,MAAM,UAAU,MAAM,QAAQ,IAAI,KAAK;CAEvC,IAAI,CAAC,YAAY;EACf,MAAM,QAAQ,MAAM,UAAU;EAE9B,MAAM,OAAO,OAAO,GAAG,OAAO,GAAG,KAAK,GAAG,G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,KAAK,MAAM,GAAG,KAAK,QAAQ,KAAK,MAAM,GAAG,CAAC;EAEhE,MAAM,MAAM,KAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;EACvD,MAAM,UAAU,UAAU,KAAK,QAAQ,IAAI;CAC7C;CAEA,OAAO;AACT"}
@@ -0,0 +1,26 @@
1
+ import { scanSource } from "./scan.mjs";
2
+
3
+ //#region ../../packages/grimoire/src/rules/focused.ts
4
+ /**
5
+ * GR4011 / GR4012: tests focused with `.only` or skipped with `.skip`.
6
+ * `.skipIf(...)` and `.todo` are not flagged; comments and strings are ignored.
7
+ */
8
+ const FOCUSED = /\b(describe|it|test|suite)((?:\.(?:concurrent|sequential))?)\.(only|skip)\b/g;
9
+ /** Find `.only` and `.skip` calls in a test file's text. */
10
+ function findFocusedTests(text) {
11
+ const { bare } = scanSource(text, "code");
12
+ const hits = [];
13
+ for (const match of bare.matchAll(FOCUSED)) {
14
+ const offset = match.index ?? 0;
15
+ hits.push({
16
+ line: bare.slice(0, offset).split("\n").length,
17
+ type: match[3] === "only" ? "only" : "skip",
18
+ call: match[0]
19
+ });
20
+ }
21
+ return hits;
22
+ }
23
+
24
+ //#endregion
25
+ export { findFocusedTests };
26
+ //# sourceMappingURL=focused.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focused.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/rules/focused.ts"],"sourcesContent":["/**\n * GR4011 / GR4012: tests focused with `.only` or skipped with `.skip`.\n * `.skipIf(...)` and `.todo` are not flagged; comments and strings are ignored.\n */\nimport { scanSource } from \"./scan\";\n\n/** One focused or skipped test call. */\nexport type FocusedHit = { line: number; type: \"only\" | \"skip\"; call: string };\n\nconst FOCUSED = /\\b(describe|it|test|suite)((?:\\.(?:concurrent|sequential))?)\\.(only|skip)\\b/g;\n\n/** Find `.only` and `.skip` calls in a test file's text. */\nexport function findFocusedTests(text: string): FocusedHit[] {\n const { bare } = scanSource(text, \"code\");\n const hits: FocusedHit[] = [];\n\n for (const match of bare.matchAll(FOCUSED)) {\n const offset = match.index ?? 0;\n\n hits.push({\n line: bare.slice(0, offset).split(\"\\n\").length,\n type: match[3] === \"only\" ? \"only\" : \"skip\",\n call: match[0],\n });\n }\n\n return hits;\n}\n"],"mappings":";;;;;;;AASA,MAAM,UAAU;;AAGhB,SAAgB,iBAAiB,MAA4B;CAC3D,MAAM,EAAE,SAAS,WAAW,MAAM,MAAM;CACxC,MAAM,OAAqB,CAAC;CAE5B,KAAK,MAAM,SAAS,KAAK,SAAS,OAAO,GAAG;EAC1C,MAAM,SAAS,MAAM,SAAS;EAE9B,KAAK,KAAK;GACR,MAAM,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC;GACxC,MAAM,MAAM,OAAO,SAAS,SAAS;GACrC,MAAM,MAAM;EACd,CAAC;CACH;CAEA,OAAO;AACT"}
@@ -0,0 +1,88 @@
1
+ import { CODE_RULES } from "../contracts/settings.mjs";
2
+ import { logicalCss } from "./logical-css.mjs";
3
+ import { noJsImports } from "./no-js-imports.mjs";
4
+ import { scanSource } from "./scan.mjs";
5
+ import { isGenericError, phraseOf, specificErrors } from "./specific-errors.mjs";
6
+ import { typeDiscriminator } from "./type-discriminator.mjs";
7
+
8
+ //#region ../../packages/grimoire/src/rules/index.ts
9
+ /**
10
+ * The code rules: four text rules over a file's content, shared by
11
+ * `grimoire check` (whole files), the guard (added lines) and the specs.
12
+ *
13
+ * Escape hatch: a comment on the line or the line above reading
14
+ * `grimoire-allow <rule>: <why>` (several rules: `grimoire-allow a, b: why`).
15
+ * Limits: the scanner is not a parser (see `scan.ts`), and editors show no
16
+ * squiggles for these rules.
17
+ */
18
+ /** The finding code of each rule. */
19
+ const RULE_CODES = {
20
+ "logical-css": "GR3007",
21
+ "specific-errors": "GR3008",
22
+ "type-discriminator": "GR3009",
23
+ "no-js-imports": "GR3010"
24
+ };
25
+ const CODE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/;
26
+ const STYLE_FILE = /\.(?:css|scss|less)$/;
27
+ const LOCALE_PATH = /(?:^|[/._-])(?:locales?|lang|langs|i18n|translations?)(?:[/._-]|$)/i;
28
+ const SPEC_FILE = /\.(?:spec|test)\.[cm]?[jt]sx?$/;
29
+ const SKIPPED_FOLDER = /(?:^|\/)(?:node_modules|dist|grimoire)\//;
30
+ /** Whether the rules read a file at all: code, style and locale JSON files, not specs, builds or `grimoire/`. */
31
+ function isRuleFile(file) {
32
+ if (SKIPPED_FOLDER.test(file) || SPEC_FILE.test(file) || file.endsWith(".d.ts")) return false;
33
+ if (file.endsWith(".json")) return LOCALE_PATH.test(file);
34
+ return CODE_FILE.test(file) || STYLE_FILE.test(file);
35
+ }
36
+ function modeOf(file) {
37
+ if (file.endsWith(".json")) return "json";
38
+ if (file.endsWith(".scss")) return "scss";
39
+ if (STYLE_FILE.test(file)) return "css";
40
+ return "code";
41
+ }
42
+ /** Lines (1-based) a `grimoire-allow` comment covers, per rule. */
43
+ function allowedLines(scanned) {
44
+ const allowed = /* @__PURE__ */ new Map();
45
+ for (const comment of scanned.comments) {
46
+ const match = /grimoire-allow\s+([a-z-]+(?:\s*,\s*[a-z-]+)*)\s*:\s*\S/.exec(comment.text);
47
+ if (!match) continue;
48
+ for (const name of (match[1] ?? "").split(",").map((part) => part.trim())) {
49
+ const lines = allowed.get(name) ?? /* @__PURE__ */ new Set();
50
+ for (let line = comment.startLine; line <= comment.endLine + 1; line++) lines.add(line);
51
+ allowed.set(name, lines);
52
+ }
53
+ }
54
+ return allowed;
55
+ }
56
+ /**
57
+ * Run the rules over one file's text. `file` decides the kind of scan (CSS,
58
+ * JSON locale, code) and whether it is skipped. Findings come back in line
59
+ * order; a rule's finding on a line a `grimoire-allow` comment covers is left out.
60
+ */
61
+ function runCodeRules(file, text, rules = CODE_RULES) {
62
+ if (!isRuleFile(file)) return [];
63
+ const mode = modeOf(file);
64
+ const scanned = scanSource(text, mode);
65
+ const allowed = allowedLines(scanned);
66
+ const style = mode === "css" || mode === "scss" ? "css" : "code";
67
+ const locale = mode === "json" || LOCALE_PATH.test(file);
68
+ const findings = [];
69
+ const add = (rule, hits) => {
70
+ for (const hit of hits) {
71
+ if (allowed.get(rule)?.has(hit.line)) continue;
72
+ findings.push({
73
+ ...hit,
74
+ rule,
75
+ code: RULE_CODES[rule]
76
+ });
77
+ }
78
+ };
79
+ for (const rule of rules) if (rule === "logical-css" && mode !== "json") add(rule, logicalCss(scanned, style));
80
+ else if (rule === "specific-errors" && style === "code") add(rule, specificErrors(scanned, locale));
81
+ else if (rule === "type-discriminator" && mode === "code") add(rule, typeDiscriminator(scanned));
82
+ else if (rule === "no-js-imports" && mode === "code") add(rule, noJsImports(scanned));
83
+ return findings.sort((left, right) => left.line - right.line || left.column - right.column);
84
+ }
85
+
86
+ //#endregion
87
+ export { RULE_CODES, isRuleFile, runCodeRules };
88
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/rules/index.ts"],"sourcesContent":["/**\n * The code rules: four text rules over a file's content, shared by\n * `grimoire check` (whole files), the guard (added lines) and the specs.\n *\n * Escape hatch: a comment on the line or the line above reading\n * `grimoire-allow <rule>: <why>` (several rules: `grimoire-allow a, b: why`).\n * Limits: the scanner is not a parser (see `scan.ts`), and editors show no\n * squiggles for these rules.\n */\nimport { CODE_RULES, type CodeRuleName } from \"../contracts/settings\";\nimport { logicalCss } from \"./logical-css\";\nimport { noJsImports } from \"./no-js-imports\";\nimport { scanSource, type ScannedSource, type ScanMode } from \"./scan\";\nimport { specificErrors } from \"./specific-errors\";\nimport { typeDiscriminator } from \"./type-discriminator\";\nimport type { RuleFinding, RuleHit } from \"./types\";\n\nexport { phraseOf, isGenericError } from \"./specific-errors\";\nexport { scanSource, type ScannedSource, type ScanMode } from \"./scan\";\nexport type { RuleFinding, RuleHit } from \"./types\";\n\n/** The finding code of each rule. */\nexport const RULE_CODES: Record<CodeRuleName, string> = {\n \"logical-css\": \"GR3007\",\n \"specific-errors\": \"GR3008\",\n \"type-discriminator\": \"GR3009\",\n \"no-js-imports\": \"GR3010\",\n};\n\nconst CODE_FILE = /\\.(?:[cm]?[jt]s|[jt]sx)$/;\nconst STYLE_FILE = /\\.(?:css|scss|less)$/;\nconst LOCALE_PATH = /(?:^|[/._-])(?:locales?|lang|langs|i18n|translations?)(?:[/._-]|$)/i;\nconst SPEC_FILE = /\\.(?:spec|test)\\.[cm]?[jt]sx?$/;\nconst SKIPPED_FOLDER = /(?:^|\\/)(?:node_modules|dist|grimoire)\\//;\n\n/** Whether the rules read a file at all: code, style and locale JSON files, not specs, builds or `grimoire/`. */\nexport function isRuleFile(file: string): boolean {\n if (SKIPPED_FOLDER.test(file) || SPEC_FILE.test(file) || file.endsWith(\".d.ts\")) return false;\n\n if (file.endsWith(\".json\")) return LOCALE_PATH.test(file);\n\n return CODE_FILE.test(file) || STYLE_FILE.test(file);\n}\n\nfunction modeOf(file: string): ScanMode {\n if (file.endsWith(\".json\")) return \"json\";\n if (file.endsWith(\".scss\")) return \"scss\";\n if (STYLE_FILE.test(file)) return \"css\";\n\n return \"code\";\n}\n\n/** Lines (1-based) a `grimoire-allow` comment covers, per rule. */\nfunction allowedLines(scanned: ScannedSource): Map<string, Set<number>> {\n const allowed = new Map<string, Set<number>>();\n\n for (const comment of scanned.comments) {\n const match = /grimoire-allow\\s+([a-z-]+(?:\\s*,\\s*[a-z-]+)*)\\s*:\\s*\\S/.exec(comment.text);\n\n if (!match) continue;\n\n for (const name of (match[1] ?? \"\").split(\",\").map((part) => part.trim())) {\n const lines = allowed.get(name) ?? new Set<number>();\n\n for (let line = comment.startLine; line <= comment.endLine + 1; line++) lines.add(line);\n\n allowed.set(name, lines);\n }\n }\n\n return allowed;\n}\n\n/**\n * Run the rules over one file's text. `file` decides the kind of scan (CSS,\n * JSON locale, code) and whether it is skipped. Findings come back in line\n * order; a rule's finding on a line a `grimoire-allow` comment covers is left out.\n */\nexport function runCodeRules(\n file: string,\n text: string,\n rules: readonly CodeRuleName[] = CODE_RULES,\n): RuleFinding[] {\n if (!isRuleFile(file)) return [];\n\n const mode = modeOf(file);\n const scanned = scanSource(text, mode);\n const allowed = allowedLines(scanned);\n const style = mode === \"css\" || mode === \"scss\" ? \"css\" : \"code\";\n const locale = mode === \"json\" || LOCALE_PATH.test(file);\n const findings: RuleFinding[] = [];\n\n const add = (rule: CodeRuleName, hits: RuleHit[]): void => {\n for (const hit of hits) {\n if (allowed.get(rule)?.has(hit.line)) continue;\n\n findings.push({ ...hit, rule, code: RULE_CODES[rule] });\n }\n };\n\n for (const rule of rules) {\n if (rule === \"logical-css\" && mode !== \"json\") add(rule, logicalCss(scanned, style));\n else if (rule === \"specific-errors\" && style === \"code\")\n add(rule, specificErrors(scanned, locale));\n else if (rule === \"type-discriminator\" && mode === \"code\")\n add(rule, typeDiscriminator(scanned));\n else if (rule === \"no-js-imports\" && mode === \"code\") add(rule, noJsImports(scanned));\n }\n\n return findings.sort((left, right) => left.line - right.line || left.column - right.column);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,MAAa,aAA2C;CACtD,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,iBAAiB;AACnB;AAEA,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,YAAY;AAClB,MAAM,iBAAiB;;AAGvB,SAAgB,WAAW,MAAuB;CAChD,IAAI,eAAe,KAAK,IAAI,KAAK,UAAU,KAAK,IAAI,KAAK,KAAK,SAAS,OAAO,GAAG,OAAO;CAExF,IAAI,KAAK,SAAS,OAAO,GAAG,OAAO,YAAY,KAAK,IAAI;CAExD,OAAO,UAAU,KAAK,IAAI,KAAK,WAAW,KAAK,IAAI;AACrD;AAEA,SAAS,OAAO,MAAwB;CACtC,IAAI,KAAK,SAAS,OAAO,GAAG,OAAO;CACnC,IAAI,KAAK,SAAS,OAAO,GAAG,OAAO;CACnC,IAA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