@t09tanaka/test-gates 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1233 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DEFAULT_FORBIDDEN_SOURCE: () => DEFAULT_FORBIDDEN_SOURCE,
34
+ DEFAULT_GATE_EXTENSIONS: () => DEFAULT_GATE_EXTENSIONS,
35
+ DEFAULT_IMPURE_IMPORTS: () => DEFAULT_IMPURE_IMPORTS,
36
+ DEFAULT_IMPURE_NAMED_IMPORTS: () => DEFAULT_IMPURE_NAMED_IMPORTS,
37
+ DEFAULT_IMPURE_PATHS: () => DEFAULT_IMPURE_PATHS,
38
+ DEFAULT_REPORT_FILE: () => DEFAULT_REPORT_FILE,
39
+ EXCLUDE_ENV: () => EXCLUDE_ENV,
40
+ MANIFEST_FILE: () => MANIFEST_FILE,
41
+ ManifestError: () => ManifestError,
42
+ checkGates: () => checkGates,
43
+ formatSummary: () => formatSummary,
44
+ formatSurvivor: () => formatSurvivor,
45
+ gateSpecs: () => gateSpecs,
46
+ judgeLcov: () => judgeLcov,
47
+ judgeMutationReport: () => judgeMutationReport,
48
+ judgeSelfcheck: () => judgeSelfcheck,
49
+ loadGates: () => loadGates,
50
+ normalizeCode: () => normalizeCode,
51
+ parseLcov: () => parseLcov,
52
+ parseManifest: () => parseManifest,
53
+ readManifest: () => readManifest,
54
+ resolveSettings: () => resolveSettings,
55
+ sliceByLocation: () => sliceByLocation
56
+ });
57
+ module.exports = __toCommonJS(index_exports);
58
+
59
+ // src/load.ts
60
+ var import_node_fs2 = __toESM(require("fs"), 1);
61
+ var import_node_path2 = __toESM(require("path"), 1);
62
+
63
+ // src/core/manifest.ts
64
+ var MANIFEST_FILE = "test-gates.json";
65
+ var ManifestError = class extends Error {
66
+ };
67
+ function isRecord(value) {
68
+ return typeof value === "object" && value !== null && !Array.isArray(value);
69
+ }
70
+ function isFilled(value) {
71
+ return typeof value === "string" && value.trim() !== "";
72
+ }
73
+ function allowanceProblems(entry) {
74
+ if (!isRecord(entry)) {
75
+ return [" must be an object"];
76
+ }
77
+ const problems = [];
78
+ if (!isFilled(entry.mutator)) {
79
+ problems.push(': "mutator" is missing');
80
+ }
81
+ if (!isFilled(entry.original)) {
82
+ problems.push(': "original" is missing');
83
+ }
84
+ if (typeof entry.replacement !== "string") {
85
+ problems.push(': "replacement" is missing');
86
+ }
87
+ if (!isFilled(entry.reason)) {
88
+ problems.push(': "reason" is missing (say why the mutant cannot be observed)');
89
+ }
90
+ if (entry.occurrence !== void 0 && !(Number.isInteger(entry.occurrence) && entry.occurrence >= 1)) {
91
+ problems.push(': "occurrence" must be an integer >= 1');
92
+ }
93
+ return problems;
94
+ }
95
+ function validateEquivalentMutants(gatePath, value) {
96
+ if (value === void 0) {
97
+ return [];
98
+ }
99
+ if (!Array.isArray(value)) {
100
+ return [{ file: MANIFEST_FILE, message: `${gatePath}: equivalentMutants must be an array` }];
101
+ }
102
+ return value.flatMap(
103
+ (entry, index) => allowanceProblems(entry).map((problem) => ({
104
+ file: MANIFEST_FILE,
105
+ message: `${gatePath}: equivalentMutants[${index}]${problem}`
106
+ }))
107
+ );
108
+ }
109
+ function isUsableEquivalentMutant(entry) {
110
+ return allowanceProblems(entry).length === 0;
111
+ }
112
+ function parseEntries(kind, entries, fields, violations) {
113
+ const usable = [];
114
+ const seen = /* @__PURE__ */ new Set();
115
+ entries.forEach((entry, index) => {
116
+ const at = `${kind}[${index}]`;
117
+ if (!isRecord(entry)) {
118
+ violations.push({ file: MANIFEST_FILE, message: `${at} must be an object` });
119
+ return;
120
+ }
121
+ if (!isFilled(entry.path)) {
122
+ violations.push({ file: MANIFEST_FILE, message: `${at}: "path" is missing` });
123
+ return;
124
+ }
125
+ for (const field of fields) {
126
+ if (!isFilled(entry[field])) {
127
+ violations.push({
128
+ file: MANIFEST_FILE,
129
+ message: `${entry.path}: "${field}" is missing in ${kind}`
130
+ });
131
+ }
132
+ }
133
+ if (seen.has(entry.path)) {
134
+ violations.push({ file: MANIFEST_FILE, message: `${entry.path}: listed twice in ${kind}` });
135
+ return;
136
+ }
137
+ seen.add(entry.path);
138
+ usable.push(entry);
139
+ });
140
+ return usable;
141
+ }
142
+ function parseManifest(text) {
143
+ let raw;
144
+ try {
145
+ raw = JSON.parse(text);
146
+ } catch (error) {
147
+ throw new ManifestError(`${MANIFEST_FILE} is not valid JSON: ${error.message}`);
148
+ }
149
+ if (!isRecord(raw)) {
150
+ throw new ManifestError(`${MANIFEST_FILE} must be a JSON object`);
151
+ }
152
+ if (!Array.isArray(raw.gates)) {
153
+ throw new ManifestError(`${MANIFEST_FILE}: "gates" must be an array`);
154
+ }
155
+ if (raw.candidates !== void 0 && !Array.isArray(raw.candidates)) {
156
+ throw new ManifestError(`${MANIFEST_FILE}: "candidates" must be an array`);
157
+ }
158
+ for (const key of Object.keys(raw)) {
159
+ if (!["$schema", "gates", "candidates", "settings"].includes(key)) {
160
+ throw new ManifestError(`${MANIFEST_FILE}: unknown top-level key ${JSON.stringify(key)}`);
161
+ }
162
+ }
163
+ const violations = [];
164
+ if (raw.gates.length === 0) {
165
+ violations.push({
166
+ file: MANIFEST_FILE,
167
+ message: "gates is empty. A project with nothing to gate should not have this file"
168
+ });
169
+ }
170
+ const gates = parseEntries("gates", raw.gates, ["decides", "impact"], violations);
171
+ const candidates = parseEntries(
172
+ "candidates",
173
+ raw.candidates ?? [],
174
+ ["decides", "blocker"],
175
+ violations
176
+ );
177
+ const gatePaths = new Set(gates.map((gate) => gate.path));
178
+ for (const candidate of candidates) {
179
+ if (gatePaths.has(candidate.path)) {
180
+ violations.push({
181
+ file: MANIFEST_FILE,
182
+ message: `${candidate.path}: listed in both gates and candidates`
183
+ });
184
+ }
185
+ }
186
+ for (const gate of gates) {
187
+ violations.push(...validateEquivalentMutants(gate.path, gate.equivalentMutants));
188
+ }
189
+ return { gates, candidates, settings: raw.settings, violations };
190
+ }
191
+
192
+ // src/core/settings.ts
193
+ var DEFAULT_REPORT_FILE = "reports/mutation/mutation.json";
194
+ var DEFAULT_GATE_EXTENSIONS = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
195
+ var DEFAULT_IMPURE_IMPORTS = [
196
+ { pattern: "^@nestjs/", reason: "NestJS runtime (DI, decorators)" },
197
+ { pattern: "^class-(validator|transformer)$", reason: "decorator-based DTO library" },
198
+ {
199
+ pattern: "^(typeorm|sequelize|mongoose|knex|pg|mysql|mysql2|ioredis|redis)(/|$)",
200
+ reason: "database client"
201
+ },
202
+ { pattern: "^@prisma/adapter-", reason: "database client" },
203
+ { pattern: "^(react|react-dom)(/|$)", reason: "React runtime" },
204
+ { pattern: "^next(/|$)", reason: "Next.js runtime" },
205
+ { pattern: "^(server-only|client-only)$", reason: "Next.js execution environment" },
206
+ { pattern: "^(vue|vue-router|vue-i18n|pinia)(/|$)", reason: "Vue runtime" },
207
+ { pattern: "^nuxt(/|$)", reason: "Nuxt runtime" },
208
+ { pattern: "^#(app|imports)(/|$)", reason: "Nuxt runtime" },
209
+ { pattern: "\\.vue$", reason: "component" },
210
+ {
211
+ pattern: "^(express|express-jwt|fastify|koa|rxjs|passport)(/|$)",
212
+ reason: "HTTP framework runtime"
213
+ },
214
+ { pattern: "^passport-", reason: "HTTP framework runtime" },
215
+ {
216
+ pattern: "^(axios|openapi-fetch|stripe|nodemailer|firebase-admin)(/|$)",
217
+ reason: "HTTP client / external service SDK"
218
+ },
219
+ { pattern: "^@(aws-sdk|sentry|slack|stripe)/", reason: "external service SDK" },
220
+ {
221
+ pattern: "^(node:)?(fs|http|https|http2|net|tls|dgram|dns|child_process|worker_threads)(/|$)",
222
+ reason: "file system / network / process access"
223
+ }
224
+ ];
225
+ var DEFAULT_IMPURE_NAMED_IMPORTS = [
226
+ { module: "@prisma/client", names: ["PrismaClient"], reason: "connects to the database" }
227
+ ];
228
+ var DEFAULT_IMPURE_PATHS = [
229
+ { pattern: "\\.(vue|jsx|tsx)$", reason: "component file" },
230
+ { pattern: "\\.d\\.[cm]?ts$", reason: "type declaration file" }
231
+ ];
232
+ var DEFAULT_FORBIDDEN_SOURCE = [
233
+ {
234
+ pattern: `^\\s*(['"])use (client|server)\\1`,
235
+ reason: "'use client' / 'use server' directive (not a pure module)"
236
+ }
237
+ ];
238
+ var SettingsError = class extends Error {
239
+ };
240
+ function isRecord2(value) {
241
+ return typeof value === "object" && value !== null && !Array.isArray(value);
242
+ }
243
+ function compile(pattern, flags, where) {
244
+ try {
245
+ return new RegExp(pattern, flags);
246
+ } catch (error) {
247
+ throw new SettingsError(
248
+ `${where}: invalid regular expression ${JSON.stringify(pattern)} (${error.message})`
249
+ );
250
+ }
251
+ }
252
+ function stringArray(value, where) {
253
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item === "")) {
254
+ throw new SettingsError(`${where}: must be an array of non-empty strings`);
255
+ }
256
+ return value;
257
+ }
258
+ function optionalString(value, where) {
259
+ if (value === void 0) {
260
+ return null;
261
+ }
262
+ if (typeof value !== "string" || value === "") {
263
+ throw new SettingsError(`${where}: must be a non-empty string`);
264
+ }
265
+ return value;
266
+ }
267
+ function rejectUnknownKeys(value, known, where) {
268
+ for (const key of Object.keys(value)) {
269
+ if (!known.includes(key)) {
270
+ throw new SettingsError(`${where}: unknown key ${JSON.stringify(key)}`);
271
+ }
272
+ }
273
+ }
274
+ function section(value, known, where) {
275
+ if (value === void 0) {
276
+ return {};
277
+ }
278
+ if (!isRecord2(value)) {
279
+ throw new SettingsError(`${where}: must be an object`);
280
+ }
281
+ rejectUnknownKeys(value, known, where);
282
+ return value;
283
+ }
284
+ function compileRules(defaults, raw, where, extraKeys = []) {
285
+ const config = section(raw, ["defaults", "add", ...extraKeys], where);
286
+ if (config.defaults !== void 0 && typeof config.defaults !== "boolean") {
287
+ throw new SettingsError(`${where}.defaults: must be a boolean`);
288
+ }
289
+ const added = config.add ?? [];
290
+ if (!Array.isArray(added)) {
291
+ throw new SettingsError(`${where}.add: must be an array`);
292
+ }
293
+ const all = [];
294
+ if (config.defaults !== false) {
295
+ defaults.forEach((rule) => all.push({ rule, where: `${where} (default)` }));
296
+ }
297
+ added.forEach((item, index) => {
298
+ const at = `${where}.add[${index}]`;
299
+ if (typeof item === "string" && item !== "") {
300
+ all.push({ rule: { pattern: item }, where: at });
301
+ return;
302
+ }
303
+ if (!isRecord2(item) || typeof item.pattern !== "string" || item.pattern === "") {
304
+ throw new SettingsError(`${at}: must be a pattern string or { pattern, flags?, reason? }`);
305
+ }
306
+ rejectUnknownKeys(item, ["pattern", "flags", "reason"], at);
307
+ if (item.flags !== void 0 && typeof item.flags !== "string") {
308
+ throw new SettingsError(`${at}.flags: must be a string`);
309
+ }
310
+ if (item.reason !== void 0 && typeof item.reason !== "string") {
311
+ throw new SettingsError(`${at}.reason: must be a string`);
312
+ }
313
+ all.push({ rule: item, where: at });
314
+ });
315
+ return {
316
+ rules: all.map(({ rule, where: at }) => ({
317
+ regex: compile(rule.pattern, rule.flags, at),
318
+ reason: rule.reason ?? `matches ${rule.pattern}`
319
+ })),
320
+ section: config
321
+ };
322
+ }
323
+ function resolveSettings(raw) {
324
+ const settings = section(
325
+ raw,
326
+ [
327
+ "gateExtensions",
328
+ "spec",
329
+ "impureImports",
330
+ "impureNamedImports",
331
+ "impurePaths",
332
+ "forbiddenSource",
333
+ "importAliases",
334
+ "gateCommand",
335
+ "selfcheck",
336
+ "stryker",
337
+ "lcov"
338
+ ],
339
+ "settings"
340
+ );
341
+ const gateExtensions = settings.gateExtensions === void 0 ? DEFAULT_GATE_EXTENSIONS : stringArray(settings.gateExtensions, "settings.gateExtensions");
342
+ if (gateExtensions.length === 0 || gateExtensions.some((ext) => !ext.startsWith("."))) {
343
+ throw new SettingsError(
344
+ 'settings.gateExtensions: must list at least one extension starting with "."'
345
+ );
346
+ }
347
+ const spec = section(settings.spec, ["suffixes", "rewrite"], "settings.spec");
348
+ const specSuffixes = spec.suffixes === void 0 ? null : stringArray(spec.suffixes, "settings.spec.suffixes");
349
+ const rewriteRaw = spec.rewrite ?? [];
350
+ if (!Array.isArray(rewriteRaw)) {
351
+ throw new SettingsError("settings.spec.rewrite: must be an array");
352
+ }
353
+ const specRewrite = rewriteRaw.map((item, index) => {
354
+ const at = `settings.spec.rewrite[${index}]`;
355
+ if (!isRecord2(item) || typeof item.from !== "string" || typeof item.to !== "string") {
356
+ throw new SettingsError(`${at}: must be { from, to }`);
357
+ }
358
+ rejectUnknownKeys(item, ["from", "to"], at);
359
+ return { regex: compile(item.from, void 0, at), to: item.to };
360
+ });
361
+ const imports = compileRules(
362
+ DEFAULT_IMPURE_IMPORTS,
363
+ settings.impureImports,
364
+ "settings.impureImports",
365
+ ["allow"]
366
+ );
367
+ const allowedImports = imports.section.allow === void 0 ? [] : stringArray(imports.section.allow, "settings.impureImports.allow").map(
368
+ (pattern, index) => compile(pattern, void 0, `settings.impureImports.allow[${index}]`)
369
+ );
370
+ const named = section(
371
+ settings.impureNamedImports,
372
+ ["defaults", "add"],
373
+ "settings.impureNamedImports"
374
+ );
375
+ if (named.defaults !== void 0 && typeof named.defaults !== "boolean") {
376
+ throw new SettingsError("settings.impureNamedImports.defaults: must be a boolean");
377
+ }
378
+ const namedAdd = named.add ?? [];
379
+ if (!Array.isArray(namedAdd)) {
380
+ throw new SettingsError("settings.impureNamedImports.add: must be an array");
381
+ }
382
+ const impureNamedImports = [
383
+ ...named.defaults === false ? [] : DEFAULT_IMPURE_NAMED_IMPORTS,
384
+ ...namedAdd.map((item, index) => {
385
+ const at = `settings.impureNamedImports.add[${index}]`;
386
+ if (!isRecord2(item) || typeof item.module !== "string" || item.module === "") {
387
+ throw new SettingsError(`${at}: must be { module, names, reason? }`);
388
+ }
389
+ rejectUnknownKeys(item, ["module", "names", "reason"], at);
390
+ const names = stringArray(item.names, `${at}.names`);
391
+ if (names.length === 0) {
392
+ throw new SettingsError(`${at}.names: must list at least one name`);
393
+ }
394
+ if (item.reason !== void 0 && typeof item.reason !== "string") {
395
+ throw new SettingsError(`${at}.reason: must be a string`);
396
+ }
397
+ return {
398
+ module: item.module,
399
+ names,
400
+ reason: item.reason ?? "not allowed in a pure module"
401
+ };
402
+ })
403
+ ];
404
+ const aliasesRaw = settings.importAliases ?? [];
405
+ if (!Array.isArray(aliasesRaw)) {
406
+ throw new SettingsError("settings.importAliases: must be an array");
407
+ }
408
+ const importAliases = aliasesRaw.map((item, index) => {
409
+ const at = `settings.importAliases[${index}]`;
410
+ if (!isRecord2(item) || typeof item.prefix !== "string" || item.prefix === "" || typeof item.target !== "string") {
411
+ throw new SettingsError(`${at}: must be { prefix, target }`);
412
+ }
413
+ rejectUnknownKeys(item, ["prefix", "target"], at);
414
+ return { prefix: item.prefix, target: item.target };
415
+ });
416
+ let gateCommand = null;
417
+ if (settings.gateCommand !== void 0) {
418
+ gateCommand = stringArray(settings.gateCommand, "settings.gateCommand");
419
+ if (gateCommand.length === 0) {
420
+ throw new SettingsError("settings.gateCommand: must not be empty");
421
+ }
422
+ }
423
+ const selfcheck = section(settings.selfcheck, ["mode", "failurePattern"], "settings.selfcheck");
424
+ if (selfcheck.mode !== void 0 && selfcheck.mode !== "all" && selfcheck.mode !== "first") {
425
+ throw new SettingsError('settings.selfcheck.mode: must be "all" or "first"');
426
+ }
427
+ const selfcheckFailurePattern = optionalString(
428
+ selfcheck.failurePattern,
429
+ "settings.selfcheck.failurePattern"
430
+ );
431
+ if (selfcheckFailurePattern !== null) {
432
+ compile(
433
+ selfcheckFailurePattern.split("{gate}").join("x"),
434
+ void 0,
435
+ "settings.selfcheck.failurePattern"
436
+ );
437
+ }
438
+ const stryker = section(settings.stryker, ["configFile", "reportFile"], "settings.stryker");
439
+ const lcov = section(settings.lcov, ["file", "summaryExclude"], "settings.lcov");
440
+ return {
441
+ gateExtensions,
442
+ specSuffixes,
443
+ specRewrite,
444
+ impureImports: imports.rules,
445
+ allowedImports,
446
+ impureNamedImports,
447
+ impurePaths: compileRules(DEFAULT_IMPURE_PATHS, settings.impurePaths, "settings.impurePaths").rules,
448
+ forbiddenSource: compileRules(
449
+ DEFAULT_FORBIDDEN_SOURCE,
450
+ settings.forbiddenSource,
451
+ "settings.forbiddenSource"
452
+ ).rules,
453
+ importAliases,
454
+ gateCommand,
455
+ selfcheckMode: selfcheck.mode ?? "all",
456
+ selfcheckFailurePattern,
457
+ strykerConfigFile: optionalString(stryker.configFile, "settings.stryker.configFile"),
458
+ strykerReportFile: optionalString(stryker.reportFile, "settings.stryker.reportFile") ?? DEFAULT_REPORT_FILE,
459
+ lcovFile: optionalString(lcov.file, "settings.lcov.file"),
460
+ lcovSummaryExclude: lcov.summaryExclude === void 0 ? [] : stringArray(lcov.summaryExclude, "settings.lcov.summaryExclude").map(
461
+ (pattern, index) => compile(pattern, void 0, `settings.lcov.summaryExclude[${index}]`)
462
+ )
463
+ };
464
+ }
465
+
466
+ // src/core/selfcheck.ts
467
+ var EXCLUDE_ENV = "TEST_GATES_EXCLUDE_SPEC";
468
+ var THRESHOLD_MESSAGE = /threshold|coverage data for/i;
469
+ function escapeRegExp(text) {
470
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
471
+ }
472
+ function judgeSelfcheck(input) {
473
+ const { status, output, gatePath } = input;
474
+ if (status === null) {
475
+ return "the gate command did not run to completion";
476
+ }
477
+ if (status === 0) {
478
+ return `the gate passed although the spec of ${gatePath} was left out. The gate does not measure this file (does the gate config honor ${EXCLUDE_ENV}?)`;
479
+ }
480
+ if (input.failurePattern) {
481
+ const pattern = input.failurePattern.split("{gate}").join(escapeRegExp(gatePath));
482
+ return new RegExp(pattern).test(output) ? null : `the gate failed (exit ${status}) but the output does not match settings.selfcheck.failurePattern`;
483
+ }
484
+ const reported = output.split("\n").some((line) => line.includes(gatePath) && THRESHOLD_MESSAGE.test(line));
485
+ return reported ? null : `the gate failed (exit ${status}) but not on the coverage threshold of ${gatePath}. It may be failing for another reason`;
486
+ }
487
+
488
+ // src/core/spec-path.ts
489
+ function gateExtensionOf(gatePath, gateExtensions) {
490
+ const matching = gateExtensions.filter((extension) => gatePath.endsWith(extension)).sort((a, b) => b.length - a.length);
491
+ return matching[0] ?? null;
492
+ }
493
+ function suffixesFor(extension, settings) {
494
+ return settings.specSuffixes ?? [`.spec${extension}`, `.test${extension}`];
495
+ }
496
+ function specCandidatesFor(gatePath, settings) {
497
+ const extension = gateExtensionOf(gatePath, settings.gateExtensions);
498
+ if (extension === null) {
499
+ return [];
500
+ }
501
+ let base = gatePath.slice(0, -extension.length);
502
+ for (const { regex, to } of settings.specRewrite) {
503
+ base = base.replace(regex, to);
504
+ }
505
+ return suffixesFor(extension, settings).map((suffix) => base + suffix);
506
+ }
507
+ function looksLikeSpec(gatePath, settings) {
508
+ const extension = gateExtensionOf(gatePath, settings.gateExtensions);
509
+ return extension !== null && suffixesFor(extension, settings).some((suffix) => gatePath.endsWith(suffix));
510
+ }
511
+
512
+ // src/fs.ts
513
+ var import_node_fs = __toESM(require("fs"), 1);
514
+ var import_node_path = __toESM(require("path"), 1);
515
+ function existsExact(rootDir, relativePath, kind = "file") {
516
+ let current = rootDir;
517
+ for (const segment of relativePath.split("/")) {
518
+ if (segment === "" || segment === ".") {
519
+ continue;
520
+ }
521
+ let entries;
522
+ try {
523
+ entries = import_node_fs.default.readdirSync(current);
524
+ } catch {
525
+ return false;
526
+ }
527
+ if (!entries.includes(segment)) {
528
+ return false;
529
+ }
530
+ current = import_node_path.default.join(current, segment);
531
+ }
532
+ try {
533
+ return kind === "any" || import_node_fs.default.statSync(current).isFile();
534
+ } catch {
535
+ return false;
536
+ }
537
+ }
538
+ function readText(rootDir, relativePath) {
539
+ return import_node_fs.default.readFileSync(import_node_path.default.join(rootDir, relativePath), "utf8");
540
+ }
541
+
542
+ // src/load.ts
543
+ function readManifest(dir) {
544
+ const absoluteDir = import_node_path2.default.resolve(dir);
545
+ const manifestPath = import_node_path2.default.join(absoluteDir, MANIFEST_FILE);
546
+ let text;
547
+ try {
548
+ text = import_node_fs2.default.readFileSync(manifestPath, "utf8");
549
+ } catch (error) {
550
+ if (error.code === "ENOENT") {
551
+ throw new ManifestError(`${MANIFEST_FILE} not found in ${absoluteDir}`);
552
+ }
553
+ throw new ManifestError(`cannot read ${manifestPath}: ${error.message}`);
554
+ }
555
+ const parsed = parseManifest(text);
556
+ let settings;
557
+ try {
558
+ settings = resolveSettings(parsed.settings);
559
+ } catch (error) {
560
+ if (error instanceof SettingsError) {
561
+ throw new ManifestError(`${MANIFEST_FILE}: ${error.message}`);
562
+ }
563
+ throw error;
564
+ }
565
+ const gates = parsed.gates.map((gate) => {
566
+ const specCandidates = specCandidatesFor(gate.path, settings);
567
+ const existingSpecs = specCandidates.filter((candidate) => existsExact(absoluteDir, candidate));
568
+ return {
569
+ ...gate,
570
+ specCandidates,
571
+ existingSpecs,
572
+ spec: existingSpecs[0] ?? specCandidates[0] ?? null
573
+ };
574
+ });
575
+ return {
576
+ dir: absoluteDir,
577
+ gates,
578
+ candidates: parsed.candidates,
579
+ settings,
580
+ violations: parsed.violations
581
+ };
582
+ }
583
+ function loadGates(dir = process.cwd()) {
584
+ const manifest = readManifest(dir);
585
+ if (manifest.violations.length > 0) {
586
+ throw new ManifestError(
587
+ `${MANIFEST_FILE} has problems (run "test-gates check"):
588
+ ` + manifest.violations.map((violation) => ` - ${violation.message}`).join("\n")
589
+ );
590
+ }
591
+ return manifest;
592
+ }
593
+ function gateSpecs(manifest, env = process.env) {
594
+ const excluded = env[EXCLUDE_ENV];
595
+ return manifest.gates.map((gate) => gate.spec).filter((spec) => spec !== null && spec !== excluded);
596
+ }
597
+
598
+ // src/commands/check.ts
599
+ var import_node_fs3 = __toESM(require("fs"), 1);
600
+ var import_node_path3 = __toESM(require("path"), 1);
601
+
602
+ // src/core/imports.ts
603
+ var FROM_STATEMENT = /(?:^|[\n;])[ \t]*(import|export)\s+(type\s+)?([\w$\s,{}*]*?)\s*\bfrom\s*(['"])([^'"\n]+)\4/g;
604
+ var SIDE_EFFECT_IMPORT = /(?:^|[\n;])[ \t]*import\s*(['"])([^'"\n]+)\1/g;
605
+ var CALL_IMPORT = /\b(?:require|import)\s*\(\s*(['"`])([^'"`\n]+)\1\s*\)/g;
606
+ function lineAt(source, index) {
607
+ let line = 1;
608
+ for (let i = 0; i < index; i += 1) {
609
+ if (source[i] === "\n") {
610
+ line += 1;
611
+ }
612
+ }
613
+ return line;
614
+ }
615
+ function parseImports(source) {
616
+ const found = [];
617
+ for (const match of source.matchAll(FROM_STATEMENT)) {
618
+ const clause = match[3];
619
+ const module2 = match[5];
620
+ const braces = /\{([^}]*)\}/.exec(clause);
621
+ const names = braces ? braces[1].split(",").map((part) => part.trim()).filter((part) => part !== "" && !/^type\s/.test(part)).map((part) => part.split(/\s+as\s+/)[0].trim()) : [];
622
+ const outsideBraces = clause.replace(/\{[^}]*\}/, "").replace(/,/g, "").trim();
623
+ found.push({
624
+ module: module2,
625
+ line: lineAt(source, match.index + match[0].lastIndexOf(module2)),
626
+ typeOnly: match[2] !== void 0,
627
+ names,
628
+ whole: outsideBraces !== ""
629
+ });
630
+ }
631
+ for (const match of source.matchAll(SIDE_EFFECT_IMPORT)) {
632
+ const module2 = match[2];
633
+ found.push({
634
+ module: module2,
635
+ line: lineAt(source, match.index + match[0].lastIndexOf(module2)),
636
+ typeOnly: false,
637
+ names: [],
638
+ whole: false
639
+ });
640
+ }
641
+ for (const match of source.matchAll(CALL_IMPORT)) {
642
+ const module2 = match[2];
643
+ found.push({
644
+ module: module2,
645
+ line: lineAt(source, match.index + match[0].lastIndexOf(module2)),
646
+ typeOnly: false,
647
+ names: [],
648
+ whole: true
649
+ });
650
+ }
651
+ return found.sort((a, b) => a.line - b.line);
652
+ }
653
+
654
+ // src/core/scan.ts
655
+ var IGNORE_DIRECTIVE = /\b(istanbul|c8|v8)\s+ignore\b/;
656
+ var DECORATOR = /^\s*@[A-Za-z_$][\w$.]*\s*\(/;
657
+ var STRYKER_COMMENT = /Stryker\s+(disable|restore)\b/;
658
+ var DISABLED_TESTS = [
659
+ { regex: /\.\s*(skip|only|todo)\b/, label: ".skip / .only / .todo" },
660
+ {
661
+ regex: /\b(?:describe|it|test|suite)(?:\s*\.\s*\w+)*\s*\.\s*(?:skipIf|runIf|fails)\b/,
662
+ label: ".skipIf / .runIf / .fails"
663
+ },
664
+ {
665
+ regex: /\b(xit|xtest|xdescribe|fit|fdescribe)\s*[.(]/,
666
+ label: "xit / xtest / xdescribe / fit / fdescribe"
667
+ }
668
+ ];
669
+ var MODULE_MOCK = /\b(?:jest|vi)\s*\.\s*(?:mock|doMock|unstable_mockModule|setMock)\s*\(\s*(?:import\s*\(\s*)?(['"`])([^'"`\n]+)\1/g;
670
+ var SCRIPT_EXTENSION = /\.[cm]?[jt]sx?$/;
671
+ function eachLine(source, visit) {
672
+ source.split("\n").forEach((line, index) => visit(line, index + 1));
673
+ }
674
+ function escapeRegExp2(text) {
675
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
676
+ }
677
+ function scanGateSource(gatePath, source, settings) {
678
+ const violations = [];
679
+ eachLine(source, (line, lineNumber) => {
680
+ if (DECORATOR.test(line)) {
681
+ violations.push({
682
+ file: gatePath,
683
+ line: lineNumber,
684
+ message: "decorator found (not a pure module). Move the file to candidates"
685
+ });
686
+ }
687
+ if (IGNORE_DIRECTIVE.test(line)) {
688
+ violations.push({ file: gatePath, line: lineNumber, message: "coverage ignore directive" });
689
+ }
690
+ if (STRYKER_COMMENT.test(line)) {
691
+ violations.push({
692
+ file: gatePath,
693
+ line: lineNumber,
694
+ message: "Stryker comment (disable / restore). Allow an equivalent mutant in test-gates.json (equivalentMutants) instead"
695
+ });
696
+ }
697
+ for (const rule of settings.forbiddenSource) {
698
+ if (rule.regex.test(line)) {
699
+ violations.push({ file: gatePath, line: lineNumber, message: rule.reason });
700
+ }
701
+ }
702
+ });
703
+ for (const imported of parseImports(source)) {
704
+ if (imported.typeOnly) {
705
+ continue;
706
+ }
707
+ if (!settings.allowedImports.some((regex) => regex.test(imported.module))) {
708
+ for (const rule of settings.impureImports) {
709
+ if (rule.regex.test(imported.module)) {
710
+ violations.push({
711
+ file: gatePath,
712
+ line: imported.line,
713
+ message: `runtime import of "${imported.module}" (${rule.reason})`
714
+ });
715
+ }
716
+ }
717
+ }
718
+ for (const rule of settings.impureNamedImports) {
719
+ if (imported.module !== rule.module) {
720
+ continue;
721
+ }
722
+ const hit = rule.names.filter(
723
+ (name) => imported.names.includes(name) || imported.whole && new RegExp(`\\b${escapeRegExp2(name)}\\b`).test(source)
724
+ );
725
+ if (hit.length > 0) {
726
+ violations.push({
727
+ file: gatePath,
728
+ line: imported.line,
729
+ message: `runtime use of ${hit.join(", ")} from "${rule.module}" (${rule.reason})`
730
+ });
731
+ }
732
+ }
733
+ }
734
+ return violations.sort((a, b) => a.line - b.line);
735
+ }
736
+ function resolveSpecifier(specifier, fromFile, aliases) {
737
+ let joined = null;
738
+ if (specifier.startsWith(".")) {
739
+ const directory = fromFile.includes("/") ? fromFile.slice(0, fromFile.lastIndexOf("/")) : "";
740
+ joined = directory === "" ? specifier : `${directory}/${specifier}`;
741
+ } else {
742
+ for (const alias of aliases) {
743
+ if (specifier.startsWith(alias.prefix)) {
744
+ joined = alias.target + specifier.slice(alias.prefix.length);
745
+ break;
746
+ }
747
+ }
748
+ }
749
+ if (joined === null) {
750
+ return null;
751
+ }
752
+ const segments = [];
753
+ for (const segment of joined.split("/")) {
754
+ if (segment === "..") {
755
+ segments.pop();
756
+ } else if (segment !== "." && segment !== "") {
757
+ segments.push(segment);
758
+ }
759
+ }
760
+ return segments.join("/").replace(SCRIPT_EXTENSION, "");
761
+ }
762
+ function scanSpecSource(gatePath, specPath, source, settings) {
763
+ const violations = [];
764
+ eachLine(source, (line, lineNumber) => {
765
+ if (IGNORE_DIRECTIVE.test(line)) {
766
+ violations.push({ file: specPath, line: lineNumber, message: "coverage ignore directive" });
767
+ }
768
+ for (const { regex, label } of DISABLED_TESTS) {
769
+ if (regex.test(line)) {
770
+ violations.push({
771
+ file: specPath,
772
+ line: lineNumber,
773
+ message: `${label} (a skipped or focused test)`
774
+ });
775
+ }
776
+ }
777
+ });
778
+ const gateModule = gatePath.replace(SCRIPT_EXTENSION, "");
779
+ const gateDirectory = gateModule.replace(/\/index$/, "");
780
+ for (const match of source.matchAll(MODULE_MOCK)) {
781
+ const specifier = match[2];
782
+ const resolved = resolveSpecifier(specifier, specPath, settings.importAliases);
783
+ if (resolved === gateModule || resolved === gateDirectory) {
784
+ let line = 1;
785
+ for (let i = 0; i < match.index; i += 1) {
786
+ if (source[i] === "\n") {
787
+ line += 1;
788
+ }
789
+ }
790
+ violations.push({
791
+ file: specPath,
792
+ line,
793
+ message: `mocks the module under test ("${specifier}")`
794
+ });
795
+ }
796
+ }
797
+ return violations.sort((a, b) => a.line - b.line);
798
+ }
799
+ var STRYKER_WEAKENING = /\b(excludedMutations|ignoreStatic|ignorers)\b/;
800
+ function scanStrykerConfig(configPath, source) {
801
+ const violations = [];
802
+ eachLine(source, (line, lineNumber) => {
803
+ const match = STRYKER_WEAKENING.exec(line);
804
+ if (match) {
805
+ violations.push({
806
+ file: configPath,
807
+ line: lineNumber,
808
+ message: `${match[1]} takes mutants out of the evaluation. Allow equivalent mutants one by one in test-gates.json instead`
809
+ });
810
+ }
811
+ });
812
+ return violations;
813
+ }
814
+
815
+ // src/commands/check.ts
816
+ var STRYKER_CONFIG_NAMES = [
817
+ "stryker.gates.config.mjs",
818
+ "stryker.gates.config.js",
819
+ "stryker.gates.config.cjs",
820
+ "stryker.gates.config.json"
821
+ ];
822
+ function findStrykerConfig(manifest) {
823
+ if (manifest.settings.strykerConfigFile !== null) {
824
+ return manifest.settings.strykerConfigFile;
825
+ }
826
+ return STRYKER_CONFIG_NAMES.find((name) => import_node_fs3.default.existsSync(import_node_path3.default.join(manifest.dir, name))) ?? null;
827
+ }
828
+ function isPlainRelativePath(file) {
829
+ return !import_node_path3.default.isAbsolute(file) && !/^[A-Za-z]:/.test(file) && !file.includes("\\") && !file.split("/").some((segment) => segment === ".." || segment === "." || segment === "");
830
+ }
831
+ function checkGates(manifest) {
832
+ const { dir, settings } = manifest;
833
+ const violations = [...manifest.violations];
834
+ for (const gate of manifest.gates) {
835
+ if (!isPlainRelativePath(gate.path)) {
836
+ violations.push({
837
+ file: MANIFEST_FILE,
838
+ message: `${gate.path}: write the path relative to the subproject, with "/" and without ".."`
839
+ });
840
+ continue;
841
+ }
842
+ if (gateExtensionOf(gate.path, settings.gateExtensions) === null) {
843
+ violations.push({
844
+ file: gate.path,
845
+ message: `a gate must be one of ${settings.gateExtensions.join(" / ")} (settings.gateExtensions)`
846
+ });
847
+ continue;
848
+ }
849
+ if (looksLikeSpec(gate.path, settings)) {
850
+ violations.push({ file: gate.path, message: "a spec cannot be a gate" });
851
+ continue;
852
+ }
853
+ for (const rule of settings.impurePaths) {
854
+ if (rule.regex.test(gate.path)) {
855
+ violations.push({
856
+ file: gate.path,
857
+ message: `cannot be a gate (${rule.reason}). Move it to candidates`
858
+ });
859
+ }
860
+ }
861
+ if (!existsExact(dir, gate.path)) {
862
+ violations.push({
863
+ file: gate.path,
864
+ message: "file not found (the check is case-sensitive)"
865
+ });
866
+ continue;
867
+ }
868
+ violations.push(...scanGateSource(gate.path, readText(dir, gate.path), settings));
869
+ if (gate.specCandidates.length === 0) {
870
+ continue;
871
+ }
872
+ if (gate.existingSpecs.length === 0) {
873
+ violations.push({
874
+ file: gate.path,
875
+ message: `spec not found (looked for ${gate.specCandidates.join(", ")}; the check is case-sensitive)`
876
+ });
877
+ continue;
878
+ }
879
+ if (gate.existingSpecs.length > 1) {
880
+ violations.push({
881
+ file: gate.path,
882
+ message: `more than one spec (${gate.existingSpecs.join(", ")}). Keep one, or narrow settings.spec.suffixes`
883
+ });
884
+ continue;
885
+ }
886
+ const specPath = gate.existingSpecs[0];
887
+ violations.push(...scanSpecSource(gate.path, specPath, readText(dir, specPath), settings));
888
+ }
889
+ for (const candidate of manifest.candidates) {
890
+ if (!isPlainRelativePath(candidate.path) || !existsExact(dir, candidate.path, "any")) {
891
+ violations.push({
892
+ file: MANIFEST_FILE,
893
+ message: `${candidate.path}: candidate not found. Remove it, or fix the path`
894
+ });
895
+ }
896
+ }
897
+ const strykerConfig = findStrykerConfig(manifest);
898
+ if (strykerConfig !== null) {
899
+ if (!import_node_fs3.default.existsSync(import_node_path3.default.join(dir, strykerConfig))) {
900
+ violations.push({ file: strykerConfig, message: "Stryker config not found" });
901
+ } else {
902
+ violations.push(...scanStrykerConfig(strykerConfig, readText(dir, strykerConfig)));
903
+ }
904
+ }
905
+ return violations;
906
+ }
907
+
908
+ // src/core/mutation-result.ts
909
+ var DETECTED = /* @__PURE__ */ new Set(["Killed", "Timeout"]);
910
+ var SURVIVED = /* @__PURE__ */ new Set(["Survived", "NoCoverage"]);
911
+ var NOT_EVALUABLE = /* @__PURE__ */ new Set(["RuntimeError", "CompileError"]);
912
+ function normalizeCode(text) {
913
+ return text.replace(/\s+/g, " ").trim();
914
+ }
915
+ function normalizePath(file) {
916
+ return file.replace(/\\/g, "/").replace(/^\.\//, "");
917
+ }
918
+ function normalizeNewlines(text) {
919
+ return text.replace(/\r\n/g, "\n");
920
+ }
921
+ function sliceByLocation(source, location) {
922
+ const lines = source.split("\n");
923
+ const { start, end } = location;
924
+ const first = lines[start.line - 1];
925
+ const last = lines[end.line - 1];
926
+ if (first === void 0 || last === void 0 || start.column < 1 || end.column < 1 || end.line < start.line || end.line === start.line && end.column < start.column) {
927
+ return null;
928
+ }
929
+ if (start.line === end.line) {
930
+ return first.slice(start.column - 1, end.column - 1);
931
+ }
932
+ return [
933
+ first.slice(start.column - 1),
934
+ ...lines.slice(start.line, end.line - 1),
935
+ last.slice(0, end.column - 1)
936
+ ].join("\n");
937
+ }
938
+ function keyOf(mutator, original, replacement) {
939
+ return JSON.stringify([mutator, normalizeCode(original), normalizeCode(replacement)]);
940
+ }
941
+ function describeAllowance(entry) {
942
+ const occurrence = entry.occurrence === void 0 ? "" : ` / occurrence ${entry.occurrence}`;
943
+ return `${entry.mutator} / ${normalizeCode(entry.original)} \u2192 ${normalizeCode(entry.replacement)}${occurrence}`;
944
+ }
945
+ function judgeMutationReport(input) {
946
+ const violations = [];
947
+ const survivors = [];
948
+ const summary = {
949
+ total: 0,
950
+ detected: 0,
951
+ timeout: 0,
952
+ allowed: 0,
953
+ notEvaluable: 0,
954
+ unallowed: 0
955
+ };
956
+ const files = /* @__PURE__ */ new Map();
957
+ for (const [file, result] of Object.entries(input.report.files ?? {})) {
958
+ files.set(normalizePath(file), result);
959
+ }
960
+ for (const gate of input.gates) {
961
+ const gatePath = normalizePath(gate.path);
962
+ const shapeViolations = validateEquivalentMutants(gate.path, gate.equivalentMutants);
963
+ violations.push(...shapeViolations);
964
+ const allowances = Array.isArray(gate.equivalentMutants) ? gate.equivalentMutants : [];
965
+ const result = files.get(gatePath);
966
+ if (!result || !Array.isArray(result.mutants) || result.mutants.length === 0) {
967
+ violations.push({
968
+ file: gate.path,
969
+ message: "no mutants in the report (the gate was not mutation tested)"
970
+ });
971
+ continue;
972
+ }
973
+ const diskSource = input.readSource(gate.path);
974
+ const source = result.source ?? diskSource;
975
+ if (source === void 0) {
976
+ violations.push({
977
+ file: gate.path,
978
+ message: "source is neither in the report nor readable on disk"
979
+ });
980
+ continue;
981
+ }
982
+ if (result.source !== void 0 && diskSource !== void 0 && normalizeNewlines(result.source) !== normalizeNewlines(diskSource)) {
983
+ violations.push({
984
+ file: gate.path,
985
+ message: "the report was made from a different version of this file. Run Stryker again"
986
+ });
987
+ continue;
988
+ }
989
+ const located = [];
990
+ const byKey = /* @__PURE__ */ new Map();
991
+ const sorted = [...result.mutants].sort(
992
+ (a, b) => a.location.start.line - b.location.start.line || a.location.start.column - b.location.start.column
993
+ );
994
+ let locationsValid = true;
995
+ for (const mutant of sorted) {
996
+ const original = sliceByLocation(normalizeNewlines(source), mutant.location);
997
+ if (original === null) {
998
+ violations.push({
999
+ file: gate.path,
1000
+ line: mutant.location.start.line,
1001
+ message: `the report location of a ${mutant.mutatorName} mutant is outside the source`
1002
+ });
1003
+ locationsValid = false;
1004
+ continue;
1005
+ }
1006
+ const replacement = mutant.replacement ?? "";
1007
+ const key = keyOf(mutant.mutatorName, original, replacement);
1008
+ const group = byKey.get(key) ?? [];
1009
+ const entry = {
1010
+ mutant,
1011
+ original,
1012
+ replacement,
1013
+ occurrence: group.length + 1,
1014
+ sameKeyCount: 0
1015
+ };
1016
+ group.push(entry);
1017
+ byKey.set(key, group);
1018
+ located.push(entry);
1019
+ }
1020
+ for (const group of byKey.values()) {
1021
+ for (const entry of group) {
1022
+ entry.sameKeyCount = group.length;
1023
+ }
1024
+ }
1025
+ if (!locationsValid) {
1026
+ continue;
1027
+ }
1028
+ const allowed = /* @__PURE__ */ new Set();
1029
+ allowances.forEach((allowance, index) => {
1030
+ if (!isUsableEquivalentMutant(allowance)) {
1031
+ return;
1032
+ }
1033
+ const at = `${gate.path}: equivalentMutants[${index}] (${describeAllowance(allowance)})`;
1034
+ const group = byKey.get(keyOf(allowance.mutator, allowance.original, allowance.replacement)) ?? [];
1035
+ if (allowance.occurrence === void 0 && group.length > 1) {
1036
+ violations.push({
1037
+ file: MANIFEST_FILE,
1038
+ message: `${at}: matches ${group.length} mutants in the file. Add "occurrence" (1-based) to pick one`
1039
+ });
1040
+ return;
1041
+ }
1042
+ const target = group[(allowance.occurrence ?? 1) - 1];
1043
+ if (!target || !SURVIVED.has(target.mutant.status)) {
1044
+ const why = target ? `the mutant is now ${target.mutant.status}` : "no such mutant in this run";
1045
+ violations.push({
1046
+ file: MANIFEST_FILE,
1047
+ message: `${at}: stale allowance (${why}). Remove it`
1048
+ });
1049
+ return;
1050
+ }
1051
+ if (allowed.has(target)) {
1052
+ violations.push({
1053
+ file: MANIFEST_FILE,
1054
+ message: `${at}: another allowance already covers this mutant`
1055
+ });
1056
+ return;
1057
+ }
1058
+ allowed.add(target);
1059
+ });
1060
+ for (const entry of located) {
1061
+ const { mutant } = entry;
1062
+ summary.total += 1;
1063
+ if (DETECTED.has(mutant.status)) {
1064
+ summary.detected += 1;
1065
+ if (mutant.status === "Timeout") {
1066
+ summary.timeout += 1;
1067
+ }
1068
+ } else if (NOT_EVALUABLE.has(mutant.status)) {
1069
+ summary.notEvaluable += 1;
1070
+ } else if (SURVIVED.has(mutant.status)) {
1071
+ if (allowed.has(entry)) {
1072
+ summary.allowed += 1;
1073
+ continue;
1074
+ }
1075
+ summary.unallowed += 1;
1076
+ survivors.push({
1077
+ file: gate.path,
1078
+ line: mutant.location.start.line,
1079
+ column: mutant.location.start.column,
1080
+ status: mutant.status,
1081
+ mutator: mutant.mutatorName,
1082
+ original: normalizeCode(entry.original),
1083
+ replacement: normalizeCode(entry.replacement),
1084
+ occurrence: entry.occurrence,
1085
+ sameKeyCount: entry.sameKeyCount,
1086
+ allowance: {
1087
+ mutator: mutant.mutatorName,
1088
+ original: normalizeCode(entry.original),
1089
+ replacement: normalizeCode(entry.replacement),
1090
+ ...entry.sameKeyCount > 1 ? { occurrence: entry.occurrence } : {},
1091
+ reason: ""
1092
+ }
1093
+ });
1094
+ } else {
1095
+ violations.push({
1096
+ file: gate.path,
1097
+ line: mutant.location.start.line,
1098
+ message: mutant.status === "Ignored" ? `a ${mutant.mutatorName} mutant was ignored. Taking mutants out with Stryker comments or mutator exclusions is not allowed` : `a ${mutant.mutatorName} mutant was not evaluated (status: ${mutant.status})`
1099
+ });
1100
+ }
1101
+ }
1102
+ }
1103
+ if (summary.total === 0) {
1104
+ violations.push({
1105
+ file: MANIFEST_FILE,
1106
+ message: "no mutants were evaluated (the mutation test ran on nothing)"
1107
+ });
1108
+ }
1109
+ return { violations, survivors, summary };
1110
+ }
1111
+ function formatSurvivor(survivor) {
1112
+ const occurrence = survivor.sameKeyCount > 1 ? ` / occurrence ${survivor.occurrence} of ${survivor.sameKeyCount}` : "";
1113
+ return `${survivor.file}:${survivor.line}:${survivor.column} / ${survivor.mutator} / ${survivor.original} \u2192 ${survivor.replacement}${occurrence} (${survivor.status})`;
1114
+ }
1115
+ function formatSummary(summary) {
1116
+ return `mutants ${summary.total} / detected ${summary.detected} (timeout ${summary.timeout}) / allowed equivalent ${summary.allowed} / not evaluable ${summary.notEvaluable} / unallowed survivors ${summary.unallowed}`;
1117
+ }
1118
+
1119
+ // src/core/lcov.ts
1120
+ function normalizePath2(file, rootDir) {
1121
+ let normalized = file.replace(/\\/g, "/");
1122
+ if (rootDir !== void 0) {
1123
+ const root = rootDir.replace(/\\/g, "/").replace(/\/+$/, "");
1124
+ if (normalized.startsWith(`${root}/`)) {
1125
+ normalized = normalized.slice(root.length + 1);
1126
+ }
1127
+ }
1128
+ return normalized.replace(/^\.\//, "");
1129
+ }
1130
+ function parseLcov(text, rootDir) {
1131
+ const files = /* @__PURE__ */ new Map();
1132
+ let record = null;
1133
+ const closeRecord = () => {
1134
+ if (record && !record.hasDa) {
1135
+ record.file.found += record.found;
1136
+ record.file.hit += record.hit;
1137
+ }
1138
+ record = null;
1139
+ };
1140
+ for (const rawLine of text.split("\n")) {
1141
+ const line = rawLine.trim();
1142
+ if (line.startsWith("SF:")) {
1143
+ closeRecord();
1144
+ const path4 = normalizePath2(line.slice(3), rootDir);
1145
+ const file = files.get(path4) ?? { lines: /* @__PURE__ */ new Map(), found: 0, hit: 0 };
1146
+ files.set(path4, file);
1147
+ record = { file, hasDa: false, found: 0, hit: 0 };
1148
+ } else if (line === "end_of_record") {
1149
+ closeRecord();
1150
+ } else if (record) {
1151
+ const open = record;
1152
+ if (line.startsWith("DA:")) {
1153
+ const [lineNumber, hits] = line.slice(3).split(",");
1154
+ const number = Number(lineNumber);
1155
+ const count = Number(hits);
1156
+ if (Number.isInteger(number) && Number.isFinite(count)) {
1157
+ open.hasDa = true;
1158
+ open.file.lines.set(number, Math.max(open.file.lines.get(number) ?? 0, count));
1159
+ }
1160
+ } else if (line.startsWith("LF:")) {
1161
+ open.found = Number(line.slice(3)) || 0;
1162
+ } else if (line.startsWith("LH:")) {
1163
+ open.hit = Number(line.slice(3)) || 0;
1164
+ }
1165
+ }
1166
+ }
1167
+ closeRecord();
1168
+ const result = /* @__PURE__ */ new Map();
1169
+ for (const [file, accumulator] of files) {
1170
+ const uncovered = [...accumulator.lines.entries()].filter(([, hits]) => hits <= 0).map(([lineNumber]) => lineNumber).sort((a, b) => a - b);
1171
+ result.set(file, {
1172
+ found: accumulator.lines.size + accumulator.found,
1173
+ hit: accumulator.lines.size - uncovered.length + accumulator.hit,
1174
+ uncovered
1175
+ });
1176
+ }
1177
+ return result;
1178
+ }
1179
+ function judgeLcov(gatePaths, coverage) {
1180
+ const violations = [];
1181
+ const results = [];
1182
+ for (const gatePath of gatePaths) {
1183
+ const file = coverage.get(normalizePath2(gatePath));
1184
+ if (!file) {
1185
+ violations.push({ file: gatePath, message: "no record in the lcov file" });
1186
+ results.push({ path: gatePath, found: 0, hit: 0, ok: false });
1187
+ continue;
1188
+ }
1189
+ if (file.found === 0) {
1190
+ violations.push({ file: gatePath, message: "no instrumented lines in the lcov record" });
1191
+ results.push({ path: gatePath, found: 0, hit: 0, ok: false });
1192
+ continue;
1193
+ }
1194
+ const ok = file.hit === file.found;
1195
+ if (!ok) {
1196
+ const shown = file.uncovered.slice(0, 20).join(", ");
1197
+ const more = file.uncovered.length > 20 ? ", \u2026" : "";
1198
+ violations.push({
1199
+ file: gatePath,
1200
+ ...file.uncovered[0] === void 0 ? {} : { line: file.uncovered[0] },
1201
+ message: `${file.hit}/${file.found} lines covered` + (shown === "" ? "" : ` (uncovered: ${shown}${more})`)
1202
+ });
1203
+ }
1204
+ results.push({ path: gatePath, found: file.found, hit: file.hit, ok });
1205
+ }
1206
+ return { violations, results };
1207
+ }
1208
+ // Annotate the CommonJS export names for ESM import in node:
1209
+ 0 && (module.exports = {
1210
+ DEFAULT_FORBIDDEN_SOURCE,
1211
+ DEFAULT_GATE_EXTENSIONS,
1212
+ DEFAULT_IMPURE_IMPORTS,
1213
+ DEFAULT_IMPURE_NAMED_IMPORTS,
1214
+ DEFAULT_IMPURE_PATHS,
1215
+ DEFAULT_REPORT_FILE,
1216
+ EXCLUDE_ENV,
1217
+ MANIFEST_FILE,
1218
+ ManifestError,
1219
+ checkGates,
1220
+ formatSummary,
1221
+ formatSurvivor,
1222
+ gateSpecs,
1223
+ judgeLcov,
1224
+ judgeMutationReport,
1225
+ judgeSelfcheck,
1226
+ loadGates,
1227
+ normalizeCode,
1228
+ parseLcov,
1229
+ parseManifest,
1230
+ readManifest,
1231
+ resolveSettings,
1232
+ sliceByLocation
1233
+ });