tsc-after 0.4.0 → 0.4.1

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
@@ -39,7 +39,7 @@ tsc-after -p packages/core
39
39
  ```
40
40
 
41
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.
42
+ It skips symbolic links and entries on other devices inside `outDir` or `declarationDir`.
43
43
 
44
44
  `--dry` lists planned removals without changing files.
45
45
  Use `--verbose` to add individual removed and skipped entries.
@@ -48,22 +48,29 @@ Use `--verbose` to add individual removed and skipped entries.
48
48
 
49
49
  `tsc-after` reads your tsconfig the way `tsc` does; this list covers only where it differs.
50
50
 
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`.
51
+ - `outDir` and `declarationDir` must hold only TypeScript outputs: anything else, including copied assets and tsconfig files, is removed as stale.
52
+ - Parent directories are not searched for `tsconfig.json`.
53
+ - `outFile`, `composite`, `incremental`, and `tsBuildInfoFile` ([#4](https://github.com/michal-kocarek/tsc-after/issues/4)) are rejected, and project references are not followed.
54
+ - Support for TypeScript versions 3.9 - 4.1 is limited:
55
+ - `rootDir` is required ([#15](https://github.com/michal-kocarek/tsc-after/issues/15)).
56
+ - 3.9 only: `emitDeclarationOnly` with `resolveJsonModule` and JSON source files, and `allowJs` with `jsx: preserve`, `declaration`, and `.jsx` source files are refused ([#15](https://github.com/michal-kocarek/tsc-after/issues/15)).
57
+ - TypeScript 7.1 beta support is experimental.
59
58
 
60
59
  Planned: `--copy`, `--exclude`, and `--watch`.
61
60
  See [`product.md`](./docs/product.md) for the roadmap.
62
61
 
62
+ ## Security measures
63
+
64
+ - Cleanup is refused unless `outDir` is set and `noEmit` is disabled.
65
+ - `outDir` and `declarationDir` must be inside, and not equal to, the current working directory.
66
+ - Cleanup is refused when `outDir` or `declarationDir` contains a source file of the project.
67
+ - Cleanup is refused when `outDir` or `declarationDir` is reached through a symbolic link.
68
+ - A `--project` path outside the current working directory is refused.
69
+
63
70
  ## Requirements
64
71
 
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.
72
+ - Node.js 16.19.0 or later, including the latest LTS.
73
+ - TypeScript 3.9.10 through 7.x, including 7.1 beta (except 7.0, which has no API support).
67
74
 
68
75
  ## Exit codes
69
76
 
package/dist/tscAfter.js CHANGED
@@ -114,88 +114,26 @@ function help() {
114
114
  }
115
115
  // src/common/paths.ts
116
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}`);
117
+ const normalizedDirPath = normalizePathForComparison(dirPath, useCaseSensitiveFileNames);
118
+ const normalizedFilePath = normalizePathForComparison(filePath, useCaseSensitiveFileNames);
119
+ return normalizedDirPath === normalizedFilePath || normalizedFilePath.startsWith(normalizedDirPath.endsWith(path.sep) ? normalizedDirPath : `${normalizedDirPath}${path.sep}`);
121
120
  }
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();
121
+ function normalizePathForComparison(filePath, useCaseSensitiveFileNames) {
122
+ const normalizedPath = path.resolve(filePath);
123
+ return useCaseSensitiveFileNames ? normalizedPath : normalizedPath.toLowerCase();
139
124
  }
140
- // src/tasks/mainAction.ts
125
+ // src/common/cleanupRoots.ts
141
126
  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
127
  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;
128
+ function readCleanupRoot(root, expectedOutputPaths, useCaseSensitiveFileNames) {
150
129
  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();
130
+ fs.lstatSync(root.path);
131
+ } catch (error) {
132
+ if (isNodeErrorOf(error, Error, "ENOENT")) return [];
133
+ throw error;
198
134
  }
135
+ const normalizedExpectedOutputPaths = new Set([...expectedOutputPaths].map((filePath) => normalizePathForComparison(filePath, useCaseSensitiveFileNames)));
136
+ return readDir(root.path);
199
137
  function readDir(dirPath) {
200
138
  const verdicts = [];
201
139
  const stat = fs.lstatSync(dirPath);
@@ -205,7 +143,7 @@ async function mainAction(args) {
205
143
  const fullPath = path.join(dirPath, child);
206
144
  const fullPathStat = fs.lstatSync(fullPath);
207
145
  if (fullPathStat.dev !== stat.dev) {
208
- if (args.values.verbose) verdicts.push({
146
+ verdicts.push({
209
147
  path: fullPath,
210
148
  reason: "different device",
211
149
  type: "skipped"
@@ -214,7 +152,7 @@ async function mainAction(args) {
214
152
  continue;
215
153
  }
216
154
  if (fullPathStat.isSymbolicLink()) {
217
- if (args.values.verbose) verdicts.push({
155
+ verdicts.push({
218
156
  path: fullPath,
219
157
  reason: "symbolic link",
220
158
  type: "skipped"
@@ -223,8 +161,8 @@ async function mainAction(args) {
223
161
  continue;
224
162
  }
225
163
  if (fullPathStat.isFile()) {
226
- if (expectedOutDirPaths.has(fullPath)) {
227
- if (args.values.verbose) verdicts.push({
164
+ if (normalizedExpectedOutputPaths.has(normalizePathForComparison(fullPath, useCaseSensitiveFileNames))) {
165
+ verdicts.push({
228
166
  path: fullPath,
229
167
  reason: "expected output file",
230
168
  type: "skipped"
@@ -239,11 +177,16 @@ async function mainAction(args) {
239
177
  continue;
240
178
  }
241
179
  if (fullPathStat.isDirectory()) {
242
- const result = readDir(fullPath);
243
- verdicts.push(...result.verdicts);
244
- if (!result.dirIsEmpty) dirIsEmpty = false;
180
+ const childVerdicts = readDir(fullPath);
181
+ verdicts.push(...childVerdicts);
182
+ if (childVerdicts.some((verdict) => verdict.type === "skipped")) dirIsEmpty = false;
245
183
  continue;
246
184
  }
185
+ verdicts.push({
186
+ path: fullPath,
187
+ reason: "unknown file type",
188
+ type: "skipped"
189
+ });
247
190
  dirIsEmpty = false;
248
191
  }
249
192
  if (dirIsEmpty) verdicts.push({
@@ -255,20 +198,109 @@ async function mainAction(args) {
255
198
  reason: "directory not empty",
256
199
  type: "skipped"
257
200
  });
258
- return {
259
- dirIsEmpty,
260
- verdicts
261
- };
201
+ return verdicts;
202
+ }
203
+ }
204
+ function resolveCleanupRoots(project, cwd, useCaseSensitiveFileNames) {
205
+ if (project.options.outDir === void 0) throw new UserError(MISSING_OUT_DIR_ERROR);
206
+ const outDirAbsolutePath = path.resolve(cwd, project.options.outDir);
207
+ const roots = [{
208
+ name: "outDir",
209
+ path: outDirAbsolutePath,
210
+ relativePath: path.relative(cwd, outDirAbsolutePath)
211
+ }];
212
+ if (project.options.declarationDir !== void 0) {
213
+ if (project.options.declaration !== true) throw new UserError(DECLARATION_DISABLED_ERROR);
214
+ const declarationDir = path.resolve(cwd, project.options.declarationDir);
215
+ roots.push({
216
+ name: "declarationDir",
217
+ path: declarationDir,
218
+ relativePath: path.relative(cwd, declarationDir)
219
+ });
262
220
  }
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: [] };
221
+ for (const root of roots) {
222
+ if (!isPathInside(cwd, root.path, useCaseSensitiveFileNames) || isPathInside(root.path, cwd, useCaseSensitiveFileNames)) throw new UserError(`Refusing to traverse outside safe paths containing tsconfig to process ${root.name}!`);
223
+ let componentPath = cwd;
224
+ for (const component of root.relativePath.split(path.sep)) {
225
+ componentPath = path.join(componentPath, component);
226
+ let stat;
227
+ try {
228
+ stat = fs.lstatSync(componentPath);
229
+ } catch (error) {
230
+ if (isNodeErrorOf(error, Error, "ENOENT")) break;
231
+ throw error;
232
+ }
233
+ if (stat.isSymbolicLink()) throw new UserError(`Refusing to clean ${root.name} through a symbolic link: ${root.relativePath}!`);
234
+ if (!stat.isDirectory()) throw new UserError(notADirectoryError(root, path.relative(cwd, componentPath)));
235
+ }
236
+ for (const file of project.programFileNames) {
237
+ const filePath = path.resolve(cwd, file);
238
+ let realFilePath = filePath;
239
+ try {
240
+ realFilePath = fs.realpathSync(filePath);
241
+ } catch (error) {
242
+ if (!isNodeErrorOf(error, Error, "ENOENT")) throw error;
243
+ }
244
+ if (isPathInside(root.path, filePath, useCaseSensitiveFileNames) || isPathInside(root.path, realFilePath, useCaseSensitiveFileNames)) throw new UserError(`Refusing to clean ${root.name} '${root.relativePath}': it contains source file '${path.relative(cwd, file)}'.`);
269
245
  }
270
- return readDir(root.path);
271
- });
246
+ }
247
+ return roots.filter((root) => root.name === "outDir" || !isPathInside(outDirAbsolutePath, root.path, useCaseSensitiveFileNames));
248
+ }
249
+ function notADirectoryError(root, componentPath) {
250
+ return `Refusing to clean ${root.name} '${root.relativePath}': '${componentPath}' is not a directory.`;
251
+ }
252
+ const TYPESCRIPT_4_0 = 4e6;
253
+ const TYPESCRIPT_4_2 = 4002e3;
254
+ function parseTypeScriptVersion(version) {
255
+ const match = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-[-.0-9A-Za-z]+)?(?:\+[-.0-9A-Za-z]+)?$/u.exec(version);
256
+ if (match?.groups === void 0) return NaN;
257
+ const { major, minor, patch } = match.groups;
258
+ return Number(major) * 1e6 + Number(minor) * 1e3 + Number(patch);
259
+ }
260
+ const typescriptVersion = parseTypeScriptVersion(ts.version);
261
+ // src/common/typescript/loadCompiler.ts
262
+ async function loadCompiler() {
263
+ if (typescriptVersion < 3009e3) throw new UserError("TypeScript 3.8 and earlier are not supported. Use TypeScript 3.9 or later.");
264
+ if (typescriptVersion < 7e6) {
265
+ const { TypeScriptPre7Compiler } = await import("./typescriptPre7Compiler-B9gRUB0n.js");
266
+ return new TypeScriptPre7Compiler();
267
+ }
268
+ if (typescriptVersion < 7001e3) throw new UserError("TypeScript 7.0 is not supported. Use TypeScript 7.1 or later.");
269
+ const { TypeScript7Compiler } = await import("./typescript7Compiler-CKul_b13.js");
270
+ return TypeScript7Compiler.create();
271
+ }
272
+ // src/tasks/mainAction.ts
273
+ const NO_EMIT_ERROR = "Refusing to clean outDir because noEmit is enabled.";
274
+ async function mainAction(args) {
275
+ const cwd = process.cwd();
276
+ const compiler = await loadCompiler();
277
+ let cleanupRoots;
278
+ let expectedOutDirPaths;
279
+ let outDirAbsolutePath;
280
+ try {
281
+ const isPathInsideWithCompiler = (dirPath, filePath) => isPathInside(dirPath, filePath, compiler.useCaseSensitiveFileNames);
282
+ const projectAbsolutePath = path.resolve(cwd, args.values.project);
283
+ if (!isPathInsideWithCompiler(cwd, projectAbsolutePath)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
284
+ const tsconfigAbsolutePath = fs.existsSync(projectAbsolutePath) && fs.statSync(projectAbsolutePath).isDirectory() ? path.join(projectAbsolutePath, "tsconfig.json") : projectAbsolutePath;
285
+ if (!isPathInsideWithCompiler(cwd, tsconfigAbsolutePath) || isPathInsideWithCompiler(tsconfigAbsolutePath, cwd)) throw new UserError(`Refusing to traverse outside current working directory to read tsconfig!`);
286
+ print(`Using tsconfig: ${path.relative(cwd, tsconfigAbsolutePath)}`);
287
+ const project = compiler.parseProject(tsconfigAbsolutePath);
288
+ if (project.options.noEmit === true) throw new UserError(NO_EMIT_ERROR);
289
+ if (project.options.outFile !== void 0) throw new UserError("outFile is not supported");
290
+ if (project.options.incremental === true) throw new UserError("Incremental mode is not supported");
291
+ if (project.options.tsBuildInfoFile !== void 0) throw new UserError("tsBuildInfoFile is not supported");
292
+ if (project.options.composite === true) throw new UserError("Composite mode is not supported");
293
+ if (project.options.project !== void 0) throw new UserError("Project mode is not supported");
294
+ cleanupRoots = resolveCleanupRoots(project, cwd, compiler.useCaseSensitiveFileNames);
295
+ const outDirRoot = cleanupRoots.find((root) => root.name === "outDir");
296
+ if (outDirRoot === void 0) throw new Error("Missing outDir cleanup root.");
297
+ outDirAbsolutePath = outDirRoot.path;
298
+ if (args.values.noClean) return;
299
+ expectedOutDirPaths = compiler.getOutputPaths(project);
300
+ } finally {
301
+ compiler.close();
302
+ }
303
+ const results = cleanupRoots.map((root) => readCleanupRoot(root, expectedOutDirPaths, compiler.useCaseSensitiveFileNames));
272
304
  const { dry, verbose } = args.values;
273
305
  const removeVerb = dry ? "Would remove" : "Removed";
274
306
  for (const [index, root] of cleanupRoots.entries()) {
@@ -276,12 +308,20 @@ async function mainAction(args) {
276
308
  if (result === void 0) throw new Error("Missing cleanup result.");
277
309
  let fileCount = 0;
278
310
  let dirCount = 0;
279
- for (const verdict of result.verdicts) {
311
+ for (const verdict of result) {
280
312
  if (root.name === "declarationDir" && isPathInside(outDirAbsolutePath, verdict.path, compiler.useCaseSensitiveFileNames)) continue;
281
313
  const displayPath = path.relative(cwd, verdict.path);
282
314
  switch (verdict.type) {
283
315
  case "removeDir":
284
- if (!dry) fs.rmdirSync(verdict.path);
316
+ if (!dry) try {
317
+ fs.rmdirSync(verdict.path);
318
+ } catch (error) {
319
+ if (verdict.path === root.path && isNodeErrorOf(error, Error, "EBUSY")) {
320
+ if (verbose) print(`Skipped (busy directory): ${displayPath}`);
321
+ break;
322
+ }
323
+ throw error;
324
+ }
285
325
  dirCount++;
286
326
  if (dry || verbose) print(`${removeVerb} empty directory: ${displayPath}`);
287
327
  break;
@@ -307,7 +347,7 @@ function formatCount(count, singular, plural) {
307
347
  return `${count.toFixed()} ${count === 1 ? singular : plural}`;
308
348
  }
309
349
  // package.json
310
- var version$1 = "0.4.0";
350
+ var version$1 = "0.4.1";
311
351
  // src/tasks/version.ts
312
352
  function version() {
313
353
  print(`${binName}/${version$1} ${process.platform}-${process.arch} node-${process.versions.node} typescript-${ts.version}`);
@@ -325,4 +365,4 @@ async function main() {
325
365
  }
326
366
  }
327
367
  main();
328
- export { typescriptVersion as n, UserError as r, TYPESCRIPT_4_2 as t };
368
+ export { UserError as i, TYPESCRIPT_4_2 as n, typescriptVersion as r, TYPESCRIPT_4_0 as t };
@@ -1,7 +1,14 @@
1
1
  import fs from "node:fs";
2
+ import { i as UserError } from "./tscAfter.js";
2
3
  import path from "node:path";
3
- import { r as UserError } from "./tscAfter.js";
4
4
  // src/common/typescript/outputPaths.ts
5
+ const declarationFileExtensions = [
6
+ ".d.ts",
7
+ ".d.mts",
8
+ ".d.cts"
9
+ ];
10
+ const esmFileExtensions = [".mts", ".mjs"];
11
+ const cjsFileExtensions = [".cts", ".cjs"];
5
12
  function getOutputFileNames(options, fileName) {
6
13
  const sourcePath = path.resolve(fileName);
7
14
  const sourceExtension = path.extname(sourcePath);
@@ -11,7 +18,7 @@ function getOutputFileNames(options, fileName) {
11
18
  const outputFileNames = [];
12
19
  const outputPath = getOutputPath(sourcePath, resolveOptionPath(options.outDir, options.configFilePath), options.rootDir, options.configFilePath);
13
20
  if (isJsonFile) {
14
- outputFileNames.push(outputPath);
21
+ if (options.emitDeclarationOnly !== true) outputFileNames.push(outputPath);
15
22
  return outputFileNames;
16
23
  }
17
24
  const javaScriptExtension = getJavaScriptExtension(sourceExtension, options.jsx);
@@ -29,8 +36,8 @@ function getOutputFileNames(options, fileName) {
29
36
  return outputFileNames;
30
37
  }
31
38
  function getDeclarationExtension(sourceExtension) {
32
- if (sourceExtension === ".mts" || sourceExtension === ".mjs") return ".d.mts";
33
- if (sourceExtension === ".cts" || sourceExtension === ".cjs") return ".d.cts";
39
+ if (esmFileExtensions.includes(sourceExtension)) return ".d.mts";
40
+ if (cjsFileExtensions.includes(sourceExtension)) return ".d.cts";
34
41
  return ".d.ts";
35
42
  }
36
43
  function getJavaScriptExtension(sourceExtension, jsx) {
@@ -46,7 +53,7 @@ function getOutputPath(sourcePath, outputDirectory, rootDir, configFilePath) {
46
53
  return path.resolve(outputDirectory, path.relative(resolvedRootDir, sourcePath));
47
54
  }
48
55
  function isDeclarationFile(fileName) {
49
- return fileName.endsWith(".d.ts") || fileName.endsWith(".d.mts") || fileName.endsWith(".d.cts");
56
+ return declarationFileExtensions.some((extension) => fileName.endsWith(extension)) || /\.d\..+\.ts$/u.test(path.basename(fileName));
50
57
  }
51
58
  function replaceExtension(fileName, extension) {
52
59
  return `${fileName.slice(0, -path.extname(fileName).length)}${extension}`;
@@ -74,12 +81,8 @@ var TypeScript7Compiler = class TypeScript7Compiler {
74
81
  this.useCaseSensitiveFileNames = api.getCanonicalFileName("a") !== api.getCanonicalFileName("A");
75
82
  }
76
83
  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;
84
+ const typescriptSync = await loadTypeScript7SyncModule();
85
+ const api = new typescriptSync.API();
83
86
  try {
84
87
  api.parseCommandLine([]);
85
88
  return new TypeScript7Compiler(typescriptSync, api);
@@ -114,8 +117,7 @@ var TypeScript7Compiler = class TypeScript7Compiler {
114
117
  }
115
118
  const program = this.program;
116
119
  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.");
120
+ const configFilePath = project.configFilePath;
119
121
  const outputOptions = {
120
122
  ...config.options,
121
123
  configFilePath,
@@ -142,20 +144,17 @@ var TypeScript7Compiler = class TypeScript7Compiler {
142
144
  getNewLine: () => this.api.getNewLine()
143
145
  }).trimEnd());
144
146
  };
145
- const readConfig = (filePath) => {
147
+ const checkConfigFile = (filePath) => {
146
148
  const result = this.api.readConfigFile(filePath);
147
149
  if (result.error !== void 0) checkDiagnostics([result.error]);
148
- return result.config;
149
150
  };
150
- const rootConfig = readConfig(configFilePath);
151
+ checkConfigFile(configFilePath);
151
152
  const config = this.api.parseConfigFile(configFilePath);
152
153
  checkDiagnostics(config.errors);
153
- const extendedConfigInfo = getExtendedConfigInfo(readConfig, configFilePath, rootConfig);
154
154
  const program = this.api.createProgram(config.fileNames, config.options);
155
155
  const project = {
156
- configFilePaths: extendedConfigInfo.configFilePaths,
156
+ configFilePath,
157
157
  fileNames: config.fileNames,
158
- hasWatchOptions: extendedConfigInfo.hasWatchOptions,
159
158
  options: config.options,
160
159
  programFileNames: program.getSourceFileNames().filter((fileName) => {
161
160
  const metadata = program.getSourceFileMetadata(fileName);
@@ -172,49 +171,7 @@ var TypeScript7Compiler = class TypeScript7Compiler {
172
171
  if (this.isClosed) throw new Error("Compiler is closed.");
173
172
  }
174
173
  };
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}'.`);
174
+ async function loadTypeScript7SyncModule() {
175
+ return await import(syncModuleSpecifier);
219
176
  }
220
177
  export { TypeScript7Compiler };
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { n as typescriptVersion, r as UserError } from "./tscAfter.js";
2
+ import { i as UserError, r as typescriptVersion } from "./tscAfter.js";
3
3
  // src/common/typescript/typescriptPre7Compiler.ts
4
4
  /** Uses the `typescript` API for TypeScript 3.9 through 6.x. */
5
5
  var TypeScriptPre7Compiler = class {
@@ -14,6 +14,8 @@ var TypeScriptPre7Compiler = class {
14
14
  if (parsedCommandLine === void 0) throw new Error("Project was not parsed by this compiler.");
15
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
16
  const emittableFileNames = project.programFileNames.filter((fileName) => !isDeclarationFileName(fileName));
17
+ if (typescriptVersion < 4e6 && parsedCommandLine.options.emitDeclarationOnly === true && parsedCommandLine.options.resolveJsonModule === true && emittableFileNames.some((fileName) => fileName.endsWith(".json"))) throw new UserError("Refusing to clean outDir: TypeScript 3.9 cannot safely determine outputs for emitDeclarationOnly with resolveJsonModule.");
18
+ if (typescriptVersion < 4e6 && parsedCommandLine.options.allowJs === true && parsedCommandLine.options.jsx === ts.JsxEmit.Preserve && parsedCommandLine.options.declaration === true && emittableFileNames.some((fileName) => fileName.endsWith(".jsx"))) throw new UserError("Refusing to clean outDir: TypeScript 3.9 cannot safely determine outputs for allowJs JSX preserve with declaration.");
17
19
  const outputCommandLine = {
18
20
  ...parsedCommandLine,
19
21
  fileNames: emittableFileNames
@@ -29,7 +31,7 @@ var TypeScriptPre7Compiler = class {
29
31
  getNewLine: () => ts.sys.newLine
30
32
  };
31
33
  const checkConfigFile = (filePath) => {
32
- const config = ts.readConfigFile(filePath, (name) => ts.sys.readFile(name));
34
+ const config = ts.readConfigFile(filePath.replaceAll("\\", "/"), (name) => ts.sys.readFile(name));
33
35
  if (config.error !== void 0) throw new UserError(ts.formatDiagnostics([config.error], formatHost).trimEnd());
34
36
  };
35
37
  checkConfigFile(configFilePath);
@@ -46,9 +48,8 @@ var TypeScriptPre7Compiler = class {
46
48
  for (const filePath of configFile?.extendedSourceFiles ?? []) checkConfigFile(filePath);
47
49
  const program = ts.createProgram(parsedCommandLine.fileNames, parsedCommandLine.options);
48
50
  const project = {
49
- configFilePaths: [configFile?.fileName ?? configFilePath, ...configFile?.extendedSourceFiles ?? []],
51
+ configFilePath: configFile?.fileName ?? configFilePath,
50
52
  fileNames: parsedCommandLine.fileNames,
51
- hasWatchOptions: parsedCommandLine.watchOptions !== void 0,
52
53
  options: parsedCommandLine.options,
53
54
  programFileNames: program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile) && !program.isSourceFileFromExternalLibrary(sourceFile)).map((sourceFile) => sourceFile.fileName)
54
55
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsc-after",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
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",