tsc-after 0.2.0 โ 0.4.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.
- package/README.md +74 -39
- package/bin/tsc-after.js +3 -0
- package/dist/tscAfter.js +328 -0
- package/dist/typescript7Compiler-D2MC51P1.js +220 -0
- package/dist/typescriptPre7Compiler-DdKME3sA.js +67 -0
- package/package.json +37 -32
- package/bin/tsc-after +0 -3
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -191
- package/dist/package.js +0 -5
package/README.md
CHANGED
|
@@ -1,50 +1,90 @@
|
|
|
1
1
|
<h1 align="center">tsc-after</h1>
|
|
2
2
|
|
|
3
|
-
<p align="center">
|
|
4
|
-
Your <code>dist</code>, as <code>tsc</code> should've left it.
|
|
5
|
-
<code>tsconfig</code>-aware. Just run <code>tsc && tsc-after</code>.
|
|
6
|
-
๐งน
|
|
7
|
-
</p>
|
|
3
|
+
<p align="center">Your <code>dist</code>, as <code>tsc</code> should've left it. ๐งน</p>
|
|
8
4
|
|
|
9
5
|
<p align="center">
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
<a href="
|
|
13
|
-
<!-- ALL-CONTRIBUTORS-BADGE:END -->
|
|
14
|
-
<!-- prettier-ignore-end -->
|
|
15
|
-
<a href="https://github.com/michal-kocarek/tsc-after/blob/main/.github/CODE_OF_CONDUCT.md" target="_blank"><img alt="๐ค Code of Conduct: Kept" src="https://img.shields.io/badge/%F0%9F%A4%9D_code_of_conduct-kept-21bb42" /></a>
|
|
16
|
-
<a href="https://codecov.io/gh/michal-kocarek/tsc-after" target="_blank"><img alt="๐งช Coverage" src="https://img.shields.io/codecov/c/github/michal-kocarek/tsc-after?label=%F0%9F%A7%AA%20coverage" /></a>
|
|
17
|
-
<a href="https://github.com/michal-kocarek/tsc-after/blob/main/LICENSE.md" target="_blank"><img alt="๐ License: MIT" src="https://img.shields.io/badge/%F0%9F%93%9D_license-MIT-21bb42.svg" /></a>
|
|
18
|
-
<a href="http://npmjs.com/package/tsc-after" target="_blank"><img alt="๐ฆ npm version" src="https://img.shields.io/npm/v/tsc-after?color=21bb42&label=%F0%9F%93%A6%20npm" /></a>
|
|
19
|
-
<img alt="๐ช TypeScript: Strict" src="https://img.shields.io/badge/%F0%9F%92%AA_typescript-strict-21bb42.svg" />
|
|
6
|
+
<a href="https://npmjs.com/package/tsc-after"><img alt="npm version" src="https://img.shields.io/npm/v/tsc-after" /></a>
|
|
7
|
+
<a href="https://codecov.io/gh/michal-kocarek/tsc-after"><img alt="Coverage" src="https://img.shields.io/codecov/c/github/michal-kocarek/tsc-after" /></a>
|
|
8
|
+
<a href="./LICENSE.md"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-blue" /></a>
|
|
20
9
|
</p>
|
|
21
10
|
|
|
11
|
+
`tsc` compiles your files, but it never deletes anything.
|
|
12
|
+
Rename `foo.ts` to `foo/index.ts`, and `dist/foo.js` lives on forever.
|
|
13
|
+
|
|
14
|
+
`tsc-after` reads your `tsconfig.json`, works out which files `tsc` would emit today, and removes the stale outputs it wouldn't.
|
|
15
|
+
|
|
22
16
|
## Usage
|
|
23
17
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
18
|
+
In `package.json`, replace the clean-then-compile command:
|
|
19
|
+
|
|
20
|
+
```diff
|
|
21
|
+
- rm -rf dist && tsc
|
|
22
|
+
+ tsc && tsc-after
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Additional usage:
|
|
27
26
|
|
|
28
27
|
```sh
|
|
29
|
-
|
|
28
|
+
# Clean after compile; run after tsc build.
|
|
29
|
+
tsc-after
|
|
30
|
+
|
|
31
|
+
# Preview planned removals for tsconfig.json.
|
|
32
|
+
tsc-after --dry
|
|
33
|
+
|
|
34
|
+
# Select a tsconfig file instead of the default.
|
|
35
|
+
tsc-after --project tsconfig.build.json
|
|
36
|
+
|
|
37
|
+
# Select a folder with a tsconfig.json.
|
|
38
|
+
tsc-after -p packages/core
|
|
30
39
|
```
|
|
31
40
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
41
|
+
`tsc-after` asks TypeScript which files the project emits, then removes every other regular file in `outDir` and `declarationDir`, along with directories left empty.
|
|
42
|
+
It skips symbolic links and entries on other devices.
|
|
43
|
+
|
|
44
|
+
`--dry` lists planned removals without changing files.
|
|
45
|
+
Use `--verbose` to add individual removed and skipped entries.
|
|
35
46
|
|
|
36
|
-
|
|
37
|
-
It may remove any regular file there that TypeScript would not emit from the current project, including copied assets.
|
|
38
|
-
Until `--copy` is available, if your build copies assets into `dist`, run cleanup before the copy step (for example, `tsc && tsc-after && cp assets/* dist/assets/`) or use a separate directory.
|
|
39
|
-
An `--exclude` option may be added later.
|
|
47
|
+
## Limitations
|
|
40
48
|
|
|
41
|
-
|
|
49
|
+
`tsc-after` reads your tsconfig the way `tsc` does; this list covers only where it differs.
|
|
42
50
|
|
|
43
|
-
|
|
51
|
+
- `outDir` must be set and hold only TypeScript outputs, and so must `declarationDir` when set.
|
|
52
|
+
Anything else there, including copied assets, is removed as stale.
|
|
53
|
+
- Cleanup is refused when `outDir` or `declarationDir` contains a source file or tsconfig file of the project.
|
|
54
|
+
- The project must be inside the current working directory, and parent directories are not searched for `tsconfig.json`.
|
|
55
|
+
- `noEmit`, `outFile`, `composite`, watch options, `incremental`, and `tsBuildInfoFile` ([#4](https://github.com/michal-kocarek/tsc-after/issues/4)) are rejected, and project references are not followed.
|
|
56
|
+
- TypeScript 3.9 through 4.1 require `rootDir`.
|
|
57
|
+
- TypeScript 7.1 beta support is experimental, and `extends` there must be a file path, not a package name.
|
|
58
|
+
- Safety checks ([#6](https://github.com/michal-kocarek/tsc-after/issues/6)) and output coverage ([#7](https://github.com/michal-kocarek/tsc-after/issues/7)) are incomplete, so keep valuable files out of `outDir`.
|
|
44
59
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
60
|
+
Planned: `--copy`, `--exclude`, and `--watch`.
|
|
61
|
+
See [`product.md`](./docs/product.md) for the roadmap.
|
|
62
|
+
|
|
63
|
+
## Requirements
|
|
64
|
+
|
|
65
|
+
- Node.js `^16.19.0 || >=18.11.0`.
|
|
66
|
+
- TypeScript 3.9.10+, 4.xโ6.x, and 7.1.0-beta through 7.x are supported; TypeScript 7.0 is not.
|
|
67
|
+
|
|
68
|
+
## Exit codes
|
|
69
|
+
|
|
70
|
+
- `0` for success, including a dry run or nothing to remove
|
|
71
|
+
- `1` for a configuration or cleanup error
|
|
72
|
+
- `2` for invalid command-line arguments
|
|
73
|
+
|
|
74
|
+
## Why not `rm -rf dist && tsc`?
|
|
75
|
+
|
|
76
|
+
Wiping `outDir` before every build (`rm -rf dist && tsc`, `rimraf dist && tsc`, or a `prebuild` script) is the usual fix for stale outputs.
|
|
77
|
+
On GitHub, about 274k `package.json` files run `rm -rf dist` and another 199k run `rimraf dist` (see [`market-research.md`](./docs/market-research.md)).
|
|
78
|
+
|
|
79
|
+
`tsc-after` is intended to remove only stale outputs rather than wiping `outDir` and rebuilding everything.
|
|
80
|
+
|
|
81
|
+
**Using a bundler such as tsup, Vite, or esbuild?**<br>
|
|
82
|
+
They already clean up after themselves, so you probably don't need `tsc-after`.
|
|
83
|
+
|
|
84
|
+
## Contributing
|
|
85
|
+
|
|
86
|
+
See [`CONTRIBUTING.md`](./.github/CONTRIBUTING.md) and [`DEVELOPMENT.md`](./.github/DEVELOPMENT.md).
|
|
87
|
+
For project-specific AI agent guidance, see [`AGENTS.md`](./AGENTS.md).
|
|
48
88
|
|
|
49
89
|
## Contributors
|
|
50
90
|
|
|
@@ -52,14 +92,9 @@ Thanks! ๐งน
|
|
|
52
92
|
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
|
|
53
93
|
<!-- prettier-ignore-start -->
|
|
54
94
|
<!-- markdownlint-disable -->
|
|
55
|
-
<
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
<td align="center"><a href="https://github.com/michal-kocarek"><img src="https://avatars.githubusercontent.com/u/762095?v=4?s=100" width="100px;" alt="Michal Koฤรกrek"/><br /><sub><b>Michal Koฤรกrek</b></sub></a><br /><a href="https://github.com/michal-kocarek/tsc-after/commits?author=michal-kocarek" title="Code">๐ป</a> <a href="#content-michal-kocarek" title="Content">๐</a> <a href="https://github.com/michal-kocarek/tsc-after/commits?author=michal-kocarek" title="Documentation">๐</a> <a href="#ideas-michal-kocarek" title="Ideas, Planning, & Feedback">๐ค</a> <a href="#infra-michal-kocarek" title="Infrastructure (Hosting, Build-Tools, etc)">๐</a> <a href="#maintenance-michal-kocarek" title="Maintenance">๐ง</a> <a href="#projectManagement-michal-kocarek" title="Project Management">๐</a> <a href="#tool-michal-kocarek" title="Tools">๐ง</a></td>
|
|
59
|
-
</tr>
|
|
60
|
-
</tbody>
|
|
61
|
-
</table>
|
|
62
|
-
|
|
95
|
+
<ul>
|
|
96
|
+
<li><a href="https://github.com/michal-kocarek">Michal Koฤรกrek</a> <span title="Code">๐ป</span> <span title="Content">๐</span> <span title="Documentation">๐</span> <span title="Ideas, Planning, & Feedback">๐ค</span> <span title="Infrastructure (Hosting, Build-Tools, etc)">๐</span> <span title="Maintenance">๐ง</span> <span title="Project Management">๐</span> <span title="Tools">๐ง</span></li>
|
|
97
|
+
</ul>
|
|
63
98
|
<!-- markdownlint-restore -->
|
|
64
99
|
<!-- prettier-ignore-end -->
|
|
65
100
|
|
package/bin/tsc-after.js
ADDED
package/dist/tscAfter.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import * as util from "node:util";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
// src/common/errors.ts
|
|
6
|
+
/** Error whose message is human-readable and printed to the user without a stack trace. */
|
|
7
|
+
var UserError = class extends Error {};
|
|
8
|
+
function assertUnreachable(value) {
|
|
9
|
+
throw new Error("Unreachable code reached.", { cause: value });
|
|
10
|
+
}
|
|
11
|
+
function isNodeErrorOf(error, errorClass, code) {
|
|
12
|
+
if (!(error instanceof errorClass)) return false;
|
|
13
|
+
if (code === void 0) return true;
|
|
14
|
+
return "code" in error && error.code === code;
|
|
15
|
+
}
|
|
16
|
+
// src/common/constants.ts
|
|
17
|
+
const binName = "tsc-after";
|
|
18
|
+
const cliArgsOptions = {
|
|
19
|
+
help: {
|
|
20
|
+
default: false,
|
|
21
|
+
helpDescription: "Print this message.",
|
|
22
|
+
short: "h",
|
|
23
|
+
type: "boolean"
|
|
24
|
+
},
|
|
25
|
+
version: {
|
|
26
|
+
default: false,
|
|
27
|
+
helpDescription: "Print the version.",
|
|
28
|
+
type: "boolean"
|
|
29
|
+
},
|
|
30
|
+
project: {
|
|
31
|
+
default: "tsconfig.json",
|
|
32
|
+
helpDescription: "Use the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.",
|
|
33
|
+
short: "p",
|
|
34
|
+
type: "string"
|
|
35
|
+
},
|
|
36
|
+
noClean: {
|
|
37
|
+
default: false,
|
|
38
|
+
helpDescription: "Disable removing stale outputs from 'outDir'.",
|
|
39
|
+
type: "boolean"
|
|
40
|
+
},
|
|
41
|
+
dry: {
|
|
42
|
+
default: false,
|
|
43
|
+
helpDescription: "Show what would be deleted.",
|
|
44
|
+
short: "d",
|
|
45
|
+
type: "boolean"
|
|
46
|
+
},
|
|
47
|
+
verbose: {
|
|
48
|
+
default: false,
|
|
49
|
+
helpDescription: "Enable verbose logging.",
|
|
50
|
+
type: "boolean"
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
// src/common/util.ts
|
|
54
|
+
const EXIT_CODE_ERROR = 1;
|
|
55
|
+
const EXIT_CODE_INVALID_ARGUMENTS = 2;
|
|
56
|
+
/**
|
|
57
|
+
* `util.styleText()` exists only from Node.js 20.12 / 21.7; older versions get plain text.
|
|
58
|
+
*/
|
|
59
|
+
const styleText = "styleText" in util ? util.styleText : (_format, text) => text;
|
|
60
|
+
function print(...messages) {
|
|
61
|
+
console.log(messages.join(" "));
|
|
62
|
+
}
|
|
63
|
+
function printError(...messages) {
|
|
64
|
+
console.error(styleText("red", `error: ${messages.join(" ")}`));
|
|
65
|
+
if ((process.exitCode ?? 0) === 0) process.exitCode = EXIT_CODE_ERROR;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* List of error codes that `util.parseArgs()` can throw
|
|
69
|
+
* @see https://nodejs.org/docs/latest/api/errors.html#nodejs-error-codes
|
|
70
|
+
*/
|
|
71
|
+
const PARSE_ARGS_ERROR_CODES = [
|
|
72
|
+
"ERR_PARSE_ARGS_UNKNOWN_OPTION",
|
|
73
|
+
"ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",
|
|
74
|
+
"ERR_PARSE_ARGS_INVALID_OPTION_VALUE"
|
|
75
|
+
];
|
|
76
|
+
function parseArgs(args) {
|
|
77
|
+
try {
|
|
78
|
+
return util.parseArgs({
|
|
79
|
+
args,
|
|
80
|
+
options: cliArgsOptions
|
|
81
|
+
});
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (isParseArgsError(error)) {
|
|
84
|
+
process.exitCode = EXIT_CODE_INVALID_ARGUMENTS;
|
|
85
|
+
throw new UserError(error.message.endsWith(".") ? error.message : `${error.message}.`);
|
|
86
|
+
}
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function isParseArgsError(error) {
|
|
91
|
+
return PARSE_ARGS_ERROR_CODES.some((code) => isNodeErrorOf(error, TypeError, code));
|
|
92
|
+
}
|
|
93
|
+
// src/tasks/help.ts
|
|
94
|
+
const FLAG_INDENT = 2;
|
|
95
|
+
const FLAG_GAP = " ";
|
|
96
|
+
function help() {
|
|
97
|
+
const flags = Object.entries(cliArgsOptions).map(([name, opts]) => ({
|
|
98
|
+
description: opts.helpDescription,
|
|
99
|
+
name: "short" in opts ? `--${name}, -${opts.short}` : `--${name}`
|
|
100
|
+
}));
|
|
101
|
+
const flagWidth = FLAG_INDENT + Math.max(...flags.map(({ name }) => name.length));
|
|
102
|
+
const heading = (text) => styleText("bold", text);
|
|
103
|
+
const command = (text, description) => ` ${styleText("blueBright", text)}\n ${description}`;
|
|
104
|
+
const flag = (name, description) => `${styleText("blueBright", name.padStart(flagWidth))}${FLAG_GAP}${description}`;
|
|
105
|
+
print([
|
|
106
|
+
`${styleText("bold", binName)}: Your outDir, as tsc should've left it.`,
|
|
107
|
+
heading("COMMON COMMANDS"),
|
|
108
|
+
command(`tsc && ${binName}`, "Removes stale outputs of the current project (tsconfig.json in the working directory)."),
|
|
109
|
+
command(`${binName} -p ./path/to/tsconfig.json`, "Removes stale outputs of the TypeScript project located at the specified path."),
|
|
110
|
+
command(`${binName} --dry`, "Shows what would be deleted from 'outDir', without deleting anything."),
|
|
111
|
+
heading("COMMAND LINE FLAGS"),
|
|
112
|
+
...flags.map(({ description, name }) => flag(name, description))
|
|
113
|
+
].join("\n\n"));
|
|
114
|
+
}
|
|
115
|
+
// src/common/paths.ts
|
|
116
|
+
function isPathInside(dirPath, filePath, useCaseSensitiveFileNames) {
|
|
117
|
+
const normalizedDirPath = useCaseSensitiveFileNames ? dirPath : dirPath.toLowerCase();
|
|
118
|
+
const normalizedFilePath = useCaseSensitiveFileNames ? filePath : filePath.toLowerCase();
|
|
119
|
+
const relativePath = path.relative(normalizedDirPath, normalizedFilePath);
|
|
120
|
+
return relativePath === "" || !path.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`);
|
|
121
|
+
}
|
|
122
|
+
const TYPESCRIPT_4_2 = 4002e3;
|
|
123
|
+
function parseTypeScriptVersion(version) {
|
|
124
|
+
const match = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-[-.0-9A-Za-z]+)?(?:\+[-.0-9A-Za-z]+)?$/u.exec(version);
|
|
125
|
+
if (match?.groups === void 0) return NaN;
|
|
126
|
+
const { major, minor, patch } = match.groups;
|
|
127
|
+
return Number(major) * 1e6 + Number(minor) * 1e3 + Number(patch);
|
|
128
|
+
}
|
|
129
|
+
const typescriptVersion = parseTypeScriptVersion(ts.version);
|
|
130
|
+
// src/common/typescript/loadCompiler.ts
|
|
131
|
+
async function loadCompiler() {
|
|
132
|
+
if (typescriptVersion < 3009e3) throw new UserError("TypeScript 3.8 and earlier are not supported. Use TypeScript 3.9 or later.");
|
|
133
|
+
if (typescriptVersion < 7e6) {
|
|
134
|
+
const { TypeScriptPre7Compiler } = await import("./typescriptPre7Compiler-DdKME3sA.js");
|
|
135
|
+
return new TypeScriptPre7Compiler();
|
|
136
|
+
}
|
|
137
|
+
if (typescriptVersion < 7001e3) throw new UserError("TypeScript 7.0 is not supported. Use TypeScript 7.1 or later.");
|
|
138
|
+
return (await import("./typescript7Compiler-D2MC51P1.js")).TypeScript7Compiler.create();
|
|
139
|
+
}
|
|
140
|
+
// src/tasks/mainAction.ts
|
|
141
|
+
const MISSING_OUT_DIR_ERROR = "outDir is not set in tsconfig.json; tsc-after only cleans a dedicated outDir. Set compilerOptions.outDir, e.g. \"dist\".";
|
|
142
|
+
const NO_EMIT_ERROR = "Refusing to clean outDir because noEmit is enabled.";
|
|
143
|
+
const DECLARATION_DISABLED_ERROR = "Refusing to clean declarationDir because declaration is not enabled.";
|
|
144
|
+
async function mainAction(args) {
|
|
145
|
+
const cwd = process.cwd();
|
|
146
|
+
const compiler = await loadCompiler();
|
|
147
|
+
let cleanupRoots;
|
|
148
|
+
let expectedOutDirPaths;
|
|
149
|
+
let outDirAbsolutePath;
|
|
150
|
+
try {
|
|
151
|
+
const isPathInsideWithCompiler = (dirPath, filePath) => isPathInside(dirPath, filePath, compiler.useCaseSensitiveFileNames);
|
|
152
|
+
const projectAbsolutePath = path.resolve(cwd, args.values.project);
|
|
153
|
+
if (!isPathInsideWithCompiler(cwd, projectAbsolutePath)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
|
|
154
|
+
const tsconfigAbsolutePath = fs.existsSync(projectAbsolutePath) && fs.statSync(projectAbsolutePath).isDirectory() ? path.join(projectAbsolutePath, "tsconfig.json") : projectAbsolutePath;
|
|
155
|
+
if (!isPathInsideWithCompiler(cwd, tsconfigAbsolutePath) || isPathInsideWithCompiler(tsconfigAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
|
|
156
|
+
print(`Using tsconfig: ${path.relative(cwd, tsconfigAbsolutePath)}`);
|
|
157
|
+
const project = compiler.parseProject(tsconfigAbsolutePath);
|
|
158
|
+
if (project.options.noEmit === true) throw new UserError(NO_EMIT_ERROR);
|
|
159
|
+
if (project.options.outFile !== void 0) throw new UserError("outFile is not supported");
|
|
160
|
+
if (project.options.outDir === void 0) throw new UserError(MISSING_OUT_DIR_ERROR);
|
|
161
|
+
outDirAbsolutePath = path.resolve(project.options.outDir);
|
|
162
|
+
const roots = [{
|
|
163
|
+
name: "outDir",
|
|
164
|
+
path: outDirAbsolutePath,
|
|
165
|
+
relativePath: path.relative(cwd, outDirAbsolutePath)
|
|
166
|
+
}];
|
|
167
|
+
if (project.options.declarationDir !== void 0) {
|
|
168
|
+
if (project.options.declaration !== true) throw new UserError(DECLARATION_DISABLED_ERROR);
|
|
169
|
+
const declarationDir = path.resolve(project.options.declarationDir);
|
|
170
|
+
roots.push({
|
|
171
|
+
name: "declarationDir",
|
|
172
|
+
path: declarationDir,
|
|
173
|
+
relativePath: path.relative(cwd, declarationDir)
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
if (project.options.incremental === true) throw new UserError("Incremental mode is not supported");
|
|
177
|
+
if (project.options.tsBuildInfoFile !== void 0) throw new UserError("tsBuildInfoFile is not supported");
|
|
178
|
+
if (project.options.composite === true) throw new UserError("Composite mode is not supported");
|
|
179
|
+
if (project.options.project !== void 0) throw new UserError("Project mode is not supported");
|
|
180
|
+
if (project.hasWatchOptions) throw new UserError("Watch mode is not supported");
|
|
181
|
+
for (const root of roots) {
|
|
182
|
+
if (!isPathInsideWithCompiler(cwd, root.path) || isPathInsideWithCompiler(root.path, cwd)) throw new UserError(`Refusing to traverse outside safe paths containing tsconfig to process ${root.name}!`);
|
|
183
|
+
const isInsideRoot = (filePath) => isPathInsideWithCompiler(root.path, filePath) || isPathInsideWithCompiler(root.path, fs.realpathSync(filePath));
|
|
184
|
+
for (const file of project.programFileNames) if (isInsideRoot(path.resolve(file))) throw new UserError(`Refusing to clean ${root.name} '${root.relativePath}': it contains source file '${path.relative(cwd, file)}'.`);
|
|
185
|
+
for (const file of project.configFilePaths) if (isInsideRoot(path.resolve(file))) throw new UserError(`Refusing to clean ${root.name} '${root.relativePath}': it contains config file '${path.relative(cwd, file)}'.`);
|
|
186
|
+
try {
|
|
187
|
+
fs.lstatSync(root.path);
|
|
188
|
+
if (fs.realpathSync(root.path) !== root.path) throw new UserError(`Refusing to clean ${root.name} through a symbolic link: ${root.relativePath}!`);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (!isNodeErrorOf(error, Error, "ENOENT")) throw error;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
cleanupRoots = roots.filter((root) => root.name === "outDir" || !isPathInsideWithCompiler(outDirAbsolutePath, root.path));
|
|
194
|
+
if (args.values.noClean) return;
|
|
195
|
+
expectedOutDirPaths = compiler.getOutputPaths(project);
|
|
196
|
+
} finally {
|
|
197
|
+
compiler.close();
|
|
198
|
+
}
|
|
199
|
+
function readDir(dirPath) {
|
|
200
|
+
const verdicts = [];
|
|
201
|
+
const stat = fs.lstatSync(dirPath);
|
|
202
|
+
if (!stat.isDirectory()) throw new UserError(`Not a directory ${dirPath}!`);
|
|
203
|
+
let dirIsEmpty = true;
|
|
204
|
+
for (const child of fs.readdirSync(dirPath).sort()) {
|
|
205
|
+
const fullPath = path.join(dirPath, child);
|
|
206
|
+
const fullPathStat = fs.lstatSync(fullPath);
|
|
207
|
+
if (fullPathStat.dev !== stat.dev) {
|
|
208
|
+
if (args.values.verbose) verdicts.push({
|
|
209
|
+
path: fullPath,
|
|
210
|
+
reason: "different device",
|
|
211
|
+
type: "skipped"
|
|
212
|
+
});
|
|
213
|
+
dirIsEmpty = false;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (fullPathStat.isSymbolicLink()) {
|
|
217
|
+
if (args.values.verbose) verdicts.push({
|
|
218
|
+
path: fullPath,
|
|
219
|
+
reason: "symbolic link",
|
|
220
|
+
type: "skipped"
|
|
221
|
+
});
|
|
222
|
+
dirIsEmpty = false;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (fullPathStat.isFile()) {
|
|
226
|
+
if (expectedOutDirPaths.has(fullPath)) {
|
|
227
|
+
if (args.values.verbose) verdicts.push({
|
|
228
|
+
path: fullPath,
|
|
229
|
+
reason: "expected output file",
|
|
230
|
+
type: "skipped"
|
|
231
|
+
});
|
|
232
|
+
dirIsEmpty = false;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
verdicts.push({
|
|
236
|
+
path: fullPath,
|
|
237
|
+
type: "removeFile"
|
|
238
|
+
});
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (fullPathStat.isDirectory()) {
|
|
242
|
+
const result = readDir(fullPath);
|
|
243
|
+
verdicts.push(...result.verdicts);
|
|
244
|
+
if (!result.dirIsEmpty) dirIsEmpty = false;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
dirIsEmpty = false;
|
|
248
|
+
}
|
|
249
|
+
if (dirIsEmpty) verdicts.push({
|
|
250
|
+
path: dirPath,
|
|
251
|
+
type: "removeDir"
|
|
252
|
+
});
|
|
253
|
+
else verdicts.push({
|
|
254
|
+
path: dirPath,
|
|
255
|
+
reason: "directory not empty",
|
|
256
|
+
type: "skipped"
|
|
257
|
+
});
|
|
258
|
+
return {
|
|
259
|
+
dirIsEmpty,
|
|
260
|
+
verdicts
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
const results = cleanupRoots.map((root) => {
|
|
264
|
+
try {
|
|
265
|
+
fs.lstatSync(root.path);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (!isNodeErrorOf(error, Error, "ENOENT")) throw error;
|
|
268
|
+
return { verdicts: [] };
|
|
269
|
+
}
|
|
270
|
+
return readDir(root.path);
|
|
271
|
+
});
|
|
272
|
+
const { dry, verbose } = args.values;
|
|
273
|
+
const removeVerb = dry ? "Would remove" : "Removed";
|
|
274
|
+
for (const [index, root] of cleanupRoots.entries()) {
|
|
275
|
+
const result = results[index];
|
|
276
|
+
if (result === void 0) throw new Error("Missing cleanup result.");
|
|
277
|
+
let fileCount = 0;
|
|
278
|
+
let dirCount = 0;
|
|
279
|
+
for (const verdict of result.verdicts) {
|
|
280
|
+
if (root.name === "declarationDir" && isPathInside(outDirAbsolutePath, verdict.path, compiler.useCaseSensitiveFileNames)) continue;
|
|
281
|
+
const displayPath = path.relative(cwd, verdict.path);
|
|
282
|
+
switch (verdict.type) {
|
|
283
|
+
case "removeDir":
|
|
284
|
+
if (!dry) fs.rmdirSync(verdict.path);
|
|
285
|
+
dirCount++;
|
|
286
|
+
if (dry || verbose) print(`${removeVerb} empty directory: ${displayPath}`);
|
|
287
|
+
break;
|
|
288
|
+
case "removeFile":
|
|
289
|
+
if (!dry) fs.rmSync(verdict.path, { recursive: false });
|
|
290
|
+
fileCount++;
|
|
291
|
+
if (dry || verbose) print(`${removeVerb} file: ${displayPath}`);
|
|
292
|
+
break;
|
|
293
|
+
case "skipped":
|
|
294
|
+
if (verbose) print(`Skipped (${verdict.reason}): ${displayPath}`);
|
|
295
|
+
break;
|
|
296
|
+
default: assertUnreachable(verdict);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const parts = [];
|
|
300
|
+
if (fileCount > 0) parts.push(formatCount(fileCount, "file", "files"));
|
|
301
|
+
if (dirCount > 0) parts.push(formatCount(dirCount, "empty directory", "empty directories"));
|
|
302
|
+
if (parts.length > 0) print(`${binName}: ${removeVerb} ${parts.join(" and ")} from ${styleText("italic", root.relativePath)}`);
|
|
303
|
+
else if (dry || cleanupRoots.length > 1) print(`${binName}: Nothing to remove from ${styleText("italic", root.relativePath)}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function formatCount(count, singular, plural) {
|
|
307
|
+
return `${count.toFixed()} ${count === 1 ? singular : plural}`;
|
|
308
|
+
}
|
|
309
|
+
// package.json
|
|
310
|
+
var version$1 = "0.4.0";
|
|
311
|
+
// src/tasks/version.ts
|
|
312
|
+
function version() {
|
|
313
|
+
print(`${binName}/${version$1} ${process.platform}-${process.arch} node-${process.versions.node} typescript-${ts.version}`);
|
|
314
|
+
}
|
|
315
|
+
// src/entrypoints/tscAfter.ts
|
|
316
|
+
async function main() {
|
|
317
|
+
try {
|
|
318
|
+
const args = parseArgs(process.argv.slice(2));
|
|
319
|
+
if (args.values.version) version();
|
|
320
|
+
else if (args.values.help) help();
|
|
321
|
+
else await mainAction(args);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
if (!(error instanceof UserError)) throw error;
|
|
324
|
+
printError(error.message);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
main();
|
|
328
|
+
export { typescriptVersion as n, UserError as r, TYPESCRIPT_4_2 as t };
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { r as UserError } from "./tscAfter.js";
|
|
4
|
+
// src/common/typescript/outputPaths.ts
|
|
5
|
+
function getOutputFileNames(options, fileName) {
|
|
6
|
+
const sourcePath = path.resolve(fileName);
|
|
7
|
+
const sourceExtension = path.extname(sourcePath);
|
|
8
|
+
if (isDeclarationFile(sourcePath)) return [];
|
|
9
|
+
const isJsonFile = sourceExtension === ".json";
|
|
10
|
+
if ((sourceExtension === ".js" || sourceExtension === ".jsx" || sourceExtension === ".mjs" || sourceExtension === ".cjs") && options.allowJs !== true) return [];
|
|
11
|
+
const outputFileNames = [];
|
|
12
|
+
const outputPath = getOutputPath(sourcePath, resolveOptionPath(options.outDir, options.configFilePath), options.rootDir, options.configFilePath);
|
|
13
|
+
if (isJsonFile) {
|
|
14
|
+
outputFileNames.push(outputPath);
|
|
15
|
+
return outputFileNames;
|
|
16
|
+
}
|
|
17
|
+
const javaScriptExtension = getJavaScriptExtension(sourceExtension, options.jsx);
|
|
18
|
+
if (javaScriptExtension === void 0) return [];
|
|
19
|
+
if (options.emitDeclarationOnly !== true) {
|
|
20
|
+
const javaScriptPath = replaceExtension(outputPath, javaScriptExtension);
|
|
21
|
+
outputFileNames.push(javaScriptPath);
|
|
22
|
+
if (options.sourceMap === true) outputFileNames.push(`${javaScriptPath}.map`);
|
|
23
|
+
}
|
|
24
|
+
if (options.declaration === true || options.composite === true) {
|
|
25
|
+
const declarationPath = replaceExtension(getOutputPath(sourcePath, resolveOptionPath(options.declarationDir ?? options.outDir, options.configFilePath), options.rootDir, options.configFilePath), getDeclarationExtension(sourceExtension));
|
|
26
|
+
outputFileNames.push(declarationPath);
|
|
27
|
+
if (options.declarationMap === true) outputFileNames.push(`${declarationPath}.map`);
|
|
28
|
+
}
|
|
29
|
+
return outputFileNames;
|
|
30
|
+
}
|
|
31
|
+
function getDeclarationExtension(sourceExtension) {
|
|
32
|
+
if (sourceExtension === ".mts" || sourceExtension === ".mjs") return ".d.mts";
|
|
33
|
+
if (sourceExtension === ".cts" || sourceExtension === ".cjs") return ".d.cts";
|
|
34
|
+
return ".d.ts";
|
|
35
|
+
}
|
|
36
|
+
function getJavaScriptExtension(sourceExtension, jsx) {
|
|
37
|
+
if (sourceExtension === ".tsx" || sourceExtension === ".jsx") return jsx === "preserve" ? ".jsx" : ".js";
|
|
38
|
+
if (sourceExtension === ".ts" || sourceExtension === ".js") return ".js";
|
|
39
|
+
if (sourceExtension === ".mts") return ".mjs";
|
|
40
|
+
if (sourceExtension === ".cts") return ".cjs";
|
|
41
|
+
if (sourceExtension === ".mjs" || sourceExtension === ".cjs") return sourceExtension;
|
|
42
|
+
}
|
|
43
|
+
function getOutputPath(sourcePath, outputDirectory, rootDir, configFilePath) {
|
|
44
|
+
if (outputDirectory === void 0) return sourcePath;
|
|
45
|
+
const resolvedRootDir = path.resolve(path.dirname(configFilePath), rootDir ?? ".");
|
|
46
|
+
return path.resolve(outputDirectory, path.relative(resolvedRootDir, sourcePath));
|
|
47
|
+
}
|
|
48
|
+
function isDeclarationFile(fileName) {
|
|
49
|
+
return fileName.endsWith(".d.ts") || fileName.endsWith(".d.mts") || fileName.endsWith(".d.cts");
|
|
50
|
+
}
|
|
51
|
+
function replaceExtension(fileName, extension) {
|
|
52
|
+
return `${fileName.slice(0, -path.extname(fileName).length)}${extension}`;
|
|
53
|
+
}
|
|
54
|
+
function resolveOptionPath(optionPath, configFilePath) {
|
|
55
|
+
return optionPath === void 0 ? void 0 : path.resolve(path.dirname(configFilePath), optionPath);
|
|
56
|
+
}
|
|
57
|
+
// src/common/typescript/typescript7Compiler.ts
|
|
58
|
+
const syncModuleSpecifier = "typescript/sync";
|
|
59
|
+
/**
|
|
60
|
+
* Uses the `typescript/sync` API for TypeScript 7.1 and later.
|
|
61
|
+
* The documented synchronous client fits this synchronous compiler contract.
|
|
62
|
+
*/
|
|
63
|
+
var TypeScript7Compiler = class TypeScript7Compiler {
|
|
64
|
+
useCaseSensitiveFileNames;
|
|
65
|
+
api;
|
|
66
|
+
cachedProject;
|
|
67
|
+
isClosed = false;
|
|
68
|
+
program;
|
|
69
|
+
projects = /* @__PURE__ */ new WeakMap();
|
|
70
|
+
typescriptSync;
|
|
71
|
+
constructor(typescriptSync, api) {
|
|
72
|
+
this.typescriptSync = typescriptSync;
|
|
73
|
+
this.api = api;
|
|
74
|
+
this.useCaseSensitiveFileNames = api.getCanonicalFileName("a") !== api.getCanonicalFileName("A");
|
|
75
|
+
}
|
|
76
|
+
static async create() {
|
|
77
|
+
const typescriptSyncModule = await import(syncModuleSpecifier);
|
|
78
|
+
if (!isTypeScript7SyncModule(typescriptSyncModule)) throw new UserError("Could not load the TypeScript 7.1 synchronous API.");
|
|
79
|
+
const apiValue = new typescriptSyncModule.API();
|
|
80
|
+
if (!isTypeScript7Api(apiValue)) throw new UserError("Could not initialize the TypeScript 7.1 synchronous API.");
|
|
81
|
+
const typescriptSync = typescriptSyncModule;
|
|
82
|
+
const api = apiValue;
|
|
83
|
+
try {
|
|
84
|
+
api.parseCommandLine([]);
|
|
85
|
+
return new TypeScript7Compiler(typescriptSync, api);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
api.close();
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
close() {
|
|
92
|
+
if (this.isClosed) return;
|
|
93
|
+
this.isClosed = true;
|
|
94
|
+
const program = this.program;
|
|
95
|
+
this.program = void 0;
|
|
96
|
+
this.cachedProject = void 0;
|
|
97
|
+
try {
|
|
98
|
+
program?.dispose();
|
|
99
|
+
} finally {
|
|
100
|
+
this.api.close();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
getOutputPaths(project) {
|
|
104
|
+
this.assertOpen();
|
|
105
|
+
const config = this.projects.get(project);
|
|
106
|
+
if (config === void 0) throw new Error("Project was not parsed by this compiler.");
|
|
107
|
+
if (this.cachedProject !== project) {
|
|
108
|
+
const previousProgram = this.program;
|
|
109
|
+
this.program = void 0;
|
|
110
|
+
this.cachedProject = void 0;
|
|
111
|
+
previousProgram?.dispose();
|
|
112
|
+
this.program = this.api.createProgram(config.fileNames, config.options);
|
|
113
|
+
this.cachedProject = project;
|
|
114
|
+
}
|
|
115
|
+
const program = this.program;
|
|
116
|
+
if (program === void 0) throw new Error("Could not create TypeScript program.");
|
|
117
|
+
const configFilePath = project.configFilePaths[0];
|
|
118
|
+
if (configFilePath === void 0) throw new Error("Project has no config file path.");
|
|
119
|
+
const outputOptions = {
|
|
120
|
+
...config.options,
|
|
121
|
+
configFilePath,
|
|
122
|
+
jsx: config.options.jsx === this.typescriptSync.JsxEmit.Preserve ? "preserve" : void 0
|
|
123
|
+
};
|
|
124
|
+
const outputPaths = program.getSourceFileNames().filter((fileName) => {
|
|
125
|
+
const metadata = program.getSourceFileMetadata(fileName);
|
|
126
|
+
return metadata !== void 0 && !metadata.isDefaultLibrary && !metadata.isFromExternalLibrary;
|
|
127
|
+
}).flatMap((fileName) => getOutputFileNames(outputOptions, fileName));
|
|
128
|
+
return new Set(outputPaths);
|
|
129
|
+
}
|
|
130
|
+
parseProject(configFilePath) {
|
|
131
|
+
this.assertOpen();
|
|
132
|
+
try {
|
|
133
|
+
fs.readFileSync(configFilePath);
|
|
134
|
+
} catch {
|
|
135
|
+
throw new UserError(`error TS5083: Cannot read file '${configFilePath}'.`);
|
|
136
|
+
}
|
|
137
|
+
const checkDiagnostics = (diagnostics) => {
|
|
138
|
+
if (diagnostics.length === 0) return;
|
|
139
|
+
throw new UserError(this.typescriptSync.formatDiagnosticsWithColorAndContext(diagnostics, {
|
|
140
|
+
getCanonicalFileName: (fileName) => this.api.getCanonicalFileName(fileName),
|
|
141
|
+
getCurrentDirectory: () => this.api.getCurrentDirectory(),
|
|
142
|
+
getNewLine: () => this.api.getNewLine()
|
|
143
|
+
}).trimEnd());
|
|
144
|
+
};
|
|
145
|
+
const readConfig = (filePath) => {
|
|
146
|
+
const result = this.api.readConfigFile(filePath);
|
|
147
|
+
if (result.error !== void 0) checkDiagnostics([result.error]);
|
|
148
|
+
return result.config;
|
|
149
|
+
};
|
|
150
|
+
const rootConfig = readConfig(configFilePath);
|
|
151
|
+
const config = this.api.parseConfigFile(configFilePath);
|
|
152
|
+
checkDiagnostics(config.errors);
|
|
153
|
+
const extendedConfigInfo = getExtendedConfigInfo(readConfig, configFilePath, rootConfig);
|
|
154
|
+
const program = this.api.createProgram(config.fileNames, config.options);
|
|
155
|
+
const project = {
|
|
156
|
+
configFilePaths: extendedConfigInfo.configFilePaths,
|
|
157
|
+
fileNames: config.fileNames,
|
|
158
|
+
hasWatchOptions: extendedConfigInfo.hasWatchOptions,
|
|
159
|
+
options: config.options,
|
|
160
|
+
programFileNames: program.getSourceFileNames().filter((fileName) => {
|
|
161
|
+
const metadata = program.getSourceFileMetadata(fileName);
|
|
162
|
+
return metadata !== void 0 && !metadata.isDefaultLibrary && !metadata.isFromExternalLibrary;
|
|
163
|
+
})
|
|
164
|
+
};
|
|
165
|
+
this.program?.dispose();
|
|
166
|
+
this.program = program;
|
|
167
|
+
this.cachedProject = project;
|
|
168
|
+
this.projects.set(project, config);
|
|
169
|
+
return project;
|
|
170
|
+
}
|
|
171
|
+
assertOpen() {
|
|
172
|
+
if (this.isClosed) throw new Error("Compiler is closed.");
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
function getExtendedConfigInfo(readConfig, configFilePath, rootConfig) {
|
|
176
|
+
const configFilePaths = /* @__PURE__ */ new Set();
|
|
177
|
+
let hasWatchOptions = false;
|
|
178
|
+
function visit(currentConfigFilePath, rawConfig) {
|
|
179
|
+
const normalizedConfigFilePath = path.resolve(currentConfigFilePath);
|
|
180
|
+
if (configFilePaths.has(normalizedConfigFilePath)) return;
|
|
181
|
+
configFilePaths.add(normalizedConfigFilePath);
|
|
182
|
+
if (!isRecord(rawConfig)) throw new UserError(`Could not safely read TypeScript config '${normalizedConfigFilePath}'.`);
|
|
183
|
+
hasWatchOptions ||= rawConfig["watchOptions"] !== void 0;
|
|
184
|
+
const extendsValue = rawConfig["extends"];
|
|
185
|
+
if (extendsValue === void 0) return;
|
|
186
|
+
const extendedConfigPaths = Array.isArray(extendsValue) ? extendsValue : [extendsValue];
|
|
187
|
+
for (const extendedConfigPath of extendedConfigPaths) {
|
|
188
|
+
if (typeof extendedConfigPath !== "string") throw new UserError(`Could not safely determine extended config paths for '${normalizedConfigFilePath}'.`);
|
|
189
|
+
const resolvedConfigPath = resolveExtendedConfigPath(normalizedConfigFilePath, extendedConfigPath);
|
|
190
|
+
visit(resolvedConfigPath, readConfig(resolvedConfigPath));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
visit(configFilePath, rootConfig);
|
|
194
|
+
return {
|
|
195
|
+
configFilePaths: [...configFilePaths],
|
|
196
|
+
hasWatchOptions
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function isRecord(value) {
|
|
200
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
201
|
+
}
|
|
202
|
+
function isTypeScript7Api(value) {
|
|
203
|
+
return isRecord(value) && typeof value["close"] === "function" && typeof value["createProgram"] === "function" && typeof value["getCanonicalFileName"] === "function" && typeof value["getCurrentDirectory"] === "function" && typeof value["getNewLine"] === "function" && typeof value["parseCommandLine"] === "function" && typeof value["parseConfigFile"] === "function" && typeof value["readConfigFile"] === "function";
|
|
204
|
+
}
|
|
205
|
+
function isTypeScript7SyncModule(value) {
|
|
206
|
+
if (!isRecord(value)) return false;
|
|
207
|
+
const jsxEmit = value["JsxEmit"];
|
|
208
|
+
return typeof value["API"] === "function" && isRecord(jsxEmit) && typeof jsxEmit["Preserve"] === "number" && typeof value["formatDiagnosticsWithColorAndContext"] === "function";
|
|
209
|
+
}
|
|
210
|
+
function resolveExtendedConfigPath(configFilePath, extendsSpecifier) {
|
|
211
|
+
const specifier = extendsSpecifier.replaceAll("\\", "/");
|
|
212
|
+
if (path.isAbsolute(specifier) || specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
213
|
+
const basePath = path.resolve(path.dirname(configFilePath), specifier);
|
|
214
|
+
for (const candidatePath of [basePath, `${basePath}.json`]) try {
|
|
215
|
+
if (fs.statSync(candidatePath).isFile()) return candidatePath;
|
|
216
|
+
} catch {}
|
|
217
|
+
}
|
|
218
|
+
throw new UserError(`Could not safely determine extended config '${extendsSpecifier}' from '${configFilePath}'.`);
|
|
219
|
+
}
|
|
220
|
+
export { TypeScript7Compiler };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { n as typescriptVersion, r as UserError } from "./tscAfter.js";
|
|
3
|
+
// src/common/typescript/typescriptPre7Compiler.ts
|
|
4
|
+
/** Uses the `typescript` API for TypeScript 3.9 through 6.x. */
|
|
5
|
+
var TypeScriptPre7Compiler = class {
|
|
6
|
+
useCaseSensitiveFileNames;
|
|
7
|
+
parsedCommandLines = /* @__PURE__ */ new WeakMap();
|
|
8
|
+
constructor() {
|
|
9
|
+
this.useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
|
|
10
|
+
}
|
|
11
|
+
close() {}
|
|
12
|
+
getOutputPaths(project) {
|
|
13
|
+
const parsedCommandLine = this.parsedCommandLines.get(project);
|
|
14
|
+
if (parsedCommandLine === void 0) throw new Error("Project was not parsed by this compiler.");
|
|
15
|
+
if (typescriptVersion < 4002e3 && parsedCommandLine.options.rootDir === void 0) throw new UserError("Refusing to clean outDir: TypeScript 3.9 through 4.1 require rootDir to be set.");
|
|
16
|
+
const emittableFileNames = project.programFileNames.filter((fileName) => !isDeclarationFileName(fileName));
|
|
17
|
+
const outputCommandLine = {
|
|
18
|
+
...parsedCommandLine,
|
|
19
|
+
fileNames: emittableFileNames
|
|
20
|
+
};
|
|
21
|
+
const outputPaths = /* @__PURE__ */ new Set();
|
|
22
|
+
for (const fileName of emittableFileNames) for (const outputPath of ts.getOutputFileNames(outputCommandLine, fileName, !this.useCaseSensitiveFileNames)) outputPaths.add(outputPath);
|
|
23
|
+
return outputPaths;
|
|
24
|
+
}
|
|
25
|
+
parseProject(configFilePath) {
|
|
26
|
+
const formatHost = {
|
|
27
|
+
getCanonicalFileName: (fileName) => fileName,
|
|
28
|
+
getCurrentDirectory: () => process.cwd(),
|
|
29
|
+
getNewLine: () => ts.sys.newLine
|
|
30
|
+
};
|
|
31
|
+
const checkConfigFile = (filePath) => {
|
|
32
|
+
const config = ts.readConfigFile(filePath, (name) => ts.sys.readFile(name));
|
|
33
|
+
if (config.error !== void 0) throw new UserError(ts.formatDiagnostics([config.error], formatHost).trimEnd());
|
|
34
|
+
};
|
|
35
|
+
checkConfigFile(configFilePath);
|
|
36
|
+
const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(configFilePath, void 0, {
|
|
37
|
+
...ts.sys,
|
|
38
|
+
onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
|
|
39
|
+
throw new UserError(ts.formatDiagnostics([diagnostic], formatHost).trimEnd());
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
if (parsedCommandLine === void 0) throw new UserError("Could not read tsconfig.json.");
|
|
43
|
+
if (parsedCommandLine.errors.length > 0) throw new UserError(ts.formatDiagnostics(parsedCommandLine.errors, formatHost).trimEnd());
|
|
44
|
+
const configFileOption = parsedCommandLine.options["configFile"];
|
|
45
|
+
const configFile = isConfigFileMetadata(configFileOption) ? configFileOption : void 0;
|
|
46
|
+
for (const filePath of configFile?.extendedSourceFiles ?? []) checkConfigFile(filePath);
|
|
47
|
+
const program = ts.createProgram(parsedCommandLine.fileNames, parsedCommandLine.options);
|
|
48
|
+
const project = {
|
|
49
|
+
configFilePaths: [configFile?.fileName ?? configFilePath, ...configFile?.extendedSourceFiles ?? []],
|
|
50
|
+
fileNames: parsedCommandLine.fileNames,
|
|
51
|
+
hasWatchOptions: parsedCommandLine.watchOptions !== void 0,
|
|
52
|
+
options: parsedCommandLine.options,
|
|
53
|
+
programFileNames: program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile) && !program.isSourceFileFromExternalLibrary(sourceFile)).map((sourceFile) => sourceFile.fileName)
|
|
54
|
+
};
|
|
55
|
+
this.parsedCommandLines.set(project, parsedCommandLine);
|
|
56
|
+
return project;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
function isConfigFileMetadata(value) {
|
|
60
|
+
if (typeof value !== "object" || value === null || !("fileName" in value) || typeof value.fileName !== "string") return false;
|
|
61
|
+
if ("extendedSourceFiles" in value && value.extendedSourceFiles !== void 0) return Array.isArray(value.extendedSourceFiles) && value.extendedSourceFiles.every((fileName) => typeof fileName === "string");
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
function isDeclarationFileName(fileName) {
|
|
65
|
+
return fileName.endsWith(".d.ts") || fileName.endsWith(".d.mts") || fileName.endsWith(".d.cts");
|
|
66
|
+
}
|
|
67
|
+
export { TypeScriptPre7Compiler };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tsc-after",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Remove stale build output that tsc leaves behind when you delete or rename source files. Tsconfig-aware: just run tsc && tsc-after. ๐งน",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"build",
|
|
@@ -25,13 +25,16 @@
|
|
|
25
25
|
"type": "module",
|
|
26
26
|
"exports": null,
|
|
27
27
|
"bin": {
|
|
28
|
-
"tsc-after": "bin/tsc-after"
|
|
28
|
+
"tsc-after": "bin/tsc-after.js"
|
|
29
29
|
},
|
|
30
30
|
"files": [
|
|
31
|
+
"bin/",
|
|
31
32
|
"dist/"
|
|
32
33
|
],
|
|
33
34
|
"scripts": {
|
|
34
35
|
"build": "tsdown",
|
|
36
|
+
"clean": "rm -rf .tmp dist coverage",
|
|
37
|
+
"dev": "node src/entrypoints/tscAfter.ts",
|
|
35
38
|
"format": "prettier --write .",
|
|
36
39
|
"lint": "eslint . --max-warnings 0",
|
|
37
40
|
"lint:knip": "KNIP_DISABLE_RAW_TRANSFER=1 knip",
|
|
@@ -40,7 +43,8 @@
|
|
|
40
43
|
"release": "release-it",
|
|
41
44
|
"test": "vitest",
|
|
42
45
|
"test:e2e": "vitest --project e2e",
|
|
43
|
-
"test:unit": "vitest --project unit"
|
|
46
|
+
"test:unit": "vitest --project unit",
|
|
47
|
+
"typecheck": "tsc"
|
|
44
48
|
},
|
|
45
49
|
"commitlint": {
|
|
46
50
|
"extends": [
|
|
@@ -51,53 +55,54 @@
|
|
|
51
55
|
"*": "prettier --ignore-unknown --write"
|
|
52
56
|
},
|
|
53
57
|
"devDependencies": {
|
|
54
|
-
"@arethetypeswrong/core": "0.18.5",
|
|
55
58
|
"@commitlint/cli": "21.2.4",
|
|
56
59
|
"@commitlint/config-conventional": "21.2.4",
|
|
57
60
|
"@eslint-community/eslint-plugin-eslint-comments": "4.8.1",
|
|
58
61
|
"@eslint/js": "10.0.1",
|
|
59
|
-
"@eslint/markdown": "
|
|
62
|
+
"@eslint/markdown": "9.0.0",
|
|
63
|
+
"@eslint/shell": "0.1.2",
|
|
60
64
|
"@release-it/conventional-changelog": "12.0.2",
|
|
61
|
-
"@tsconfig/node-lts": "
|
|
62
|
-
"@tsconfig/node-ts": "23.6.
|
|
63
|
-
"@tsconfig/strictest": "2.0.
|
|
64
|
-
"@types/node": "26.6.
|
|
65
|
-
"@vitest/coverage-v8": "5.
|
|
66
|
-
"@vitest/eslint-plugin": "1.6.
|
|
65
|
+
"@tsconfig/node-lts": "26.0.1",
|
|
66
|
+
"@tsconfig/node-ts": "23.6.5",
|
|
67
|
+
"@tsconfig/strictest": "2.0.9",
|
|
68
|
+
"@types/node": "26.6.6",
|
|
69
|
+
"@vitest/coverage-v8": "5.1.1",
|
|
70
|
+
"@vitest/eslint-plugin": "1.6.28",
|
|
67
71
|
"console-fail-test": "0.10.0",
|
|
68
72
|
"conventional-changelog-conventionalcommits": "10.4.1",
|
|
69
|
-
"cspell": "10.
|
|
70
|
-
"eslint": "10.
|
|
73
|
+
"cspell": "10.5.2",
|
|
74
|
+
"eslint": "10.15.0",
|
|
71
75
|
"eslint-import-resolver-typescript": "4.4.5",
|
|
72
|
-
"eslint-plugin-import-x": "4.
|
|
73
|
-
"eslint-plugin-jsdoc": "65.
|
|
76
|
+
"eslint-plugin-import-x": "4.18.1",
|
|
77
|
+
"eslint-plugin-jsdoc": "65.5.0",
|
|
74
78
|
"eslint-plugin-jsonc": "3.4.2",
|
|
75
79
|
"eslint-plugin-n": "18.5.0",
|
|
76
|
-
"eslint-plugin-package-json": "1.
|
|
77
|
-
"eslint-plugin-perfectionist": "5.
|
|
78
|
-
"eslint-plugin-regexp": "3.3.
|
|
79
|
-
"eslint-plugin-yml": "3.
|
|
80
|
-
"execa": "10.2.
|
|
80
|
+
"eslint-plugin-package-json": "1.14.0",
|
|
81
|
+
"eslint-plugin-perfectionist": "5.14.0",
|
|
82
|
+
"eslint-plugin-regexp": "3.3.3",
|
|
83
|
+
"eslint-plugin-yml": "3.10.0",
|
|
84
|
+
"execa": "10.2.1",
|
|
81
85
|
"husky": "9.1.7",
|
|
82
|
-
"knip": "6.
|
|
83
|
-
"lint-staged": "17.6.
|
|
84
|
-
"prettier": "3.
|
|
85
|
-
"prettier-plugin-curly": "0.4.
|
|
86
|
-
"prettier-plugin-packagejson": "3.0
|
|
86
|
+
"knip": "6.47.0",
|
|
87
|
+
"lint-staged": "17.6.1",
|
|
88
|
+
"prettier": "3.10.1",
|
|
89
|
+
"prettier-plugin-curly": "0.4.2",
|
|
90
|
+
"prettier-plugin-packagejson": "3.1.0",
|
|
87
91
|
"prettier-plugin-sentences-per-line": "0.2.5",
|
|
88
92
|
"prettier-plugin-sh": "0.20.2",
|
|
89
93
|
"publint": "0.3.25",
|
|
90
|
-
"release-it": "21.1.
|
|
91
|
-
"tsdown": "0.23.
|
|
94
|
+
"release-it": "21.1.2",
|
|
95
|
+
"tsdown": "0.23.7",
|
|
92
96
|
"typescript": "6.0.3",
|
|
93
|
-
"typescript-
|
|
94
|
-
"
|
|
97
|
+
"typescript-7": "npm:typescript@7.1.0-beta",
|
|
98
|
+
"typescript-eslint": "8.73.0",
|
|
99
|
+
"vitest": "5.1.1"
|
|
95
100
|
},
|
|
96
101
|
"peerDependencies": {
|
|
97
|
-
"typescript": ">=
|
|
102
|
+
"typescript": ">=3.9.10 <7 || >=7.1.0-beta <8"
|
|
98
103
|
},
|
|
99
|
-
"packageManager": "pnpm@12.
|
|
104
|
+
"packageManager": "pnpm@12.21.0",
|
|
100
105
|
"engines": {
|
|
101
|
-
"node": "
|
|
106
|
+
"node": "^16.19.0 || >=18.11.0"
|
|
102
107
|
}
|
|
103
108
|
}
|
package/bin/tsc-after
DELETED
package/dist/index.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {}
|
package/dist/index.js
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
import { name, version } from "./package.js";
|
|
2
|
-
import fs from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { parseArgs, styleText } from "node:util";
|
|
5
|
-
import ts from "typescript";
|
|
6
|
-
//#region src/index.ts
|
|
7
|
-
const argsConfig = { options: {
|
|
8
|
-
project: {
|
|
9
|
-
default: "tsconfig.json",
|
|
10
|
-
helpDescription: "Path to configuration file for this project, or to a folder with a 'tsconfig.json'.",
|
|
11
|
-
helpPlaceholder: "<path>",
|
|
12
|
-
short: "p",
|
|
13
|
-
type: "string"
|
|
14
|
-
},
|
|
15
|
-
dryRun: {
|
|
16
|
-
default: false,
|
|
17
|
-
helpDescription: "Do not delete any files.",
|
|
18
|
-
type: "boolean"
|
|
19
|
-
},
|
|
20
|
-
verbose: {
|
|
21
|
-
default: false,
|
|
22
|
-
helpDescription: "Print verbose output.",
|
|
23
|
-
type: "boolean"
|
|
24
|
-
},
|
|
25
|
-
version: {
|
|
26
|
-
default: false,
|
|
27
|
-
helpDescription: "Print version.",
|
|
28
|
-
type: "boolean"
|
|
29
|
-
},
|
|
30
|
-
help: {
|
|
31
|
-
default: false,
|
|
32
|
-
helpDescription: "Print this message.",
|
|
33
|
-
short: "h",
|
|
34
|
-
type: "boolean"
|
|
35
|
-
}
|
|
36
|
-
} };
|
|
37
|
-
const BIN_NAME = name;
|
|
38
|
-
function isNodeErrorOf(error, errorClass, code) {
|
|
39
|
-
if (!(error instanceof errorClass)) return false;
|
|
40
|
-
return !(code !== void 0 && "code" in error && error.code !== code);
|
|
41
|
-
}
|
|
42
|
-
function main() {
|
|
43
|
-
let args;
|
|
44
|
-
try {
|
|
45
|
-
args = parseArgs(argsConfig);
|
|
46
|
-
} catch (error) {
|
|
47
|
-
if (isNodeErrorOf(error, TypeError, "ERR_PARSE_ARGS_UNKNOWN_OPTION")) {
|
|
48
|
-
printError(`${error.message}.`);
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
throw error;
|
|
52
|
-
}
|
|
53
|
-
if (args.values.help) {
|
|
54
|
-
const heading = (text) => styleText(["bold"], text), option = (name, description) => ` ${styleText("blueBright", name.padEnd(23))}${description}`;
|
|
55
|
-
print([
|
|
56
|
-
`${styleText("bold", BIN_NAME)} - Your dist, as tsc should've left it.`,
|
|
57
|
-
"",
|
|
58
|
-
"A tsconfig-aware companion to tsc. Removes stale build output by default.",
|
|
59
|
-
"",
|
|
60
|
-
heading("USAGE"),
|
|
61
|
-
` tsc && ${BIN_NAME} [options]`,
|
|
62
|
-
"",
|
|
63
|
-
heading("OPTIONS"),
|
|
64
|
-
...Object.entries(argsConfig.options).map(([name, opts]) => {
|
|
65
|
-
const keyParts = [`--${name}`];
|
|
66
|
-
if ("short" in opts) keyParts.push(`, -${opts.short}`);
|
|
67
|
-
switch (opts.type) {
|
|
68
|
-
case "boolean": break;
|
|
69
|
-
case "string": keyParts.push(` ${opts.helpPlaceholder}`);
|
|
70
|
-
}
|
|
71
|
-
return option(keyParts.join(""), opts.helpDescription);
|
|
72
|
-
})
|
|
73
|
-
].join("\n"));
|
|
74
|
-
process.exit(0);
|
|
75
|
-
}
|
|
76
|
-
if (args.values.version) {
|
|
77
|
-
print(`${BIN_NAME}/${version} ${process.platform}-${process.arch} node-${process.versions.node} typescript-${ts.version}`);
|
|
78
|
-
process.exit(0);
|
|
79
|
-
}
|
|
80
|
-
const cwd = process.cwd(), tsconfigAbsolutePath = path.resolve(cwd, args.values.project), tsconfigRelativePath = path.relative(cwd, tsconfigAbsolutePath);
|
|
81
|
-
if (tsconfigRelativePath === "" || tsconfigRelativePath === ".." || tsconfigRelativePath.startsWith(`..${path.sep}`) || path.isAbsolute(tsconfigRelativePath)) throw new Error(`Refusing to traverse outside current working directory to read tsconfig!`);
|
|
82
|
-
print(`Using tsconfig: ${tsconfigRelativePath}`);
|
|
83
|
-
const tsconfig = ts.getParsedCommandLineOfConfigFile(args.values.project, void 0, {
|
|
84
|
-
...ts.sys,
|
|
85
|
-
onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
|
|
86
|
-
printError(JSON.stringify(diagnostic));
|
|
87
|
-
throw new Error("Unrecoverable config file diagnostic");
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
if (tsconfig?.options.outDir === void 0) throw new Error("outDir is required");
|
|
91
|
-
const outDirRelativePath = path.relative(path.dirname(tsconfigAbsolutePath), tsconfig.options.outDir);
|
|
92
|
-
if (outDirRelativePath === "" || outDirRelativePath === ".." || outDirRelativePath.startsWith(`..${path.sep}`) || path.isAbsolute(outDirRelativePath)) throw new Error(`Refusing to traverse outside safe paths containing tsconfig to process outDir!`);
|
|
93
|
-
if (tsconfig.options.incremental === true) throw new Error("Incremental mode is not supported");
|
|
94
|
-
if (tsconfig.options.tsBuildInfoFile !== void 0) throw new Error("tsBuildInfoFile is not supported");
|
|
95
|
-
if (tsconfig.options.composite === true) throw new Error("Composite mode is not supported");
|
|
96
|
-
if (tsconfig.options.project !== void 0) throw new Error("Project mode is not supported");
|
|
97
|
-
if (tsconfig.options.declarationDir !== void 0) throw new Error("declarationDir is not supported");
|
|
98
|
-
if (tsconfig.watchOptions) throw new Error("Watch mode is not supported");
|
|
99
|
-
print(JSON.stringify(tsconfig));
|
|
100
|
-
const expectedOutDirPaths = /* @__PURE__ */ new Set();
|
|
101
|
-
for (const file of tsconfig.fileNames) {
|
|
102
|
-
const output = ts.getOutputFileNames(tsconfig, file, !ts.sys.useCaseSensitiveFileNames), stat = fs.statSync(file);
|
|
103
|
-
print(file, " => ", JSON.stringify(output), JSON.stringify(stat));
|
|
104
|
-
output.forEach((fiePath) => expectedOutDirPaths.add(fiePath));
|
|
105
|
-
}
|
|
106
|
-
print(JSON.stringify(expectedOutDirPaths));
|
|
107
|
-
function readDir(dirPath) {
|
|
108
|
-
const verdicts = [], stat = fs.lstatSync(dirPath);
|
|
109
|
-
if (!stat.isDirectory()) throw new Error(`Not a directory ${dirPath}!`);
|
|
110
|
-
let dirIsEmpty = true;
|
|
111
|
-
for (const child of fs.readdirSync(dirPath)) {
|
|
112
|
-
const fullPath = path.join(dirPath, child), fullPathStat = fs.lstatSync(fullPath);
|
|
113
|
-
if (fullPathStat.dev !== stat.dev) {
|
|
114
|
-
if (args.values.verbose) verdicts.push({
|
|
115
|
-
path: fullPath,
|
|
116
|
-
reason: "different device",
|
|
117
|
-
type: "skipped"
|
|
118
|
-
});
|
|
119
|
-
dirIsEmpty = false;
|
|
120
|
-
continue;
|
|
121
|
-
}
|
|
122
|
-
if (fullPathStat.isFile()) {
|
|
123
|
-
if (expectedOutDirPaths.has(fullPath)) {
|
|
124
|
-
if (args.values.verbose) verdicts.push({
|
|
125
|
-
path: fullPath,
|
|
126
|
-
reason: "expected output file",
|
|
127
|
-
type: "skipped"
|
|
128
|
-
});
|
|
129
|
-
dirIsEmpty = false;
|
|
130
|
-
continue;
|
|
131
|
-
}
|
|
132
|
-
verdicts.push({
|
|
133
|
-
path: fullPath,
|
|
134
|
-
type: "removeFile"
|
|
135
|
-
});
|
|
136
|
-
continue;
|
|
137
|
-
}
|
|
138
|
-
if (fullPathStat.isDirectory()) {
|
|
139
|
-
const result = readDir(fullPath);
|
|
140
|
-
verdicts.push(...result.verdicts);
|
|
141
|
-
if (!result.dirIsEmpty) dirIsEmpty = false;
|
|
142
|
-
continue;
|
|
143
|
-
}
|
|
144
|
-
dirIsEmpty = false;
|
|
145
|
-
}
|
|
146
|
-
if (dirIsEmpty) verdicts.push({
|
|
147
|
-
path: dirPath,
|
|
148
|
-
type: "removeDir"
|
|
149
|
-
});
|
|
150
|
-
else verdicts.push({
|
|
151
|
-
path: dirPath,
|
|
152
|
-
reason: "directory not empty",
|
|
153
|
-
type: "skipped"
|
|
154
|
-
});
|
|
155
|
-
return {
|
|
156
|
-
dirIsEmpty,
|
|
157
|
-
verdicts
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
const result = readDir(tsconfig.options.outDir);
|
|
161
|
-
if (args.values.verbose) for (const verdict of result.verdicts) switch (verdict.type) {
|
|
162
|
-
case "removeDir":
|
|
163
|
-
print(`Remove empty directory: ${verdict.path}`);
|
|
164
|
-
break;
|
|
165
|
-
case "removeFile":
|
|
166
|
-
print(`Remove file: ${verdict.path}`);
|
|
167
|
-
break;
|
|
168
|
-
case "skipped": print(`Skipped (${verdict.reason}): ${verdict.path}`);
|
|
169
|
-
}
|
|
170
|
-
let removedDirs = 0, removedFiles = 0;
|
|
171
|
-
if (!args.values.dryRun) for (const verdict of result.verdicts) switch (verdict.type) {
|
|
172
|
-
case "removeDir":
|
|
173
|
-
fs.rmdirSync(verdict.path);
|
|
174
|
-
removedDirs++;
|
|
175
|
-
break;
|
|
176
|
-
case "removeFile":
|
|
177
|
-
fs.rmSync(verdict.path, { recursive: false });
|
|
178
|
-
removedFiles++;
|
|
179
|
-
}
|
|
180
|
-
if (args.values.dryRun || removedDirs > 0 || removedFiles > 0) print(`${BIN_NAME}: ${args.values.dryRun ? "Would remove" : "Removed"} ${removedFiles.toFixed()} files${removedDirs > 0 ? ` and ${removedDirs.toFixed()} empty directories` : ""} from ${styleText("italic", outDirRelativePath)}`);
|
|
181
|
-
}
|
|
182
|
-
function print(...messages) {
|
|
183
|
-
console.log(messages.join(" "));
|
|
184
|
-
}
|
|
185
|
-
function printError(...messages) {
|
|
186
|
-
console.error(styleText("red", `error: ${messages.join(" ")}`));
|
|
187
|
-
process.exitCode = 1;
|
|
188
|
-
}
|
|
189
|
-
main();
|
|
190
|
-
//#endregion
|
|
191
|
-
export {};
|