dt-clean 1.0.1 → 1.1.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/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [v1.1.1](https://github.com/ljharb/dt-clean/compare/v1.1.0...v1.1.1) - 2026-06-21
9
+
10
+ ### Commits
11
+
12
+ - [Fix] `--setup`: never duplicate `dt-clean`, and converge on the preferred hook [`bc32122`](https://github.com/ljharb/dt-clean/commit/bc321229b54decfd6000e8d58d202604c36af206)
13
+ - [Dev Deps] add `dt-clean` (self-reference) [`d1a6cdf`](https://github.com/ljharb/dt-clean/commit/d1a6cdf7de2c29d1a17858bf8febf4bd586253f6)
14
+
15
+ ## [v1.1.0](https://github.com/ljharb/dt-clean/compare/v1.0.1...v1.1.0) - 2026-06-21
16
+
17
+ ### Commits
18
+
19
+ - [New] add `--auto`, meant for the `dependencies` lifecycle script [`bc60a91`](https://github.com/ljharb/dt-clean/commit/bc60a91bf4f3e4d0964f8dcb71d1b0d1182612f9)
20
+ - [Tests] treat taken-down registry packages as skipped, not failures [`d020cc6`](https://github.com/ljharb/dt-clean/commit/d020cc62dd06de08189eebfe45e79a372ec8e5a1)
21
+ - [meta] run `dt-clean --setup` [`459cc0c`](https://github.com/ljharb/dt-clean/commit/459cc0cc3a5a2b64e498946c8930ae49899eb8b3)
22
+
8
23
  ## [v1.0.1](https://github.com/ljharb/dt-clean/compare/v1.0.0...v1.0.1) - 2026-06-19
9
24
 
10
25
  ### Commits
package/README.md CHANGED
@@ -47,8 +47,46 @@ With `--update` (`-u`), `dt-clean` edits `package.json` in place - adding, movin
47
47
  ### Options
48
48
 
49
49
  - `-u`, `--update`: apply the changes to `package.json` (default: report only).
50
+ - `--setup`: idempotently wire `dt-clean --auto` into a `dependencies` lifecycle script, without overwriting any existing script (see [Automatic cleanup](#automatic-cleanup)).
51
+ - `--auto`: for use in a `dependencies` lifecycle script - apply the changes like `--update` during `npm install`, but during `npm ci` only print what would change and exit `0` (see [Automatic cleanup](#automatic-cleanup)).
50
52
  - `--help`: show usage.
51
53
 
54
+ ### Automatic cleanup
55
+
56
+ To keep your `@types/*` set tidy on every install, run `dt-clean --auto` from a [`dependencies` lifecycle script](https://docs.npmjs.com/cli/using-npm/scripts#npm-install) - the one npm's installer (arborist) runs after any operation that changes `node_modules`.
57
+
58
+ The one-step way to set this up, in any project, is:
59
+
60
+ ```sh
61
+ npx dt-clean --setup
62
+ ```
63
+
64
+ `--setup` edits `package.json` for you and is safe to run anywhere:
65
+
66
+ - if you have no `dependencies` script, it adds `"dependencies": "dt-clean --auto"`;
67
+ - if you already have one, it adds `dt-clean --auto` to a free `postdependencies` (or `predependencies`) hook instead, so your existing script is never touched - and if every hook is taken, it appends `&& dt-clean --auto` to your `dependencies` script rather than clobbering it;
68
+ - if it already added `dt-clean --auto` to a `post`/`pre` hook and the preferred `dependencies` slot later frees up, re-running moves it back to the most-preferred available hook;
69
+ - if `dt-clean --auto` is already in the best available hook, it does nothing; and if some other `dt-clean` invocation (or a customized one you wrote) is already present, it leaves that alone rather than adding a duplicate.
70
+
71
+ It only ever manages this one invocation and leaves the rest of your `package.json` (and its formatting) alone, so it's safe to re-run - repeated runs converge on the same result. That result is simply the equivalent of:
72
+
73
+ ```json
74
+ {
75
+ "scripts": {
76
+ "dependencies": "dt-clean --auto"
77
+ }
78
+ }
79
+ ```
80
+
81
+ Once it's wired in, `dt-clean --auto` inspects `npm_command` to decide what to do:
82
+
83
+ - under `npm install`, it applies the changes for you, so a fresh install keeps your `@types/*` set tidy automatically;
84
+ - under `npm ci` (typically used in CI pipelines, where `package.json` must not be mutated), it only prints what would change and exits `0`, so it never edits a checked-in file and never fails the install.
85
+
86
+ When `npm_command` is anything else (or absent), `--auto` applies the changes, exactly as under `npm install`.
87
+
88
+ To avoid surprising edits, `--auto` runs *only* inside the `dependencies` lifecycle (or its `predependencies`/`postdependencies` hooks): it checks `npm_lifecycle_event`, and if it is invoked any other way (for example directly from the shell) it refuses to do anything and exits nonzero. Use `--update` to apply changes manually.
89
+
52
90
  ### Exit codes
53
91
 
54
92
  In the default report-only mode, the exit code is a bitmask of the kinds of pending changes, so a clean project exits `0` and you can fail CI (or a `git` pre-commit hook) on drift:
package/applyChanges.mjs CHANGED
@@ -1,11 +1,7 @@
1
1
  import { join } from 'path';
2
2
  import { readFile, writeFile } from 'fs/promises';
3
3
 
4
- /** @param {string} raw */
5
- function detectIndent(raw) {
6
- const match = (/^[ \t]+/m).exec(raw);
7
- return match?.[0] ?? '\t';
8
- }
4
+ import detectIndent from '#/detectIndent';
9
5
 
10
6
  /** @type {<K extends string, V>(obj: Record<K, V>) => Record<K, V>} */
11
7
  function sortKeys(obj) {
package/bin.mjs CHANGED
@@ -8,20 +8,36 @@ import getDelTa from '#/getDelTa';
8
8
  import applyChanges from '#/applyChanges';
9
9
  import formatReport from '#/report';
10
10
  import exitCode from '#/exitCode';
11
+ import setupScripts from '#/setup';
11
12
 
12
13
  const {
13
- values: { json, update },
14
+ values: {
15
+ auto,
16
+ json,
17
+ setup,
18
+ update,
19
+ },
14
20
  positionals,
15
21
  help,
16
22
  } = await pargs(import.meta.filename, {
17
23
  allowPositionals: 1,
18
24
  description: 'Reports which DefinitelyTyped (`@types/*`) packages a project should add, move, or remove. By default it only reports; with `--update` it edits `package.json`.',
19
25
  options: {
26
+ auto: {
27
+ default: false,
28
+ description: 'for a `dependencies` lifecycle script (or its `pre`/`post` hooks): apply the changes like `--update` during `npm install`, but during `npm ci` only print what would change and exit zero',
29
+ type: 'boolean',
30
+ },
20
31
  json: {
21
32
  default: false,
22
33
  description: 'print the result as JSON on stdout (the human-readable report moves to stderr)',
23
34
  type: 'boolean',
24
35
  },
36
+ setup: {
37
+ default: false,
38
+ description: 'idempotently add `dt-clean --auto` to a `dependencies` lifecycle script in `package.json`, without overwriting any existing script',
39
+ type: 'boolean',
40
+ },
25
41
  update: {
26
42
  default: false,
27
43
  description: 'apply the changes to `package.json`, then run `npm install` (or your package manager\'s equivalent)',
@@ -36,54 +52,87 @@ await help();
36
52
 
37
53
  const cwd = positionals.length > 0 ? resolve(positionals[0]) : process.cwd();
38
54
 
39
- const {
40
- present,
41
- toAdd,
42
- toMove,
43
- toRemain,
44
- toRemove,
45
- } = await getDelTa(cwd);
55
+ const { npm_command: npmCommand, npm_lifecycle_event: lifecycleEvent } = process.env;
46
56
 
47
- const report = formatReport({
48
- present,
49
- toAdd,
50
- toMove,
51
- toRemove,
52
- });
57
+ // the `dependencies` lifecycle and its `pre`/`post` hooks are the only safe slots for `--auto`,
58
+ // since npm runs them after a reify; `postdependencies`/`predependencies` let you add it without
59
+ // clobbering an existing `dependencies` script.
60
+ const DEPENDENCY_HOOKS = [
61
+ 'predependencies',
62
+ 'dependencies',
63
+ 'postdependencies',
64
+ ];
53
65
 
54
- if (json) {
55
- console.log(JSON.stringify({
56
- present: Object.fromEntries(present),
57
- toAdd: Object.fromEntries(toAdd),
58
- toMove: Object.fromEntries(toMove),
59
- toRemain: Array.from(toRemain),
60
- toRemove,
61
- }, null, '\t'));
62
- console.error(report);
66
+ if (setup) {
67
+ const { action, script } = await setupScripts(cwd);
68
+ console.log({
69
+ chained: `Appended \`dt-clean --auto\` to the existing \`${script}\` script in \`package.json\`.`,
70
+ exists: `\`${script}\` already invokes \`dt-clean\` (without \`--auto\`); leaving it unchanged - add \`--auto\` there yourself for install-time cleanup.`,
71
+ moved: `Moved \`dt-clean --auto\` to the preferred \`${script}\` script in \`package.json\`.`,
72
+ present: `\`${script}\` already runs \`dt-clean --auto\`; nothing to do.`,
73
+ set: `Added \`dt-clean --auto\` to the \`${script}\` script in \`package.json\`.`,
74
+ }[action]);
75
+ } else if (auto && (!lifecycleEvent || !DEPENDENCY_HOOKS.includes(lifecycleEvent))) {
76
+ console.error('`--auto` only runs inside a `dependencies` (or `pre`/`postdependencies`) lifecycle script (see the README); use `--update` to apply changes manually.');
77
+ process.exitCode = 1;
63
78
  } else {
64
- console.log(report);
65
- }
66
-
67
- if (update) {
68
- // `--update` applies the changes, leaving the project clean, so a successful run exits zero;
69
- // only an error (e.g. a failed write, which throws) yields a nonzero exit.
70
- const changed = await applyChanges(cwd, {
79
+ const {
80
+ present,
71
81
  toAdd,
72
82
  toMove,
83
+ toRemain,
73
84
  toRemove,
74
- });
75
- console.error(changed
76
- ? '\nUpdated `package.json`; run `npm install` (or your package manager’s equivalent) to sync.'
77
- : '\nNo changes needed.');
78
- } else {
79
- // report-only: the exit code is a bitmask of the pending change kinds, so a clean project exits zero.
80
- const code = exitCode({
85
+ } = await getDelTa(cwd);
86
+
87
+ const report = formatReport({
88
+ present,
81
89
  toAdd,
82
90
  toMove,
83
91
  toRemove,
84
92
  });
85
- process.exitCode = code;
86
- if (code > 0) {
87
- console.error('\nRe-run with `--update` (`-u`) to apply these changes to `package.json`.');
93
+
94
+ if (json) {
95
+ console.log(JSON.stringify({
96
+ present: Object.fromEntries(present),
97
+ toAdd: Object.fromEntries(toAdd),
98
+ toMove: Object.fromEntries(toMove),
99
+ toRemain: Array.from(toRemain),
100
+ toRemove,
101
+ }, null, '\t'));
102
+ console.error(report);
103
+ } else {
104
+ console.log(report);
105
+ }
106
+
107
+ if (update || (auto && npmCommand !== 'ci')) {
108
+ // `--update` applies the changes, leaving the project clean, so a successful run exits zero;
109
+ // only an error (e.g. a failed write, which throws) yields a nonzero exit.
110
+ const changed = await applyChanges(cwd, {
111
+ toAdd,
112
+ toMove,
113
+ toRemove,
114
+ });
115
+ console.error(changed
116
+ ? '\nUpdated `package.json`; run `npm install` (or your package manager’s equivalent) to sync.'
117
+ : '\nNo changes needed.');
118
+ } else {
119
+ const code = exitCode({
120
+ toAdd,
121
+ toMove,
122
+ toRemove,
123
+ });
124
+ if (auto) {
125
+ // `--auto` under `npm ci`: leave the exit code at zero so a CI install never fails; the
126
+ // report above already lists what `npm install` would change.
127
+ if (code > 0) {
128
+ console.error('\n`npm ci` detected; `package.json` left unchanged. Run `npm install` or `dt-clean --update` to apply these changes.');
129
+ }
130
+ } else {
131
+ // report-only: the exit code is a bitmask of the pending change kinds, so a clean project exits zero.
132
+ process.exitCode = code;
133
+ if (code > 0) {
134
+ console.error('\nRe-run with `--update` (`-u`) to apply these changes to `package.json`.');
135
+ }
136
+ }
88
137
  }
89
138
  }
@@ -0,0 +1,3 @@
1
+ declare function detectIndent(raw: string): string;
2
+
3
+ export = detectIndent;
@@ -0,0 +1,5 @@
1
+ /** @type {import('./detectIndent.d.ts')} */
2
+ export default function detectIndent(raw) {
3
+ const match = (/^[ \t]+/m).exec(raw);
4
+ return match?.[0] ?? '\t';
5
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dt-clean",
3
- "version": "1.0.1",
3
+ "version": "1.1.1",
4
4
  "description": "Ensures the only DefinitelyTyped (`@types`) packages you have installed are the ones you need",
5
5
  "bin": "./bin.mjs",
6
6
  "exports": {
@@ -23,7 +23,8 @@
23
23
  "lint": "eslint .",
24
24
  "posttest": "npx npm@'>= 10.2' audit --production",
25
25
  "version": "auto-changelog && git add CHANGELOG.md",
26
- "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
26
+ "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"",
27
+ "dependencies": "dt-clean --auto"
27
28
  },
28
29
  "repository": {
29
30
  "type": "git",
@@ -50,6 +51,7 @@
50
51
  "@types/semver": "^7.7.1",
51
52
  "auto-changelog": "^2.6.0",
52
53
  "c8": "^11.0.0",
54
+ "dt-clean": "file:./",
53
55
  "eslint": "^10.5.0",
54
56
  "esmock": "^2.7.6",
55
57
  "globals": "^17.6.0",
package/setup.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ declare function setup(cwd: string): Promise<setup.SetupResult>;
2
+
3
+ declare namespace setup {
4
+ type DependencyHook = 'predependencies' | 'dependencies' | 'postdependencies';
5
+
6
+ type SetupResult = {
7
+ action: 'present' | 'exists' | 'set' | 'moved' | 'chained';
8
+ script: DependencyHook;
9
+ };
10
+ }
11
+
12
+ export = setup;
package/setup.mjs ADDED
@@ -0,0 +1,82 @@
1
+ import { join } from 'path';
2
+ import { readFile, writeFile } from 'fs/promises';
3
+
4
+ import detectIndent from '#/detectIndent';
5
+
6
+ /** @import { PackageJSON } from './types/types.d.ts' */
7
+ /** @import { SetupResult } from './setup.d.ts' */
8
+
9
+ const AUTO = 'dt-clean --auto';
10
+
11
+ // listed most-preferred first: the `dependencies` event itself, then its `post`/`pre` hooks.
12
+ const HOOKS = /** @type {const} */ ([
13
+ 'dependencies',
14
+ 'postdependencies',
15
+ 'predependencies',
16
+ ]);
17
+
18
+ /** @param {string | undefined} script */
19
+ function hasAuto(script) {
20
+ // matches a `dt-clean … --auto` invocation confined to one `&&`/`;`/`|`-delimited segment
21
+ return typeof script === 'string' && (/\bdt-clean\b[^&|;]*--auto\b/).test(script);
22
+ }
23
+
24
+ /** @param {string | undefined} script */
25
+ function hasDtClean(script) {
26
+ return typeof script === 'string' && (/\bdt-clean\b/).test(script);
27
+ }
28
+
29
+ /** @type {import('./setup.d.ts')} */
30
+ export default async function setup(cwd) {
31
+ const packageJSONpath = join(cwd, 'package.json');
32
+ const raw = `${await readFile(packageJSONpath)}`;
33
+
34
+ /** @type {PackageJSON} */
35
+ const pkg = JSON.parse(raw);
36
+
37
+ /** @type {NonNullable<PackageJSON['scripts']>} */
38
+ const scripts = { ...pkg.scripts };
39
+
40
+ // a standalone `dt-clean --auto` we wrote ourselves, which we may therefore safely relocate.
41
+ const owned = HOOKS.find((hook) => scripts[hook] === AUTO);
42
+
43
+ if (!owned) {
44
+ // a `dt-clean --auto` we didn't write (chained or customized): leave it exactly as-is.
45
+ const wired = HOOKS.find((hook) => hasAuto(scripts[hook]));
46
+ if (wired) {
47
+ return { action: 'present', script: wired };
48
+ }
49
+ // some other `dt-clean` invocation: don't add a second one.
50
+ const existing = HOOKS.find((hook) => hasDtClean(scripts[hook]));
51
+ if (existing) {
52
+ return { action: 'exists', script: existing };
53
+ }
54
+ }
55
+
56
+ // the most-preferred hook our invocation should occupy: free, or already holding it.
57
+ const target = HOOKS.find((hook) => !scripts[hook] || scripts[hook] === AUTO);
58
+
59
+ if (owned && owned === target) {
60
+ return { action: 'present', script: owned };
61
+ }
62
+
63
+ /** @type {SetupResult} */
64
+ let result;
65
+ if (target) {
66
+ if (owned) {
67
+ // a more-preferred hook is now free: relocate to it.
68
+ delete scripts[owned];
69
+ }
70
+ scripts[target] = AUTO;
71
+ result = { action: owned ? 'moved' : 'set', script: target };
72
+ } else {
73
+ // every hook is occupied, so chain onto `dependencies` rather than clobber anything.
74
+ scripts.dependencies = `${scripts.dependencies} && ${AUTO}`;
75
+ result = { action: 'chained', script: 'dependencies' };
76
+ }
77
+
78
+ const next = { ...pkg, scripts };
79
+ await writeFile(packageJSONpath, `${JSON.stringify(next, null, detectIndent(raw))}\n`);
80
+
81
+ return result;
82
+ }