test-inventory 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # test-inventory
2
2
 
3
+ ## 0.10.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#99](https://github.com/Huldoser/test-inventory/pull/99) [`df8968d`](https://github.com/Huldoser/test-inventory/commit/df8968dc0357353913b96fadd417a266ab290b2c) - Keep Playwright declaring modifiers when functions are stored in variables or selected inline. Read logical choices with the same rules as the other runners, and classify each nested branch once to avoid exponential traversal.
8
+
9
+ Match Vite's alias merge precedence and preserve object aliases when mixed with lists. Mark imports as unfollowed when an unreadable alias entry or find could match them.
10
+
11
+ Ignore annotation and step line numbers in inventory diffs, so moving unchanged tests to another line does not report metadata changes.
12
+
13
+ - [#100](https://github.com/Huldoser/test-inventory/pull/100) [`fa10d39`](https://github.com/Huldoser/test-inventory/commit/fa10d3970046e4e99b6f175ff5dcf0eee13ccfcd) - Read locally declared describe callbacks passed by name, preserving suite placement, inherited state, lexical values and expanded table arguments. Keep suite hashes, dependencies and nested parent links complete, including when a child is written before its calling parent. Apply the existing helper traversal limits and runner callback checks to these callbacks.
14
+
15
+ ## 0.10.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [#96](https://github.com/Huldoser/test-inventory/pull/96) [`86e1765`](https://github.com/Huldoser/test-inventory/commit/86e1765d7b8fb763f34d0f024fb53931192b4e1b) - Compare two complete saved scans with `test-inventory diff old.json new.json` or `diffInventories(before, after)`.
20
+ Reports additions, removals, renamed and moved tests, changed code and dependencies, state, tags and other metadata.
21
+ Matches ids first, then body hashes with file, suite or dependency context, leaving ambiguous matches unmatched.
22
+ Includes exact body clone groups, JSON Schema, and escaped Markdown output through `--format markdown` or
23
+ `formatDiffMarkdown`. Hash comparisons and rename matching require identical tool versions; incomplete scans warn.
24
+
25
+ ### Patch Changes
26
+
27
+ - [#96](https://github.com/Huldoser/test-inventory/pull/96) [`86e1765`](https://github.com/Huldoser/test-inventory/commit/86e1765d7b8fb763f34d0f024fb53931192b4e1b) - Keep unreadable config aliases as dependency gaps rather than silently treating their imports as installed packages.
28
+ Read string concatenation and templates in config paths. Follow config aliases in setup paths, Jasmine helper globs,
29
+ Cypress's default and configured support files, Bun preload files, and Node script preloads in dependencies and
30
+ dependencyHash, so --related keeps tests affected by changes to those files.
31
+
32
+ - [#96](https://github.com/Huldoser/test-inventory/pull/96) [`86e1765`](https://github.com/Huldoser/test-inventory/commit/86e1765d7b8fb763f34d0f024fb53931192b4e1b) - Apply Mocha's focus filtering, including Cypress and WebdriverIO on Mocha, so an outer describe.only does not focus
33
+ tests that a more specific focus excludes. A root focused test in standalone Mocha excludes child suites across
34
+ files. Contain refused calls inside node:test and Bun describe callbacks: Node keeps earlier tests and tests outside
35
+ the describe; Bun loses that describe only. Vitest reads allowOnly per project, does not fail unconditionally skipped
36
+ focused tests, and refuses modifiers after a called each or for table.
37
+
3
38
  ## 0.9.1
4
39
 
5
40
  ### Patch Changes
package/README.md CHANGED
@@ -9,6 +9,9 @@ when the state only applies sometimes. Each test has an id that survives a move
9
9
  it runs, from its hooks and fixtures to its page objects, test data, snapshots and config, so it can also list the tests
10
10
  a change can affect. It parses the code and runs nothing, so it needs no browsers, no build and no runner configuration.
11
11
 
12
+ Compare saved scans with `test-inventory diff old.json new.json`: additions, removals, renames and moves, changes to
13
+ code, dependencies, state and tags, as JSON or Markdown. See [Compare inventories](https://huldoser.github.io/test-inventory/guide/diff).
14
+
12
15
  Documentation: [huldoser.github.io/test-inventory](https://huldoser.github.io/test-inventory/)
13
16
 
14
17
  ## Install
package/dist/cli.d.ts CHANGED
@@ -6,6 +6,6 @@ export interface Io {
6
6
  /** Read for `--related -`. */
7
7
  stdin?: Readable;
8
8
  }
9
- export declare const HELP = "Usage: test-inventory [glob...] [options]\n\nLists the tests in the matching files as JSON, read from the source code without running them. Without globs, the\ntest files are those the runner's configs in the root and the folders below it run, or for node:test and Bun those\nnode --test and bun test run.\n\nOptions:\n --framework <name> playwright, vitest, jest, mocha, jasmine, cypress, webdriverio, node or bun\n (default: the one the project uses)\n --root <dir> project root; paths in the output are relative to it (default: current directory)\n --ignore <glob> leave out matching files; can be repeated (node_modules is always left out)\n --framework-version <x.y.z> apply the rules of this framework version instead of the one in the project\n --comments <mode> comments above tests: all, non-active or none (default: non-active)\n --expand-cases one record per case of a .each or .for table and per pass of a loop, with its title\n --state <state> keep tests in this state, such as skip or fixme; can be repeated\n --tag <tag> keep tests with this tag, such as @smoke; can be repeated\n --grep <regex> keep tests whose full name matches, ignoring case\n --only keep tests that use .only, or are inside a describe that does\n --without-reason keep tests that don't run and give no reason\n --related <file> keep tests a change to this file can affect; can be repeated; - reads files, one per\n line, from standard input, as git diff --name-only writes them\n --fields <keys> write only these keys of each test, separated by commas; id is always kept\n --format <format> json or jsonl, one record per line (default: json)\n -o, --output <file> write to a file instead of standard output\n --pretty indent the JSON\n -h, --help show this help\n -v, --version show the version\n\nExit codes: 0 when the scan finishes, even with diagnostics; 2 for invalid arguments, an output that cannot be\nwritten, or a crash. 1 is reserved for a future release.\n\nExamples:\n test-inventory \"tests/**/*.spec.ts\" --framework playwright --output inventory.json\n test-inventory \"tests/**/*.spec.ts\" --framework playwright --state skip --fields fullName,reason\n";
9
+ export declare const HELP = "Usage: test-inventory [glob...] [options]\n test-inventory diff old.json new.json [--format json|markdown] [--pretty] [--output file]\n\nLists the tests in the matching files as JSON, read from the source code without running them. Without globs, the\ntest files are those the runner's configs in the root and the folders below it run, or for node:test and Bun those\nnode --test and bun test run.\n\nOptions:\n --framework <name> playwright, vitest, jest, mocha, jasmine, cypress, webdriverio, node or bun\n (default: the one the project uses)\n --root <dir> project root; paths in the output are relative to it (default: current directory)\n --ignore <glob> leave out matching files; can be repeated (node_modules is always left out)\n --framework-version <x.y.z> apply the rules of this framework version instead of the one in the project\n --comments <mode> comments above tests: all, non-active or none (default: non-active)\n --expand-cases one record per case of a .each or .for table and per pass of a loop, with its title\n --state <state> keep tests in this state, such as skip or fixme; can be repeated\n --tag <tag> keep tests with this tag, such as @smoke; can be repeated\n --grep <regex> keep tests whose full name matches, ignoring case\n --only keep tests that use .only, or are inside a describe that does\n --without-reason keep tests that don't run and give no reason\n --related <file> keep tests a change to this file can affect; can be repeated; - reads files, one per\n line, from standard input, as git diff --name-only writes them\n --fields <keys> write only these keys of each test, separated by commas; id is always kept\n --format <format> json or jsonl, one record per line (default: json)\n -o, --output <file> write to a file instead of standard output\n --pretty indent the JSON\n -h, --help show this help\n -v, --version show the version\n\nExit codes: 0 when the scan finishes, even with diagnostics; 2 for invalid arguments, an output that cannot be\nwritten, or a crash. 1 is reserved for a future release.\n\nExamples:\n test-inventory \"tests/**/*.spec.ts\" --framework playwright --output inventory.json\n test-inventory \"tests/**/*.spec.ts\" --framework playwright --state skip --fields fullName,reason\n";
10
10
  /** Runs the command line with the given arguments and streams. Resolves to the exit code. */
11
11
  export declare function run(argv: string[], io: Io): Promise<number>;
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createWriteStream, openSync, renameSync, rmSync } from 'node:fs';
2
2
  import { once } from 'node:events';
3
+ import { readFile } from 'node:fs/promises';
3
4
  import path from 'node:path';
4
5
  import { parseArgs } from 'node:util';
5
6
  import { readFailure } from "./files.js";
@@ -8,7 +9,10 @@ import { writeInventory, writeInventoryLines } from "./json.js";
8
9
  import { OptionsError, toPosixPath } from "./options.js";
9
10
  import { scan } from "./scan.js";
10
11
  import { toolVersion } from "./version.js";
12
+ import { diffInventories } from "./diff.js";
13
+ import { formatDiffMarkdown } from "./diff-markdown.js";
11
14
  export const HELP = `Usage: test-inventory [glob...] [options]
15
+ test-inventory diff old.json new.json [--format json|markdown] [--pretty] [--output file]
12
16
 
13
17
  Lists the tests in the matching files as JSON, read from the source code without running them. Without globs, the
14
18
  test files are those the runner's configs in the root and the folders below it run, or for node:test and Bun those
@@ -99,8 +103,84 @@ async function text(stream) {
99
103
  /** ESLint's exit codes. 1 is reserved for a future release. */
100
104
  const FINISHED = 0;
101
105
  const FAILED = 2;
106
+ async function runDiff(argv, io) {
107
+ const fail = (message) => {
108
+ io.stderr.write(`test-inventory diff: ${message}\nRun test-inventory diff --help for usage.\n`);
109
+ return FAILED;
110
+ };
111
+ let parsed;
112
+ try {
113
+ parsed = parseArgs({
114
+ args: argv,
115
+ allowPositionals: true,
116
+ strict: true,
117
+ options: {
118
+ format: { type: 'string' },
119
+ pretty: { type: 'boolean' },
120
+ output: { type: 'string', short: 'o' },
121
+ help: { type: 'boolean', short: 'h' },
122
+ },
123
+ });
124
+ }
125
+ catch (error) {
126
+ return fail(error.message);
127
+ }
128
+ const { values, positionals } = parsed;
129
+ if (values.help) {
130
+ io.stdout.write('Usage: test-inventory diff old.json new.json [--format json|markdown] [--pretty] [--output file]\n\nCompares complete JSON inventories. Use the same tool version, framework, root, filters and case expansion for both scans.\n');
131
+ return FINISHED;
132
+ }
133
+ if (positionals.length !== 2)
134
+ return fail('pass two inventory files: old.json new.json.');
135
+ const format = values.format ?? 'json';
136
+ if (!['json', 'markdown'].includes(format))
137
+ return fail('--format must be json or markdown.');
138
+ if (format === 'markdown' && values.pretty)
139
+ return fail('--pretty indents JSON, so it does not go with --format markdown.');
140
+ let result;
141
+ try {
142
+ const inputs = [];
143
+ for (const file of positionals) {
144
+ let content;
145
+ try {
146
+ content = await readFile(path.resolve(io.cwd, file), 'utf8');
147
+ }
148
+ catch (error) {
149
+ return fail(`could not read ${file}: ${readFailure(error)}.`);
150
+ }
151
+ try {
152
+ inputs.push(JSON.parse(content));
153
+ }
154
+ catch {
155
+ return fail(`${file} is not a JSON inventory. Save a scan without --format jsonl.`);
156
+ }
157
+ }
158
+ result = diffInventories(inputs[0], inputs[1]);
159
+ }
160
+ catch (error) {
161
+ return fail(error.message);
162
+ }
163
+ const quiet = () => undefined;
164
+ io.stdout.on('error', quiet);
165
+ try {
166
+ await writeOutput(io, values.output, (output) => writeTo(output, format === 'markdown'
167
+ ? formatDiffMarkdown(result)
168
+ : `${JSON.stringify(result, null, values.pretty ? 2 : undefined)}\n`));
169
+ }
170
+ catch (error) {
171
+ if (error.code === 'EPIPE')
172
+ return FINISHED;
173
+ return fail(`could not write ${values.output ?? 'the output'}: ${readFailure(error)}.`);
174
+ }
175
+ finally {
176
+ io.stdout.off('error', quiet);
177
+ }
178
+ return FINISHED;
179
+ }
102
180
  /** Runs the command line with the given arguments and streams. Resolves to the exit code. */
103
181
  export async function run(argv, io) {
182
+ if (argv[0] === 'diff')
183
+ return runDiff(argv.slice(1), io);
104
184
  const fail = (message) => {
105
185
  io.stderr.write(`test-inventory: ${message}\nRun test-inventory --help for usage.\n`);
106
186
  return FAILED;
@@ -1,4 +1,5 @@
1
- import type { ConfigRuns, Placement } from './config-runs.ts';
1
+ import { type ConfigRuns, type Placement } from './config-runs.ts';
2
+ import type { ImportMap } from './resolve.ts';
2
3
  import type { ModuleReader, ModuleSource, Span } from './model.ts';
3
4
  import { SourceText } from './source.ts';
4
5
  import type { Framework } from './types.ts';
@@ -38,12 +39,16 @@ export declare class ConfigDependencies {
38
39
  private readonly framework;
39
40
  private readonly runs;
40
41
  private readonly readerFor;
42
+ private readonly root;
41
43
  /** The files setup projects may run. */
42
44
  private readonly candidates;
43
45
  private readonly found;
44
46
  private readonly ids;
45
- constructor(framework: Framework, runs: ConfigRuns, readerFor: (fromFile: string) => ModuleReader, candidates: readonly string[]);
47
+ private nodeRuns;
48
+ constructor(framework: Framework, runs: ConfigRuns, readerFor: (fromFile: string, map?: ImportMap | null) => ModuleReader, candidates: readonly string[], root: string);
46
49
  of(placement: Placement): RunsWith;
50
+ /** Node has no config file: its package scripts name modules loaded before the tests. */
51
+ private nodeSetup;
47
52
  private idOf;
48
53
  private read;
49
54
  /** Whether Playwright's `snapshotDir` is the testDir of every project that runs the file, its default. */
@@ -1,4 +1,6 @@
1
1
  import path from 'node:path';
2
+ import { globSync } from 'tinyglobby';
3
+ import { importMap, nodeTestArguments } from "./config-runs.js";
2
4
  import { settingAt } from "./config.js";
3
5
  import { SourceText } from "./source.js";
4
6
  const NOTHING = { config: null, modules: [], gaps: [], moved: null };
@@ -34,7 +36,7 @@ const SETUP_KEYS = {
34
36
  jest: [['setupFiles'], ['setupFilesAfterEnv'], ['globalSetup'], ['globalTeardown']],
35
37
  // Mocha loads both before the tests: `require` for root hooks and global fixtures, `file` as test files.
36
38
  mocha: [['require'], ['file']],
37
- // Jasmine's `helpers` are globs from `spec_dir`, which these paths from the config's folder don't cover.
39
+ // Jasmine's helpers are read separately as globs from spec_dir.
38
40
  jasmine: [],
39
41
  // The support file Cypress loads before every spec.
40
42
  cypress: [
@@ -44,7 +46,7 @@ const SETUP_KEYS = {
44
46
  // Mocha's `require` runs before the specs, as root hooks may.
45
47
  webdriverio: [['mochaOpts', 'require']],
46
48
  node: [],
47
- bun: [],
49
+ bun: [['test', 'preload']],
48
50
  };
49
51
  const UNKNOWN_PROJECTS = "The projects that run the file can't be worked out, so dependencyHash doesn't cover their setup.";
50
52
  /**
@@ -57,17 +59,22 @@ export class ConfigDependencies {
57
59
  framework;
58
60
  runs;
59
61
  readerFor;
62
+ root;
60
63
  /** The files setup projects may run. */
61
64
  candidates;
62
65
  found = new Map();
63
66
  ids = new Map();
64
- constructor(framework, runs, readerFor, candidates) {
67
+ nodeRuns = null;
68
+ constructor(framework, runs, readerFor, candidates, root) {
65
69
  this.framework = framework;
66
70
  this.runs = runs;
67
71
  this.readerFor = readerFor;
68
72
  this.candidates = candidates;
73
+ this.root = root;
69
74
  }
70
75
  of(placement) {
76
+ if (this.framework === 'node')
77
+ return this.nodeSetup();
71
78
  const { config } = placement;
72
79
  if (config === null)
73
80
  return NOTHING;
@@ -81,6 +88,31 @@ export class ConfigDependencies {
81
88
  }
82
89
  return found;
83
90
  }
91
+ /** Node has no config file: its package scripts name modules loaded before the tests. */
92
+ nodeSetup() {
93
+ if (this.nodeRuns)
94
+ return this.nodeRuns;
95
+ const manifest = path.join(this.root, 'package.json');
96
+ const files = nodeTestArguments(manifest, true).flat();
97
+ const own = files.length > 0 ? this.module(manifest) : null;
98
+ if (!own)
99
+ return (this.nodeRuns = NOTHING);
100
+ const modules = [];
101
+ const gaps = [];
102
+ for (const file of files) {
103
+ const read = this.setupFile(this.root, file);
104
+ if (read && !('reason' in read))
105
+ modules.push(read);
106
+ else if (read)
107
+ gaps.push({
108
+ module: own,
109
+ text: file,
110
+ message: `The script preload '${file}' ${read.reason}, so dependencyHash doesn't cover it.`,
111
+ isQuiet: false,
112
+ });
113
+ }
114
+ return (this.nodeRuns = { config: own, modules, gaps, moved: null });
115
+ }
84
116
  idOf(project) {
85
117
  let id = this.ids.get(project);
86
118
  if (id === undefined) {
@@ -102,19 +134,25 @@ export class ConfigDependencies {
102
134
  const gaps = [];
103
135
  const places = new Set();
104
136
  /** The setup files a key of `settings` names, found from `root`, as written in the config `module`. */
105
- const setup = (module, settings, root, keys) => {
137
+ const map = importMap(placement, this.framework);
138
+ const setup = (module, settings, root, keys, globs = false, fallback) => {
106
139
  const key = keys.join('.');
107
- const found = written(settings, keys);
140
+ const found = fallback === undefined
141
+ ? written(settings, keys)
142
+ : { setting: { kind: 'value', value: fallback }, isInherited: false };
108
143
  for (const item of found ? listOf(found.setting) : []) {
109
144
  if (item.kind === 'value' && typeof item.value === 'string') {
110
145
  // Jest's `<rootDir>` at the start of a path is the project's root.
111
146
  const file = item.value.startsWith('<rootDir>') ? `.${item.value.slice(9)}` : item.value;
112
- const read = this.setupFile(root, file);
113
- if (read && !('reason' in read))
114
- modules.add(read);
115
- else if (read) {
116
- const message = `${key} names '${item.value}', which ${read.reason}, so dependencyHash doesn't cover it.`;
117
- gaps.push({ module, text: item.value, message, isQuiet: false });
147
+ const files = globs ? globSync(file, { cwd: root, absolute: true, onlyFiles: true }) : [file];
148
+ for (const named of files) {
149
+ const read = this.setupFile(root, named, map);
150
+ if (read && !('reason' in read))
151
+ modules.add(read);
152
+ else if (read) {
153
+ const message = `${key} names '${item.value}', which ${read.reason}, so dependencyHash doesn't cover it.`;
154
+ gaps.push({ module, text: item.value, message, isQuiet: false });
155
+ }
118
156
  }
119
157
  }
120
158
  else if (item.kind === 'unknown') {
@@ -155,7 +193,19 @@ export class ConfigDependencies {
155
193
  const written = 'config' in project ? this.module(project.config.file) : own;
156
194
  modules.add(written);
157
195
  for (const keys of SETUP_KEYS[this.framework])
158
- setup(written, project.settings, project.root, keys);
196
+ setup(written, project.settings, project.root, keys, this.framework === 'cypress');
197
+ if (this.framework === 'jasmine') {
198
+ const dir = settingAt(project.settings, ['spec_dir']);
199
+ const specDir = dir?.kind === 'value' && typeof dir.value === 'string' ? dir.value : '';
200
+ setup(written, project.settings, path.resolve(this.root, specDir), ['helpers'], true);
201
+ }
202
+ if (this.framework === 'cypress') {
203
+ const type = 'name' in project && project.name === 'component' ? 'component' : 'e2e';
204
+ const support = settingAt(project.settings, [type, 'supportFile']);
205
+ if (support === null || (support.kind === 'value' && support.value === undefined)) {
206
+ setup(written, project.settings, project.root, [type, 'supportFile'], true, `cypress/support/${type}.{js,jsx,ts,tsx}`);
207
+ }
208
+ }
159
209
  const { container } = project;
160
210
  const outer = container && this.module(container.file);
161
211
  if (container && outer) {
@@ -224,12 +274,18 @@ export class ConfigDependencies {
224
274
  * A setup file a config names, found from `root` as the runners find it; null for a name that isn't a file there,
225
275
  * which is a package, whose code is left out as installed code is.
226
276
  */
227
- setupFile(root, file) {
277
+ setupFile(root, file, map = null) {
228
278
  // `path.join(__dirname, 'setup.ts')` gives an absolute path.
229
279
  const relative = path.isAbsolute(file) ? path.relative(root, file).replaceAll('\\', '/') : file;
230
280
  const isPath = /^\.\.?[\\/]/.test(relative);
231
- const read = this.readerFor(path.join(root, 'config'))(isPath ? relative : `./${relative}`);
232
- return 'reason' in read && !isPath ? null : read;
281
+ const reader = this.readerFor(path.join(root, 'config'), map);
282
+ const read = reader(relative);
283
+ if (!('reason' in read) || isPath)
284
+ return read;
285
+ const local = reader(`./${relative}`);
286
+ if (!('reason' in local))
287
+ return local;
288
+ return read.reason === 'is not a local file, a path alias or a workspace package' ? null : read;
233
289
  }
234
290
  /** A file the scan reads code from, by its absolute path, as the modules a test imports are read. */
235
291
  module(file) {
@@ -226,8 +226,8 @@ export declare class ConfigRuns {
226
226
  private vitestFiles;
227
227
  }
228
228
  /**
229
- * What the config a file uses gives it: Playwright's `forbidOnly` or Vitest's `allowOnly`, read from the top level
230
- * only, as the runners read them, and for each test, the projects that run it and what they set; null without a config.
229
+ * What the config a file uses gives it: Playwright's `forbidOnly`, Vitest's per-project `allowOnly`, and for each test,
230
+ * the projects that run it and what they set; null without a config.
231
231
  */
232
232
  export declare function fileConfig(placement: Placement, framework: Framework, version: [number, number] | null, file: string): FileConfig | null;
233
233
  /**
@@ -250,4 +250,9 @@ export declare function webdriverioFramework(placement: Placement, configs: Conf
250
250
  * config, or when it maps nothing.
251
251
  */
252
252
  export declare function importMap(placement: Placement, framework: Framework): ImportMap | null;
253
+ /**
254
+ * The `node --test` commands of the `test` script and the scripts it runs, or else of the first script that runs one,
255
+ * each as the files it gives; none when no script runs it or there is no package.json.
256
+ */
257
+ export declare function nodeTestArguments(manifest: string, setups?: boolean): string[][];
253
258
  export {};
@@ -1702,8 +1702,8 @@ const UNKNOWN_DEFAULTS = {
1702
1702
  parallel: false,
1703
1703
  };
1704
1704
  /**
1705
- * What the config a file uses gives it: Playwright's `forbidOnly` or Vitest's `allowOnly`, read from the top level
1706
- * only, as the runners read them, and for each test, the projects that run it and what they set; null without a config.
1705
+ * What the config a file uses gives it: Playwright's `forbidOnly`, Vitest's per-project `allowOnly`, and for each test,
1706
+ * the projects that run it and what they set; null without a config.
1707
1707
  */
1708
1708
  export function fileConfig(placement, framework, version, file) {
1709
1709
  const { config, projects } = placement;
@@ -1714,18 +1714,34 @@ export function fileConfig(placement, framework, version, file) {
1714
1714
  return framework === 'vitest' ? { forbidOnly, forTest: () => NO_CONFIG, tags, configTags: [] } : null;
1715
1715
  }
1716
1716
  return {
1717
- forbidOnly: onlyRule(framework, config.settings),
1717
+ forbidOnly: projectOnlyRule(framework, config.settings, projects),
1718
1718
  forTest(test, suites) {
1719
1719
  if (projects === null)
1720
1720
  return { projects: null, defaults: UNKNOWN_DEFAULTS };
1721
1721
  const running = projectsRunning(projects, test, suites, file, placement.tags);
1722
1722
  // A grep the scan can't match leaves the projects that run the file, which may still agree.
1723
- return { projects: running?.map(({ name }) => name) ?? null, defaults: configDefaults(running ?? projects) };
1723
+ return {
1724
+ projects: running?.map(({ name }) => name) ?? null,
1725
+ defaults: configDefaults(running ?? projects),
1726
+ forbidOnly: projectOnlyRule(framework, config.settings, running ?? projects),
1727
+ };
1724
1728
  },
1725
1729
  tags: agreedTags(projects),
1726
1730
  configTags: placement.tags ?? [],
1727
1731
  };
1728
1732
  }
1733
+ function projectOnlyRule(framework, settings, projects) {
1734
+ if (framework !== 'vitest' || projects === null || projects.length === 0)
1735
+ return onlyRule(framework, settings);
1736
+ const rules = projects.map((project) => onlyRule(framework, project.settings));
1737
+ const first = rules[0];
1738
+ if (rules.every((rule) => JSON.stringify(rule) === JSON.stringify(first)))
1739
+ return first;
1740
+ return {
1741
+ message: 'The projects disagree on allowOnly; this .only fails in the projects that disable it.',
1742
+ isSure: false,
1743
+ };
1744
+ }
1729
1745
  /**
1730
1746
  * Why a `.only` fails: with Playwright's `forbidOnly` or Mocha's `forbid-only`, the run, before any test; with Vitest's
1731
1747
  * `allowOnly` off, the test itself, which Vitest marks failed instead of running it (checked in 3.2.4, 4.1.12 and
@@ -1900,8 +1916,11 @@ function readImportMap(config, settings, placement, framework) {
1900
1916
  for (const key of [
1901
1917
  ['test', 'alias'],
1902
1918
  ['resolve', 'alias'],
1903
- ])
1904
- map.aliases.push(...viteAliases(settingAt(source, key)));
1919
+ ]) {
1920
+ const parent = settingAt(source, key.slice(0, -1));
1921
+ if (parent?.kind === 'object')
1922
+ map.aliases.push(...viteAliases(parent.keys.get('alias') ?? null));
1923
+ }
1905
1924
  }
1906
1925
  }
1907
1926
  else if (framework === 'jest') {
@@ -1910,9 +1929,11 @@ function readImportMap(config, settings, placement, framework) {
1910
1929
  for (const [pattern, target] of mapper?.kind === 'object' ? mapper.keys : []) {
1911
1930
  const replacements = (target.kind === 'list' ? strings(target) : stringOf(target)).map((item) => replaceRootDir(rootDir, item));
1912
1931
  const find = regExp(pattern, '');
1913
- if (find && replacements.length > 0)
1932
+ if (find)
1914
1933
  map.aliases.push({ find, replacements, replacesName: true });
1915
1934
  }
1935
+ if (mapper?.kind === 'unknown')
1936
+ map.aliases.push({ find: /./, replacements: [], replacesName: true });
1916
1937
  map.paths = strings(settingAt(settings, ['modulePaths'])).map((item) => path.resolve(rootDir, replaceRootDir(rootDir, item)));
1917
1938
  // A `<rootDir>` entry of moduleDirectories is a folder, as a modulePaths entry is, not a name to look for.
1918
1939
  for (const item of strings(settingAt(settings, ['moduleDirectories']))) {
@@ -1927,21 +1948,32 @@ function readImportMap(config, settings, placement, framework) {
1927
1948
  }
1928
1949
  /**
1929
1950
  * Vite's aliases: an object of names and their replacements, or a list of `{ find, replacement }`, where `find` is a
1930
- * name or a regex. Entries the scan can't work out are left out.
1951
+ * name or a regex. An unreadable replacement keeps its match, so its imports are marked unfollowed.
1931
1952
  */
1932
1953
  function viteAliases(setting) {
1933
1954
  if (setting?.kind === 'object') {
1934
- return [...setting.keys].flatMap(([find, target]) => stringOf(target).map((replacement) => ({ find, replacements: [replacement], replacesName: false })));
1955
+ const aliases = [...setting.keys].map(([find, target]) => ({
1956
+ find,
1957
+ replacements: stringOf(target),
1958
+ replacesName: false,
1959
+ }));
1960
+ if (setting.rest)
1961
+ aliases.push({ find: /./, replacements: [], replacesName: false });
1962
+ return aliases;
1935
1963
  }
1964
+ if (setting?.kind === 'unknown')
1965
+ return [{ find: /./, replacements: [], replacesName: false }];
1936
1966
  if (setting?.kind !== 'list')
1937
1967
  return [];
1938
1968
  return setting.items.flatMap((item) => {
1939
1969
  const find = settingAt(item, ['find']);
1970
+ if (find?.kind === 'unknown')
1971
+ return [{ find: /./, replacements: [], replacesName: false }];
1940
1972
  const replacements = stringOf(settingAt(item, ['replacement']));
1941
1973
  const name = find?.kind === 'value' && typeof find.value === 'string' ? find.value : null;
1942
1974
  const pattern = find?.kind === 'regex' ? regExp(find.source, find.flags) : null;
1943
1975
  const written = name ?? pattern;
1944
- return written !== null && replacements.length > 0 ? [{ find: written, replacements, replacesName: false }] : [];
1976
+ return written !== null ? [{ find: written, replacements, replacesName: false }] : [];
1945
1977
  });
1946
1978
  }
1947
1979
  /** A setting's string as a list of one; empty for anything else. */
@@ -1959,7 +1991,7 @@ function stripsTypes(version) {
1959
1991
  * The `node --test` commands of the `test` script and the scripts it runs, or else of the first script that runs one,
1960
1992
  * each as the files it gives; none when no script runs it or there is no package.json.
1961
1993
  */
1962
- function nodeTestArguments(manifest) {
1994
+ export function nodeTestArguments(manifest, setups = false) {
1963
1995
  let scripts = {};
1964
1996
  try {
1965
1997
  scripts = JSON.parse(readFileSync(manifest, 'utf8')).scripts ?? {};
@@ -1967,9 +1999,10 @@ function nodeTestArguments(manifest) {
1967
1999
  catch {
1968
2000
  return [];
1969
2001
  }
1970
- const fromTest = scriptsRunBy(scripts, 'test').flatMap(nodeTestCommands);
2002
+ const read = (script) => nodeTestCommands(script, setups);
2003
+ const fromTest = scriptsRunBy(scripts, 'test').flatMap(read);
1971
2004
  if (fromTest.length > 0)
1972
2005
  return fromTest;
1973
2006
  const others = Object.values(scripts).filter((script) => typeof script === 'string');
1974
- return others.map(nodeTestCommands).find((commands) => commands.length > 0) ?? [];
2007
+ return others.map(read).find((commands) => commands.length > 0) ?? [];
1975
2008
  }
package/dist/config.d.ts CHANGED
@@ -50,7 +50,7 @@ export declare function settingAt(setting: Setting, keys: readonly string[]): Se
50
50
  * Vite's `mergeConfig(base, over)`: objects merge key by key, lists are joined with a single setting taken as a list
51
51
  * of one, and `null` or `undefined` keeps the other side.
52
52
  */
53
- export declare function mergeDeep(base: Setting, over: Setting): Setting;
53
+ export declare function mergeDeep(base: Setting, over: Setting, rootPath?: string): Setting;
54
54
  /** The config a scanned file uses, read once however many files use it. */
55
55
  export interface ConfigFile {
56
56
  /** The config's absolute path. */
package/dist/config.js CHANGED
@@ -232,7 +232,7 @@ function either(a, b, at) {
232
232
  * Vite's `mergeConfig(base, over)`: objects merge key by key, lists are joined with a single setting taken as a list
233
233
  * of one, and `null` or `undefined` keeps the other side.
234
234
  */
235
- export function mergeDeep(base, over) {
235
+ export function mergeDeep(base, over, rootPath = '') {
236
236
  if (isNullish(over))
237
237
  return base;
238
238
  if (isNullish(base) || over.kind === 'unknown')
@@ -249,10 +249,46 @@ export function mergeDeep(base, over) {
249
249
  const keys = new Map(base.kind === 'object' && !over.rest ? base.keys : []);
250
250
  for (const [key, value] of over.keys) {
251
251
  const existing = child(base, key);
252
- keys.set(key, existing ? mergeDeep(existing, value) : value);
252
+ keys.set(key, existing
253
+ ? key === 'alias' && (rootPath === '' || rootPath === 'resolve')
254
+ ? mergeAliases(existing, value)
255
+ : mergeDeep(existing, value, rootPath ? `${rootPath}.${key}` : key)
256
+ : value);
253
257
  }
254
258
  return { kind: 'object', keys, rest: over.rest ?? (base.kind === 'object' ? base.rest : base) };
255
259
  }
260
+ /** Vite puts overriding list aliases first and normalizes object aliases when either side is a list. */
261
+ function mergeAliases(base, over) {
262
+ if (isNullish(over))
263
+ return base;
264
+ if (isNullish(base))
265
+ return over;
266
+ if (base.kind === 'object' && over.kind === 'object') {
267
+ return {
268
+ kind: 'object',
269
+ keys: new Map([...(over.rest ? [] : base.keys), ...over.keys]),
270
+ rest: over.rest ?? base.rest,
271
+ };
272
+ }
273
+ const entries = (setting) => {
274
+ if (setting.kind === 'list')
275
+ return setting.items;
276
+ if (setting.kind !== 'object')
277
+ return [setting];
278
+ return [
279
+ ...[...setting.keys].map(([find, replacement]) => ({
280
+ kind: 'object',
281
+ keys: new Map([
282
+ ['find', { kind: 'value', value: find }],
283
+ ['replacement', replacement],
284
+ ]),
285
+ rest: null,
286
+ })),
287
+ ...(setting.rest ? [setting.rest] : []),
288
+ ];
289
+ };
290
+ return { kind: 'list', items: [...entries(over), ...entries(base)] };
291
+ }
256
292
  /** Works out a config's settings from its code, following the modules it imports them from. */
257
293
  class ConfigCode {
258
294
  /** The modules read for the config besides itself, in the order they were first followed. */
@@ -331,6 +367,28 @@ class ConfigCode {
331
367
  return this.call(expression, frame, scopes);
332
368
  case 'NewExpression':
333
369
  return this.newUrl(expression, frame, scopes);
370
+ case 'BinaryExpression': {
371
+ if (expression.operator !== '+')
372
+ break;
373
+ const left = this.evaluate(expression.left, frame, scopes);
374
+ const right = this.evaluate(expression.right, frame, scopes);
375
+ if (left.kind === 'value' && right.kind === 'value') {
376
+ if (typeof left.value === 'string' || typeof right.value === 'string') {
377
+ return { kind: 'value', value: String(left.value) + String(right.value) };
378
+ }
379
+ }
380
+ break;
381
+ }
382
+ case 'TemplateLiteral': {
383
+ const values = expression.expressions.map((item) => this.evaluate(item, frame, scopes));
384
+ if (values.every((item) => item.kind === 'value')) {
385
+ const value = expression.quasis
386
+ .map((item, index) => item.value.cooked + (index < values.length ? String(values[index].value) : ''))
387
+ .join('');
388
+ return { kind: 'value', value };
389
+ }
390
+ break;
391
+ }
334
392
  case 'Literal':
335
393
  if ('regex' in expression)
336
394
  return { kind: 'regex', source: expression.regex.pattern, flags: expression.regex.flags };
@@ -1491,11 +1491,13 @@ export function fileDependencies(graph, main, extraction, types, report, runsWit
1491
1491
  let units = suiteUnits.get(suite);
1492
1492
  if (!units) {
1493
1493
  // A describe without a callback has no tests in it.
1494
- const fn = suite.declaration.fn;
1494
+ const fn = (suite.declaration.fn ?? suite.declaration.hashed);
1495
+ // Its load code is listed separately; following a named reference would pull in sibling test bodies too.
1496
+ const callback = suite.declaration.fn ? [] : suite.call.arguments.slice(-1);
1495
1497
  units = [
1496
1498
  graph.unit(moduleOf(suite.frame), [suite.call, ...bodyNodes(fn).filter(isLoadCode)],
1497
1499
  // Offsets in another file could match these by chance.
1498
- [fn, ...suite.cuts, ...(suite.frame === main ? registered : [])], types),
1500
+ [fn, ...callback, ...suite.cuts, ...(suite.frame === main ? registered : [])], types),
1499
1501
  ...registering(suite.registeredBy),
1500
1502
  ];
1501
1503
  suiteUnits.set(suite, units);
@@ -0,0 +1,3 @@
1
+ import type { InventoryDiff } from './diff.ts';
2
+ /** A report ready to save as Markdown or use as the body of a pull request comment. */
3
+ export declare function formatDiffMarkdown(diff: InventoryDiff): string;