tsc-after 0.3.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 CHANGED
@@ -15,9 +15,21 @@ Rename `foo.ts` to `foo/index.ts`, and `dist/foo.js` lives on forever.
15
15
 
16
16
  ## Usage
17
17
 
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:
26
+
18
27
  ```sh
19
- # Preview for tsconfig.json; --verbose lists individual paths.
20
- tsc-after --dry --verbose
28
+ # Clean after compile; run after tsc build.
29
+ tsc-after
30
+
31
+ # Preview planned removals for tsconfig.json.
32
+ tsc-after --dry
21
33
 
22
34
  # Select a tsconfig file instead of the default.
23
35
  tsc-after --project tsconfig.build.json
@@ -26,37 +38,32 @@ tsc-after --project tsconfig.build.json
26
38
  tsc-after -p packages/core
27
39
  ```
28
40
 
29
- The project path must be inside the current working directory.
30
- Positional arguments and unknown flags are rejected.
31
-
32
- For a basic project with a dedicated `outDir`, `tsc-after` uses TypeScript's output-name API to identify expected outputs, removes other regular files in `outDir`, and removes directories left empty by cleanup.
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.
33
42
  It skips symbolic links and entries on other devices.
34
- This behavior and its safety limits are not yet verified for every TypeScript configuration or output type.
35
43
 
36
- `--dry` leaves files unchanged, but individual paths are currently printed only with `--verbose`; its summary also reports zero files removed rather than counting planned removals ([issue #8](https://github.com/michal-kocarek/tsc-after/issues/8)).
44
+ `--dry` lists planned removals without changing files.
45
+ Use `--verbose` to add individual removed and skipped entries.
37
46
 
38
47
  ## Limitations
39
48
 
40
- - `outDir` must be set and dedicated to TypeScript outputs.
41
- Other regular files there, including copied assets, are treated as stale.
42
- - By default, `tsc-after` reads `tsconfig.json` from the current directory and does not search parent directories.
43
- - `incremental`, `tsBuildInfoFile`, `composite`, `declarationDir`, and watch configurations are rejected.
44
- Project references are not followed.
45
- - Source files reached only through imports or `paths` aliases are not included when checking source/output overlap or expected outputs.
46
- Cleanup may delete those sources if they are inside `outDir`, or delete their emitted files as stale ([issue #2](https://github.com/michal-kocarek/tsc-after/issues/2)).
47
- - Cleanup confinement and source/output overlap checks are incomplete.
48
- Do not rely on the current checks to protect valuable files.
49
- - Handling of TypeScript configurations and emitted file types is incomplete and still needs verification.
49
+ `tsc-after` reads your tsconfig the way `tsc` does; this list covers only where it differs.
50
50
 
51
- Related open work: [configuration handling (#2)](https://github.com/michal-kocarek/tsc-after/issues/2), [incremental build state (#4)](https://github.com/michal-kocarek/tsc-after/issues/4), [cleanup safety (#6)](https://github.com/michal-kocarek/tsc-after/issues/6), and [output coverage (#7)](https://github.com/michal-kocarek/tsc-after/issues/7).
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`.
52
59
 
53
60
  Planned: `--copy`, `--exclude`, and `--watch`.
54
61
  See [`product.md`](./docs/product.md) for the roadmap.
55
62
 
56
63
  ## Requirements
57
64
 
58
- - the project's tsconfig file must exist inside the current working directory (unlike `tsc`, it does not search parent directories for `tsconfig.json`)
59
- - source code must be compiled in dedicated `outDir` path
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.
60
67
 
61
68
  ## Exit codes
62
69
 
@@ -70,7 +77,6 @@ Wiping `outDir` before every build (`rm -rf dist && tsc`, `rimraf dist && tsc`,
70
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)).
71
78
 
72
79
  `tsc-after` is intended to remove only stale outputs rather than wiping `outDir` and rebuilding everything.
73
- Incremental builds are not supported.
74
80
 
75
81
  **Using a bundler such as tsup, Vite, or esbuild?**<br>
76
82
  They already clean up after themselves, so you probably don't need `tsc-after`.
package/dist/tscAfter.js CHANGED
@@ -5,6 +5,9 @@ import ts from "typescript";
5
5
  // src/common/errors.ts
6
6
  /** Error whose message is human-readable and printed to the user without a stack trace. */
7
7
  var UserError = class extends Error {};
8
+ function assertUnreachable(value) {
9
+ throw new Error("Unreachable code reached.", { cause: value });
10
+ }
8
11
  function isNodeErrorOf(error, errorClass, code) {
9
12
  if (!(error instanceof errorClass)) return false;
10
13
  if (code === void 0) return true;
@@ -110,59 +113,95 @@ function help() {
110
113
  ].join("\n\n"));
111
114
  }
112
115
  // src/common/paths.ts
113
- function isPathInside(dirPath, filePath) {
114
- const normalizedDirPath = ts.sys.useCaseSensitiveFileNames ? dirPath : dirPath.toLowerCase();
115
- const normalizedFilePath = ts.sys.useCaseSensitiveFileNames ? filePath : filePath.toLowerCase();
116
+ function isPathInside(dirPath, filePath, useCaseSensitiveFileNames) {
117
+ const normalizedDirPath = useCaseSensitiveFileNames ? dirPath : dirPath.toLowerCase();
118
+ const normalizedFilePath = useCaseSensitiveFileNames ? filePath : filePath.toLowerCase();
116
119
  const relativePath = path.relative(normalizedDirPath, normalizedFilePath);
117
120
  return relativePath === "" || !path.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith(`..${path.sep}`);
118
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
+ }
119
140
  // src/tasks/mainAction.ts
120
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\".";
121
- function mainAction(args) {
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) {
122
145
  const cwd = process.cwd();
123
- const projectAbsolutePath = path.resolve(cwd, args.values.project);
124
- if (!isPathInside(cwd, projectAbsolutePath)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
125
- const tsconfigAbsolutePath = fs.existsSync(projectAbsolutePath) && fs.statSync(projectAbsolutePath).isDirectory() ? path.join(projectAbsolutePath, "tsconfig.json") : projectAbsolutePath;
126
- if (!isPathInside(cwd, tsconfigAbsolutePath) || isPathInside(tsconfigAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
127
- print(`Using tsconfig: ${path.relative(cwd, tsconfigAbsolutePath)}`);
128
- const formatHost = {
129
- getCanonicalFileName: (fileName) => fileName,
130
- getCurrentDirectory: () => cwd,
131
- getNewLine: () => ts.sys.newLine
132
- };
133
- const tsconfig = ts.getParsedCommandLineOfConfigFile(tsconfigAbsolutePath, void 0, {
134
- ...ts.sys,
135
- onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
136
- throw new UserError(ts.formatDiagnostics([diagnostic], formatHost).trimEnd());
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
+ });
137
175
  }
138
- });
139
- if (tsconfig === void 0) throw new UserError("Could not read tsconfig.json.");
140
- if (tsconfig.errors.length > 0) throw new UserError(ts.formatDiagnostics(tsconfig.errors, formatHost).trimEnd());
141
- if (tsconfig.options.outDir === void 0) throw new UserError(MISSING_OUT_DIR_ERROR);
142
- const outDir = tsconfig.options.outDir;
143
- const outDirAbsolutePath = path.resolve(outDir);
144
- const outDirRelativePath = path.relative(cwd, outDirAbsolutePath);
145
- if (!isPathInside(cwd, outDirAbsolutePath) || isPathInside(outDirAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside safe paths containing tsconfig to process outDir!`);
146
- if (tsconfig.options.incremental === true) throw new UserError("Incremental mode is not supported");
147
- if (tsconfig.options.tsBuildInfoFile !== void 0) throw new UserError("tsBuildInfoFile is not supported");
148
- if (tsconfig.options.composite === true) throw new UserError("Composite mode is not supported");
149
- if (tsconfig.options.project !== void 0) throw new UserError("Project mode is not supported");
150
- if (tsconfig.options.declarationDir !== void 0) throw new UserError("declarationDir is not supported");
151
- if (tsconfig.watchOptions) throw new UserError("Watch mode is not supported");
152
- const isInsideOutDir = (filePath) => isPathInside(outDirAbsolutePath, filePath) || isPathInside(outDirAbsolutePath, fs.realpathSync(filePath));
153
- for (const file of tsconfig.fileNames) if (isInsideOutDir(path.resolve(file))) throw new UserError(`Refusing to clean outDir '${outDirRelativePath}': it contains source file '${path.relative(cwd, file)}'.`);
154
- const configFile = tsconfig.options["configFile"];
155
- const configFilePaths = [configFile?.fileName ?? tsconfigAbsolutePath, ...configFile?.extendedSourceFiles ?? []];
156
- for (const file of configFilePaths) if (isInsideOutDir(path.resolve(file))) throw new UserError(`Refusing to clean outDir '${outDirRelativePath}': it contains config file '${path.relative(cwd, file)}'.`);
157
- if (args.values.noClean) return;
158
- const expectedOutDirPaths = /* @__PURE__ */ new Set();
159
- for (const file of tsconfig.fileNames) ts.getOutputFileNames(tsconfig, file, !ts.sys.useCaseSensitiveFileNames).forEach((fiePath) => expectedOutDirPaths.add(fiePath));
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
+ }
160
199
  function readDir(dirPath) {
161
200
  const verdicts = [];
162
201
  const stat = fs.lstatSync(dirPath);
163
202
  if (!stat.isDirectory()) throw new UserError(`Not a directory ${dirPath}!`);
164
203
  let dirIsEmpty = true;
165
- for (const child of fs.readdirSync(dirPath)) {
204
+ for (const child of fs.readdirSync(dirPath).sort()) {
166
205
  const fullPath = path.join(dirPath, child);
167
206
  const fullPathStat = fs.lstatSync(fullPath);
168
207
  if (fullPathStat.dev !== stat.dev) {
@@ -221,54 +260,69 @@ function mainAction(args) {
221
260
  verdicts
222
261
  };
223
262
  }
224
- let outDirExists = true;
225
- try {
226
- fs.lstatSync(outDir);
227
- } catch (error) {
228
- if (!isNodeErrorOf(error, Error, "ENOENT")) throw error;
229
- outDirExists = false;
230
- }
231
- if (outDirExists && fs.realpathSync(outDir) !== path.resolve(outDir)) throw new UserError(`Refusing to clean outDir through a symbolic link: ${outDirRelativePath}!`);
232
- const result = outDirExists ? readDir(outDir) : { verdicts: [] };
233
- if (args.values.verbose) for (const verdict of result.verdicts) switch (verdict.type) {
234
- case "removeDir":
235
- print(`Remove empty directory: ${verdict.path}`);
236
- break;
237
- case "removeFile":
238
- print(`Remove file: ${verdict.path}`);
239
- break;
240
- case "skipped": print(`Skipped (${verdict.reason}): ${verdict.path}`);
241
- }
242
- let removedDirs = 0;
243
- let removedFiles = 0;
244
- if (!args.values.dry) for (const verdict of result.verdicts) switch (verdict.type) {
245
- case "removeDir":
246
- fs.rmdirSync(verdict.path);
247
- removedDirs++;
248
- break;
249
- case "removeFile":
250
- fs.rmSync(verdict.path, { recursive: false });
251
- removedFiles++;
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)}`);
252
304
  }
253
- if (args.values.dry || removedDirs > 0 || removedFiles > 0) print(`${binName}: ${args.values.dry ? "Would remove" : "Removed"} ${removedFiles.toFixed()} files${removedDirs > 0 ? ` and ${removedDirs.toFixed()} empty directories` : ""} from ${styleText("italic", outDirRelativePath)}`);
305
+ }
306
+ function formatCount(count, singular, plural) {
307
+ return `${count.toFixed()} ${count === 1 ? singular : plural}`;
254
308
  }
255
309
  // package.json
256
- var version$1 = "0.3.0";
310
+ var version$1 = "0.4.0";
257
311
  // src/tasks/version.ts
258
312
  function version() {
259
313
  print(`${binName}/${version$1} ${process.platform}-${process.arch} node-${process.versions.node} typescript-${ts.version}`);
260
314
  }
261
315
  // src/entrypoints/tscAfter.ts
262
- function main() {
316
+ async function main() {
263
317
  try {
264
318
  const args = parseArgs(process.argv.slice(2));
265
319
  if (args.values.version) version();
266
320
  else if (args.values.help) help();
267
- else mainAction(args);
321
+ else await mainAction(args);
268
322
  } catch (error) {
269
323
  if (!(error instanceof UserError)) throw error;
270
324
  printError(error.message);
271
325
  }
272
326
  }
273
327
  main();
274
- export {};
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.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",
@@ -60,6 +60,7 @@
60
60
  "@eslint-community/eslint-plugin-eslint-comments": "4.8.1",
61
61
  "@eslint/js": "10.0.1",
62
62
  "@eslint/markdown": "9.0.0",
63
+ "@eslint/shell": "0.1.2",
63
64
  "@release-it/conventional-changelog": "12.0.2",
64
65
  "@tsconfig/node-lts": "26.0.1",
65
66
  "@tsconfig/node-ts": "23.6.5",
@@ -93,11 +94,12 @@
93
94
  "release-it": "21.1.2",
94
95
  "tsdown": "0.23.7",
95
96
  "typescript": "6.0.3",
97
+ "typescript-7": "npm:typescript@7.1.0-beta",
96
98
  "typescript-eslint": "8.73.0",
97
99
  "vitest": "5.1.1"
98
100
  },
99
101
  "peerDependencies": {
100
- "typescript": ">=5.9.3"
102
+ "typescript": ">=3.9.10 <7 || >=7.1.0-beta <8"
101
103
  },
102
104
  "packageManager": "pnpm@12.21.0",
103
105
  "engines": {