@terreno/test 57.17.0 → 57.19.2

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 (115) hide show
  1. package/CHANGELOG.md +1681 -0
  2. package/README.md +6 -0
  3. package/dist/assertions/expectAPIError.d.ts +18 -0
  4. package/dist/assertions/expectAPIError.js +33 -0
  5. package/dist/assertions/strictResponseProperties.d.ts +14 -0
  6. package/dist/assertions/strictResponseProperties.js +37 -0
  7. package/dist/cache/mongoTestCache.js +2 -2
  8. package/dist/cli/collectFiles.d.ts +38 -0
  9. package/dist/cli/collectFiles.js +73 -0
  10. package/dist/cli/testHygiene.d.ts +134 -0
  11. package/dist/cli/testHygiene.js +357 -0
  12. package/dist/cli/testHygieneCli.d.ts +2 -0
  13. package/dist/cli/testHygieneCli.js +5 -0
  14. package/dist/cli/testHygieneRules.d.ts +58 -0
  15. package/dist/cli/testHygieneRules.js +517 -0
  16. package/dist/cli/testShard.d.ts +155 -0
  17. package/dist/cli/testShard.js +377 -0
  18. package/dist/cli/testShardCli.d.ts +2 -0
  19. package/dist/cli/testShardCli.js +5 -0
  20. package/dist/expo/authTokenStorage.d.ts +76 -0
  21. package/dist/expo/authTokenStorage.js +160 -0
  22. package/dist/expo/expoModuleMocks.d.ts +24 -0
  23. package/dist/expo/expoModuleMocks.js +456 -0
  24. package/dist/expo/libraryModuleMocks.d.ts +17 -0
  25. package/dist/expo/libraryModuleMocks.js +347 -0
  26. package/dist/expo/mockHelpers.d.ts +39 -0
  27. package/dist/expo/mockHelpers.js +45 -0
  28. package/dist/expo/mockModuleAliases.d.ts +50 -0
  29. package/dist/expo/mockModuleAliases.js +174 -0
  30. package/dist/expo/reactNativeMock.d.ts +39 -0
  31. package/dist/expo/reactNativeMock.js +421 -0
  32. package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
  33. package/dist/expo/registerExpoTestEnvironment.js +163 -0
  34. package/dist/expo/renderWithTerreno.d.ts +47 -0
  35. package/dist/expo/renderWithTerreno.js +47 -0
  36. package/dist/http/authWithToken.d.ts +20 -0
  37. package/dist/http/authWithToken.js +30 -0
  38. package/dist/index.d.ts +14 -1
  39. package/dist/index.js +33 -1
  40. package/dist/logging/silenceLogs.js +0 -2
  41. package/dist/mocks/aiSdk.d.ts +77 -0
  42. package/dist/mocks/aiSdk.js +102 -0
  43. package/dist/mocks/cloudTasks.d.ts +91 -0
  44. package/dist/mocks/cloudTasks.js +197 -0
  45. package/dist/mocks/expoPush.d.ts +53 -0
  46. package/dist/mocks/expoPush.js +57 -0
  47. package/dist/mocks/gcs.d.ts +101 -0
  48. package/dist/mocks/gcs.js +162 -0
  49. package/dist/mocks/googleAuth.d.ts +69 -0
  50. package/dist/mocks/googleAuth.js +55 -0
  51. package/dist/mocks/mockGroup.d.ts +11 -0
  52. package/dist/mocks/mockGroup.js +21 -0
  53. package/dist/mocks/notifiers.d.ts +21 -0
  54. package/dist/mocks/notifiers.js +26 -0
  55. package/dist/mocks/sendgrid.d.ts +22 -0
  56. package/dist/mocks/sendgrid.js +32 -0
  57. package/dist/mocks/twilio.d.ts +72 -0
  58. package/dist/mocks/twilio.js +64 -0
  59. package/dist/preload/registerBackendPreload.js +4 -1
  60. package/dist/time/freezeTime.d.ts +16 -0
  61. package/dist/time/freezeTime.js +49 -0
  62. package/dist/transaction/testTransaction.d.ts +43 -6
  63. package/dist/transaction/testTransaction.js +371 -92
  64. package/dist/utils/waitUntil.d.ts +22 -0
  65. package/dist/utils/waitUntil.js +34 -0
  66. package/package.json +53 -8
  67. package/src/assertions/expectAPIError.ts +51 -0
  68. package/src/assertions/strictResponseProperties.ts +42 -0
  69. package/src/cache/mongoTestCache.ts +2 -2
  70. package/src/cli/collectFiles.ts +115 -0
  71. package/src/cli/testHygiene.ts +539 -0
  72. package/src/cli/testHygieneCli.ts +4 -0
  73. package/src/cli/testHygieneRules.ts +719 -0
  74. package/src/cli/testShard.ts +532 -0
  75. package/src/cli/testShardCli.ts +4 -0
  76. package/src/expo/authTokenStorage.ts +198 -0
  77. package/src/expo/expoModuleMocks.ts +503 -0
  78. package/src/expo/libraryModuleMocks.ts +411 -0
  79. package/src/expo/mockHelpers.ts +73 -0
  80. package/src/expo/mockModuleAliases.ts +252 -0
  81. package/src/expo/reactNativeMock.ts +534 -0
  82. package/src/expo/registerExpoTestEnvironment.ts +260 -0
  83. package/src/expo/renderWithTerreno.ts +79 -0
  84. package/src/http/authWithToken.ts +38 -0
  85. package/src/index.ts +82 -1
  86. package/src/logging/silenceLogs.ts +0 -2
  87. package/src/mocks/aiSdk.ts +199 -0
  88. package/src/mocks/cloudTasks.ts +323 -0
  89. package/src/mocks/expoPush.ts +134 -0
  90. package/src/mocks/gcs.ts +305 -0
  91. package/src/mocks/googleAuth.ts +136 -0
  92. package/src/mocks/mockGroup.ts +32 -0
  93. package/src/mocks/notifiers.ts +36 -0
  94. package/src/mocks/sendgrid.ts +57 -0
  95. package/src/mocks/twilio.ts +143 -0
  96. package/src/preload/registerBackendPreload.ts +4 -1
  97. package/src/time/freezeTime.ts +61 -0
  98. package/src/transaction/testTransaction.ts +456 -124
  99. package/src/utils/waitUntil.ts +47 -0
  100. package/biome.jsonc +0 -20
  101. package/bunfig.toml +0 -16
  102. package/src/cache/mongoTestCache.test.ts +0 -103
  103. package/src/env/setTerrenoTestEnv.test.ts +0 -26
  104. package/src/http/authAsUser.test.ts +0 -40
  105. package/src/http/getBaseServer.test.ts +0 -45
  106. package/src/logging/setupEnvironment.test.ts +0 -24
  107. package/src/logging/silenceLogs.test.ts +0 -52
  108. package/src/logging/testLogger.test.ts +0 -58
  109. package/src/mocks/sentryBun.test.ts +0 -230
  110. package/src/mongo/connection.test.ts +0 -43
  111. package/src/mongo/mongoServer.test.ts +0 -99
  112. package/src/preload/registerBackendPreload.test.ts +0 -10
  113. package/src/transaction/testTransaction.test.ts +0 -64
  114. package/src/utils/helpers.test.ts +0 -46
  115. package/tsconfig.json +0 -18
@@ -0,0 +1,357 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runTestHygieneCli = exports.parseTestHygieneArgs = exports.resolveHygieneConfig = exports.countByRule = exports.parseBaseline = exports.diffAgainstBaseline = exports.buildBaseline = exports.checkTestSource = exports.applySuppressions = void 0;
7
+ /**
8
+ * Test-hygiene checker: runs the AST rules in `testHygieneRules.ts` over a tree of test files,
9
+ * honors suppression comments, and compares against a committed baseline so only new
10
+ * violations fail CI.
11
+ *
12
+ * - Suppress one finding with `// test-hygiene-disable-next-line <rule-id>[, <rule-id>] -- reason`
13
+ * on the line before it.
14
+ * - A baseline is a JSON array of `{file, rule, count}`. For each file/rule pair the first
15
+ * `count` violations (by line) are tolerated; regenerate it with `--update-baseline`.
16
+ */
17
+ const node_fs_1 = require("node:fs");
18
+ const node_path_1 = __importDefault(require("node:path"));
19
+ const node_util_1 = require("node:util");
20
+ const collectFiles_1 = require("./collectFiles");
21
+ const testHygieneRules_1 = require("./testHygieneRules");
22
+ const SUPPRESSION_DIRECTIVE = "test-hygiene-disable-next-line";
23
+ /** Config file looked up in the working directory when `--config` is not passed. */
24
+ const DEFAULT_CONFIG_FILE = "test-hygiene.config.json";
25
+ /** Baseline file, relative to the root, used when the config does not name one. */
26
+ const DEFAULT_BASELINE_FILE = "test-hygiene-baseline.json";
27
+ const isHygieneRuleId = (value) => testHygieneRules_1.HYGIENE_RULE_IDS.includes(value);
28
+ /**
29
+ * Drops violations whose preceding line carries a matching suppression directive. The directive
30
+ * accepts a comma-separated rule list, followed by an optional `-- reason`.
31
+ */
32
+ const applySuppressions = ({ sourceText, violations, }) => {
33
+ const lines = sourceText.split("\n");
34
+ const directive = new RegExp(`${SUPPRESSION_DIRECTIVE}\\s+([\\w-]+(?:\\s*,\\s*[\\w-]+)*)`, "u");
35
+ return {
36
+ violations: violations.filter((violation) => {
37
+ const precedingLine = lines[violation.line - 2];
38
+ const match = precedingLine?.match(directive);
39
+ if (!match) {
40
+ return true;
41
+ }
42
+ const suppressed = match[1].split(",").map((rule) => rule.trim());
43
+ return !suppressed.includes(violation.ruleId);
44
+ }),
45
+ };
46
+ };
47
+ exports.applySuppressions = applySuppressions;
48
+ /** Parses, runs the enabled rules on, and suppression-filters one file. Filesystem free. */
49
+ const checkTestSource = ({ fileName, sourceText, config, rules, }) => {
50
+ const { violations } = (0, testHygieneRules_1.runHygieneRules)({ config, fileName, rules, sourceText });
51
+ return (0, exports.applySuppressions)({ sourceText, violations });
52
+ };
53
+ exports.checkTestSource = checkTestSource;
54
+ const baselineKey = ({ file, rule }) => `${file}::${rule}`;
55
+ /** Counts violations per file/rule pair, sorted by file then rule for stable diffs. */
56
+ const buildBaseline = ({ violations, }) => {
57
+ const counts = new Map();
58
+ for (const violation of violations) {
59
+ const key = baselineKey({ file: violation.file, rule: violation.ruleId });
60
+ const entry = counts.get(key) ?? { count: 0, file: violation.file, rule: violation.ruleId };
61
+ entry.count += 1;
62
+ counts.set(key, entry);
63
+ }
64
+ const entries = [...counts.values()].sort((a, b) => a.file.localeCompare(b.file) || a.rule.localeCompare(b.rule));
65
+ return { entries };
66
+ };
67
+ exports.buildBaseline = buildBaseline;
68
+ /**
69
+ * Splits violations into new ones (beyond the baseline count for their file/rule pair) and
70
+ * reports baseline entries whose count is now higher than reality, so the baseline can ratchet.
71
+ */
72
+ const diffAgainstBaseline = ({ violations, baseline, }) => {
73
+ const grouped = new Map();
74
+ for (const violation of violations) {
75
+ const key = baselineKey({ file: violation.file, rule: violation.ruleId });
76
+ grouped.set(key, [...(grouped.get(key) ?? []), violation]);
77
+ }
78
+ const allowed = new Map(baseline.map((entry) => [baselineKey(entry), entry.count]));
79
+ const newViolations = [];
80
+ for (const [key, list] of grouped) {
81
+ const sorted = [...list].sort((a, b) => a.line - b.line);
82
+ newViolations.push(...sorted.slice(allowed.get(key) ?? 0));
83
+ }
84
+ const staleEntries = baseline.filter((entry) => (grouped.get(baselineKey(entry))?.length ?? 0) < entry.count);
85
+ return {
86
+ newViolations: newViolations.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line),
87
+ staleEntries,
88
+ };
89
+ };
90
+ exports.diffAgainstBaseline = diffAgainstBaseline;
91
+ /** Parses and validates baseline JSON. */
92
+ const parseBaseline = ({ text, }) => {
93
+ let data;
94
+ try {
95
+ data = JSON.parse(text);
96
+ }
97
+ catch (error) {
98
+ return { error: `Baseline is not valid JSON: ${error.message}` };
99
+ }
100
+ if (!Array.isArray(data)) {
101
+ return { error: "Baseline must be a JSON array of {file, rule, count}" };
102
+ }
103
+ const entries = [];
104
+ for (const item of data) {
105
+ const entry = item;
106
+ if (typeof entry?.file !== "string" ||
107
+ typeof entry.rule !== "string" ||
108
+ !isHygieneRuleId(entry.rule) ||
109
+ typeof entry.count !== "number") {
110
+ return { error: `Invalid baseline entry: ${JSON.stringify(item)}` };
111
+ }
112
+ entries.push({ count: entry.count, file: entry.file, rule: entry.rule });
113
+ }
114
+ return { entries };
115
+ };
116
+ exports.parseBaseline = parseBaseline;
117
+ /** Counts violations per rule, including rules with zero findings, in rule order. */
118
+ const countByRule = ({ violations, rules = testHygieneRules_1.HYGIENE_RULE_IDS, }) => {
119
+ const counts = Object.fromEntries(rules.map((rule) => [rule, 0]));
120
+ for (const violation of violations) {
121
+ counts[violation.ruleId] = (counts[violation.ruleId] ?? 0) + 1;
122
+ }
123
+ return { counts };
124
+ };
125
+ exports.countByRule = countByRule;
126
+ /** Applies defaults and resolves config-file paths against `configDir`. */
127
+ const resolveHygieneConfig = ({ file = {}, configDir, }) => {
128
+ const rootDir = node_path_1.default.resolve(configDir, file.root ?? ".");
129
+ const rules = testHygieneRules_1.HYGIENE_RULE_IDS.filter((rule) => file.rules?.[rule] !== false);
130
+ return {
131
+ config: {
132
+ baselinePath: file.baseline
133
+ ? node_path_1.default.resolve(configDir, file.baseline)
134
+ : node_path_1.default.join(rootDir, DEFAULT_BASELINE_FILE),
135
+ exclude: file.exclude ?? [],
136
+ excludeDirs: [...collectFiles_1.DEFAULT_EXCLUDED_DIRS, ...(file.excludeDirs ?? [])],
137
+ include: file.include ?? [...collectFiles_1.DEFAULT_TEST_PATTERNS],
138
+ paths: file.paths ?? ["."],
139
+ rootDir,
140
+ ruleConfig: {
141
+ barrelAliases: file.barrels?.aliases ?? [],
142
+ barrelMockAllowlist: file.barrels?.allowMockIn ?? [],
143
+ barrelPaths: file.barrels?.paths ?? [],
144
+ mockHelperModules: file.mockHelperModules ?? [],
145
+ realExportGetterModules: file.realExportGetters?.modules ?? [],
146
+ realExportGetterNamePattern: file.realExportGetters?.namePattern,
147
+ rootDir,
148
+ sleepCallees: file.sleepCallees ?? [...testHygieneRules_1.DEFAULT_SLEEP_CALLEES],
149
+ },
150
+ rules,
151
+ },
152
+ };
153
+ };
154
+ exports.resolveHygieneConfig = resolveHygieneConfig;
155
+ const TEST_HYGIENE_USAGE = `Usage: terreno-test-hygiene [options] [path ...]
156
+
157
+ Checks Bun test files for mock-isolation and timing hazards. Paths default to the root.
158
+
159
+ Options:
160
+ --config <file> JSON config (default: ./${DEFAULT_CONFIG_FILE} when present).
161
+ --root <dir> Root that paths, globs, and barrel paths are relative to.
162
+ --include <glob> Test file glob, root relative (repeatable).
163
+ Default: ${collectFiles_1.DEFAULT_TEST_PATTERNS.join(", ")}
164
+ --exclude <glob> Skip files matching this root-relative glob (repeatable).
165
+ --exclude-dir <name> Skip directories with this name at any depth (repeatable).
166
+ --baseline <file> Baseline JSON (default: <root>/${DEFAULT_BASELINE_FILE}).
167
+ --update-baseline Write current violations to the baseline and exit 0.
168
+ --no-baseline Ignore any baseline; report every violation.
169
+ --rule <id> Run only these rules (repeatable).
170
+ --disable-rule <id> Turn a rule off (repeatable).
171
+ --barrel-alias <glob> Bare specifier that names a shared barrel, e.g. @hooks (repeatable).
172
+ --barrel-path <glob> Root-relative module path of a shared barrel, e.g. hooks (repeatable).
173
+ --mock-helper <module> Module whose named imports register mock.module (repeatable).
174
+ --sleep-callee <name> Extra sleep callee to flag, e.g. timeout (repeatable).
175
+ --format <text|json> Output format (default text).
176
+ -h, --help Show this help.
177
+
178
+ Rules: ${testHygieneRules_1.HYGIENE_RULE_IDS.join(", ")}
179
+ Suppress one finding: // ${SUPPRESSION_DIRECTIVE} <rule-id> -- reason
180
+
181
+ Exit code: 0 when no violations beyond the baseline, 1 otherwise, 2 on usage errors.`;
182
+ /** Throws on unknown flags or missing flag values (strict mode). */
183
+ const parseHygieneFlags = (args) => (0, node_util_1.parseArgs)({
184
+ allowPositionals: true,
185
+ args,
186
+ options: {
187
+ "barrel-alias": { multiple: true, type: "string" },
188
+ "barrel-path": { multiple: true, type: "string" },
189
+ baseline: { type: "string" },
190
+ config: { type: "string" },
191
+ "disable-rule": { multiple: true, type: "string" },
192
+ exclude: { multiple: true, type: "string" },
193
+ "exclude-dir": { multiple: true, type: "string" },
194
+ format: { type: "string" },
195
+ help: { short: "h", type: "boolean" },
196
+ include: { multiple: true, type: "string" },
197
+ "mock-helper": { multiple: true, type: "string" },
198
+ "no-baseline": { type: "boolean" },
199
+ root: { type: "string" },
200
+ rule: { multiple: true, type: "string" },
201
+ "sleep-callee": { multiple: true, type: "string" },
202
+ "update-baseline": { type: "boolean" },
203
+ },
204
+ strict: true,
205
+ });
206
+ /** Merges the config file (if any) with CLI flags. Flags win; list flags extend the config. */
207
+ const parseTestHygieneArgs = ({ argv, cwd, readFile = (filePath) => (0, node_fs_1.existsSync)(filePath) ? (0, node_fs_1.readFileSync)(filePath, "utf-8") : undefined, }) => {
208
+ let parsed;
209
+ try {
210
+ parsed = parseHygieneFlags(argv);
211
+ }
212
+ catch (error) {
213
+ return { error: error.message };
214
+ }
215
+ const { values, positionals } = parsed;
216
+ const configPath = node_path_1.default.resolve(cwd, values.config ?? DEFAULT_CONFIG_FILE);
217
+ const configText = readFile(configPath);
218
+ if (values.config && configText === undefined) {
219
+ return { error: `Config file not found: ${configPath}` };
220
+ }
221
+ let file = {};
222
+ if (configText !== undefined) {
223
+ try {
224
+ file = JSON.parse(configText);
225
+ }
226
+ catch (error) {
227
+ return { error: `Config ${configPath} is not valid JSON: ${error.message}` };
228
+ }
229
+ }
230
+ const configDir = configText === undefined ? cwd : node_path_1.default.dirname(configPath);
231
+ const ruleFlags = [...(values.rule ?? []), ...(values["disable-rule"] ?? [])];
232
+ const unknownRule = ruleFlags.find((rule) => !isHygieneRuleId(rule));
233
+ if (unknownRule) {
234
+ return { error: `Unknown rule "${unknownRule}". Rules: ${testHygieneRules_1.HYGIENE_RULE_IDS.join(", ")}` };
235
+ }
236
+ const format = values.format ?? "text";
237
+ if (format !== "text" && format !== "json") {
238
+ return { error: `--format must be text or json, got "${format}"` };
239
+ }
240
+ const merged = {
241
+ ...file,
242
+ barrels: {
243
+ ...file.barrels,
244
+ aliases: [...(file.barrels?.aliases ?? []), ...(values["barrel-alias"] ?? [])],
245
+ paths: [...(file.barrels?.paths ?? []), ...(values["barrel-path"] ?? [])],
246
+ },
247
+ exclude: [...(file.exclude ?? []), ...(values.exclude ?? [])],
248
+ excludeDirs: [...(file.excludeDirs ?? []), ...(values["exclude-dir"] ?? [])],
249
+ include: values.include ?? file.include,
250
+ mockHelperModules: [...(file.mockHelperModules ?? []), ...(values["mock-helper"] ?? [])],
251
+ sleepCallees: [
252
+ ...(file.sleepCallees ?? testHygieneRules_1.DEFAULT_SLEEP_CALLEES),
253
+ ...(values["sleep-callee"] ?? []),
254
+ ],
255
+ };
256
+ // CLI --root/--baseline/paths are relative to the cwd, not to the config file.
257
+ if (values.root) {
258
+ merged.root = node_path_1.default.resolve(cwd, values.root);
259
+ }
260
+ if (values.baseline) {
261
+ merged.baseline = node_path_1.default.resolve(cwd, values.baseline);
262
+ }
263
+ if (positionals.length > 0) {
264
+ const rootForPaths = node_path_1.default.resolve(configDir, merged.root ?? ".");
265
+ merged.paths = positionals.map((p) => node_path_1.default.relative(rootForPaths, node_path_1.default.resolve(cwd, p)) || ".");
266
+ }
267
+ const { config } = (0, exports.resolveHygieneConfig)({ configDir, file: merged });
268
+ const onlyRules = values.rule ?? [];
269
+ const disabled = new Set(values["disable-rule"] ?? []);
270
+ config.rules = config.rules.filter((rule) => (onlyRules.length === 0 || onlyRules.includes(rule)) && !disabled.has(rule));
271
+ return {
272
+ options: {
273
+ config,
274
+ format,
275
+ isHelp: values.help ?? false,
276
+ isUpdateBaseline: values["update-baseline"] ?? false,
277
+ useBaseline: !(values["no-baseline"] ?? false),
278
+ },
279
+ };
280
+ };
281
+ exports.parseTestHygieneArgs = parseTestHygieneArgs;
282
+ const formatCounts = ({ counts }) => Object.entries(counts)
283
+ .map(([rule, count]) => ` ${rule}: ${count}`)
284
+ .join("\n");
285
+ /**
286
+ * CLI entry point: scans test files, applies the baseline, prints findings and per-rule counts,
287
+ * and returns the exit code instead of exiting so it is testable.
288
+ */
289
+ const runTestHygieneCli = ({ argv, cwd = process.cwd(), logger = console, }) => {
290
+ const parsed = (0, exports.parseTestHygieneArgs)({ argv, cwd });
291
+ if ("error" in parsed) {
292
+ logger.error(`${parsed.error}\n\n${TEST_HYGIENE_USAGE}`);
293
+ return { exitCode: 2 };
294
+ }
295
+ const { options } = parsed;
296
+ if (options.isHelp) {
297
+ logger.info(TEST_HYGIENE_USAGE);
298
+ return { exitCode: 0 };
299
+ }
300
+ const { config } = options;
301
+ const { files, missingPaths } = (0, collectFiles_1.collectFiles)({
302
+ cwd: config.rootDir,
303
+ exclude: config.exclude,
304
+ excludeDirs: config.excludeDirs,
305
+ paths: config.paths,
306
+ patterns: config.include,
307
+ });
308
+ if (missingPaths.length > 0) {
309
+ logger.error(`Path(s) do not exist under ${config.rootDir}: ${missingPaths.join(", ")}`);
310
+ return { exitCode: 2 };
311
+ }
312
+ const violations = files.flatMap((file) => (0, exports.checkTestSource)({
313
+ config: config.ruleConfig,
314
+ fileName: node_path_1.default.join(config.rootDir, file),
315
+ rules: config.rules,
316
+ sourceText: (0, node_fs_1.readFileSync)(node_path_1.default.join(config.rootDir, file), "utf-8"),
317
+ }).violations);
318
+ if (options.isUpdateBaseline) {
319
+ const { entries } = (0, exports.buildBaseline)({ violations });
320
+ (0, node_fs_1.writeFileSync)(config.baselinePath, `${JSON.stringify(entries, null, 2)}\n`, "utf-8");
321
+ logger.info(`Wrote ${config.baselinePath}: ${violations.length} violation(s) across ${entries.length} file/rule pair(s).`);
322
+ return { exitCode: 0 };
323
+ }
324
+ let baseline = [];
325
+ if (options.useBaseline && (0, node_fs_1.existsSync)(config.baselinePath)) {
326
+ const parsedBaseline = (0, exports.parseBaseline)({ text: (0, node_fs_1.readFileSync)(config.baselinePath, "utf-8") });
327
+ if ("error" in parsedBaseline) {
328
+ logger.error(`${config.baselinePath}: ${parsedBaseline.error}`);
329
+ return { exitCode: 2 };
330
+ }
331
+ baseline = parsedBaseline.entries;
332
+ }
333
+ const { newViolations, staleEntries } = (0, exports.diffAgainstBaseline)({ baseline, violations });
334
+ const exitCode = newViolations.length === 0 ? 0 : 1;
335
+ if (options.format === "json") {
336
+ logger.info(JSON.stringify({
337
+ baselined: violations.length - newViolations.length,
338
+ countsByRule: (0, exports.countByRule)({ rules: config.rules, violations }).counts,
339
+ filesChecked: files.length,
340
+ newCountsByRule: (0, exports.countByRule)({ rules: config.rules, violations: newViolations }).counts,
341
+ newViolations,
342
+ staleBaselineEntries: staleEntries,
343
+ }, null, 2));
344
+ return { exitCode };
345
+ }
346
+ for (const violation of newViolations) {
347
+ logger.error(`${violation.file}:${violation.line} ${violation.ruleId} ${violation.message}`);
348
+ }
349
+ logger.info(`\nChecked ${files.length} file(s) under ${config.rootDir}: ${violations.length} violation(s), ` +
350
+ `${violations.length - newViolations.length} baselined, ${newViolations.length} new.`);
351
+ logger.info(formatCounts((0, exports.countByRule)({ rules: config.rules, violations: newViolations })));
352
+ if (staleEntries.length > 0) {
353
+ logger.info(`${staleEntries.length} baseline entr(ies) are higher than current counts; run --update-baseline to ratchet.`);
354
+ }
355
+ return { exitCode };
356
+ };
357
+ exports.runTestHygieneCli = runTestHygieneCli;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const testHygiene_1 = require("./testHygiene");
5
+ process.exitCode = (0, testHygiene_1.runTestHygieneCli)({ argv: process.argv.slice(2) }).exitCode;
@@ -0,0 +1,58 @@
1
+ export declare const HYGIENE_RULE_IDS: readonly ["no-module-scope-mock-module", "no-direct-barrel-mock", "no-sleep", "no-cache-busted-import", "no-late-real-capture", "no-component-snapshot"];
2
+ export type HygieneRuleId = (typeof HYGIENE_RULE_IDS)[number];
3
+ export interface HygieneViolation {
4
+ /** Path relative to the configured root, POSIX separators. */
5
+ file: string;
6
+ /** 1-based line. */
7
+ line: number;
8
+ ruleId: HygieneRuleId;
9
+ message: string;
10
+ }
11
+ /** App-specific knowledge the rules need. Every field is optional; empty disables that aspect. */
12
+ export interface HygieneRuleConfig {
13
+ /** Absolute directory that relative barrel paths and reported file paths are relative to. */
14
+ rootDir: string;
15
+ /**
16
+ * Globs matched against bare (non-relative) import specifiers that name a shared barrel,
17
+ * e.g. `@hooks`, `@store`, `@app/*`.
18
+ */
19
+ barrelAliases?: readonly string[];
20
+ /**
21
+ * Globs matched against the root-relative, extension-stripped path a relative specifier
22
+ * resolves to, e.g. `hooks`, `store/sdk`. A trailing `/index` is also matched as its directory.
23
+ */
24
+ barrelPaths?: readonly string[];
25
+ /** Globs of root-relative test files allowed to mock barrels directly (e.g. `tests/mocks/**`). */
26
+ barrelMockAllowlist?: readonly string[];
27
+ /**
28
+ * Module names or path suffixes (e.g. `bunModuleAliases`) whose named imports are helpers that
29
+ * register `mock.module()` internally and take the mock factory as their first argument.
30
+ */
31
+ mockHelperModules?: readonly string[];
32
+ /** Module names or path suffixes exporting "get the real exports" helpers. */
33
+ realExportGetterModules?: readonly string[];
34
+ /** Regex source that a getter import's name must match (default: any name). */
35
+ realExportGetterNamePattern?: string;
36
+ /** Extra sleep callees flagged by `no-sleep`, as written at the call site (e.g. `Bun.sleep`). */
37
+ sleepCallees?: readonly string[];
38
+ }
39
+ export declare const DEFAULT_SLEEP_CALLEES: readonly string[];
40
+ /** Determines whether a `mock.module()`/`require()`/`import()` specifier targets a shared barrel. */
41
+ export declare const resolvesToBarrel: ({ config, fromFile, specifier, }: {
42
+ config: HygieneRuleConfig;
43
+ fromFile: string;
44
+ specifier: string;
45
+ }) => boolean;
46
+ /**
47
+ * Runs the enabled rules against one parsed file. Pure and filesystem free. Returned violations
48
+ * carry the root-relative path and are not yet suppression filtered.
49
+ */
50
+ export declare const runHygieneRules: ({ fileName, sourceText, config, rules, }: {
51
+ /** Absolute path, used for relative-specifier resolution and reported paths. */
52
+ fileName: string;
53
+ sourceText: string;
54
+ config: HygieneRuleConfig;
55
+ rules?: readonly HygieneRuleId[];
56
+ }) => {
57
+ violations: HygieneViolation[];
58
+ };