Skip to content

feat(typescript-estree): add defaultProject for project service #8815

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/packages/TypeScript_ESTree.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,14 @@ interface ParseAndGenerateServicesOptions extends ParseOptions {
*/
interface ProjectServiceOptions {
/**
* Globs of files to allow running with the default inferred project settings.
* Globs of files to allow running with the default project compiler options.
*/
allowDefaultProjectForFiles?: string[];

/**
* Path to a TSConfig to use instead of TypeScript's default project configuration.
*/
defaultProject?: string;
}

interface ParserServices {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* eslint-disable @typescript-eslint/no-empty-function -- for TypeScript APIs*/
import os from 'node:os';

import type * as ts from 'typescript/lib/tsserverlibrary';

import type { ProjectServiceOptions } from '../parser-options';
Expand Down Expand Up @@ -58,6 +60,42 @@ export function createProjectService(
jsDocParsingMode,
});

if (typeof options === 'object' && options.defaultProject) {
let configRead;

try {
configRead = tsserver.readConfigFile(
options.defaultProject,
system.readFile,
);
} catch (error) {
throw new Error(
`Could not parse default project '${options.defaultProject}': ${(error as Error).message}`,
);
}

if (configRead.error) {
throw new Error(
`Could not read default project '${options.defaultProject}': ${tsserver.formatDiagnostic(
configRead.error,
{
getCurrentDirectory: system.getCurrentDirectory,
getCanonicalFileName: fileName => fileName,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't figure out a way to get this to execute in tests. 🤷

getNewLine: () => os.EOL,
},
)}`,
);
}

service.setCompilerOptionsForInferredProjects(
(
configRead.config as {
compilerOptions: ts.server.protocol.InferredProjectCompilerOptions;
}
).compilerOptions,
);
}

return {
allowDefaultProjectForFiles:
typeof options === 'object'
Expand Down
7 changes: 6 additions & 1 deletion packages/typescript-estree/src/parser-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,14 @@ interface ParseOptions {
*/
export interface ProjectServiceOptions {
/**
* Globs of files to allow running with the default inferred project settings.
* Globs of files to allow running with the default project compiler options.
*/
allowDefaultProjectForFiles?: string[];

/**
* Path to a TSConfig to use instead of TypeScript's default project configuration.
*/
defaultProject?: string;
}

interface ParseAndGenerateServicesOptions extends ParseOptions {
Expand Down
76 changes: 76 additions & 0 deletions packages/typescript-estree/tests/lib/createProjectService.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import * as ts from 'typescript';

import { createProjectService } from '../../src/create-program/createProjectService';

const mockReadConfigFile = jest.fn();
const mockSetCompilerOptionsForInferredProjects = jest.fn();

jest.mock('typescript/lib/tsserverlibrary', () => ({
...jest.requireActual('typescript/lib/tsserverlibrary'),
readConfigFile: mockReadConfigFile,
server: {
ProjectService: class {
setCompilerOptionsForInferredProjects =
mockSetCompilerOptionsForInferredProjects;
},
},
}));

describe('createProjectService', () => {
it('sets allowDefaultProjectForFiles when options.allowDefaultProjectForFiles is defined', () => {
const allowDefaultProjectForFiles = ['./*.js'];
Expand All @@ -18,4 +34,64 @@ describe('createProjectService', () => {

expect(settings.allowDefaultProjectForFiles).toBeUndefined();
});

it('throws an error when options.defaultProject is set and readConfigFile returns an error', () => {
mockReadConfigFile.mockReturnValue({
error: {
category: ts.DiagnosticCategory.Error,
code: 1234,
file: ts.createSourceFile('./tsconfig.json', '', {
languageVersion: ts.ScriptTarget.Latest,
}),
start: 0,
length: 0,
messageText: 'Oh no!',
} satisfies ts.Diagnostic,
});

expect(() =>
createProjectService(
{
allowDefaultProjectForFiles: ['file.js'],
defaultProject: './tsconfig.json',
},
undefined,
),
).toThrow(
/Could not read default project '\.\/tsconfig.json': .+ error TS1234: Oh no!/,
);
});

it('throws an error when options.defaultProject is set and readConfigFile throws an error', () => {
mockReadConfigFile.mockImplementation(() => {
throw new Error('Oh no!');
});

expect(() =>
createProjectService(
{
allowDefaultProjectForFiles: ['file.js'],
defaultProject: './tsconfig.json',
},
undefined,
),
).toThrow("Could not parse default project './tsconfig.json': Oh no!");
});

it('uses the default projects compiler options when options.defaultProject is set and readConfigFile succeeds', () => {
const compilerOptions = { strict: true };
mockReadConfigFile.mockReturnValue({ config: { compilerOptions } });

const { service } = createProjectService(
{
allowDefaultProjectForFiles: ['file.js'],
defaultProject: './tsconfig.json',
},
undefined,
);

expect(service.setCompilerOptionsForInferredProjects).toHaveBeenCalledWith(
compilerOptions,
);
});
});
Loading