@syntopica/quality-config 0.13.1 → 0.14.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
@@ -19,7 +19,7 @@ files/exports/dependencies (knip), module boundaries and dependency cycles
19
19
  ## Install
20
20
 
21
21
  ```bash
22
- pnpm add -D @syntopica/quality-config@^0.1.0 typescript
22
+ pnpm add -D @syntopica/quality-config typescript
23
23
  ```
24
24
 
25
25
  Add `knip` and/or `dependency-cruiser` for the gates you use.
@@ -34,6 +34,25 @@ Add `knip` and/or `dependency-cruiser` for the gates you use.
34
34
  | `@syntopica/quality-config/type-coverage` | Minimum non-`any` type coverage threshold |
35
35
  | `@syntopica/quality-config/lefthook` | Shared git hook pipeline |
36
36
 
37
+ ### `knip --production`
38
+
39
+ Every preset marks its runtime entries and source globs with knip's production
40
+ suffix (`!`) and leaves configuration files unmarked, and tests, mocks and
41
+ stories are excluded in production mode only. `knip --production` then starts
42
+ from the code that ships: a dependency only a test imports, or a build plugin in
43
+ `dependencies`, is reported there, while the default run is unchanged. A
44
+ `project` or `entry` glob you pass that holds runtime code needs the `!` too
45
+ (`'components/**/*.tsx!'`); unmarked, it is left out of the production run.
46
+
47
+ ### Module boundaries on the resolved graph
48
+
49
+ `createDepCruiserConfig({ moduleRoots: ['src/features'] })` treats each child of
50
+ `src/features` as a module and fails any file in one module that reaches a file
51
+ of another module other than its `index`. It runs on resolved paths, so an
52
+ alias, a re-export or a relative `../../` are all caught the same way, which
53
+ code-policy's `public-api-imports` and `no-cross-module-deep-imports` cannot do
54
+ from the import string. Off unless roots are named.
55
+
37
56
  ### `baseline-env-init`
38
57
 
39
58
  Seeds a gitignored `.env` from the committed `.env.example`, so a freshly cloned
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syntopica/quality-config",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Shared configuration for cross-file quality gates: knip, dependency-cruiser, type-coverage, jscpd, lefthook",
@@ -73,12 +73,12 @@
73
73
  },
74
74
  "devDependencies": {
75
75
  "@arethetypeswrong/cli": "^0.18.5",
76
- "@syntopica/eslint-config": "0.9.0",
77
- "@types/node": "^26.6.4",
76
+ "@syntopica/eslint-config": "0.10.0",
77
+ "@types/node": "^26.6.5",
78
78
  "dependency-cruiser": "^18.5.0",
79
79
  "eslint": "^10.12.0",
80
80
  "eslint-plugin-regexp": "^3.3.1",
81
- "knip": "^6.40.0",
81
+ "knip": "^6.41.0",
82
82
  "publint": "^0.3.25",
83
83
  "typescript": "npm:@typescript/typescript6@^6.0.2",
84
84
  "vitest": "^5.0.3"
@@ -0,0 +1,14 @@
1
+ import type { KnipFramework } from './knip-framework'
2
+
3
+ /**
4
+ * Framework packages that serve the app but are imported only by its config
5
+ * file. `knip --production` drops config files, so it reports `astro` and
6
+ * `nuxt` as unused; both are runtime dependencies. The trailing `!` makes the
7
+ * ignore apply to production mode only, so the default run still checks them.
8
+ */
9
+ export const FRAMEWORK_RUNTIME_PACKAGES: Partial<
10
+ Record<KnipFramework, string[]>
11
+ > = {
12
+ astro: ['astro!'],
13
+ nuxt: ['nuxt!'],
14
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The configuration files knip's Lefthook plugin reads, as of knip 6.41.
3
+ * With one present, the plugin reports `lefthook` as used: under `CI` it adds
4
+ * the package outright, and elsewhere it reads the installed `.git/hooks`,
5
+ * which call the `lefthook` binary.
6
+ */
7
+ export const LEFTHOOK_CONFIG_FILES: readonly string[] = [
8
+ 'lefthook.yml',
9
+ 'lefthook.yaml',
10
+ 'lefthook.json',
11
+ 'lefthook.jsonc',
12
+ 'lefthook.toml',
13
+ '.lefthook.yml',
14
+ '.lefthook.yaml',
15
+ '.lefthook.json',
16
+ '.lefthook.jsonc',
17
+ '.lefthook.toml',
18
+ '.config/lefthook.yml',
19
+ '.config/lefthook.yaml',
20
+ '.config/lefthook.json',
21
+ '.config/lefthook.jsonc',
22
+ '.config/lefthook.toml',
23
+ ]
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Project files that never ship, excluded from `knip --production` only: the
3
+ * leading `!` negates, the trailing `!` limits the negation to production mode,
4
+ * so the default run still analyses tests and stories. Without it a test file
5
+ * matched by a production project glob counts as runtime code, and a
6
+ * dependency only the tests import would pass for a production one.
7
+ */
8
+ export const PRODUCTION_PROJECT_EXCLUSIONS = [
9
+ '!**/*.{test,spec}.{ts,tsx,mts,cts,js,jsx,mjs,cjs}!',
10
+ '!**/{__tests__,__mocks__,test,tests}/**!',
11
+ '!**/*.stories.{ts,tsx,js,jsx,mdx}!',
12
+ ]
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The words after which a script name runs that script rather than a binary:
3
+ * `pnpm type-coverage`, `pnpm run type-coverage`, `npm run type-coverage`,
4
+ * `yarn type-coverage`. `exec` and `dlx` are deliberately absent, since
5
+ * `pnpm exec type-coverage` does run the binary.
6
+ */
7
+ export const SCRIPT_RUNNERS: ReadonlySet<string> = new Set([
8
+ 'pnpm',
9
+ 'yarn',
10
+ 'bun',
11
+ 'run',
12
+ 'run-s',
13
+ 'run-p',
14
+ ])
@@ -1,5 +1,7 @@
1
1
  import type { IConfiguration, IForbiddenRuleType } from 'dependency-cruiser'
2
2
 
3
+ import { moduleBoundaryRules } from './moduleBoundaryRules'
4
+
3
5
  // Next.js App Router file conventions. Next loads each of these by filename at
4
6
  // build or request time, so nothing imports them and having no importer is
5
7
  // their normal state rather than a defect.
@@ -109,12 +111,16 @@ const REPO_SCOPE_RULES: IForbiddenRuleType[] = [
109
111
  * the framework-convention ones built in here. Use it for directories a
110
112
  * repo-wide run cannot judge - typically a workspace whose path aliases only
111
113
  * resolve under its own tsconfig, cruised separately at `scope: 'workspace'`.
114
+ *
115
+ * `moduleRoots` (opt-in) names directories whose children are modules, such
116
+ * as `src/features`: a module may reach another only through its `index`.
112
117
  */
113
118
  export const createDepCruiserConfig = (
114
119
  options: {
115
120
  tsConfigPath?: string
116
121
  scope?: 'repo' | 'workspace'
117
122
  orphanExemptions?: string[]
123
+ moduleRoots?: string[]
118
124
  } = {},
119
125
  ): IConfiguration => ({
120
126
  forbidden: [
@@ -130,6 +136,7 @@ export const createDepCruiserConfig = (
130
136
  to: {},
131
137
  },
132
138
  ...(options.scope === 'workspace' ? [] : REPO_SCOPE_RULES),
139
+ ...moduleBoundaryRules(options.moduleRoots ?? []),
133
140
  ],
134
141
  options: {
135
142
  doNotFollow: { path: 'node_modules' },
@@ -11,9 +11,13 @@ const GLOB_CHARACTERS = /[*?{}[\]!]/u
11
11
  * pattern (no matches)" hint the caller cannot silence.
12
12
  */
13
13
  export const existingEntries = (entries: string[], cwd: string): string[] =>
14
- entries.filter(
15
- (entry) =>
16
- GLOB_CHARACTERS.test(entry) ||
14
+ entries.filter((entry) => {
15
+ // A trailing `!` marks a production entry, not a glob: `src/index.ts!` is
16
+ // still the literal `src/index.ts`.
17
+ const path = entry.replace(/!$/u, '')
18
+ return (
19
+ GLOB_CHARACTERS.test(path) ||
17
20
  // eslint-disable-next-line security/detect-non-literal-fs-filename -- the entry is the preset's own literal, resolved against the project root
18
- existsSync(join(cwd, entry)),
19
- )
21
+ existsSync(join(cwd, path))
22
+ )
23
+ })
@@ -0,0 +1,11 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import { LEFTHOOK_CONFIG_FILES } from './LEFTHOOK_CONFIG_FILES'
5
+
6
+ /** Whether `cwd` has a configuration file knip's Lefthook plugin reads. */
7
+ export const hasLefthookConfig = (cwd: string): boolean =>
8
+ LEFTHOOK_CONFIG_FILES.some((file) =>
9
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- fixed file names under the project root
10
+ existsSync(join(cwd, file)),
11
+ )
@@ -0,0 +1,16 @@
1
+ import { SCRIPT_RUNNERS } from './SCRIPT_RUNNERS'
2
+
3
+ /**
4
+ * Whether `word` names a `package.json` script that the previous word runs.
5
+ * `"check:quality": "pnpm type-coverage"` runs the `type-coverage` script, not
6
+ * the `type-coverage` binary, and knip resolves it that way, so reading it as
7
+ * a use of the binary would leave the package neither ignored nor used.
8
+ */
9
+ export const isScriptInvocation = (
10
+ word: string,
11
+ previous: string | undefined,
12
+ scriptNames: ReadonlySet<string>,
13
+ ): boolean =>
14
+ previous !== undefined &&
15
+ SCRIPT_RUNNERS.has(previous) &&
16
+ scriptNames.has(word)
@@ -10,6 +10,17 @@
10
10
  * imports it by design. knip 6.35 started applying `includeEntryExports` to
11
11
  * the files its own plugins register, so a blanket `true` failed the gate in
12
12
  * six of the eight templates with exports no project can remove.
13
+ *
14
+ * A trailing `!` marks a pattern as production code for `knip --production`,
15
+ * which keeps only marked entries and marked project files: the runtime roots
16
+ * and sources carry it, framework and build configuration does not. Without
17
+ * the mark, production mode treated every source file as outside the project
18
+ * and reported runtime dependencies - `vue`, `zod`, `@nestjs/core` - as unused.
19
+ * Tests sitting beside the sources are excluded from production through
20
+ * PRODUCTION_PROJECT_EXCLUSIONS. Configuration stays unmarked - knip drops a
21
+ * plugin's config files from production whatever their mark - so a Vite plugin
22
+ * imported only by `vite.config.*` and declared in `dependencies` is reported
23
+ * there, rightly: it is a build tool.
13
24
  */
14
25
  export type KnipFramework =
15
26
  | 'astro'
@@ -27,13 +38,13 @@ export const FRAMEWORK_ENTRIES: Record<
27
38
  { entry: string[]; project: string[]; includeEntryExports: boolean }
28
39
  > = {
29
40
  astro: {
30
- entry: ['src/pages/**/*.{astro,ts,tsx}', 'astro.config.*'],
31
- project: ['src/**/*.{astro,ts,tsx}'],
41
+ entry: ['src/pages/**/*.{astro,ts,tsx}!', 'astro.config.*'],
42
+ project: ['src/**/*.{astro,ts,tsx}!'],
32
43
  includeEntryExports: false,
33
44
  },
34
45
  nestjs: {
35
- entry: ['src/main.ts', 'src/**/*.module.ts'],
36
- project: ['src/**/*.ts'],
46
+ entry: ['src/main.ts!', 'src/**/*.module.ts!'],
47
+ project: ['src/**/*.ts!'],
37
48
  includeEntryExports: true,
38
49
  },
39
50
  // The App Router lives at either `app/` or `src/app/`, and the proxy follows
@@ -51,15 +62,15 @@ export const FRAMEWORK_ENTRIES: Record<
51
62
  // "Refine entry pattern (no matches)" hint in a project that has neither.
52
63
  nextjs: {
53
64
  entry: [
54
- '{,src/}app/**/{page,layout,loading,error,global-error,not-found,route,template,default,sitemap,robots,manifest,icon,apple-icon,opengraph-image,twitter-image}.{ts,tsx}',
65
+ '{,src/}app/**/{page,layout,loading,error,global-error,not-found,route,template,default,sitemap,robots,manifest,icon,apple-icon,opengraph-image,twitter-image}.{ts,tsx}!',
55
66
  'next.config.*',
56
67
  ],
57
- project: ['{,src/}app/**/*.{ts,tsx}', 'src/**/*.{ts,tsx}'],
68
+ project: ['{,src/}app/**/*.{ts,tsx}!', 'src/**/*.{ts,tsx}!'],
58
69
  includeEntryExports: false,
59
70
  },
60
71
  nuxt: {
61
- entry: ['app/**/*.vue', 'server/**/*.ts', 'nuxt.config.*'],
62
- project: ['app/**/*.{ts,vue}', 'server/**/*.ts'],
72
+ entry: ['app/**/*.vue!', 'server/**/*.ts!', 'nuxt.config.*'],
73
+ project: ['app/**/*.{ts,vue}!', 'server/**/*.ts!'],
63
74
  includeEntryExports: false,
64
75
  },
65
76
  // TanStack Start has no index.html and no src/main.tsx: the router is the
@@ -70,37 +81,37 @@ export const FRAMEWORK_ENTRIES: Record<
70
81
  // becoming "Refine entry pattern" hints.
71
82
  'tanstack-start': {
72
83
  entry: [
73
- 'src/router.{ts,tsx}',
74
- 'src/routes/**/*.{ts,tsx}',
75
- 'src/{server,start,client}.{ts,tsx}',
84
+ 'src/router.{ts,tsx}!',
85
+ 'src/routes/**/*.{ts,tsx}!',
86
+ 'src/{server,start,client}.{ts,tsx}!',
76
87
  'vite.config.*',
77
88
  ],
78
- project: ['src/**/*.{ts,tsx}'],
89
+ project: ['src/**/*.{ts,tsx}!'],
79
90
  includeEntryExports: false,
80
91
  },
81
92
  tauri: {
82
93
  // The scaffolded tauri-app frontend is React, so its entry is
83
94
  // src/main.tsx, not src/main.ts; keep both extensions so a plain-TS
84
95
  // Tauri frontend also matches.
85
- entry: ['src/main.{ts,tsx}', 'vite.config.*'],
86
- project: ['src/**/*.{ts,tsx}'],
96
+ entry: ['src/main.{ts,tsx}!', 'vite.config.*'],
97
+ project: ['src/**/*.{ts,tsx}!'],
87
98
  includeEntryExports: false,
88
99
  },
89
100
  'ts-package': {
90
- entry: ['src/index.ts'],
91
- project: ['src/**/*.ts'],
101
+ entry: ['src/index.ts!'],
102
+ project: ['src/**/*.ts!'],
92
103
  includeEntryExports: true,
93
104
  },
94
105
  // `src/main.*` is reached through index.html's module script; listing it as
95
106
  // well was a "Remove redundant entry pattern" hint in both Vite templates.
96
107
  'vite-react': {
97
- entry: ['index.html', 'vite.config.*'],
98
- project: ['src/**/*.{ts,tsx}'],
108
+ entry: ['index.html!', 'vite.config.*'],
109
+ project: ['src/**/*.{ts,tsx}!'],
99
110
  includeEntryExports: false,
100
111
  },
101
112
  'vite-vue': {
102
- entry: ['index.html', 'vite.config.*'],
103
- project: ['src/**/*.{ts,vue}'],
113
+ entry: ['index.html!', 'vite.config.*'],
114
+ project: ['src/**/*.{ts,vue}!'],
104
115
  includeEntryExports: false,
105
116
  },
106
117
  }
package/src/knip.ts CHANGED
@@ -6,7 +6,10 @@
6
6
  import type { KnipConfiguration } from 'knip'
7
7
 
8
8
  import { existingEntries } from './existingEntries'
9
+ import { FRAMEWORK_RUNTIME_PACKAGES } from './FRAMEWORK_RUNTIME_PACKAGES'
9
10
  import { FRAMEWORK_ENTRIES, type KnipFramework } from './knip-framework'
11
+ import { peersOfListedDependencies } from './peersOfListedDependencies'
12
+ import { PRODUCTION_PROJECT_EXCLUSIONS } from './PRODUCTION_PROJECT_EXCLUSIONS'
10
13
  import { runnerDependenciesToIgnore } from './runnerDependenciesToIgnore'
11
14
 
12
15
  // Every template installs these as peer dependencies of
@@ -31,7 +34,10 @@ import { runnerDependenciesToIgnore } from './runnerDependenciesToIgnore'
31
34
  // `<package> knip.config.ts Remove from ignoreDependencies`. That is a hint,
32
35
  // not a gate failure. Do not filter the list consumer-side to silence it: the
33
36
  // filter would drift the moment this list changes, and the cost of being wrong
34
- // is a dependency that silently stops being checked.
37
+ // is a dependency that silently stops being checked. The one filter applied
38
+ // here mirrors knip's own rule: a package another installed dependency
39
+ // declares as a peer (`eslint-plugin-astro` hosts `typescript-eslint`) is
40
+ // counted as used by knip, so it is not ignored.
35
41
  const ESLINT_PEER_DEPENDENCIES = [
36
42
  '@eslint/js',
37
43
  'eslint-config-prettier',
@@ -81,6 +87,10 @@ export const createKnipConfig = (options: {
81
87
  * dependency reached only from there reports as unused. This is a merge, not
82
88
  * a replacement: the preset's globs stay, so a project cannot silently opt
83
89
  * out of scanning the directories the framework does own.
90
+ *
91
+ * Add a trailing `!` to a glob that holds runtime code
92
+ * (`'components/**\/*.tsx!'`): `knip --production` analyses only marked
93
+ * globs, so an unmarked one drops out of that run.
84
94
  */
85
95
  project?: string[]
86
96
  /**
@@ -89,6 +99,8 @@ export const createKnipConfig = (options: {
89
99
  * a CLI, a script the app spawns. A preset entry that is a literal path
90
100
  * missing from the project (`ts-package`'s `src/index.ts` in a CLI package)
91
101
  * is dropped once this is set, so it cannot become a "no matches" hint.
102
+ * Mark a runtime root with a trailing `!` (`'src/cli/main.ts!'`) so
103
+ * `knip --production` starts from it too; leave scripts and tooling unmarked.
92
104
  */
93
105
  entry?: string[]
94
106
  /**
@@ -110,6 +122,7 @@ export const createKnipConfig = (options: {
110
122
  cwd?: string
111
123
  }): KnipConfiguration => {
112
124
  const cwd = options.cwd ?? process.cwd()
125
+ const hostedPeers = peersOfListedDependencies(cwd)
113
126
  const { entry, project, includeEntryExports } =
114
127
  FRAMEWORK_ENTRIES[options.framework]
115
128
 
@@ -117,7 +130,11 @@ export const createKnipConfig = (options: {
117
130
  entry: options.entry
118
131
  ? [...existingEntries(entry, cwd), ...options.entry]
119
132
  : entry,
120
- project: [...project, ...(options.project ?? [])],
133
+ project: [
134
+ ...project,
135
+ ...(options.project ?? []),
136
+ ...PRODUCTION_PROJECT_EXCLUSIONS,
137
+ ],
121
138
  ...(options.ignore ? { ignore: options.ignore } : {}),
122
139
  ...(options.drizzle === false ? { drizzle: false } : {}),
123
140
  // Without this, exports of entry files are never checked, so a dead export
@@ -141,7 +158,10 @@ export const createKnipConfig = (options: {
141
158
  ignoreBinaries: ['gitleaks', ...(options.ignoreBinaries ?? [])],
142
159
  ignoreDependencies: [
143
160
  ...runnerDependenciesToIgnore(cwd),
144
- ...ESLINT_PEER_DEPENDENCIES,
161
+ ...(FRAMEWORK_RUNTIME_PACKAGES[options.framework] ?? []),
162
+ ...ESLINT_PEER_DEPENDENCIES.filter(
163
+ (dependency) => !hostedPeers.has(dependency),
164
+ ),
145
165
  ...(options.ignoreDependencies ?? []),
146
166
  ],
147
167
  rules: {
@@ -0,0 +1,22 @@
1
+ import type { IForbiddenRuleType } from 'dependency-cruiser'
2
+
3
+ /**
4
+ * One rule per module root (`src/features`, say): a file in one module may
5
+ * import another module only through that module's `index`. Matched on the
6
+ * resolved path, so an alias, a re-export or a relative `../` all count, which
7
+ * the ESLint import rules cannot see from the specifier string alone.
8
+ */
9
+ export const moduleBoundaryRules = (roots: string[]): IForbiddenRuleType[] =>
10
+ roots.map((root) => {
11
+ const prefix = `^${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/`
12
+ return {
13
+ name: 'no-deep-cross-module-import',
14
+ severity: 'error',
15
+ comment: `Import another module under ${root}/ through its index, not its internal files.`,
16
+ from: { path: `${prefix}([^/]+)/` },
17
+ to: {
18
+ path: `${prefix}[^/]+/`,
19
+ pathNot: [`${prefix}$1/`, `${prefix}[^/]+/index\\.[cm]?[jt]sx?$`],
20
+ },
21
+ }
22
+ })
@@ -0,0 +1,15 @@
1
+ import { readListedDependencies } from './readListedDependencies'
2
+ import { readPeerDependencyNames } from './readPeerDependencyNames'
3
+
4
+ /**
5
+ * Every package some dependency of `cwd` declares as a peer. knip counts a
6
+ * peer of a used dependency as used itself (`eslint-plugin-astro` hosting
7
+ * `typescript-eslint`), so ignoring one of these is a `Remove from
8
+ * ignoreDependencies` hint the consumer cannot silence.
9
+ */
10
+ export const peersOfListedDependencies = (cwd: string): Set<string> =>
11
+ new Set(
12
+ readListedDependencies(cwd).flatMap((name) =>
13
+ readPeerDependencyNames(cwd, name),
14
+ ),
15
+ )
@@ -0,0 +1,24 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /**
5
+ * The names in `dependencies` and `devDependencies` of `cwd`'s
6
+ * `package.json`; an unreadable or malformed manifest gives none.
7
+ */
8
+ export const readListedDependencies = (cwd: string): string[] => {
9
+ try {
10
+ const manifest = JSON.parse(
11
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- fixed file name under the project root
12
+ readFileSync(join(cwd, 'package.json'), 'utf8'),
13
+ ) as {
14
+ dependencies?: Record<string, string>
15
+ devDependencies?: Record<string, string>
16
+ }
17
+ return [
18
+ ...Object.keys(manifest.dependencies ?? {}),
19
+ ...Object.keys(manifest.devDependencies ?? {}),
20
+ ]
21
+ } catch {
22
+ return []
23
+ }
24
+ }
@@ -0,0 +1,21 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /**
5
+ * The `peerDependencies` names of the package `name` as installed under
6
+ * `cwd`'s `node_modules`; a package that is not installed gives none.
7
+ */
8
+ export const readPeerDependencyNames = (
9
+ cwd: string,
10
+ name: string,
11
+ ): string[] => {
12
+ try {
13
+ const manifest = JSON.parse(
14
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a listed dependency's manifest under the project's node_modules
15
+ readFileSync(join(cwd, 'node_modules', name, 'package.json'), 'utf8'),
16
+ ) as { peerDependencies?: Record<string, string> }
17
+ return Object.keys(manifest.peerDependencies ?? {})
18
+ } catch {
19
+ return []
20
+ }
21
+ }
@@ -1,9 +1,13 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
 
4
+ import { isScriptInvocation } from './isScriptInvocation'
5
+
4
6
  /**
5
7
  * Every word of every `package.json` script in `cwd`, so a caller can ask
6
- * whether a binary is named anywhere. Unreadable or malformed manifests give
8
+ * whether a binary is named anywhere. A word that only runs another script
9
+ * (`pnpm type-coverage` where a `type-coverage` script exists) is left out:
10
+ * it names the script, not the binary. Unreadable or malformed manifests give
7
11
  * an empty set: the caller then ignores the dependency, which is the safe side.
8
12
  */
9
13
  export const readScriptWords = (cwd: string): Set<string> => {
@@ -12,11 +16,20 @@ export const readScriptWords = (cwd: string): Set<string> => {
12
16
  // eslint-disable-next-line security/detect-non-literal-fs-filename -- fixed file name under the project root
13
17
  readFileSync(join(cwd, 'package.json'), 'utf8'),
14
18
  )
15
- const scripts = (manifest as { scripts?: Record<string, unknown> }).scripts
16
- const text = Object.values(scripts ?? {})
17
- .filter((script): script is string => typeof script === 'string')
18
- .join('\n')
19
- return new Set(text.split(/[\s;&|()]+/u).filter(Boolean))
19
+ const scripts =
20
+ (manifest as { scripts?: Record<string, unknown> }).scripts ?? {}
21
+ const scriptNames = new Set(Object.keys(scripts))
22
+ const words = new Set<string>()
23
+ for (const script of Object.values(scripts)) {
24
+ if (typeof script !== 'string') continue
25
+ const tokens = script.split(/[\s;&|()]+/u).filter(Boolean)
26
+ tokens.forEach((word, index) => {
27
+ if (!isScriptInvocation(word, tokens[index - 1], scriptNames)) {
28
+ words.add(word)
29
+ }
30
+ })
31
+ }
32
+ return words
20
33
  } catch {
21
34
  return new Set()
22
35
  }
@@ -1,5 +1,6 @@
1
- import { RUNNER_BINARIES } from './RUNNER_BINARIES'
1
+ import { hasLefthookConfig } from './hasLefthookConfig'
2
2
  import { readScriptWords } from './readScriptWords'
3
+ import { RUNNER_BINARIES } from './RUNNER_BINARIES'
3
4
 
4
5
  /**
5
6
  * The runner dependencies knip cannot see used, and so must be ignored.
@@ -11,10 +12,17 @@ import { readScriptWords } from './readScriptWords'
11
12
  * `"deps:graph": "depcruise src"`) lets knip resolve it, and ignoring it then
12
13
  * becomes a permanent `Remove from ignoreDependencies` hint no consumer can
13
14
  * silence. So only the packages no script names directly are ignored.
15
+ *
16
+ * `lefthook` is also resolved by knip's own Lefthook plugin whenever a
17
+ * Lefthook configuration file exists, so it is ignored only without one.
14
18
  */
15
19
  export const runnerDependenciesToIgnore = (cwd: string): string[] => {
16
20
  const words = readScriptWords(cwd)
21
+ const lefthookConfigured = hasLefthookConfig(cwd)
17
22
  return Object.entries(RUNNER_BINARIES)
18
23
  .filter(([, binaries]) => !binaries.some((binary) => words.has(binary)))
24
+ .filter(
25
+ ([dependency]) => !(dependency === 'lefthook' && lefthookConfigured),
26
+ )
19
27
  .map(([dependency]) => dependency)
20
28
  }