Skip to content
This repository was archived by the owner on Oct 23, 2025. It is now read-only.
Draft
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
11 changes: 11 additions & 0 deletions lib/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ const options = [
description: 'Recursively look into files until the project is clean',
default: false,
},
{
name: 'read-package-json',
alias: 'P',
type: 'boolean',
description: 'Load entrypoints defined in package.json',
default: false,
},
{
name: 'include-d-ts',
type: 'boolean',
Expand Down Expand Up @@ -76,6 +83,9 @@ Examples:
# Check unused code for a project with a custom tsconfig.json
tsr --project tsconfig.app.json 'src/main\\.ts$'

# Load entrypoints from package.json
tsr --read-package-json

# Check unused code for a project with multiple entrypoints in src/pages
tsr 'src/pages/.*\\.ts$'

Expand Down Expand Up @@ -105,6 +115,7 @@ const main = () => {
configFile: parsed.project || 'tsconfig.json',
recursive: parsed.recursive,
includeDts: parsed['include-d-ts'],
readPackageJson: parsed['read-package-json'],
}).catch((error) => {
if (error instanceof CheckResultError || error instanceof ArgError) {
process.exitCode = 1;
Expand Down
9 changes: 9 additions & 0 deletions lib/tsr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { relative, resolve } from 'node:path';
import { formatCount } from './util/formatCount.js';
import { CliOutput } from './util/CliOutput.js';
import { ArgError, CheckResultError } from './util/error.js';
import { loadEntrypoints } from './util/loadEntrypoints.js';

const createNodeJsLogger = (): Logger =>
'isTTY' in stdout && stdout.isTTY
Expand All @@ -34,6 +35,7 @@ export type Config = {
system?: ts.System;
logger?: Logger;
includeDts?: boolean;
readPackageJson?: boolean;
};

// is async for backwards compatibility
Expand All @@ -46,6 +48,7 @@ export const tsr = async ({
system = ts.sys,
logger = createNodeJsLogger(),
includeDts = false,
readPackageJson = false,
}: Config) => {
const configPath = resolve(projectRoot, configFile);

Expand All @@ -63,6 +66,12 @@ export const tsr = async ({
fileNames.map((n) => [n, system.readFile(n) || '']),
);

if (readPackageJson) {
fileService.set('/package.json', system.readFile('package.json') || '');
entrypoints = entrypoints.concat(loadEntrypoints({ options, fileService }));
fileService.delete('/package.json');
}

const entrypointFiles = fileNames.filter(
(fileName) =>
entrypoints.some((regex) => regex.test(fileName)) ||
Expand Down
32 changes: 32 additions & 0 deletions lib/util/loadEntrypoints.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it } from 'node:test';
import { MemoryFileService } from './MemoryFileService.js';
import assert from 'node:assert/strict';
import ts from 'typescript';
import { loadEntrypoints } from './loadEntrypoints.js';

describe('loadEntrypoints', () => {
it('should load entrypoints from package.json using tsconfig as reference', async () => {
const options: ts.CompilerOptions = {
rootDir: '/src',
outDir: '/dist',
};
const fileService = new MemoryFileService();
fileService.set(
'/package.json',
JSON.stringify({
bin: './dist/cli.js',
main: './dist/index.js',
exports: { '.': 'dist/default-export.js' },
}),
);
fileService.set(
'/src/index.ts',
`export const a = 'a'; export const a2 = 'a2';`,
);
assert.deepEqual(loadEntrypoints({ options, fileService }), [
new RegExp(/^\/src\/cli\.(js|jsx|ts|tsx|mjs|mts)$/),
new RegExp(/^\/src\/index\.(js|jsx|ts|tsx|mjs|mts)$/),
new RegExp(/^\/src\/default\x2dexport\.(js|jsx|ts|tsx|mjs|mts)$/),
]);
});
});
68 changes: 68 additions & 0 deletions lib/util/loadEntrypoints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import path from 'node:path';
import type ts from 'typescript';
import { FileService } from './FileService.js';
import escapeStringRegexp from 'escape-string-regexp';

// circular references https://github.com/microsoft/TypeScript/issues/3496#issuecomment-128553540
type PackageJsonExports = string | PackageJsonExportsObject;
interface PackageJsonExportsObject {
[x: string]: PackageJsonExports;
}

interface PackageJson {
// https://nodejs.org/api/packages.html#package-entry-points
// https://nodejs.org/api/packages.html#conditional-exports
bin?: string;
main?: string;
exports?: PackageJsonExports;
}

function findPackageJsonExportsEntries(
exports: PackageJsonExports,
results: string[],
): void {
if (typeof exports === 'string') results.push(exports);
if (exports !== null && typeof exports === 'object')
for (const value of Object.values(exports))
findPackageJsonExportsEntries(value, results);
}

export const loadEntrypoints = ({
options,
fileService,
}: {
options: ts.CompilerOptions;
fileService: FileService;
}): RegExp[] => {
if (!options.outDir || !options.rootDir) return [];

const packageJson = JSON.parse(
fileService.get('/package.json'),
) as PackageJson;

const entries = [];

if (packageJson.bin) entries.push(packageJson.bin);
if (packageJson.main) entries.push(packageJson.main);
if (packageJson.exports)
findPackageJsonExportsEntries(packageJson.exports, entries);

const outDir = path.basename(options.outDir);

return entries.map((entry) => {
const ext = path.extname(entry);

const relativePath = path.relative(outDir, entry);
const rootDirRelative = path.join(options.rootDir!, relativePath);

// remove extension
const dirname = path.dirname(rootDirRelative);
const base = path.basename(rootDirRelative, ext);

const fullPathNoExt = path.join(dirname, base);

return new RegExp(
`^${escapeStringRegexp(fullPathNoExt)}\\.(js|jsx|ts|tsx|mjs|mts)$`,
);
});
};
41 changes: 30 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"typescript-eslint": "^8.14.0"
},
"dependencies": {
"escape-string-regexp": "^5.0.0",
"mri": "^1.2.0",
"picocolors": "^1.1.1"
},
Expand Down