@virtocommerce/test-automation-framework 0.0.0-stage → 0.1.0-alpha.1

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 (233) hide show
  1. package/.biome/formatter.json +11 -0
  2. package/.biome/imports.json +52 -0
  3. package/.biome/preset.json +4 -0
  4. package/.biome/rules.json +45 -0
  5. package/.claude/agents/qa-automation-expert.md +119 -0
  6. package/.claude/agents/qa-coverage.md +96 -0
  7. package/.claude/agents/qa-explorer.md +112 -0
  8. package/.claude/agents/qa-healer.md +88 -0
  9. package/.claude/agents/qa-judge.md +102 -0
  10. package/.claude/agents/qa-planner.md +104 -0
  11. package/.claude/agents/qa-reviewer.md +121 -0
  12. package/.claude/checks/browser-secrets.mts +107 -0
  13. package/.claude/checks/contract.mts +469 -0
  14. package/.claude/checks/expectation-guard.mts +665 -0
  15. package/.claude/checks/explore-extractors.mts +4 -0
  16. package/.claude/checks/judge-verdict.mts +165 -0
  17. package/.claude/checks/project-facts.mts +491 -0
  18. package/.claude/checks/prove-fails.mts +770 -0
  19. package/.claude/checks/rank-gaps.mts +177 -0
  20. package/.claude/checks/readonly-shell.mts +740 -0
  21. package/.claude/checks/reconcile-run.mts +270 -0
  22. package/.claude/checks/scan-prompts.mts +351 -0
  23. package/.claude/checks/stand.mts +45 -0
  24. package/.claude/checks/test-duration.mts +134 -0
  25. package/.claude/checks/test-shape.mts +224 -0
  26. package/.claude/checks/ticket-card.mts +195 -0
  27. package/.claude/commands/qa-coverage.md +13 -0
  28. package/.claude/commands/qa-explore.md +17 -0
  29. package/.claude/commands/qa-heal.md +44 -0
  30. package/.claude/commands/qa-implement.md +60 -0
  31. package/.claude/commands/qa-plan.md +55 -0
  32. package/.claude/commands/qa-review.md +90 -0
  33. package/.claude/commands/qa.md +156 -0
  34. package/.claude/hooks/readonly-shell.mts +65 -0
  35. package/.claude/settings.json +15 -0
  36. package/.claude/skills/coverage-analysis/SKILL.md +107 -0
  37. package/.claude/skills/create-graphql-layer/SKILL.md +159 -0
  38. package/.claude/skills/create-ui-layer/SKILL.md +189 -0
  39. package/.claude/skills/explore-api/SKILL.md +74 -0
  40. package/.claude/skills/explore-frontend/SKILL.md +85 -0
  41. package/.claude/skills/framework-rules/SKILL.md +189 -0
  42. package/.claude/skills/heal-tests/SKILL.md +197 -0
  43. package/.claude/skills/heal-tests/guard-recipe.md +53 -0
  44. package/.claude/skills/judge-criteria/SKILL.md +40 -0
  45. package/.claude/skills/judge-criteria/coverage.md +9 -0
  46. package/.claude/skills/judge-criteria/expert.md +23 -0
  47. package/.claude/skills/judge-criteria/explorer.md +9 -0
  48. package/.claude/skills/judge-criteria/healer.md +13 -0
  49. package/.claude/skills/judge-criteria/planner.md +12 -0
  50. package/.claude/skills/plan-implementation/SKILL.md +82 -0
  51. package/.claude/skills/plan-implementation/contract-template.md +72 -0
  52. package/.claude/skills/plan-test-strategy/SKILL.md +100 -0
  53. package/.claude/skills/project-facts/SKILL.md +130 -0
  54. package/.claude/skills/read-change/SKILL.md +64 -0
  55. package/.claude/skills/read-ticket/SKILL.md +63 -0
  56. package/.claude/skills/read-ticket/providers.md +58 -0
  57. package/.claude/skills/review-pr/SKILL.md +152 -0
  58. package/.claude/skills/review-test-code/SKILL.md +208 -0
  59. package/.claude/skills/write-e2e-test/SKILL.md +175 -0
  60. package/.claude/skills/write-graphql-test/SKILL.md +158 -0
  61. package/.claude/skills/write-rest-api-test/SKILL.md +182 -0
  62. package/.claude/skills/write-security-test/SKILL.md +253 -0
  63. package/.qa/project.example.json +71 -0
  64. package/CHANGELOG.md +1 -0
  65. package/LICENSE +12 -0
  66. package/README.md +53 -2
  67. package/bin/install-qa-agents.mjs +94 -0
  68. package/dist/auth/credentials.d.ts +10 -0
  69. package/dist/auth/credentials.js +2 -0
  70. package/dist/auth/credentials.js.map +1 -0
  71. package/dist/auth/frontend-browser-sessions.d.ts +71 -0
  72. package/dist/auth/frontend-browser-sessions.js +130 -0
  73. package/dist/auth/frontend-browser-sessions.js.map +1 -0
  74. package/dist/auth/index.d.ts +9 -0
  75. package/dist/auth/index.js +5 -0
  76. package/dist/auth/index.js.map +1 -0
  77. package/dist/auth/platform-browser-sessions.d.ts +47 -0
  78. package/dist/auth/platform-browser-sessions.js +92 -0
  79. package/dist/auth/platform-browser-sessions.js.map +1 -0
  80. package/dist/auth/sign-in-lock.d.ts +14 -0
  81. package/dist/auth/sign-in-lock.js +70 -0
  82. package/dist/auth/sign-in-lock.js.map +1 -0
  83. package/dist/auth/storage-state.d.ts +3 -0
  84. package/dist/auth/storage-state.js +2 -0
  85. package/dist/auth/storage-state.js.map +1 -0
  86. package/dist/auth/token-client.d.ts +82 -0
  87. package/dist/auth/token-client.js +111 -0
  88. package/dist/auth/token-client.js.map +1 -0
  89. package/dist/auth/token-manager.d.ts +67 -0
  90. package/dist/auth/token-manager.js +138 -0
  91. package/dist/auth/token-manager.js.map +1 -0
  92. package/dist/core/default-reporters.d.ts +31 -0
  93. package/dist/core/default-reporters.js +36 -0
  94. package/dist/core/default-reporters.js.map +1 -0
  95. package/dist/core/default-use.d.ts +28 -0
  96. package/dist/core/default-use.js +25 -0
  97. package/dist/core/default-use.js.map +1 -0
  98. package/dist/core/env.d.ts +24 -0
  99. package/dist/core/env.js +33 -0
  100. package/dist/core/env.js.map +1 -0
  101. package/dist/core/error-message.d.ts +10 -0
  102. package/dist/core/error-message.js +13 -0
  103. package/dist/core/error-message.js.map +1 -0
  104. package/dist/core/index.d.ts +16 -0
  105. package/dist/core/index.js +11 -0
  106. package/dist/core/index.js.map +1 -0
  107. package/dist/core/is-ci.d.ts +14 -0
  108. package/dist/core/is-ci.js +18 -0
  109. package/dist/core/is-ci.js.map +1 -0
  110. package/dist/core/parse-env.d.ts +13 -0
  111. package/dist/core/parse-env.js +21 -0
  112. package/dist/core/parse-env.js.map +1 -0
  113. package/dist/core/projects.d.ts +24 -0
  114. package/dist/core/projects.js +33 -0
  115. package/dist/core/projects.js.map +1 -0
  116. package/dist/core/run-options.d.ts +31 -0
  117. package/dist/core/run-options.js +43 -0
  118. package/dist/core/run-options.js.map +1 -0
  119. package/dist/core/secret.d.ts +105 -0
  120. package/dist/core/secret.js +167 -0
  121. package/dist/core/secret.js.map +1 -0
  122. package/dist/core/string-schemas.d.ts +39 -0
  123. package/dist/core/string-schemas.js +56 -0
  124. package/dist/core/string-schemas.js.map +1 -0
  125. package/dist/core/url-path.d.ts +7 -0
  126. package/dist/core/url-path.js +2 -0
  127. package/dist/core/url-path.js.map +1 -0
  128. package/dist/dataset/collection.d.ts +44 -0
  129. package/dist/dataset/collection.js +76 -0
  130. package/dist/dataset/collection.js.map +1 -0
  131. package/dist/dataset/index.d.ts +11 -0
  132. package/dist/dataset/index.js +6 -0
  133. package/dist/dataset/index.js.map +1 -0
  134. package/dist/dataset/load-dataset.d.ts +39 -0
  135. package/dist/dataset/load-dataset.js +62 -0
  136. package/dist/dataset/load-dataset.js.map +1 -0
  137. package/dist/dataset/manifest.d.ts +77 -0
  138. package/dist/dataset/manifest.js +10 -0
  139. package/dist/dataset/manifest.js.map +1 -0
  140. package/dist/dataset/placeholders.d.ts +66 -0
  141. package/dist/dataset/placeholders.js +87 -0
  142. package/dist/dataset/placeholders.js.map +1 -0
  143. package/dist/dataset/seed-collection.d.ts +53 -0
  144. package/dist/dataset/seed-collection.js +115 -0
  145. package/dist/dataset/seed-collection.js.map +1 -0
  146. package/dist/dataset/seed-dataset.d.ts +70 -0
  147. package/dist/dataset/seed-dataset.js +138 -0
  148. package/dist/dataset/seed-dataset.js.map +1 -0
  149. package/dist/dataset/seed-events.d.ts +81 -0
  150. package/dist/dataset/seed-events.js +2 -0
  151. package/dist/dataset/seed-events.js.map +1 -0
  152. package/dist/dataset/seed-requests.d.ts +102 -0
  153. package/dist/dataset/seed-requests.js +160 -0
  154. package/dist/dataset/seed-requests.js.map +1 -0
  155. package/dist/dataset/seed-scope.d.ts +39 -0
  156. package/dist/dataset/seed-scope.js +67 -0
  157. package/dist/dataset/seed-scope.js.map +1 -0
  158. package/dist/fixtures/default-fixtures.d.ts +93 -0
  159. package/dist/fixtures/default-fixtures.js +105 -0
  160. package/dist/fixtures/default-fixtures.js.map +1 -0
  161. package/dist/fixtures/index.d.ts +2 -0
  162. package/dist/fixtures/index.js +2 -0
  163. package/dist/fixtures/index.js.map +1 -0
  164. package/dist/graphql/graphql-client.d.ts +78 -0
  165. package/dist/graphql/graphql-client.js +83 -0
  166. package/dist/graphql/graphql-client.js.map +1 -0
  167. package/dist/graphql/graphql-codegen.d.ts +56 -0
  168. package/dist/graphql/graphql-codegen.js +42 -0
  169. package/dist/graphql/graphql-codegen.js.map +1 -0
  170. package/dist/graphql/graphql-error.d.ts +54 -0
  171. package/dist/graphql/graphql-error.js +74 -0
  172. package/dist/graphql/graphql-error.js.map +1 -0
  173. package/dist/graphql/index.d.ts +6 -0
  174. package/dist/graphql/index.js +4 -0
  175. package/dist/graphql/index.js.map +1 -0
  176. package/dist/http/authentication.d.ts +16 -0
  177. package/dist/http/authentication.js +2 -0
  178. package/dist/http/authentication.js.map +1 -0
  179. package/dist/http/http-client.d.ts +110 -0
  180. package/dist/http/http-client.js +237 -0
  181. package/dist/http/http-client.js.map +1 -0
  182. package/dist/http/http-error.d.ts +26 -0
  183. package/dist/http/http-error.js +34 -0
  184. package/dist/http/http-error.js.map +1 -0
  185. package/dist/http/http-method.d.ts +2 -0
  186. package/dist/http/http-method.js +2 -0
  187. package/dist/http/http-method.js.map +1 -0
  188. package/dist/http/http-response.d.ts +137 -0
  189. package/dist/http/http-response.js +166 -0
  190. package/dist/http/http-response.js.map +1 -0
  191. package/dist/http/index.d.ts +7 -0
  192. package/dist/http/index.js +4 -0
  193. package/dist/http/index.js.map +1 -0
  194. package/dist/http/request-options.d.ts +62 -0
  195. package/dist/http/request-options.js +2 -0
  196. package/dist/http/request-options.js.map +1 -0
  197. package/dist/modules/index.d.ts +2 -0
  198. package/dist/modules/index.js +2 -0
  199. package/dist/modules/index.js.map +1 -0
  200. package/dist/modules/installed-modules.d.ts +86 -0
  201. package/dist/modules/installed-modules.js +135 -0
  202. package/dist/modules/installed-modules.js.map +1 -0
  203. package/docs/README.md +43 -0
  204. package/docs/concepts/areas.md +38 -0
  205. package/docs/concepts/auth.md +92 -0
  206. package/docs/concepts/config.md +102 -0
  207. package/docs/concepts/dataset.md +183 -0
  208. package/docs/concepts/environment.md +54 -0
  209. package/docs/concepts/fixtures.md +109 -0
  210. package/docs/concepts/graphql.md +76 -0
  211. package/docs/concepts/http.md +88 -0
  212. package/docs/concepts/modules.md +63 -0
  213. package/docs/concepts/secrets.md +50 -0
  214. package/docs/contributing/architecture.md +67 -0
  215. package/docs/contributing/conventions.md +39 -0
  216. package/docs/contributing/documentation.md +37 -0
  217. package/docs/contributing/releasing.md +76 -0
  218. package/docs/examples/auth.ts +20 -0
  219. package/docs/examples/config.ts +36 -0
  220. package/docs/examples/dataset.ts +70 -0
  221. package/docs/examples/environment.ts +8 -0
  222. package/docs/examples/fixtures.ts +41 -0
  223. package/docs/examples/getting-started.ts +22 -0
  224. package/docs/examples/graphql-codegen.ts +9 -0
  225. package/docs/examples/graphql.ts +32 -0
  226. package/docs/examples/http.ts +18 -0
  227. package/docs/examples/modules.ts +19 -0
  228. package/docs/examples/secrets.ts +11 -0
  229. package/docs/examples/tsconfig.json +10 -0
  230. package/docs/getting-started.md +106 -0
  231. package/docs/guides/generating-types.md +75 -0
  232. package/docs/guides/qa-agents.md +66 -0
  233. package/package.json +156 -4
@@ -0,0 +1,665 @@
1
+ import type { ProjectFacts } from "./project-facts.mts";
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs";
6
+ import { homedir, tmpdir } from "node:os";
7
+ import { basename, dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
8
+
9
+ import { PROJECT_FACTS_PATH, parseProjectFacts } from "./project-facts.mts";
10
+
11
+ export type ChangedExpectation = { file: string; line: string };
12
+
13
+ type Hunk = { old: number; added: number };
14
+
15
+ type DiffLine = { file: string; marker: string; text: string; first: boolean };
16
+
17
+ const CLI_FILE_NAME = "expectation-guard.mts";
18
+ const BASE_FLAG = "--base=";
19
+ const SNAPSHOT_FLAG = "--snapshot";
20
+ const FINGERPRINT_FLAG = "--repo-fingerprint";
21
+ const DEFAULT_BASE = "HEAD";
22
+ const USAGE =
23
+ "expectation-guard: usage is node .claude/checks/expectation-guard.mts [--base=<tree-ish> | --snapshot | --repo-fingerprint]";
24
+ const FILTER_SECTION = "filter";
25
+ const FILTER_SETTINGS = ["clean", "smudge", "process"];
26
+ const HOOK_SECTION = "hook";
27
+ const HOOK_EVENTS = ["post-index-change"];
28
+ const FINGERPRINT_DIRS = ["info", "hooks"];
29
+ const MISSING = "missing";
30
+ const FINDING_EXIT_CODE = 1;
31
+ const ERROR_EXIT_CODE = 2;
32
+ const WHOLE_FILE_CONTEXT = 100_000;
33
+ const MAX_BUFFER = 256 * 1024 * 1024;
34
+ const NO_FILE = "/dev/null";
35
+ const TEMP_PREFIX = "expectation-guard-index-";
36
+ const OUTSIDE_PREFIX = "outside healer paths: ";
37
+ const FILE_ORIGIN = "file:";
38
+ const INCLUDE_PATH_KEYS = "^include(if\\..*)?\\.path$";
39
+ const NO_MATCH_EXIT_CODE = 1;
40
+ const HOME_PREFIX = /^~\//;
41
+ const UNEXPANDED_PREFIXES = [/^~(?!\/)/, /^%\(prefix\)/];
42
+ const PARTIAL_CLONE_KEY = "^extensions\\.partialclone$";
43
+ const PROMISOR_KEYS = "^remote\\..*\\.promisor$";
44
+ const TRAILING_CARRIAGE_RETURN = /\r$/;
45
+ const TRUE_VALUES: ReadonlySet<string> = new Set(["true", "yes", "on", "1"]);
46
+ const FALSE_VALUES: ReadonlySet<string> = new Set(["false", "no", "off", "0", ""]);
47
+ const GIT_VERSION = /^git version (\d+)\.(\d+)/;
48
+ const LAZY_FETCH_SINCE = { major: 2, minor: 44 };
49
+ const CASE_INSENSITIVE_PLATFORMS: ReadonlySet<NodeJS.Platform> = new Set(["win32", "darwin"]);
50
+ const ADDED_PREFIX = "added ";
51
+ const HUNK_HEADER = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/;
52
+ const PATH_PREFIX = /^[ab]\//;
53
+ const PATH_SUFFIX = /\t.*$/;
54
+ const TRAILING_SLASHES = /\/+$/;
55
+ const STRING_LITERAL = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
56
+ const OPENERS = new Set(["(", "[", "{"]);
57
+ const CLOSERS = new Set([")", "]", "}"]);
58
+ const EXPECTATION = [
59
+ /\bexpect\w*\s*[.(]/,
60
+ /\.(?:expect|verify|assert)\w*\s*\(/,
61
+ /\.\s*to(?:Be|Equal|StrictEqual|Have|Match|Contain|Throw|Satisfy)\w*\s*\(/,
62
+ /\bassert\s*:/,
63
+ /\bassert\s*(?:\.\s*\w+\s*)?\(/,
64
+ /expected\w*\s*[:=]/i,
65
+ ];
66
+ const SUPPRESSION = [
67
+ /\btest\s*\.\s*(?:skip|fixme|fail|slow|setTimeout)\b/,
68
+ /\bdescribe\s*\.\s*(?:skip|fixme|fail|slow|configure)\b/,
69
+ /\b(?:testInfo|test\s*\.\s*info\s*\(\s*\))\s*\.\s*(?:skip|fixme|fail)\b/,
70
+ /["'`](?:node:)?(?:fs|child_process)(?:\/promises)?["'`]/,
71
+ /\brequire\s*[.(]/,
72
+ /\bimport\s*\(/,
73
+ /\bprocess\s*(?:\.\s*env\b|\[)/,
74
+ /\b(?:writeFileSync|appendFileSync|rmSync|unlinkSync|execSync|spawn\w*)\b/,
75
+ /\bwaitForTimeout\b/,
76
+ /networkidle/,
77
+ /\bexpect\.(?:extend|poll|configure)\b/,
78
+ /\bcatch\s*\{/,
79
+ /\bcatch\s*\([^)]*\)\s*\{\s*\}/,
80
+ /\.catch\(\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*=>/,
81
+ /\.catch\(\s*noop\b/,
82
+ /\bsetTimeout\s*\(/,
83
+ /\bforce\s*:\s*true\b/,
84
+ /\b(?:test|describe)(?:\.\w+)*\s*\[\s*["'`](?:skip|fixme|fail|slow|setTimeout|configure)["'`]\s*\]/,
85
+ /\b(?:retries|timeout)\s*:/,
86
+ /\bprocess\.exit\b/,
87
+ ];
88
+
89
+ function holdsExpectation(text: string): boolean {
90
+ return EXPECTATION.some((pattern) => pattern.test(text));
91
+ }
92
+
93
+ function bracketBalance(text: string): number {
94
+ let balance = 0;
95
+ for (const character of text.replace(STRING_LITERAL, "")) {
96
+ if (OPENERS.has(character)) {
97
+ balance += 1;
98
+ } else if (CLOSERS.has(character)) {
99
+ balance -= 1;
100
+ }
101
+ }
102
+ return balance;
103
+ }
104
+
105
+ function pathOf(header: string): string {
106
+ const path = header.replace(PATH_SUFFIX, "").replace(/^"|"$/g, "");
107
+ return path === NO_FILE ? "" : path.replace(PATH_PREFIX, "");
108
+ }
109
+
110
+ function countOf(text: string | undefined): number {
111
+ return text === undefined ? 1 : Number(text);
112
+ }
113
+
114
+ function withoutCarriageReturn(text: string): string {
115
+ return text.endsWith("\r") ? text.slice(0, -1) : text;
116
+ }
117
+
118
+ function diffLines(diff: string): DiffLine[] {
119
+ const lines: DiffLine[] = [];
120
+ let oldPath = "";
121
+ let file = "";
122
+ let hunk: Hunk = { old: 0, added: 0 };
123
+ let first = false;
124
+ for (const raw of diff.split("\n")) {
125
+ if (hunk.old > 0 || hunk.added > 0) {
126
+ const marker = raw.charAt(0);
127
+ if (marker === "\\") {
128
+ continue;
129
+ }
130
+ if (marker === "+") {
131
+ hunk = { old: hunk.old, added: hunk.added - 1 };
132
+ } else {
133
+ hunk = { old: hunk.old - 1, added: marker === " " || raw === "" ? hunk.added - 1 : hunk.added };
134
+ }
135
+ lines.push({ file, marker, text: withoutCarriageReturn(raw.slice(1)), first });
136
+ first = false;
137
+ continue;
138
+ }
139
+ const header = HUNK_HEADER.exec(raw);
140
+ if (header !== null) {
141
+ hunk = { old: countOf(header[1]), added: countOf(header[2]) };
142
+ first = true;
143
+ } else if (raw.startsWith("--- ")) {
144
+ oldPath = pathOf(raw.slice(4));
145
+ } else if (raw.startsWith("+++ ")) {
146
+ file = pathOf(raw.slice(4)) || oldPath;
147
+ }
148
+ }
149
+ return lines;
150
+ }
151
+
152
+ /**
153
+ * Finds every removed or changed line, in any file, that holds an expectation: an `expect…` call or helper, a
154
+ * `.expect…`, `.verify…` or `.assert…` method call, a `toBe…`, `toEqual`, `toHave…` style matcher, an `assert:` step,
155
+ * or an `expected…` value; a line inside a multi-line expectation counts too. Added lines are never findings here.
156
+ * Give it a diff with the whole file as context (`--unified=100000`) so the start of a long expectation is seen.
157
+ */
158
+ export function findChangedExpectations(diff: string): ChangedExpectation[] {
159
+ const findings: ChangedExpectation[] = [];
160
+ let depth = 0;
161
+ for (const { file, marker, text, first } of diffLines(diff)) {
162
+ if (marker === "+") {
163
+ continue;
164
+ }
165
+ if (first) {
166
+ depth = 0;
167
+ }
168
+ const starts = holdsExpectation(text);
169
+ if (marker === "-" && (starts || depth > 0)) {
170
+ findings.push({ file, line: text });
171
+ }
172
+ depth = starts || depth > 0 ? Math.max(0, depth + bracketBalance(text)) : 0;
173
+ }
174
+ return findings;
175
+ }
176
+
177
+ /**
178
+ * Finds every added line, in any file, that switches a check off or hides a failure: `test.skip|fixme|fail|slow|
179
+ * setTimeout`, `describe.skip|fixme|fail|slow|configure`, `waitForTimeout`, `networkidle`, `expect.extend|poll|
180
+ * configure`, `testInfo.skip|fixme|fail` and `test.info().skip|fixme|fail`, an empty-handed `catch {` or
181
+ * `.catch(() =>`, `process.exit`, a `setTimeout`, `force: true`, `retries:` or `timeout:`; and code that reaches past the
182
+ * page: the `fs` and `child_process` modules, `require`, a dynamic `import(`, `process.env` and the file-writing and
183
+ * process-spawning calls. A bare `return` or `throw` is too common to flag.
184
+ */
185
+ export function findAddedSuppressions(diff: string): ChangedExpectation[] {
186
+ return diffLines(diff)
187
+ .filter(({ marker, text }) => marker === "+" && SUPPRESSION.some((pattern) => pattern.test(text)))
188
+ .map(({ file, text }) => ({ file, line: text }));
189
+ }
190
+
191
+ /**
192
+ * Returns the files that are not under one of the healer paths: a path is a directory prefix, with or without its
193
+ * trailing slash, and `pages` does not allow `pages-extra/`. A file that is not allowed is a finding whatever it holds.
194
+ */
195
+ export function findOutsideHealerPaths(files: readonly string[], healerPaths: readonly string[]): string[] {
196
+ const allowed = healerPaths.map((path) => path.replace(TRAILING_SLASHES, ""));
197
+ return files.filter((file) => !allowed.some((path) => file === path || file.startsWith(`${path}/`)));
198
+ }
199
+
200
+ type Mode = { kind: "snapshot" } | { kind: "fingerprint" } | { kind: "compare"; base: string };
201
+
202
+ export type Git = (args: readonly string[], index?: string) => string;
203
+
204
+ function parseMode(args: readonly string[]): Mode {
205
+ let base: string | undefined;
206
+ let snapshot = false;
207
+ let fingerprint = false;
208
+ for (const arg of args) {
209
+ if (arg === SNAPSHOT_FLAG) {
210
+ snapshot = true;
211
+ } else if (arg === FINGERPRINT_FLAG) {
212
+ fingerprint = true;
213
+ } else if (arg.startsWith(BASE_FLAG)) {
214
+ base = arg.slice(BASE_FLAG.length);
215
+ if (base === "" || base.startsWith("-")) {
216
+ throw new Error(`expectation-guard: ${arg} is not a tree-ish`);
217
+ }
218
+ } else {
219
+ throw new Error(USAGE);
220
+ }
221
+ }
222
+ if (Number(snapshot) + Number(fingerprint) + Number(base !== undefined) > 1) {
223
+ throw new Error(USAGE);
224
+ }
225
+ if (snapshot) {
226
+ return { kind: "snapshot" };
227
+ }
228
+ return fingerprint ? { kind: "fingerprint" } : { kind: "compare", base: base ?? DEFAULT_BASE };
229
+ }
230
+
231
+ function execGit(args: readonly string[], index?: string): string {
232
+ return execFileSync(
233
+ "git",
234
+ [
235
+ "--no-replace-objects",
236
+ "-c",
237
+ "core.quotepath=off",
238
+ "-c",
239
+ "core.safecrlf=false",
240
+ "-c",
241
+ "diff.noprefix=false",
242
+ "-c",
243
+ "diff.mnemonicPrefix=false",
244
+ ...args,
245
+ ],
246
+ {
247
+ encoding: "utf8",
248
+ maxBuffer: MAX_BUFFER,
249
+ env: {
250
+ ...process.env,
251
+ GIT_OPTIONAL_LOCKS: "0",
252
+ GIT_ATTR_NOSYSTEM: "1",
253
+ GIT_NO_LAZY_FETCH: "1",
254
+ ...(index === undefined ? {} : { GIT_INDEX_FILE: index }),
255
+ },
256
+ stdio: ["ignore", "pipe", "ignore"],
257
+ },
258
+ );
259
+ }
260
+
261
+ function configuredNames(git: Git, section: string): string[] {
262
+ let keys: string;
263
+ try {
264
+ keys = git(["config", "--name-only", "--get-regexp", `^${section}\\.`]);
265
+ } catch {
266
+ return [];
267
+ }
268
+ const pattern = new RegExp(`^${section}\\.(.+)\\.[^.]+$`);
269
+ const names = [...new Set(keys.split("\n").flatMap((key) => pattern.exec(key.trim())?.[1] ?? []))];
270
+ if (names.some((name) => name.includes("="))) {
271
+ throw new Error(`expectation-guard: a ${section} name holds '=' and cannot be switched off`);
272
+ }
273
+ return names;
274
+ }
275
+
276
+ function switchedOff(git: Git): string[] {
277
+ const filters = configuredNames(git, FILTER_SECTION).flatMap((driver) => [
278
+ ...FILTER_SETTINGS.flatMap((setting) => ["-c", `filter.${driver}.${setting}=`]),
279
+ "-c",
280
+ `filter.${driver}.required=false`,
281
+ ]);
282
+ const hooks = [...HOOK_EVENTS, ...configuredNames(git, HOOK_SECTION)].flatMap((name) => [
283
+ "-c",
284
+ `hook.${name}.enabled=false`,
285
+ "-c",
286
+ `hook.${name}.command=`,
287
+ ]);
288
+ return [...filters, ...hooks];
289
+ }
290
+
291
+ /** True when `git --version` output names git 2.44 or newer, the first that honours `GIT_NO_LAZY_FETCH`. */
292
+ export function honoursNoLazyFetch(versionOutput: string): boolean {
293
+ const match = GIT_VERSION.exec(versionOutput.trim());
294
+ if (match === null) {
295
+ return false;
296
+ }
297
+ const [major, minor] = [Number(match[1]), Number(match[2])];
298
+ return major > LAZY_FETCH_SINCE.major || (major === LAZY_FETCH_SINCE.major && minor >= LAZY_FETCH_SINCE.minor);
299
+ }
300
+
301
+ function installedGitVersion(): string {
302
+ try {
303
+ return execGit(["--version"]);
304
+ } catch {
305
+ return "";
306
+ }
307
+ }
308
+
309
+ /** `git config <args>`, or "" when nothing matches; any other failure is an error. */
310
+ function configListing(git: Git, args: readonly string[]): string {
311
+ try {
312
+ return git(["config", ...args]);
313
+ } catch (error) {
314
+ if (exitStatus(error) !== NO_MATCH_EXIT_CODE) {
315
+ throw new Error("expectation-guard: git config --get-regexp for the partial clone settings failed");
316
+ }
317
+ return "";
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Refuses a partial clone (`extensions.partialClone` set, or any `remote.<name>.promisor` that is true) when git is
323
+ * older than 2.44: such a git ignores `GIT_NO_LAZY_FETCH`, so a read could fetch a missing object from a promisor
324
+ * remote. The promisor values are read raw: `true`, `yes`, `on`, `1` (any case) or no value at all count; `false`,
325
+ * `no`, `off`, `0` and an empty value do not; any other value does not count either, but on git older than 2.44 it is
326
+ * named in the error, since such a git may read it as true. An ordinary clone works with any git, and a junk value
327
+ * never blocks a git 2.44 or newer. `version` returns the `git --version` output; it is a parameter for the tests.
328
+ */
329
+ export function refuseLazyFetchOnOldGit(git: Git, version: () => string = installedGitVersion): void {
330
+ const partialClone = configListing(git, ["--name-only", "--get-regexp", PARTIAL_CLONE_KEY]).trim() !== "";
331
+ const promisors = configListing(git, ["--get-regexp", PROMISOR_KEYS])
332
+ .split("\n")
333
+ .map((line) => line.replace(TRAILING_CARRIAGE_RETURN, ""))
334
+ .filter((line) => line.trim() !== "")
335
+ .map((line) => {
336
+ const space = line.indexOf(" ");
337
+ return space < 0 ? { key: line, value: undefined } : { key: line.slice(0, space), value: line.slice(space + 1) };
338
+ });
339
+ const promisor = promisors.some(({ value }) => value === undefined || TRUE_VALUES.has(value.trim().toLowerCase()));
340
+ const unreadable = promisors.filter(
341
+ ({ value }) =>
342
+ value !== undefined &&
343
+ !TRUE_VALUES.has(value.trim().toLowerCase()) &&
344
+ !FALSE_VALUES.has(value.trim().toLowerCase()),
345
+ );
346
+ if (!partialClone && !promisor && unreadable.length === 0) {
347
+ return;
348
+ }
349
+ if (honoursNoLazyFetch(version())) {
350
+ return;
351
+ }
352
+ const named = unreadable.map(({ key, value }) => `${key}=${JSON.stringify(value)}`).join(", ");
353
+ throw new Error(
354
+ partialClone || promisor
355
+ ? "expectation-guard: this repository is a partial clone and git is older than 2.44, which can fetch missing objects while the guard reads; update git to 2.44 or newer"
356
+ : `expectation-guard: git is older than 2.44 and these promisor values are neither true nor false: ${named}; fix them or update git to 2.44 or newer`,
357
+ );
358
+ }
359
+
360
+ /**
361
+ * Runs `work` with a git that reads the repository and runs no command the repository or the user configured, reads
362
+ * no replace ref (`--no-replace-objects`) and fetches no missing object of a partial clone (`GIT_NO_LAZY_FETCH`): no
363
+ * fsmonitor, hook scripts from an empty directory, every hook defined in the configuration (`hook.<name>.command`) and
364
+ * the hook events the guard's own commands raise disabled, no global or system attributes file, and every filter
365
+ * driver git knows switched off, so a planted `.git/config` or `.git/info/attributes` cannot run a command or rewrite
366
+ * what is hashed. A partial clone on git older than 2.44, which ignores `GIT_NO_LAZY_FETCH`, is refused before any
367
+ * work (`refuseLazyFetchOnOldGit`). The temporary directory also holds the throw-away index and is removed afterwards.
368
+ */
369
+ function withSafeGit<T>(work: (git: Git, scratch: string) => T): T {
370
+ const scratch = mkdtempSync(join(tmpdir(), TEMP_PREFIX));
371
+ try {
372
+ const hooks = join(scratch, "hooks");
373
+ mkdirSync(hooks);
374
+ const safety = [
375
+ "-c",
376
+ "core.fsmonitor=false",
377
+ "-c",
378
+ `core.hooksPath=${hooks}`,
379
+ "-c",
380
+ `core.attributesFile=${join(scratch, "none")}`,
381
+ ];
382
+ const off = switchedOff((args, index) => execGit([...safety, ...args], index));
383
+ const git: Git = (args, index) => execGit([...safety, ...off, ...args], index);
384
+ refuseLazyFetchOnOldGit(git);
385
+ return work(git, scratch);
386
+ } finally {
387
+ rmSync(scratch, { recursive: true, force: true });
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Writes the working tree, untracked files included and ignored files left out, as a git tree object through a
393
+ * throw-away index. The repository's own index, branch and files are not touched.
394
+ */
395
+ function snapshotTree(git: Git, scratch: string): string {
396
+ try {
397
+ const index = join(scratch, "index");
398
+ git(["add", "-A", "--", ":/"], index);
399
+ return git(["write-tree"], index).trim();
400
+ } catch {
401
+ throw new Error("expectation-guard: the working tree could not be snapshotted");
402
+ }
403
+ }
404
+
405
+ function resolveTree(git: Git, base: string): string {
406
+ try {
407
+ return git(["rev-parse", "--verify", "--quiet", `${base}^{tree}`]).trim();
408
+ } catch {
409
+ throw new Error(`expectation-guard: ${base} is not a tree or commit in this repository`);
410
+ }
411
+ }
412
+
413
+ function baselineFacts(git: Git, baseTree: string): ProjectFacts {
414
+ let text: string;
415
+ try {
416
+ text = git(["show", `${baseTree}:${PROJECT_FACTS_PATH}`]);
417
+ } catch {
418
+ throw new Error(`project.json: ${PROJECT_FACTS_PATH} cannot be read in the baseline`);
419
+ }
420
+ let json: unknown;
421
+ try {
422
+ json = JSON.parse(text);
423
+ } catch {
424
+ throw new Error(`project.json: ${PROJECT_FACTS_PATH} is not valid JSON in the baseline`);
425
+ }
426
+ return parseProjectFacts(json);
427
+ }
428
+
429
+ function changedFiles(git: Git, base: string, current: string): string[] {
430
+ try {
431
+ return git(["diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", base, current, "--"])
432
+ .split("\0")
433
+ .filter((file) => file !== "");
434
+ } catch {
435
+ throw new Error("expectation-guard: git diff failed");
436
+ }
437
+ }
438
+
439
+ function diffTrees(git: Git, base: string, current: string): string {
440
+ try {
441
+ return git([
442
+ "diff",
443
+ `--unified=${WHOLE_FILE_CONTEXT}`,
444
+ "--no-renames",
445
+ "--no-color",
446
+ "--no-ext-diff",
447
+ "--no-textconv",
448
+ "--text",
449
+ base,
450
+ current,
451
+ "--",
452
+ ]);
453
+ } catch {
454
+ throw new Error("expectation-guard: git diff failed");
455
+ }
456
+ }
457
+
458
+ function guard(git: Git, scratch: string, base: string): string[] {
459
+ const baseTree = resolveTree(git, base);
460
+ const healerPaths = baselineFacts(git, baseTree).healerPaths;
461
+ const currentTree = snapshotTree(git, scratch);
462
+ const diff = diffTrees(git, baseTree, currentTree);
463
+ const outside = findOutsideHealerPaths(changedFiles(git, baseTree, currentTree), healerPaths).map(
464
+ (file) => `${OUTSIDE_PREFIX}${file}`,
465
+ );
466
+ const expectations = findChangedExpectations(diff).map(({ file, line }) => `${file}: ${line.trim()}`);
467
+ const suppressions = findAddedSuppressions(diff).map(({ file, line }) => `${file}: ${ADDED_PREFIX}${line.trim()}`);
468
+ return [...outside, ...expectations, ...suppressions];
469
+ }
470
+
471
+ function contentHash(path: string): string {
472
+ try {
473
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
474
+ } catch {
475
+ return MISSING;
476
+ }
477
+ }
478
+
479
+ function fingerprintEntries(label: string, path: string): string[] {
480
+ let names: string[];
481
+ try {
482
+ if (!statSync(path).isDirectory()) {
483
+ return [`${label}\0${contentHash(path)}`];
484
+ }
485
+ names = readdirSync(path).sort();
486
+ } catch {
487
+ return [`${label}\0${MISSING}`];
488
+ }
489
+ return [`${label}/\0dir`, ...names.flatMap((name) => fingerprintEntries(`${label}/${name}`, join(path, name)))];
490
+ }
491
+
492
+ function configuredHooksDir(): string {
493
+ try {
494
+ return execGit(["-c", "core.fsmonitor=false", "rev-parse", "--path-format=absolute", "--git-path", "hooks"]).trim();
495
+ } catch {
496
+ throw new Error("expectation-guard: the hooks directory cannot be resolved");
497
+ }
498
+ }
499
+
500
+ /**
501
+ * The real path of the deepest part of `path` that exists, with the rest appended, so a file that does not exist yet
502
+ * is still compared through the real directories above it.
503
+ */
504
+ function canonical(path: string): string {
505
+ const rest: string[] = [];
506
+ let existing = path;
507
+ for (;;) {
508
+ try {
509
+ return join(realpathSync.native(existing), ...rest);
510
+ } catch {
511
+ const parent = dirname(existing);
512
+ if (parent === existing) {
513
+ return path;
514
+ }
515
+ rest.unshift(basename(existing));
516
+ existing = parent;
517
+ }
518
+ }
519
+ }
520
+
521
+ /**
522
+ * True when `path` is `directory` or lies inside it. Letter case is ignored only where the file system usually ignores
523
+ * it (Windows and macOS); elsewhere the paths are compared exactly. The path rules are the platform's own (`win32` or
524
+ * `posix`). `platform` is a parameter for the tests.
525
+ */
526
+ export function isUnder(path: string, directory: string, platform: NodeJS.Platform = process.platform): boolean {
527
+ const paths = platform === "win32" ? win32 : posix;
528
+ const fold = CASE_INSENSITIVE_PLATFORMS.has(platform) ? (text: string) => text.toLowerCase() : (text: string) => text;
529
+ const inside = paths.relative(fold(directory), fold(path));
530
+ return inside === "" || !(inside === ".." || inside.startsWith(`..${paths.sep}`) || paths.isAbsolute(inside));
531
+ }
532
+
533
+ function exitStatus(error: unknown): unknown {
534
+ return typeof error === "object" && error !== null && "status" in error ? error.status : undefined;
535
+ }
536
+
537
+ function originDir(top: string, origin: string): string {
538
+ return origin.startsWith(FILE_ORIGIN) ? dirname(resolve(top, origin.slice(FILE_ORIGIN.length))) : top;
539
+ }
540
+
541
+ /**
542
+ * The files every `include.path` and `includeIf.<condition>.path` names, resolved the way git does: relative to the
543
+ * directory of the configuration file that holds it, `~/` from the home directory. A value git would expand some other
544
+ * way (`~user/…`, any other `~…`, `%(prefix)…`) is not emulated: it refuses the heal. A target is listed whether or not it
545
+ * exists or holds anything, since the healer could create or fill it. Git runs in `top` (`-C`), so a relative origin
546
+ * it prints is relative to `top` wherever the guard itself was started.
547
+ */
548
+ function includeTargets(git: Git, top: string): string[] {
549
+ let listing = "";
550
+ try {
551
+ listing = git(["-C", top, "config", "--show-origin", "-z", "--get-regexp", INCLUDE_PATH_KEYS]);
552
+ } catch (error) {
553
+ if (exitStatus(error) !== NO_MATCH_EXIT_CODE) {
554
+ throw new Error("expectation-guard: git config --get-regexp for the include paths failed");
555
+ }
556
+ }
557
+ const fields = listing.split("\0");
558
+ const targets: string[] = [];
559
+ for (let index = 0; index + 1 < fields.length; index += 2) {
560
+ const entry = fields[index + 1] ?? "";
561
+ const newline = entry.indexOf("\n");
562
+ if (newline < 0) {
563
+ continue;
564
+ }
565
+ const value = entry.slice(newline + 1);
566
+ if (UNEXPANDED_PREFIXES.some((prefix) => prefix.test(value))) {
567
+ throw new Error(`expectation-guard: cannot resolve include path ${value}; healing refused`);
568
+ }
569
+ const home = process.env["HOME"] ?? homedir();
570
+ targets.push(
571
+ HOME_PREFIX.test(value) ? join(home, value.slice(2)) : resolve(originDir(top, fields[index] ?? ""), value),
572
+ );
573
+ }
574
+ return targets;
575
+ }
576
+
577
+ /**
578
+ * Returns the configuration files git reads (`git config --list --show-origin`, includes followed) and the targets of
579
+ * every include path (`includeTargets`) that lie under one of the healer paths of the facts file in the working tree,
580
+ * compared by real path (`isUnder`). Git runs in `top` (`-C`), so the relative origins it prints resolve against `top`
581
+ * even when the guard runs from a subdirectory. The healer may write there, so such a file could change the
582
+ * configuration without changing the fingerprint.
583
+ */
584
+ function configFilesUnderHealerPaths(git: Git, top: string): string[] {
585
+ let facts: ProjectFacts;
586
+ try {
587
+ facts = parseProjectFacts(JSON.parse(readFileSync(join(top, PROJECT_FACTS_PATH), "utf8")));
588
+ } catch (error) {
589
+ throw new Error(`expectation-guard: ${error instanceof Error ? error.message : String(error)}`);
590
+ }
591
+ let listing: string;
592
+ try {
593
+ listing = git(["-C", top, "config", "--list", "--show-origin", "--name-only", "-z"]);
594
+ } catch {
595
+ throw new Error("expectation-guard: git config --list --show-origin failed");
596
+ }
597
+ const origins = listing
598
+ .split("\0")
599
+ .filter((field, index) => index % 2 === 0 && field.startsWith(FILE_ORIGIN))
600
+ .map((field) => resolve(top, field.slice(FILE_ORIGIN.length)));
601
+ const files = [...new Set([...origins, ...includeTargets(git, top)])];
602
+ const healerDirs = facts.healerPaths.map((path) => canonical(resolve(top, path.replace(TRAILING_SLASHES, ""))));
603
+ return files.filter((file) => healerDirs.some((directory) => isUnder(canonical(file), directory)));
604
+ }
605
+
606
+ /**
607
+ * Hashes `.git/config`, `config.worktree`, every file under `.git/info/` and `.git/hooks/`, every file in the directory
608
+ * git runs hooks from (`core.hooksPath`, wherever it points), and `.qa/project.json` into one sha256, missing files
609
+ * included, so adding a hook or a config line changes it. Refuses, as an error, when git reads a configuration file
610
+ * under a healer path (`configFilesUnderHealerPaths`), since the healer could change that file unseen. Reads only.
611
+ */
612
+ function repoFingerprint(git: Git): string {
613
+ let paths: string[];
614
+ try {
615
+ paths = git(["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir", "--show-toplevel"])
616
+ .split("\n")
617
+ .map((line) => line.trim());
618
+ } catch {
619
+ throw new Error("expectation-guard: not inside a git repository");
620
+ }
621
+ const [gitDir = "", commonDir = "", top = ""] = paths;
622
+ if (gitDir === "" || commonDir === "" || top === "") {
623
+ throw new Error("expectation-guard: not inside a git repository");
624
+ }
625
+ const planted = configFilesUnderHealerPaths(git, top).map((file) => relative(top, file).split(sep).join("/"));
626
+ if (planted.length > 0) {
627
+ throw new Error(`expectation-guard: git reads configuration under a healer path: ${planted.join(", ")}`);
628
+ }
629
+ const entries = [
630
+ ...fingerprintEntries("config", join(commonDir, "config")),
631
+ ...fingerprintEntries("config.worktree", join(gitDir, "config.worktree")),
632
+ ...FINGERPRINT_DIRS.flatMap((dir) => fingerprintEntries(dir, join(commonDir, dir))),
633
+ ...fingerprintEntries("hooksPath", configuredHooksDir()),
634
+ ...fingerprintEntries(PROJECT_FACTS_PATH, join(top, PROJECT_FACTS_PATH)),
635
+ ];
636
+ return createHash("sha256").update(entries.join("\n")).digest("hex");
637
+ }
638
+
639
+ if (basename(process.argv[1] ?? "") === CLI_FILE_NAME) {
640
+ try {
641
+ const mode = parseMode(process.argv.slice(2));
642
+ withSafeGit((git, scratch) => {
643
+ if (mode.kind === "snapshot") {
644
+ process.stdout.write(`${snapshotTree(git, scratch)}\n`);
645
+ return;
646
+ }
647
+ if (mode.kind === "fingerprint") {
648
+ process.stdout.write(`${repoFingerprint(git)}\n`);
649
+ return;
650
+ }
651
+ const findings = guard(git, scratch, mode.base);
652
+ if (findings.length === 0) {
653
+ process.stdout.write("expectation-guard: ok\n");
654
+ } else {
655
+ process.stdout.write(
656
+ `expectation-guard: ${findings.length} finding(s) since ${mode.base}\n${findings.join("\n")}\n`,
657
+ );
658
+ process.exitCode = FINDING_EXIT_CODE;
659
+ }
660
+ });
661
+ } catch (error) {
662
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
663
+ process.exitCode = ERROR_EXIT_CODE;
664
+ }
665
+ }
@@ -0,0 +1,4 @@
1
+ export const PAGE_EXTRACTOR =
2
+ "() => [...document.querySelectorAll('*')].map((element) => ({ tag: element.tagName.toLowerCase(), attributes: [...element.attributes].filter((attribute) => attribute.name.startsWith('data-') || ['id', 'role', 'name', 'class'].includes(attribute.name)).map((attribute) => [attribute.name, attribute.value]), text: (element.textContent || '').trim().slice(0, 60) })).filter((item) => item.attributes.length > 0).slice(0, 400)";
3
+
4
+ export const EXTRACTORS: readonly string[] = [PAGE_EXTRACTOR];