@hughescr/stryker-bun-runner 1.6.0 → 1.7.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.
@@ -0,0 +1,902 @@
1
+ // @bun
2
+ // src/coverage/import-scan.ts
3
+ import { readFileSync, realpathSync, statSync } from "fs";
4
+ import { createRequire, isBuiltin } from "module";
5
+ import path from "path";
6
+ import { pathToFileURL } from "url";
7
+ var INSTRUMENTER_GLOBAL_IDIOM = 'globalThis.Math === Math && globalThis || new Function("return this")()';
8
+
9
+ class ScanProblem extends Error {
10
+ name = "ScanProblem";
11
+ }
12
+ var BEFORE_EXPRESSION = new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await", "extends"]);
13
+ var HEAD_KEYWORDS = new Set(["if", "while", "for", "with"]);
14
+ var BEFORE_DIVISION = new Set(["]", "++", "--"]);
15
+ var OTHER_WHITESPACE = new Set([160, 5760, 8232, 8233, 8239, 8287, 12288, 65279]);
16
+ var LINE_TERMINATORS = new Set([10, 13, 8232, 8233]);
17
+ var isWhitespace = (c) => c === 32 || c >= 9 && c <= 13 || c >= 8192 && c <= 8202 || OTHER_WHITESPACE.has(c);
18
+ var isDigit = (c) => c >= 48 && c <= 57;
19
+ var isAsciiLetter = (c) => c >= 65 && c <= 90 || c >= 97 && c <= 122;
20
+ var isNameStart = (c) => isAsciiLetter(c) || c === 95 || c === 36 || c >= 128 && !isWhitespace(c);
21
+ var isNamePart = (c) => isNameStart(c) || isDigit(c);
22
+ function decodeEscaped(text) {
23
+ if (!text.startsWith('"')) {
24
+ return;
25
+ }
26
+ try {
27
+ return JSON.parse(text);
28
+ } catch {
29
+ return;
30
+ }
31
+ }
32
+
33
+ class Tokenizer {
34
+ code;
35
+ tokens = [];
36
+ braces = [];
37
+ parens = [];
38
+ i = 0;
39
+ constructor(code) {
40
+ this.code = code;
41
+ }
42
+ run() {
43
+ if (this.code.startsWith("#!")) {
44
+ this.skipLine();
45
+ }
46
+ while (this.i < this.code.length) {
47
+ this.step();
48
+ }
49
+ if (this.braces.length > 0 || this.parens.length > 0) {
50
+ throw new ScanProblem("unbalanced brackets");
51
+ }
52
+ return this.tokens;
53
+ }
54
+ at(offset = 0) {
55
+ return this.code.codePointAt(this.i + offset) ?? -1;
56
+ }
57
+ step() {
58
+ const c = this.at();
59
+ const ch = this.code[this.i];
60
+ switch (ch) {
61
+ case "/": {
62
+ this.slash();
63
+ break;
64
+ }
65
+ case '"':
66
+ case "'": {
67
+ this.string(ch);
68
+ break;
69
+ }
70
+ case "`": {
71
+ this.i = this.template(this.i + 1);
72
+ break;
73
+ }
74
+ default: {
75
+ this.other(c, ch);
76
+ }
77
+ }
78
+ }
79
+ other(c, ch) {
80
+ if (isWhitespace(c)) {
81
+ this.i++;
82
+ } else if (isNameStart(c) || ch === "#" && isNameStart(this.at(1))) {
83
+ this.name();
84
+ } else if (isDigit(c) || ch === "." && isDigit(this.at(1))) {
85
+ this.number();
86
+ } else {
87
+ this.punctuator(ch);
88
+ }
89
+ }
90
+ skipLine() {
91
+ while (this.i < this.code.length && !LINE_TERMINATORS.has(this.at())) {
92
+ this.i++;
93
+ }
94
+ }
95
+ slash() {
96
+ const next = this.code[this.i + 1];
97
+ if (next === "/") {
98
+ this.skipLine();
99
+ } else if (next === "*") {
100
+ const end = this.code.indexOf("*/", this.i + 2);
101
+ if (end === -1) {
102
+ throw new ScanProblem("an unterminated comment");
103
+ }
104
+ this.i = end + 2;
105
+ } else if (this.regexAllowed()) {
106
+ this.regex();
107
+ } else {
108
+ this.punctuator("/");
109
+ }
110
+ }
111
+ regexAllowed() {
112
+ const prev = this.tokens.at(-1);
113
+ if (prev === undefined) {
114
+ return true;
115
+ }
116
+ if (prev.kind === "name") {
117
+ return BEFORE_EXPRESSION.has(prev.text);
118
+ }
119
+ if (prev.kind !== "punct") {
120
+ return false;
121
+ }
122
+ return prev.text === ")" ? prev.closesHead === true : !BEFORE_DIVISION.has(prev.text);
123
+ }
124
+ regex() {
125
+ const start = this.i;
126
+ let inClass = false;
127
+ this.i++;
128
+ while (inClass || this.code[this.i] !== "/") {
129
+ if (this.i >= this.code.length || LINE_TERMINATORS.has(this.at())) {
130
+ throw new ScanProblem("an unterminated regular expression");
131
+ }
132
+ const ch = this.code[this.i];
133
+ if (ch === "\\") {
134
+ this.i++;
135
+ } else if (ch === "[" || ch === "]") {
136
+ inClass = ch === "[";
137
+ }
138
+ this.i++;
139
+ }
140
+ this.i++;
141
+ while (this.i < this.code.length && isNamePart(this.at())) {
142
+ this.i++;
143
+ }
144
+ this.tokens.push({ kind: "regex", text: this.code.slice(start, this.i) });
145
+ }
146
+ string(quote) {
147
+ const start = this.i;
148
+ let escaped = false;
149
+ this.i++;
150
+ while (this.code[this.i] !== quote) {
151
+ if (this.i >= this.code.length || this.code[this.i] === `
152
+ ` || this.code[this.i] === "\r") {
153
+ throw new ScanProblem("an unterminated string literal");
154
+ }
155
+ if (this.code[this.i] === "\\") {
156
+ escaped = true;
157
+ this.i++;
158
+ }
159
+ this.i++;
160
+ }
161
+ this.i++;
162
+ const text = this.code.slice(start, this.i);
163
+ this.tokens.push({ kind: "string", text, value: escaped ? decodeEscaped(text) : text.slice(1, -1) });
164
+ }
165
+ template(start) {
166
+ let j = start;
167
+ while (j < this.code.length) {
168
+ const ch = this.code[j];
169
+ if (ch === "`") {
170
+ this.tokens.push({ kind: "template", text: this.code.slice(start - 1, j + 1) });
171
+ return j + 1;
172
+ }
173
+ if (ch === "$" && this.code[j + 1] === "{") {
174
+ this.tokens.push({ kind: "template", text: this.code.slice(start - 1, j) }, { kind: "punct", text: "${" });
175
+ this.braces.push(true);
176
+ return j + 2;
177
+ }
178
+ j += ch === "\\" ? 2 : 1;
179
+ }
180
+ throw new ScanProblem("an unterminated template literal");
181
+ }
182
+ name() {
183
+ const start = this.i;
184
+ this.i++;
185
+ while (this.i < this.code.length && isNamePart(this.at())) {
186
+ this.i++;
187
+ }
188
+ if (this.code[this.i] === "\\") {
189
+ throw new ScanProblem("an escape sequence in a name");
190
+ }
191
+ this.tokens.push({ kind: "name", text: this.code.slice(start, this.i) });
192
+ }
193
+ number() {
194
+ const start = this.i;
195
+ const hex = /^0x/i.test(this.code.slice(start, start + 2));
196
+ this.i++;
197
+ for (;; ) {
198
+ const ch = this.code[this.i];
199
+ const exponentSign = !hex && (ch === "+" || ch === "-") && /e/i.test(this.code[this.i - 1]);
200
+ if (!(isNamePart(this.at()) || ch === "." || exponentSign)) {
201
+ break;
202
+ }
203
+ this.i++;
204
+ }
205
+ this.tokens.push({ kind: "number", text: this.code.slice(start, this.i) });
206
+ }
207
+ punctuator(ch) {
208
+ switch (ch) {
209
+ case "{": {
210
+ this.braces.push(false);
211
+ this.push(ch);
212
+ break;
213
+ }
214
+ case "}": {
215
+ this.closeBrace();
216
+ break;
217
+ }
218
+ case "(": {
219
+ const prev = this.tokens.at(-1);
220
+ this.parens.push(prev?.kind === "name" && HEAD_KEYWORDS.has(prev.text));
221
+ this.push(ch);
222
+ break;
223
+ }
224
+ case ")": {
225
+ const closesHead = this.parens.pop();
226
+ if (closesHead === undefined) {
227
+ throw new ScanProblem("an unbalanced )");
228
+ }
229
+ this.tokens.push({ kind: "punct", text: ch, closesHead });
230
+ this.i++;
231
+ break;
232
+ }
233
+ case "\\": {
234
+ throw new ScanProblem("an escape sequence in a name");
235
+ }
236
+ default: {
237
+ this.push(this.multiCharacter(ch));
238
+ }
239
+ }
240
+ }
241
+ multiCharacter(ch) {
242
+ const two = this.code.slice(this.i, this.i + 2);
243
+ if (this.code.startsWith("...", this.i)) {
244
+ return "...";
245
+ }
246
+ if (two === "?." && !isDigit(this.at(2))) {
247
+ return two;
248
+ }
249
+ return ["++", "--", "=>"].includes(two) ? two : ch;
250
+ }
251
+ closeBrace() {
252
+ const resumesTemplate = this.braces.pop();
253
+ if (resumesTemplate === undefined) {
254
+ throw new ScanProblem("an unbalanced }");
255
+ }
256
+ this.tokens.push({ kind: "punct", text: "}" });
257
+ this.i = resumesTemplate ? this.template(this.i + 1) : this.i + 1;
258
+ }
259
+ push(text) {
260
+ this.tokens.push({ kind: "punct", text });
261
+ this.i += text.length;
262
+ }
263
+ }
264
+ function tokenize(code) {
265
+ return new Tokenizer(code).run();
266
+ }
267
+ var MODULE_PROPERTIES = new Set(["exports", "id", "filename", "loaded", "path", "paths"]);
268
+ var COMPUTED_HOLDERS = new Set(["module", "Bun"]);
269
+ var GLOBAL_OBJECTS = new Set(["globalThis", "global", "self", "window"]);
270
+ var LITERAL_KEY_KINDS = new Set(["string", "number", "template"]);
271
+ var LITERAL_KEY_NAMES = new Set(["true", "false", "null"]);
272
+ var LOADER_MODULES = new Set(["module", "node:module", "vm", "node:vm"]);
273
+ var FORBIDDEN_WORDS = /(?<![\w$])(?:createRequire|getBuiltinModule|mainModule|registerHooks|_load|eval)(?![\w$])/;
274
+ var WORD_REQUIRE = /(?<![\w$])require(?![\w$])/g;
275
+ var WORD_IMPORT_CALL = /(?<![\w$.])import\s*\(/g;
276
+ var WORD_FUNCTION = /(?<![\w$])Function(?![\w$])/g;
277
+ var WORD_PLUGIN = /(?<![\w$])plugin(?![\w$])/;
278
+ var MACRO_ATTRIBUTE = /\btype\s*:\s*['"]macro['"]/;
279
+ var count = (text, pattern) => [...text.matchAll(pattern)].length;
280
+ var sorted = (list) => JSON.stringify(list.toSorted((a, b) => a.localeCompare(b)));
281
+ var sameList = (a, b) => sorted(a) === sorted(b);
282
+
283
+ class CallCollector {
284
+ tokens;
285
+ imports = [];
286
+ requires = [];
287
+ requireResolves = [];
288
+ metaResolves = [];
289
+ requireNames = 0;
290
+ importCalls = 0;
291
+ requireUnknown = false;
292
+ unknown;
293
+ constructor(tokens) {
294
+ this.tokens = tokens;
295
+ for (const [index, token] of tokens.entries()) {
296
+ if (token.kind === "name") {
297
+ this.visit(index, token.text);
298
+ }
299
+ }
300
+ }
301
+ flag(reason) {
302
+ this.unknown ??= reason;
303
+ }
304
+ is(index, text) {
305
+ const token = this.tokens[index];
306
+ return token !== undefined && token.kind !== "string" && token.kind !== "template" && token.text === text;
307
+ }
308
+ literalArgument(open) {
309
+ const argument = this.tokens[open + 1];
310
+ return this.is(open, "(") && argument?.kind === "string" && this.is(open + 2, ")") ? argument.value : undefined;
311
+ }
312
+ visit(index, name) {
313
+ const member = this.is(index - 1, ".") || this.is(index - 1, "?.");
314
+ const afterTypeof = this.is(index - 1, "typeof");
315
+ if (name === "require") {
316
+ this.require(index, member, afterTypeof);
317
+ } else if (!member) {
318
+ this.visitFree(index, name, afterTypeof);
319
+ }
320
+ }
321
+ visitFree(index, name, afterTypeof) {
322
+ if (COMPUTED_HOLDERS.has(name) && this.is(index + 1, "[")) {
323
+ this.flag(`a computed member access on ${name}`);
324
+ }
325
+ if (GLOBAL_OBJECTS.has(name) && this.callThroughComputedKey(index)) {
326
+ this.flag(`a call through a computed key on ${name}`);
327
+ }
328
+ if (name === "import") {
329
+ this.import(index);
330
+ } else if (name === "module" && !afterTypeof && !this.plainModuleProperty(index)) {
331
+ this.flag("module used other than through module.exports or another plain property");
332
+ }
333
+ if (name === "Bun" && this.is(index + 1, ".") && this.is(index + 2, "plugin")) {
334
+ this.flag("a bun plugin is installed");
335
+ }
336
+ }
337
+ callThroughComputedKey(index) {
338
+ const open = this.is(index + 1, "?.") ? index + 2 : index + 1;
339
+ if (!this.is(open, "[")) {
340
+ return false;
341
+ }
342
+ const close = this.closingBracket(open);
343
+ if (close === undefined) {
344
+ return true;
345
+ }
346
+ if (close === open + 2 && this.literalKey(this.tokens[open + 1])) {
347
+ return false;
348
+ }
349
+ let start = index;
350
+ let end = close;
351
+ while (this.is(start - 1, "(") && this.is(end + 1, ")") && this.startsExpression(start - 2)) {
352
+ start--;
353
+ end++;
354
+ }
355
+ const constructed = this.is(start - 1, "new") && ![".", "?.", "["].some((text) => this.is(end + 1, text));
356
+ return constructed || this.is(end + 1, "(") || this.is(end + 1, "?.") && this.is(end + 2, "(") || this.tokens[end + 1]?.kind === "template";
357
+ }
358
+ literalKey(key) {
359
+ return LITERAL_KEY_KINDS.has(key.kind) || key.kind === "name" && LITERAL_KEY_NAMES.has(key.text);
360
+ }
361
+ startsExpression(index) {
362
+ const token = this.tokens[index];
363
+ if (token === undefined) {
364
+ return true;
365
+ }
366
+ if (token.kind === "name") {
367
+ return BEFORE_EXPRESSION.has(token.text);
368
+ }
369
+ if (token.kind !== "punct") {
370
+ return false;
371
+ }
372
+ return token.text === ")" ? token.closesHead === true : !["?.", "]"].includes(token.text);
373
+ }
374
+ closingBracket(open) {
375
+ let depth = 0;
376
+ for (let index = open;index < this.tokens.length; index++) {
377
+ if (this.is(index, "[")) {
378
+ depth++;
379
+ } else if (this.is(index, "]") && --depth === 0) {
380
+ return index;
381
+ }
382
+ }
383
+ return;
384
+ }
385
+ plainModuleProperty(index) {
386
+ return this.is(index + 1, ".") && MODULE_PROPERTIES.has(this.tokens[index + 2]?.text ?? "");
387
+ }
388
+ bareTypeof(index) {
389
+ const next = this.tokens[index + 1];
390
+ return next === undefined || next.kind !== "template" && !["(", "?.", ".", "["].some((text) => this.is(index + 1, text));
391
+ }
392
+ require(index, member, afterTypeof) {
393
+ this.requireNames++;
394
+ if (member) {
395
+ this.flagRequire("a require reached through a member access (x.require)");
396
+ return;
397
+ }
398
+ if (afterTypeof && this.bareTypeof(index)) {
399
+ return;
400
+ }
401
+ const called = this.literalArgument(index + 1);
402
+ const resolved = this.is(index + 1, ".") && this.is(index + 2, "resolve") ? this.literalArgument(index + 3) : undefined;
403
+ if (called !== undefined) {
404
+ this.requires.push(called);
405
+ } else if (resolved === undefined) {
406
+ this.flagRequire("a computed, aliased or passed require");
407
+ } else {
408
+ this.requireResolves.push(resolved);
409
+ }
410
+ }
411
+ flagRequire(reason) {
412
+ this.requireUnknown = true;
413
+ this.flag(reason);
414
+ }
415
+ import(index) {
416
+ if (this.is(index + 1, "(")) {
417
+ this.importCalls++;
418
+ const called = this.literalArgument(index + 1);
419
+ if (called === undefined) {
420
+ this.flag("a computed import()");
421
+ } else {
422
+ this.imports.push(called);
423
+ }
424
+ } else if (this.is(index + 1, ".") && this.is(index + 2, "meta")) {
425
+ if (!this.is(index + 3, ".") || this.tokens[index + 4]?.kind !== "name") {
426
+ this.flag("import.meta used other than through a named property");
427
+ return;
428
+ }
429
+ const resolved = this.is(index + 4, "resolve") ? this.literalArgument(index + 5) : undefined;
430
+ if (resolved !== undefined) {
431
+ this.metaResolves.push(resolved);
432
+ }
433
+ }
434
+ }
435
+ }
436
+ function wordReason(output, calls) {
437
+ const forbidden = FORBIDDEN_WORDS.exec(output);
438
+ if (forbidden !== null) {
439
+ return `${forbidden[0]} is used`;
440
+ }
441
+ if (count(output, WORD_FUNCTION) > output.split(INSTRUMENTER_GLOBAL_IDIOM).length - 1) {
442
+ return "the Function constructor is used";
443
+ }
444
+ if (count(output, WORD_REQUIRE) > calls.requireNames) {
445
+ return "the word require appears outside code (in a string, a template or a regular expression)";
446
+ }
447
+ if (count(output, WORD_IMPORT_CALL) > calls.importCalls) {
448
+ return "import( appears outside code (in a string, a template or a regular expression)";
449
+ }
450
+ return;
451
+ }
452
+ function scannerAgrees(scanned, calls) {
453
+ const scannerList = (kind) => scanned.filter((entry) => entry.kind === kind).map((entry) => entry.path);
454
+ const scannerRequires = scannerList("require-call");
455
+ const requiresAgree = scannerRequires.length === 0 || sameList(scannerRequires, calls.requires);
456
+ return requiresAgree && sameList(scannerList("dynamic-import"), calls.imports) && sameList(scannerList("require-resolve"), calls.requireResolves);
457
+ }
458
+ function analyseOutput(output, scanned) {
459
+ const records = scanned.filter((entry) => entry.kind === "import-statement").map((entry) => ({ kind: "static", specifier: entry.path }));
460
+ let calls;
461
+ try {
462
+ calls = new CallCollector(tokenize(output));
463
+ } catch (error) {
464
+ return { records, unknown: `bun's output could not be read (${error.message})` };
465
+ }
466
+ const wordProblem = wordReason(output, calls);
467
+ if (wordProblem !== undefined) {
468
+ calls.flag(wordProblem);
469
+ }
470
+ if (!scannerAgrees(scanned, calls)) {
471
+ calls.flag("bun's scanner and the scan read the file's import(), require() or require.resolve() calls differently");
472
+ }
473
+ for (const specifier of calls.requireUnknown ? calls.imports : [...calls.imports, ...calls.requires]) {
474
+ records.push({ kind: "call", specifier });
475
+ }
476
+ for (const specifier of [...calls.requireResolves, ...calls.metaResolves]) {
477
+ records.push({ kind: "resolve", specifier });
478
+ }
479
+ const loader = records.find((record) => LOADER_MODULES.has(record.specifier));
480
+ if (loader !== undefined) {
481
+ calls.flag(`${loader.specifier} is imported`);
482
+ }
483
+ if (records.some((record) => record.specifier === "bun") && WORD_PLUGIN.test(output)) {
484
+ calls.flag("a bun plugin may be installed (plugin from bun)");
485
+ }
486
+ return { records, unknown: calls.unknown };
487
+ }
488
+ var MAX_EXTENDS_DEPTH = 32;
489
+ function resolveTsconfigBase(base, dir) {
490
+ const relative = base.startsWith(".") || path.isAbsolute(base);
491
+ const spellings = relative ? [path.resolve(dir, base), path.resolve(dir, `${base}.json`)] : [base, `${base}.json`, `${base}/tsconfig.json`];
492
+ for (const spelling of spellings) {
493
+ try {
494
+ return relative ? realpathSync(spelling) : Bun.resolveSync(spelling, dir);
495
+ } catch {}
496
+ }
497
+ throw new ScanProblem(`the tsconfig base ${base} cannot be found from ${dir}`);
498
+ }
499
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
500
+ function readCompilerOptions(file, depth = 0) {
501
+ if (depth > MAX_EXTENDS_DEPTH) {
502
+ throw new ScanProblem(`the tsconfig extends chain at ${file} is longer than ${MAX_EXTENDS_DEPTH} (a cycle?)`);
503
+ }
504
+ let parsed;
505
+ try {
506
+ parsed = Bun.JSONC.parse(readFileSync(file, "utf8"));
507
+ } catch (error) {
508
+ throw new ScanProblem(`the tsconfig ${file} cannot be read (${error.message})`);
509
+ }
510
+ if (!isPlainObject(parsed)) {
511
+ throw new ScanProblem(`the tsconfig ${file} is not an object`);
512
+ }
513
+ const bases = parsed.extends === undefined ? [] : [parsed.extends].flat();
514
+ let merged = {};
515
+ for (const base of bases) {
516
+ if (typeof base !== "string") {
517
+ throw new ScanProblem(`the tsconfig ${file} has an extends entry that is not a string`);
518
+ }
519
+ merged = { ...merged, ...readCompilerOptions(resolveTsconfigBase(base, path.dirname(file)), depth + 1) };
520
+ }
521
+ const own = parsed.compilerOptions ?? {};
522
+ if (!isPlainObject(own)) {
523
+ throw new ScanProblem(`the compilerOptions of the tsconfig ${file} are not an object`);
524
+ }
525
+ return { ...merged, ...own };
526
+ }
527
+ function loaderOf(file) {
528
+ if (file.endsWith(".tsx")) {
529
+ return "tsx";
530
+ }
531
+ if (/\.[cm]?ts$/.test(file)) {
532
+ return "ts";
533
+ }
534
+ return /\.[cm]js$/.test(file) ? "js" : "jsx";
535
+ }
536
+ var CODE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/;
537
+ var JSX_RUNTIME = /^.+\/jsx(?:-dev)?-runtime$/;
538
+ var DIRECTORY_CONFIGS = ["tsconfig.json", "jsconfig.json"];
539
+ var RUNTIME = "/jsx-runtime";
540
+ var DEV_RUNTIME = "/jsx-dev-runtime";
541
+ function jsxRuntimeSibling(specifier) {
542
+ return specifier.endsWith(RUNTIME) ? `${specifier.slice(0, -RUNTIME.length)}${DEV_RUNTIME}` : `${specifier.slice(0, -DEV_RUNTIME.length)}${RUNTIME}`;
543
+ }
544
+ function staticJsxRuntimes(scanned) {
545
+ return scanned.filter((entry) => entry.kind === "import-statement" && JSX_RUNTIME.test(entry.path)).map((entry) => entry.path);
546
+ }
547
+ function generatedJsxRuntimes(transpiled, written) {
548
+ const runtimes = staticJsxRuntimes(transpiled);
549
+ if (runtimes.length === 0) {
550
+ return [];
551
+ }
552
+ const left = new Map;
553
+ for (const specifier of staticJsxRuntimes(written())) {
554
+ left.set(specifier, (left.get(specifier) ?? 0) + 1);
555
+ }
556
+ return runtimes.filter((specifier) => {
557
+ const writtenLeft = left.get(specifier) ?? 0;
558
+ left.set(specifier, writtenLeft - 1);
559
+ return writtenLeft <= 0;
560
+ });
561
+ }
562
+ function generatedJsxResolution(resolutions, reason) {
563
+ const found = resolutions.filter((resolution) => resolution.kind !== "missing");
564
+ if (found.length === 0) {
565
+ return resolutions[0];
566
+ }
567
+ return found.every((resolution) => resolution.kind === "ignore" && resolution.projectFile !== true) ? { kind: "ignore" } : { kind: "unknown", reason };
568
+ }
569
+ var STATIC_EDGES = new Set(["static"]);
570
+ var LOADING_EDGES = new Set(["static", "possible"]);
571
+ function attempt(how) {
572
+ try {
573
+ return how();
574
+ } catch {
575
+ return;
576
+ }
577
+ }
578
+ function real(file) {
579
+ try {
580
+ return realpathSync(file);
581
+ } catch {
582
+ return file;
583
+ }
584
+ }
585
+
586
+ class ImportScan {
587
+ input;
588
+ projectReal;
589
+ candidatesAt = new Map;
590
+ always;
591
+ roots;
592
+ rootSet;
593
+ reasons = [];
594
+ notes = [];
595
+ tsconfig;
596
+ transpilers = new Map;
597
+ outputScanner = new Bun.Transpiler({ loader: "js" });
598
+ resolutions = new Map;
599
+ requires = new Map;
600
+ configChains = new Map;
601
+ analysed = new Map;
602
+ importers = new Map;
603
+ constructor(input) {
604
+ this.input = input;
605
+ this.projectReal = real(input.projectDir);
606
+ for (const file of input.eager) {
607
+ for (const key of new Set([file, real(file)])) {
608
+ this.candidatesAt.set(key, [...this.candidatesAt.get(key) ?? [], file]);
609
+ }
610
+ }
611
+ this.always = new Set(input.always);
612
+ this.roots = input.roots.map((root) => real(root));
613
+ this.rootSet = new Set(this.roots);
614
+ if (input.tsconfig !== null) {
615
+ try {
616
+ this.tsconfig = JSON.stringify({ compilerOptions: readCompilerOptions(input.tsconfig) });
617
+ this.notes.push(`tsconfig: ${input.tsconfig}`);
618
+ } catch (error) {
619
+ this.reasons.push(error.message);
620
+ }
621
+ }
622
+ }
623
+ run() {
624
+ const mandatoryFiles = new Set;
625
+ this.reach(this.roots, STATIC_EDGES, mandatoryFiles, (info) => this.noteFirst(info));
626
+ const mandatory = this.candidatesIn(mandatoryFiles);
627
+ const namedFiles = new Set(mandatoryFiles);
628
+ const namedTargets = this.roots.flatMap((root) => this.edgesOf([root], "named"));
629
+ this.reach(namedTargets, STATIC_EDGES, namedFiles, (info) => this.noteFirst(info));
630
+ const named = new Set([...this.candidatesIn(namedFiles)].filter((file) => !mandatory.has(file)));
631
+ const covered = (file) => mandatory.has(file) || named.has(file) || this.always.has(file);
632
+ return {
633
+ answer: this.answer(namedFiles, (file) => covered(file)),
634
+ mandatory: this.input.eager.filter((file) => mandatory.has(file)),
635
+ named: this.input.eager.filter((file) => named.has(file)),
636
+ reasons: this.reasons,
637
+ notes: this.notes,
638
+ scannedFiles: this.analysed.size
639
+ };
640
+ }
641
+ answer(namedFiles, covered) {
642
+ if (this.input.eager.every((file) => covered(file))) {
643
+ this.reasons.length = 0;
644
+ return "full";
645
+ }
646
+ if (this.reasons.length > 0) {
647
+ return "dynamic";
648
+ }
649
+ const clean = this.reach(this.edgesOf([...namedFiles], "possible"), LOADING_EDGES, new Set(namedFiles), (info, file) => {
650
+ const uncovered = (this.candidatesAt.get(file) ?? []).find((candidate) => !covered(candidate));
651
+ if (info.unknown !== undefined) {
652
+ this.reasons.push(info.unknown);
653
+ } else if (uncovered !== undefined) {
654
+ const from = this.display(this.importers.get(file) ?? file);
655
+ this.reasons.push(`project code can load ${this.display(uncovered)} through a literal import() or require() outside the test files and preloads (from ${from})`);
656
+ }
657
+ return info.unknown === undefined && uncovered === undefined;
658
+ });
659
+ return clean && this.reasons.length === 0 ? "static" : "dynamic";
660
+ }
661
+ noteFirst(info) {
662
+ if (info.unknown !== undefined && this.reasons.length === 0) {
663
+ this.reasons.push(info.unknown);
664
+ }
665
+ return true;
666
+ }
667
+ edgesOf(files, type) {
668
+ return files.flatMap((file) => this.analyse(file).edges.filter((edge) => edge.type === type).map((edge) => edge.target));
669
+ }
670
+ candidatesIn(files) {
671
+ return new Set([...files].flatMap((file) => this.candidatesAt.get(file) ?? []));
672
+ }
673
+ reach(start, types, seen, visit) {
674
+ const queue = start.filter((file) => !seen.has(file));
675
+ for (let file = queue.pop();file !== undefined; file = queue.pop()) {
676
+ if (!seen.has(file)) {
677
+ seen.add(file);
678
+ const info = this.analyse(file);
679
+ if (!visit(info, file)) {
680
+ return false;
681
+ }
682
+ queue.push(...info.edges.filter((edge) => types.has(edge.type) && !seen.has(edge.target)).map((edge) => edge.target));
683
+ }
684
+ }
685
+ return true;
686
+ }
687
+ display(file) {
688
+ const relative = path.relative(this.projectReal, file);
689
+ return relative.startsWith("..") || path.isAbsolute(relative) ? file : relative;
690
+ }
691
+ isPackageCode(file) {
692
+ const relative = path.relative(this.projectReal, file);
693
+ const inside = !relative.startsWith("..") && !path.isAbsolute(relative);
694
+ return (inside ? relative : file).split(path.sep).includes("node_modules");
695
+ }
696
+ transpilerFor(loader, autoImportJSX = true) {
697
+ const key = `${loader} ${autoImportJSX}`;
698
+ let transpiler = this.transpilers.get(key);
699
+ if (transpiler === undefined) {
700
+ const options = { loader, trimUnusedImports: loader === "ts" || loader === "tsx", autoImportJSX };
701
+ try {
702
+ transpiler = new Bun.Transpiler({ ...options, ...this.tsconfig === undefined ? {} : { tsconfig: this.tsconfig } });
703
+ } catch (error) {
704
+ this.reasons.push(`the tsconfig ${this.input.tsconfig} is not usable by bun's transpiler (${error.message})`);
705
+ this.tsconfig = undefined;
706
+ transpiler = new Bun.Transpiler(options);
707
+ }
708
+ this.transpilers.set(key, transpiler);
709
+ }
710
+ return transpiler;
711
+ }
712
+ analyse(file) {
713
+ let info = this.analysed.get(file);
714
+ if (info === undefined) {
715
+ try {
716
+ info = this.analyseFile(file);
717
+ } catch (error) {
718
+ info = { edges: [], unknown: `cannot scan ${this.display(file)} (${error.message})` };
719
+ }
720
+ this.analysed.set(file, info);
721
+ }
722
+ return info;
723
+ }
724
+ analyseFile(file) {
725
+ const source = readFileSync(file, "utf8");
726
+ if (MACRO_ATTRIBUTE.test(source)) {
727
+ return { edges: [], unknown: `a macro import in ${this.display(file)}` };
728
+ }
729
+ const loader = loaderOf(file);
730
+ const output = this.transpilerFor(loader).transformSync(source);
731
+ const scanned = this.outputScanner.scan(output).imports;
732
+ const facts = analyseOutput(output, scanned);
733
+ let unknown = this.configProblem(file) ?? (facts.unknown === undefined ? undefined : `${facts.unknown} in ${this.display(file)}`);
734
+ const edges = [];
735
+ const generated = generatedJsxRuntimes(scanned, () => this.outputScanner.scan(this.transpilerFor(loader, false).transformSync(source)).imports);
736
+ for (const record of facts.records) {
737
+ const index = generated.indexOf(record.specifier);
738
+ const resolved = index === -1 ? this.resolve(record.specifier, file) : this.resolveGeneratedJsx(generated.splice(index, 1)[0], file);
739
+ if ("reason" in resolved) {
740
+ unknown ??= resolved.reason;
741
+ } else if (resolved.kind === "follow") {
742
+ edges.push(...this.edgeFor(record.kind, resolved.file, file));
743
+ }
744
+ }
745
+ for (const edge of edges) {
746
+ if (!this.importers.has(edge.target)) {
747
+ this.importers.set(edge.target, file);
748
+ }
749
+ }
750
+ return { edges, unknown };
751
+ }
752
+ resolveGeneratedJsx(specifier, from) {
753
+ const sibling = jsxRuntimeSibling(specifier);
754
+ const reason = `the JSX runtime that bun adds to ${this.display(from)} (${specifier} or ${sibling}) is project code or a mutated file, and the scan cannot tell which of the two the tests load`;
755
+ return generatedJsxResolution([this.resolve(specifier, from), this.resolve(sibling, from)], reason);
756
+ }
757
+ edgeFor(kind, target, from) {
758
+ if (kind === "static") {
759
+ return [{ type: "static", target }];
760
+ }
761
+ if (kind === "call") {
762
+ return [{ type: this.rootSet.has(from) ? "named" : "possible", target }];
763
+ }
764
+ return this.candidatesAt.has(target) ? [{ type: "possible", target }] : [];
765
+ }
766
+ resolve(specifier, from) {
767
+ const key = `${path.dirname(from)}\x00${specifier}`;
768
+ let resolution = this.resolutions.get(key);
769
+ if (resolution === undefined) {
770
+ resolution = specifier === "bun" || specifier.startsWith("bun:") || isBuiltin(specifier) ? { kind: "ignore" } : this.resolveBothWays(specifier, from);
771
+ this.resolutions.set(key, resolution);
772
+ }
773
+ return resolution;
774
+ }
775
+ resolveBothWays(specifier, from) {
776
+ const dir = path.dirname(from);
777
+ const asImport = attempt(() => Bun.resolveSync(specifier, dir));
778
+ const asRequire = attempt(() => this.requireFrom(dir, from).resolve(specifier));
779
+ const where = `${specifier} from ${this.display(from)}`;
780
+ if (asImport === undefined && asRequire === undefined) {
781
+ return { kind: "missing", reason: `cannot resolve ${where}` };
782
+ }
783
+ const [importTarget, requireTarget] = [asImport, asRequire].map((target) => target === undefined ? undefined : this.identity(target));
784
+ if (![importTarget, requireTarget].some((target) => target !== undefined && this.isProjectCode(target))) {
785
+ return { kind: "ignore" };
786
+ }
787
+ if (importTarget === undefined || requireTarget === undefined) {
788
+ return { kind: "unknown", reason: `${where} resolves only as ${importTarget === undefined ? "a require" : "an import"}` };
789
+ }
790
+ if (importTarget !== requireTarget) {
791
+ return { kind: "unknown", reason: `${where} resolves differently for import and require` };
792
+ }
793
+ return CODE_FILE.test(importTarget) ? { kind: "follow", file: importTarget } : { kind: "ignore", projectFile: true };
794
+ }
795
+ isProjectCode(target) {
796
+ return path.isAbsolute(target) && (!this.isPackageCode(target) || this.candidatesAt.has(target));
797
+ }
798
+ requireFrom(dir, from) {
799
+ let resolver = this.requires.get(dir);
800
+ if (resolver === undefined) {
801
+ resolver = createRequire(pathToFileURL(from).href);
802
+ this.requires.set(dir, resolver);
803
+ }
804
+ return resolver;
805
+ }
806
+ configProblem(file) {
807
+ const dir = path.dirname(file);
808
+ const relative = path.relative(this.projectReal, dir);
809
+ return relative.startsWith("..") || path.isAbsolute(relative) ? undefined : this.configChainProblem(dir);
810
+ }
811
+ configChainProblem(dir) {
812
+ if (this.configChains.has(dir)) {
813
+ return this.configChains.get(dir);
814
+ }
815
+ const parent = path.dirname(dir);
816
+ const problem = this.directoryConfigProblem(dir) ?? (dir === this.projectReal || parent === dir ? undefined : this.configChainProblem(parent));
817
+ this.configChains.set(dir, problem);
818
+ return problem;
819
+ }
820
+ directoryConfigProblem(dir) {
821
+ for (const name of DIRECTORY_CONFIGS) {
822
+ const file = path.join(dir, name);
823
+ let text;
824
+ try {
825
+ if (statSync(file, { throwIfNoEntry: false }) === undefined) {
826
+ continue;
827
+ }
828
+ text = readFileSync(file, "utf8");
829
+ } catch (error) {
830
+ return `the ${name} ${this.display(file)} cannot be read (${error.message})`;
831
+ }
832
+ try {
833
+ Bun.JSONC.parse(text);
834
+ } catch (error) {
835
+ return `the ${name} ${this.display(file)} cannot be parsed (${error.message})`;
836
+ }
837
+ }
838
+ return;
839
+ }
840
+ identity(resolved) {
841
+ if (!path.isAbsolute(resolved)) {
842
+ return resolved;
843
+ }
844
+ const query = resolved.indexOf("?", resolved.lastIndexOf("/"));
845
+ return real(query === -1 ? resolved : resolved.slice(0, query));
846
+ }
847
+ }
848
+ function scanImports(input) {
849
+ const started = performance.now();
850
+ const result = new ImportScan(input).run();
851
+ return { ...result, elapsedMs: Number((performance.now() - started).toFixed(1)) };
852
+ }
853
+ function parseScanInput(text) {
854
+ const value = JSON.parse(text);
855
+ if (!isPlainObject(value)) {
856
+ throw new Error("the input is not a JSON object");
857
+ }
858
+ const paths = (field) => {
859
+ const list = value[field];
860
+ if (!Array.isArray(list) || !list.every((entry) => typeof entry === "string" && path.isAbsolute(entry))) {
861
+ throw new Error(`${field} must be an array of absolute paths`);
862
+ }
863
+ return list;
864
+ };
865
+ const { tsconfig, projectDir } = value;
866
+ if (tsconfig !== null && (typeof tsconfig !== "string" || !path.isAbsolute(tsconfig))) {
867
+ throw new Error("tsconfig must be an absolute path or null");
868
+ }
869
+ if (typeof projectDir !== "string" || !path.isAbsolute(projectDir)) {
870
+ throw new Error("projectDir must be an absolute path");
871
+ }
872
+ return { eager: paths("eager"), roots: paths("roots"), always: paths("always"), tsconfig, projectDir };
873
+ }
874
+ function main(inputFile) {
875
+ try {
876
+ if (inputFile === undefined) {
877
+ throw new Error("usage: bun --no-macros --no-install --config=<an empty file> import-scan.js <input.json>");
878
+ }
879
+ process.stdout.write(`${JSON.stringify(scanImports(parseScanInput(readFileSync(inputFile, "utf8"))))}
880
+ `);
881
+ } catch (error) {
882
+ process.stderr.write(`stryker-bun-runner import scan: ${error.message}
883
+ `);
884
+ process.exitCode = 1;
885
+ }
886
+ }
887
+ if (import.meta.main) {
888
+ main(process.argv[2]);
889
+ }
890
+ export {
891
+ INSTRUMENTER_GLOBAL_IDIOM,
892
+ MACRO_ATTRIBUTE,
893
+ ScanProblem,
894
+ analyseOutput,
895
+ generatedJsxResolution,
896
+ generatedJsxRuntimes,
897
+ jsxRuntimeSibling,
898
+ parseScanInput,
899
+ readCompilerOptions,
900
+ scanImports,
901
+ tokenize
902
+ };