xo 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,21 +1,14 @@
1
- import ts from 'typescript';
2
1
  /**
3
- This function checks if the files are matched by the tsconfig include, exclude, and it returns the unmatched files.
2
+ This function checks if the files are matched by the tsconfig include/exclude, and returns the unmatched files.
4
3
 
5
- If no tsconfig is found, it will create an in-memory TypeScript Program for type-aware linting.
4
+ All unincluded files are routed through a generated tsconfig (`parserOptions.project`) so that autofix works correctly across multiple ESLint passes. The in-memory Program approach is intentionally not used here because `@typescript-eslint/typescript-estree` always returns the AST built from the original file text when using `parserOptions.programs`, ignoring the updated `code` ESLint passes on subsequent fix passes, which causes file corruption.
6
5
 
7
6
  @param options - The options for handling the tsconfig.
8
7
  @param options.files - The TypeScript files to check against the tsconfig.
9
8
  @param options.cwd - The current working directory.
10
- @param options.cacheLocation - The cache directory used to detect virtual/stdin files.
11
- @returns The unmatched files and an in-memory TypeScript Program.
9
+ @returns The unincluded files.
12
10
  */
13
- export declare function handleTsconfig({ files, cwd, cacheLocation }: {
11
+ export declare function handleTsconfig({ files, cwd }: {
14
12
  files: string[];
15
13
  cwd: string;
16
- cacheLocation?: string;
17
- }): {
18
- existingFiles: string[];
19
- virtualFiles: string[];
20
- program: ts.Program | undefined;
21
- };
14
+ }): string[];
@@ -1,9 +1,7 @@
1
1
  import path from 'node:path';
2
- import fs from 'node:fs';
3
2
  import { createRequire } from 'node:module';
4
3
  import ts from 'typescript';
5
4
  import { getTsconfig, createFilesMatcher } from 'get-tsconfig';
6
- import { tsconfigDefaults } from './constants.js';
7
5
  let hasWarnedAboutTypeScriptVersion = false;
8
6
  /**
9
7
  Warns once if the project's own TypeScript is an older major than the version XO bundles. Mixing TypeScript versions in one process can crash type-aware linting (notably under pnpm), because the TypeFlags enum was renumbered in TypeScript 6.
@@ -29,61 +27,17 @@ const warnOnOutdatedProjectTypeScript = (cwd) => {
29
27
  hasWarnedAboutTypeScriptVersion = true;
30
28
  console.warn(`XO bundles TypeScript ${ts.version}, but your project has TypeScript ${projectVersion}. Mixing TypeScript versions in one process can crash type-aware linting (notably with pnpm). Upgrade your project's \`typescript\` to ${bundledMajor} or later, or pin it (for example, a pnpm \`overrides\` entry).`);
31
29
  };
32
- const createInMemoryProgram = (files, cwd) => {
33
- if (files.length === 0) {
34
- return undefined;
35
- }
36
- try {
37
- const compilerOptions = getFallbackCompilerOptions(cwd);
38
- const program = ts.createProgram(files, { ...compilerOptions });
39
- Object.defineProperty(program, 'toJSON', {
40
- value: () => ({
41
- __type: 'TypeScriptProgram',
42
- files: files.map(file => path.relative(cwd, file)),
43
- }),
44
- configurable: true,
45
- });
46
- return program;
47
- }
48
- catch (error) {
49
- console.warn('XO: Failed to create TypeScript Program for type-aware linting. Continuing without type information for unincluded files.', error instanceof Error ? error.message : String(error));
50
- return undefined;
51
- }
52
- };
53
- const fallbackCompilerOptionsCache = new Map();
54
- const getFallbackCompilerOptions = (cwd) => {
55
- const cacheKey = path.resolve(cwd);
56
- const cached = fallbackCompilerOptionsCache.get(cacheKey);
57
- if (cached) {
58
- return cached;
59
- }
60
- const compilerOptionsResult = ts.convertCompilerOptionsFromJson(tsconfigDefaults.compilerOptions ?? {}, cacheKey);
61
- if (compilerOptionsResult.errors.length > 0) {
62
- throw new Error('XO: Invalid default TypeScript compiler options');
63
- }
64
- const compilerOptions = {
65
- ...compilerOptionsResult.options,
66
- esModuleInterop: true,
67
- resolveJsonModules: true,
68
- allowJs: true,
69
- skipLibCheck: true,
70
- skipDefaultLibCheck: true,
71
- };
72
- fallbackCompilerOptionsCache.set(cacheKey, compilerOptions);
73
- return compilerOptions;
74
- };
75
30
  /**
76
- This function checks if the files are matched by the tsconfig include, exclude, and it returns the unmatched files.
31
+ This function checks if the files are matched by the tsconfig include/exclude, and returns the unmatched files.
77
32
 
78
- If no tsconfig is found, it will create an in-memory TypeScript Program for type-aware linting.
33
+ All unincluded files are routed through a generated tsconfig (`parserOptions.project`) so that autofix works correctly across multiple ESLint passes. The in-memory Program approach is intentionally not used here because `@typescript-eslint/typescript-estree` always returns the AST built from the original file text when using `parserOptions.programs`, ignoring the updated `code` ESLint passes on subsequent fix passes, which causes file corruption.
79
34
 
80
35
  @param options - The options for handling the tsconfig.
81
36
  @param options.files - The TypeScript files to check against the tsconfig.
82
37
  @param options.cwd - The current working directory.
83
- @param options.cacheLocation - The cache directory used to detect virtual/stdin files.
84
- @returns The unmatched files and an in-memory TypeScript Program.
38
+ @returns The unincluded files.
85
39
  */
86
- export function handleTsconfig({ files, cwd, cacheLocation }) {
40
+ export function handleTsconfig({ files, cwd }) {
87
41
  warnOnOutdatedProjectTypeScript(cwd);
88
42
  const unincludedFiles = [];
89
43
  const filesMatcherCache = new Map();
@@ -104,39 +58,6 @@ export function handleTsconfig({ files, cwd, cacheLocation }) {
104
58
  }
105
59
  unincludedFiles.push(filePath);
106
60
  }
107
- if (unincludedFiles.length === 0) {
108
- return { existingFiles: [], virtualFiles: [], program: undefined };
109
- }
110
- // Separate real files from virtual/cache files
111
- // Virtual files include: stdin files (in cache dir), non-existent files
112
- // TypeScript will surface opaque diagnostics for missing files; pre-filter so we only pay the program cost for real files.
113
- const existingFiles = [];
114
- const virtualFiles = [];
115
- for (const file of unincludedFiles) {
116
- // Files that don't exist are always virtual
117
- if (!fs.existsSync(file)) {
118
- virtualFiles.push(file);
119
- continue;
120
- }
121
- // Check if file is in cache directory (like stdin files)
122
- // These need tsconfig treatment even though they exist on disk
123
- if (cacheLocation !== undefined) {
124
- const absolutePath = path.resolve(file);
125
- const cacheRoot = path.resolve(cacheLocation);
126
- const relativeToCache = path.relative(cacheRoot, absolutePath);
127
- // File is inside cache if relative path doesn't escape (no '..')
128
- const isInCache = !relativeToCache.startsWith('..') && !path.isAbsolute(relativeToCache);
129
- if (isInCache) {
130
- virtualFiles.push(file);
131
- continue;
132
- }
133
- }
134
- existingFiles.push(file);
135
- }
136
- return {
137
- existingFiles,
138
- virtualFiles,
139
- program: createInMemoryProgram(existingFiles, cwd),
140
- };
61
+ return unincludedFiles;
141
62
  }
142
63
  //# sourceMappingURL=handle-ts-files.js.map
package/dist/lib/xo.d.ts CHANGED
@@ -23,13 +23,11 @@ export declare class Xo {
23
23
  private prepareEslintConfig;
24
24
  private discoverFiles;
25
25
  /**
26
- Add virtual files to the config with a tsconfig approach.
27
- */
28
- private addVirtualFilesToConfig;
29
- /**
30
- Add existing files to the config with an in-memory TypeScript Program.
26
+ Add unincluded files to the config with a generated tsconfig approach. Passing an empty array removes the generated config entry.
27
+
28
+ This uses `parserOptions.project` rather than an in-memory `parserOptions.programs`. A pre-built program's AST is built once from the original file text and is never updated between ESLint's multiple `--fix` passes, so stale offsets corrupt the output. A file-based project is re-read on each pass, so autofix stays correct.
31
29
  */
32
- private addExistingFilesToConfig;
30
+ private addUnincludedFilesToConfig;
33
31
  private processReport;
34
32
  private getReportStatistics;
35
33
  /**
@@ -46,7 +44,7 @@ export declare class Xo {
46
44
  */
47
45
  ensureCacheDirectory(): Promise<void>;
48
46
  /**
49
- Checks every TS file to ensure its included in the tsconfig and any that are not included are added to an in-memory TypeScript Program for type aware linting.
47
+ Checks every TS file to ensure it is included in the tsconfig. Any that are not included are routed through a generated tsconfig (`tsconfig.generated.json`) so that autofix works correctly across multiple ESLint passes.
50
48
 
51
49
  @param files - The TypeScript files being linted.
52
50
  */
package/dist/lib/xo.js CHANGED
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import syncFs from 'node:fs';
4
4
  import fs from 'node:fs/promises';
5
5
  import process from 'node:process';
6
+ import { createHash } from 'node:crypto';
6
7
  import { ESLint } from 'eslint';
7
8
  import findCacheDirectory from 'find-cache-directory';
8
9
  import { globby, isDynamicPattern } from 'globby';
@@ -39,6 +40,17 @@ const createIgnoredLintResult = (filePath) => ({
39
40
  });
40
41
  const normalizeGlobPath = (filePath) => filePath.split(path.sep).join('/');
41
42
  const pathMatchesPattern = (filePath, pattern) => micromatch.isMatch(normalizeGlobPath(filePath), normalizeGlobPath(pattern), { dot: true });
43
+ const isPathInside = (parentPath, childPath) => {
44
+ const relativePath = path.relative(parentPath, childPath);
45
+ return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
46
+ };
47
+ const getGeneratedTsconfigPath = (directory, files) => {
48
+ const hash = createHash('sha256')
49
+ .update(JSON.stringify(files.toSorted((first, second) => first.localeCompare(second))))
50
+ .digest('hex')
51
+ .slice(0, 16);
52
+ return path.join(directory, `tsconfig.generated.${hash}.json`);
53
+ };
42
54
  const isIgnoredByPatterns = (filePath, patterns) => {
43
55
  let isIgnored = false;
44
56
  for (const pattern of patterns) {
@@ -233,6 +245,14 @@ export class Xo {
233
245
  */
234
246
  #cacheLocation;
235
247
  /**
248
+ Directory for generated tsconfigs for unincluded TypeScript files.
249
+ */
250
+ #generatedTsconfigDirectory;
251
+ /**
252
+ File path to the currently active generated tsconfig.
253
+ */
254
+ #currentGeneratedTsconfigPath;
255
+ /**
236
256
  XO config derived from both the base config and the resolved flat config.
237
257
  */
238
258
  #xoConfig;
@@ -258,17 +278,6 @@ export class Xo {
258
278
  We use this to also add negative glob patterns in case a user overrides the parserOptions in their XO config.
259
279
  */
260
280
  #tsFilesIgnoresGlob = [];
261
- /**
262
- Store per-file configs separately from base config to prevent unbounded array growth.
263
- Key: file path, Value: config for that file.
264
- This prevents memory bloat in long-running processes (e.g., language servers).
265
- */
266
- #fileConfigs = new Map();
267
- /**
268
- Track virtual/stdin files that share a single tsconfig.stdin.json.
269
- These are handled differently from regular files.
270
- */
271
- #virtualFiles = new Set();
272
281
  constructor(_linterOptions, _baseXoConfig = {}) {
273
282
  this.#linterOptions = _linterOptions;
274
283
  this.#baseXoConfig = _baseXoConfig;
@@ -284,6 +293,9 @@ export class Xo {
284
293
  }
285
294
  const backupCacheLocation = path.join(os.tmpdir(), cacheDirName);
286
295
  this.#cacheLocation = findCacheDirectory({ name: cacheDirName, cwd: this.#linterOptions.cwd }) ?? backupCacheLocation;
296
+ this.#generatedTsconfigDirectory = isPathInside(this.#linterOptions.cwd, this.#cacheLocation)
297
+ ? this.#cacheLocation
298
+ : path.join(this.#linterOptions.cwd, 'node_modules', '.cache', cacheDirName);
287
299
  }
288
300
  /**
289
301
  Initializes the ESLint flat config on the XO instance.
@@ -320,98 +332,74 @@ export class Xo {
320
332
  };
321
333
  }
322
334
  /**
323
- Add virtual files to the config with a tsconfig approach.
335
+ Add unincluded files to the config with a generated tsconfig approach. Passing an empty array removes the generated config entry.
336
+
337
+ This uses `parserOptions.project` rather than an in-memory `parserOptions.programs`. A pre-built program's AST is built once from the original file text and is never updated between ESLint's multiple `--fix` passes, so stale offsets corrupt the output. A file-based project is re-read on each pass, so autofix stays correct.
324
338
  */
325
- async addVirtualFilesToConfig(files) {
339
+ async addUnincludedFilesToConfig(files) {
326
340
  if (!this.#xoConfig) {
327
341
  return;
328
342
  }
329
343
  try {
330
- const nextVirtualFiles = new Set(files);
331
- const tsconfigPath = path.join(this.#cacheLocation, 'tsconfig.stdin.json');
332
- const configIndex = this.#xoConfig.findIndex(configItem => {
333
- const { languageOptions } = configItem;
334
- const parserOptions = languageOptions?.['parserOptions'];
335
- return parserOptions?.project === tsconfigPath;
336
- });
337
- if (nextVirtualFiles.size > 0) {
338
- const filesArray = [...nextVirtualFiles];
339
- const relativeFiles = filesArray.map(file => path.relative(this.#linterOptions.cwd, file));
340
- const tsconfigContent = {
341
- compilerOptions: {
342
- ...tsconfigDefaults.compilerOptions,
343
- module: 'ESNext',
344
- moduleResolution: 'NodeNext',
345
- esModuleInterop: true,
346
- skipLibCheck: true,
347
- },
348
- files: filesArray,
349
- };
350
- await fs.writeFile(tsconfigPath, JSON.stringify(tsconfigContent, null, 2));
351
- if (configIndex === -1) {
352
- const parserOptions = {
353
- projectService: false,
354
- project: tsconfigPath,
355
- tsconfigRootDir: this.#linterOptions.cwd,
356
- };
357
- this.#xoConfig.push({
358
- files: relativeFiles,
359
- languageOptions: {
360
- parser: typescriptParser,
361
- parserOptions,
362
- },
363
- });
364
- }
365
- else {
366
- const existingConfig = this.#xoConfig[configIndex];
367
- this.#xoConfig[configIndex] = {
368
- ...existingConfig,
369
- files: relativeFiles,
370
- };
344
+ const previousTsconfigPath = this.#currentGeneratedTsconfigPath;
345
+ const configIndex = previousTsconfigPath === undefined
346
+ ? -1
347
+ : this.#xoConfig.findIndex(configItem => {
348
+ const { languageOptions } = configItem;
349
+ const parserOptions = languageOptions?.['parserOptions'];
350
+ return parserOptions?.project === previousTsconfigPath;
351
+ });
352
+ if (files.length === 0) {
353
+ if (configIndex !== -1) {
354
+ this.#xoConfig.splice(configIndex, 1);
371
355
  }
372
- this.#virtualFiles.clear();
373
- for (const file of nextVirtualFiles) {
374
- this.#virtualFiles.add(file);
356
+ if (previousTsconfigPath !== undefined) {
357
+ this.#currentGeneratedTsconfigPath = undefined;
375
358
  }
376
359
  return;
377
360
  }
378
- if (configIndex >= 0) {
379
- this.#xoConfig.splice(configIndex, 1);
361
+ const tsconfigPath = getGeneratedTsconfigPath(this.#generatedTsconfigDirectory, files);
362
+ // The generated tsconfig references files by absolute path; the ESLint config matches them by path relative to `cwd`.
363
+ const relativeFiles = files.map(file => path.relative(this.#linterOptions.cwd, file));
364
+ const tsconfigContent = {
365
+ compilerOptions: {
366
+ ...tsconfigDefaults.compilerOptions,
367
+ module: 'ESNext',
368
+ moduleResolution: 'NodeNext',
369
+ esModuleInterop: true,
370
+ resolveJsonModule: true,
371
+ skipLibCheck: true,
372
+ // JS files are routed here too (type-aware rules apply to JS). Without `allowJs`, TypeScript does not load them as source files, so the parser reports "file not found in project".
373
+ allowJs: true,
374
+ // TypeScript 6 only auto-includes `@types/*` packages when `types` contains `'*'`. Without this, unincluded files resolve imports to `any` and type-aware rules misfire.
375
+ types: ['*'],
376
+ },
377
+ files,
378
+ };
379
+ await fs.mkdir(path.dirname(tsconfigPath), { recursive: true });
380
+ await fs.writeFile(tsconfigPath, JSON.stringify(tsconfigContent, null, 2));
381
+ this.#currentGeneratedTsconfigPath = tsconfigPath;
382
+ const parserOptions = {
383
+ projectService: false,
384
+ project: tsconfigPath,
385
+ tsconfigRootDir: this.#linterOptions.cwd,
386
+ };
387
+ const generatedConfig = {
388
+ files: relativeFiles,
389
+ languageOptions: {
390
+ parser: typescriptParser,
391
+ parserOptions,
392
+ },
393
+ };
394
+ if (configIndex === -1) {
395
+ this.#xoConfig.push(generatedConfig);
396
+ }
397
+ else {
398
+ this.#xoConfig[configIndex] = generatedConfig;
380
399
  }
381
- this.#virtualFiles.clear();
382
- await fs.rm(tsconfigPath, { force: true });
383
400
  }
384
401
  catch (error) {
385
- console.warn('XO: Failed to create tsconfig for virtual files. Type-aware linting will be disabled for these files.', error instanceof Error ? error.message : String(error));
386
- }
387
- }
388
- /**
389
- Add existing files to the config with an in-memory TypeScript Program.
390
- */
391
- addExistingFilesToConfig(files, program) {
392
- if (!this.#xoConfig || files.length === 0) {
393
- return;
394
- }
395
- const parserOptions = {
396
- project: false,
397
- projectService: false,
398
- };
399
- if (program) {
400
- parserOptions.programs = [program];
401
- }
402
- const config = {
403
- files: files.map(file => path.relative(this.#linterOptions.cwd, file)),
404
- languageOptions: {
405
- parser: typescriptParser,
406
- parserOptions,
407
- },
408
- };
409
- // IMPORTANT: All files intentionally share the same config object reference for memory efficiency.
410
- // This prevents unbounded memory growth in long-running processes (e.g., language servers).
411
- // The config is immutable after creation, so sharing is safe.
412
- // Deduplication happens in setEslintConfig() via Set to avoid duplicate configs in the final array.
413
- for (const file of files) {
414
- this.#fileConfigs.set(file, config);
402
+ console.warn('XO: Failed to create tsconfig for unincluded files. Type-aware linting will be disabled for these files.', error instanceof Error ? error.message : String(error));
415
403
  }
416
404
  }
417
405
  processReport(report, { rulesMeta = {} } = {}) {
@@ -490,14 +478,11 @@ export class Xo {
490
478
  if (!this.#xoConfig) {
491
479
  throw new Error('"Xo.setEslintConfig" failed');
492
480
  }
493
- // Combine base config with per-file configs from Map
494
- // Deduplicate configs since multiple files can share the same config object
495
481
  const [baseConfig = {}, ...resolvedConfigs] = this.#xoConfig;
496
482
  const { ignores, ...configWithoutCliIgnores } = baseConfig;
497
483
  const expandedResolvedConfigs = resolvedConfigs.map(config => expandGlobalIgnoreConfigForEslint(config));
498
- const uniqueFileConfigs = [...new Set(this.#fileConfigs.values())];
499
484
  const cliIgnoreConfig = cliIgnores.length > 0 ? [{ ignores: expandIgnoreNegationsForEslint(cliIgnores) }] : [];
500
- const allConfigs = [configWithoutCliIgnores, ...expandedResolvedConfigs, ...cliIgnoreConfig, ...uniqueFileConfigs];
485
+ const allConfigs = [configWithoutCliIgnores, ...expandedResolvedConfigs, ...cliIgnoreConfig];
501
486
  // Always regenerate to support instance reuse with new files
502
487
  this.#eslintConfig = xoToEslintConfig(allConfigs);
503
488
  if (stripDefaultIgnores) {
@@ -525,33 +510,24 @@ export class Xo {
525
510
  }
526
511
  }
527
512
  /**
528
- Checks every TS file to ensure its included in the tsconfig and any that are not included are added to an in-memory TypeScript Program for type aware linting.
513
+ Checks every TS file to ensure it is included in the tsconfig. Any that are not included are routed through a generated tsconfig (`tsconfig.generated.json`) so that autofix works correctly across multiple ESLint passes.
529
514
 
530
515
  @param files - The TypeScript files being linted.
531
516
  */
532
517
  async handleUnincludedTsFiles(files) {
533
- if (!this.#linterOptions.ts || !files || files.length === 0) {
518
+ if (!this.#linterOptions.ts) {
534
519
  return;
535
520
  }
536
- // Get ALL TypeScript files being linted (both new and previously handled)
537
- const allTsFiles = matchFilesForTsConfig(this.#linterOptions.cwd, files, this.#tsFilesGlob, this.#tsFilesIgnoresGlob);
538
- if (allTsFiles.length === 0) {
539
- this.#fileConfigs.clear();
540
- if (this.#virtualFiles.size > 0) {
541
- await this.addVirtualFilesToConfig([]);
542
- }
521
+ if (!files || files.length === 0) {
522
+ await this.addUnincludedFilesToConfig([]);
543
523
  return;
544
524
  }
545
- const { program, existingFiles, virtualFiles } = handleTsconfig({
546
- files: allTsFiles,
547
- cwd: this.#linterOptions.cwd,
548
- cacheLocation: this.#cacheLocation,
549
- });
550
- this.#fileConfigs.clear();
551
- if (existingFiles.length > 0) {
552
- this.addExistingFilesToConfig(existingFiles, program);
553
- }
554
- await this.addVirtualFilesToConfig(virtualFiles);
525
+ // Get ALL TypeScript files being linted
526
+ const allTsFiles = matchFilesForTsConfig(this.#linterOptions.cwd, files, this.#tsFilesGlob, this.#tsFilesIgnoresGlob);
527
+ const unincludedFiles = allTsFiles.length === 0
528
+ ? []
529
+ : handleTsconfig({ files: allTsFiles, cwd: this.#linterOptions.cwd });
530
+ await this.addUnincludedFilesToConfig(unincludedFiles);
555
531
  }
556
532
  /**
557
533
  Initializes the ESLint instance on the XO instance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xo",
3
- "version": "3.0.0",
3
+ "version": "3.0.2",
4
4
  "description": "JavaScript/TypeScript linter (ESLint wrapper) with great defaults",
5
5
  "license": "MIT",
6
6
  "repository": "xojs/xo",