@syntopica/quality-config 0.15.0 → 0.16.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/PUBLIC_API.md CHANGED
@@ -97,3 +97,28 @@ not resolution bugs:
97
97
  `attw`'s sandbox only contains this package's own tarball, so it cannot see
98
98
  peers a real consumer installs, and flags those imports as unresolved. This is
99
99
  the intended shape of an optional peer, not a broken `exports` entry.
100
+
101
+ ## Canonical dependency-cruiser TypeScript configuration
102
+
103
+ `@syntopica/quality-config/cruise-tsconfig` exports
104
+ `withCruiseTsconfig(configPath, operation, { requirePaths = false })`. It
105
+ synchronously invokes `operation` with an absolute tsconfig filename and returns
106
+ the operation's result. Promise-like results are rejected. The original
107
+ configuration and default input location are unchanged, and an exclusively
108
+ created temporary file beside the original configuration is removed even if the
109
+ operation fails.
110
+
111
+ The existing required TypeScript peer reads JSONC and inherited configuration.
112
+ Alias targets become absolute using the effective baseUrl, or the compiler's
113
+ declaring-config origin when baseUrl is absent. The effective baseUrl is
114
+ preserved. The latter origin uses checked internal `pathsBasePath` metadata:
115
+ compiler versions without an absolute origin fail explicitly, with no CWD
116
+ fallback. This does not establish compatibility with every version admitted by
117
+ the existing peer range. No-paths configurations use their original filename
118
+ unless `requirePaths` is true.
119
+
120
+ `baseline-deps-graph --cwd-only app` selects only the invoking project's app
121
+ directory. Without `--cwd-only`, existing recursive workspace discovery is
122
+ preserved for both explicit and default source arguments. In cwd-only mode,
123
+ every explicit source must exist or the command fails. Generated projects use
124
+ the published runtime and never import the monorepo root runner.
@@ -0,0 +1 @@
1
+ export const AUDIT_LEVELS = ['info', 'low', 'moderate', 'high', 'critical']
@@ -1,147 +1,32 @@
1
1
  #!/usr/bin/env node
2
- // `pnpm audit` with an allowlist that expires.
3
- //
4
- // Usage:
5
- // baseline-audit [--level low|moderate|high|critical] [--file <path>]
6
- //
7
- // The problem this replaces: two advisories in this repository sat below the
8
- // `--audit-level=high` line and were documented as prose in TODO.md. Nothing
9
- // re-checked them, nothing expired them, and the only way to raise the audit
10
- // level was to accept the noise of findings that had already been judged.
11
- //
12
- // An allowlist entry is a decision with a date on it. `reason` is required and
13
- // `expires` is required, so a waiver comes back on its own and has to be
14
- // re-argued rather than inherited. That is what makes it safe to gate at
15
- // `moderate` instead of `high`: the known exceptions stop being noise.
16
- //
17
- // Allowlist file (`.baseline-advisories.json`), keyed by GitHub advisory ID:
18
- //
19
- // {
20
- // "GHSA-w5hq-g745-h8pq": {
21
- // "reason": "via @lhci/cli > uuid, resolved at 8.3.2; no consumer release past 0.15.1",
22
- // "expires": "2026-12-31"
23
- // }
24
- // }
25
- import { spawnSync } from 'node:child_process'
26
- import { readFile } from 'node:fs/promises'
2
+ // Run the existing dated advisory policy only after a complete audit response.
27
3
  import { resolve } from 'node:path'
28
4
  import { argv, cwd, exit } from 'node:process'
29
- import { pnpmCommand } from './pnpmCommand.mjs'
5
+ import { classifyAuditAdvisories } from './classifyAuditAdvisories.mjs'
6
+ import { parseAuditArguments } from './parseAuditArguments.mjs'
7
+ import { readAuditAllowlist } from './readAuditAllowlist.mjs'
8
+ import { reportAuditOutcome } from './reportAuditOutcome.mjs'
9
+ import { runPackageAudit } from './runPackageAudit.mjs'
30
10
 
31
- const LEVELS = ['info', 'low', 'moderate', 'high', 'critical']
32
- const DEFAULT_FILE = '.baseline-advisories.json'
33
-
34
- const flag = (name, fallback) => {
35
- const index = argv.indexOf(`--${name}`)
36
- return index === -1 ? fallback : (argv[index + 1] ?? fallback)
37
- }
38
-
39
- const level = flag('level', 'moderate')
40
- if (!LEVELS.includes(level)) {
41
- console.error(`baseline-audit: --level must be one of ${LEVELS.join(', ')}.`)
42
- exit(2)
43
- }
44
- const minimum = LEVELS.indexOf(level)
45
- const today = new Date().toISOString().slice(0, 10)
46
- const root = cwd()
47
-
48
- const allowlist = await readAllowlist(resolve(root, flag('file', DEFAULT_FILE)))
49
-
50
- // `pnpm audit` exits non-zero when it finds anything, which is the whole
51
- // point, so its status is not an error condition here - the JSON is.
52
- const [pnpm, ...pnpmArgs] = pnpmCommand()
53
- const result = spawnSync(pnpm, [...pnpmArgs, 'audit', '--json'], {
54
- encoding: 'utf8',
55
- maxBuffer: 64 * 1024 * 1024,
56
- })
57
- if (result.error) {
58
- console.error(
59
- `baseline-audit: could not run pnpm audit: ${result.error.message}`,
60
- )
61
- exit(2)
62
- }
63
-
64
- let report
65
- try {
66
- report = JSON.parse(result.stdout)
67
- } catch {
68
- console.error('baseline-audit: pnpm audit did not return JSON.')
69
- console.error(result.stdout.slice(0, 2000))
70
- exit(2)
71
- }
72
-
73
- const advisories = Object.values(report.advisories ?? {})
74
- const failures = []
75
- const waived = []
76
- const stale = []
77
-
78
- for (const advisory of advisories) {
79
- if (LEVELS.indexOf(advisory.severity) < minimum) continue
80
-
81
- const entry =
82
- allowlist[advisory.github_advisory_id] ?? allowlist[String(advisory.id)]
83
- if (!entry) {
84
- failures.push(advisory)
85
- continue
86
- }
87
- if (entry.expires < today) {
88
- stale.push({ advisory, entry })
89
- continue
90
- }
91
- waived.push({ advisory, entry })
92
- }
93
-
94
- for (const { advisory, entry } of waived) {
95
- console.log(
96
- `waived ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
97
- `${advisory.module_name} (expires ${entry.expires})\n ${entry.reason}`,
98
- )
99
- }
100
-
101
- for (const { advisory, entry } of stale) {
102
- console.error(
103
- `EXPIRED ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
104
- `${advisory.module_name} (expired ${entry.expires})\n ${entry.reason}\n` +
105
- ' Re-check it, then renew the entry or remove it.',
106
- )
107
- }
108
-
109
- for (const advisory of failures) {
110
- console.error(
111
- `FAIL ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
112
- `${advisory.module_name} ${advisory.vulnerable_versions}\n` +
113
- ` patched in ${advisory.patched_versions} - ${advisory.url}\n` +
114
- ` via ${(advisory.findings?.[0]?.paths ?? []).slice(0, 2).join(', ')}`,
115
- )
116
- }
117
-
118
- const failed = failures.length + stale.length
119
- console.log(
120
- `\nbaseline-audit: ${advisories.length} advisories, gate at ${level}: ` +
121
- `${failures.length} unwaived, ${stale.length} expired, ${waived.length} waived.`,
122
- )
123
- if (failed) exit(1)
124
-
125
- async function readAllowlist(path) {
126
- let raw
11
+ export async function runBaselineAudit() {
127
12
  try {
128
- // eslint-disable-next-line security/detect-non-literal-fs-filename
129
- raw = await readFile(path, 'utf8')
130
- } catch {
131
- return {}
13
+ const { level, file } = parseAuditArguments(argv.slice(2))
14
+ const allowlist = await readAuditAllowlist(resolve(cwd(), file))
15
+ const report = runPackageAudit()
16
+ const advisories = Object.values(report.advisories)
17
+ const outcome = classifyAuditAdvisories(
18
+ advisories,
19
+ allowlist,
20
+ level,
21
+ new Date().toISOString().slice(0, 10),
22
+ )
23
+ return reportAuditOutcome(advisories, outcome, level)
24
+ } catch (error) {
25
+ console.error(
26
+ `baseline-audit: ${error instanceof Error ? error.message : 'Could not validate audit response.'}`,
27
+ )
28
+ return 2
132
29
  }
133
-
134
- const parsed = JSON.parse(raw)
135
- for (const [id, entry] of Object.entries(parsed)) {
136
- // Both fields are required, and the check is here rather than at use: an
137
- // entry missing one is a waiver nobody can audit, and treating it as
138
- // absent would hide the mistake behind a passing gate.
139
- if (!entry?.reason || !entry?.expires) {
140
- console.error(
141
- `baseline-audit: allowlist entry ${id} needs both \`reason\` and \`expires\`.`,
142
- )
143
- exit(2)
144
- }
145
- }
146
- return parsed
147
30
  }
31
+
32
+ exit(await runBaselineAudit())
@@ -11,96 +11,88 @@
11
11
  // baseline-deps-graph # src, app, server, lib
12
12
  // baseline-deps-graph src app # only these
13
13
  // baseline-deps-graph --config path.cjs src
14
- import { spawnSync } from 'node:child_process'
15
- import { existsSync, readdirSync } from 'node:fs'
14
+ import { existsSync } from 'node:fs'
16
15
  import { relative, resolve } from 'node:path'
17
16
  import { argv, cwd, exit } from 'node:process'
17
+ import { cruiseWorkspaceSelection } from './cruiseWorkspaceSelection.mjs'
18
+ import { DEFAULT_CRUISE_SOURCES } from './defaultCruiseSources.mjs'
19
+ import { findCruiseWorkspaces } from './findCruiseWorkspaces.mjs'
20
+ import { parseCruiseArguments } from './parseCruiseArguments.mjs'
18
21
  import { pnpmCommand } from './pnpmCommand.mjs'
22
+ import { presentCruiseSources } from './presentCruiseSources.mjs'
23
+ import { spawnCruise } from './spawnCruise.mjs'
24
+ import { withCruiseTsconfig } from './withCruiseTsconfig.mjs'
19
25
 
20
- const DEFAULT_SOURCES = ['src', 'app', 'server', 'lib']
21
- const SKIPPED_DIRECTORIES = new Set([
22
- 'node_modules',
23
- 'dist',
24
- 'build',
25
- 'coverage',
26
- 'target',
27
- '.git',
28
- '.next',
29
- '.nuxt',
30
- '.output',
31
- '.astro',
32
- ])
33
- const MAX_DEPTH = 3
34
-
35
- const args = argv.slice(2)
36
- const configIndex = args.indexOf('--config')
37
- const configPath = resolve(
38
- cwd(),
39
- configIndex === -1
40
- ? '.dependency-cruiser.cjs'
41
- : (args[configIndex + 1] ?? ''),
42
- )
43
- const sources = (
44
- configIndex === -1
45
- ? args
46
- : [...args.slice(0, configIndex), ...args.slice(configIndex + 2)]
47
- ).filter(Boolean)
48
- const sourceDirectories = sources.length ? sources : DEFAULT_SOURCES
49
-
50
- // Every path below is derived from the invoking project's own tree, which is
51
- // the point of this tool - not untrusted input.
52
- /* eslint-disable security/detect-non-literal-fs-filename */
53
- if (!existsSync(configPath)) {
54
- console.error(
55
- `baseline-deps-graph: no dependency-cruiser config at ${relative(cwd(), configPath)}. ` +
56
- 'Pass one with --config.',
26
+ export function runDependencyGraphs() {
27
+ const { configPath, sources, cwdOnly } = parseCruiseArguments(
28
+ argv.slice(2),
29
+ cwd(),
57
30
  )
58
- exit(1)
59
- }
31
+ const sourceDirectories = sources.length ? sources : DEFAULT_CRUISE_SOURCES
60
32
 
61
- function findWorkspaces(root, depth = 0) {
62
- const found = []
63
- if (existsSync(resolve(root, 'tsconfig.json'))) found.push(root)
64
- if (depth >= MAX_DEPTH) return found
65
-
66
- for (const entry of readdirSync(root, { withFileTypes: true })) {
67
- if (!entry.isDirectory() || SKIPPED_DIRECTORIES.has(entry.name)) continue
68
- found.push(...findWorkspaces(resolve(root, entry.name), depth + 1))
33
+ // Every path below is derived from the invoking project's own tree, which is
34
+ // the point of this tool - not untrusted input.
35
+ /* eslint-disable security/detect-non-literal-fs-filename */
36
+ if (!existsSync(configPath)) {
37
+ console.error(
38
+ `baseline-deps-graph: no dependency-cruiser config at ${relative(cwd(), configPath)}. ` +
39
+ 'Pass one with --config.',
40
+ )
41
+ exit(1)
69
42
  }
70
- return found
71
- }
72
43
 
73
- const [pnpm, ...pnpmArgs] = pnpmCommand()
44
+ const [pnpm, ...pnpmArgs] = pnpmCommand()
74
45
 
75
- const failed = []
76
- for (const workspace of findWorkspaces(cwd())) {
77
- const present = sourceDirectories.filter((directory) =>
78
- existsSync(resolve(workspace, directory)),
79
- )
80
- if (!present.length) continue
46
+ const failed = []
47
+ for (const workspace of cruiseWorkspaceSelection(
48
+ cwd(),
49
+ cwdOnly,
50
+ findCruiseWorkspaces,
51
+ )) {
52
+ const present = presentCruiseSources(workspace, sourceDirectories)
53
+ if (
54
+ cwdOnly &&
55
+ sources.length > 0 &&
56
+ present.length !== sourceDirectories.length
57
+ ) {
58
+ console.error(`deps-graph: missing explicit source in ${workspace}`)
59
+ failed.push(relative(cwd(), workspace) || '.')
60
+ continue
61
+ }
62
+ if (!present.length) continue
81
63
 
82
- const label = relative(cwd(), workspace) || '.'
83
- console.log(`deps-graph: cruising ${label} (${present.join(', ')})`)
84
- const result = spawnSync(
85
- pnpm,
86
- [
87
- ...pnpmArgs,
88
- 'exec',
89
- 'depcruise',
90
- ...present,
91
- '--config',
92
- configPath,
93
- '--ts-config',
94
- 'tsconfig.json',
95
- ],
96
- { cwd: workspace, stdio: 'inherit' },
97
- )
98
- if (result.status !== 0) failed.push(label)
99
- }
100
- /* eslint-enable security/detect-non-literal-fs-filename */
64
+ const label = relative(cwd(), workspace) || '.'
65
+ console.log(`deps-graph: cruising ${label} (${present.join(', ')})`)
66
+ try {
67
+ const result = withCruiseTsconfig(
68
+ resolve(workspace, 'tsconfig.json'),
69
+ spawnCruise.bind(
70
+ null,
71
+ pnpm,
72
+ [
73
+ ...pnpmArgs,
74
+ 'exec',
75
+ 'depcruise',
76
+ ...present,
77
+ '--config',
78
+ configPath,
79
+ ],
80
+ workspace,
81
+ ),
82
+ )
83
+ if (result.status !== 0) failed.push(label)
84
+ } catch (error) {
85
+ console.error(`deps-graph: ${label}: ${String(error)}`)
86
+ failed.push(label)
87
+ }
88
+ }
89
+ /* eslint-enable security/detect-non-literal-fs-filename */
101
90
 
102
- if (failed.length) {
103
- console.error(`deps-graph: failed for ${failed.join(', ')}`)
104
- exit(1)
91
+ if (failed.length) {
92
+ console.error(`deps-graph: failed for ${failed.join(', ')}`)
93
+ exit(1)
94
+ }
95
+ console.log('deps-graph: no violations found.')
105
96
  }
106
- console.log('deps-graph: no violations found.')
97
+
98
+ runDependencyGraphs()
@@ -38,7 +38,7 @@ import { tmpdir } from 'node:os'
38
38
  import { join } from 'node:path'
39
39
  import { argv, exit } from 'node:process'
40
40
  import { fileURLToPath } from 'node:url'
41
- import { pnpmCommand } from './pnpmCommand.mjs'
41
+ import { localNodeToolCommand } from './localNodeToolCommand.mjs'
42
42
 
43
43
  const PACKAGED_CONFIG = fileURLToPath(new URL('../jscpd.json', import.meta.url))
44
44
 
@@ -109,8 +109,8 @@ if (found.value !== -1) args[found.value] = config
109
109
  else if (found.inline !== -1) args[found.inline] = `--config=${config}`
110
110
  else args.push('--config', config)
111
111
 
112
- const [pnpm, ...pnpmArgs] = pnpmCommand()
113
- const result = spawnSync(pnpm, [...pnpmArgs, 'exec', 'jscpd', ...args], {
112
+ const [node, tool] = localNodeToolCommand('jscpd')
113
+ const result = spawnSync(node, [tool, ...args], {
114
114
  stdio: 'inherit',
115
115
  })
116
116
 
@@ -36,7 +36,7 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'
36
36
  import { dirname, relative, resolve } from 'node:path'
37
37
  import { argv, cwd, exit } from 'node:process'
38
38
  import { fileURLToPath } from 'node:url'
39
- import { pnpmCommand } from './pnpmCommand.mjs'
39
+ import { localNodeToolCommand } from './localNodeToolCommand.mjs'
40
40
 
41
41
  const IGNORED_FILES = ['.next/**', '.nuxt/**', 'tests/**', '**/*.test.*']
42
42
  const SKIPPED_DIRECTORIES = new Set([
@@ -217,17 +217,17 @@ if (!workspaces.length) {
217
217
  exit(1)
218
218
  }
219
219
 
220
- const [pnpm, ...pnpmArgs] = pnpmCommand()
221
-
222
220
  let failed = false
223
221
  for (const workspace of workspaces) {
224
222
  const label = relative(cwd(), workspace.project ?? workspace.directory) || '.'
223
+ const [node, tool] = localNodeToolCommand(
224
+ 'type-coverage',
225
+ workspace.directory,
226
+ )
225
227
  const result = spawnSync(
226
- pnpm,
228
+ node,
227
229
  [
228
- ...pnpmArgs,
229
- 'exec',
230
- 'type-coverage',
230
+ tool,
231
231
  '--strict',
232
232
  '--at-least',
233
233
  threshold,
@@ -257,7 +257,7 @@ if (failed) {
257
257
  (override === undefined
258
258
  ? '.\n'
259
259
  : ` (this project's own floor; the shared bar is ${declared[1]}%).\n`) +
260
- 'Run `pnpm exec type-coverage --strict --detail` in the failing workspace to see where.',
260
+ 'Run the installed `type-coverage --strict --detail` in the failing workspace to see where.',
261
261
  )
262
262
  exit(1)
263
263
  }
@@ -0,0 +1,22 @@
1
+ import { AUDIT_LEVELS } from './auditLevels.mjs'
2
+
3
+ export function classifyAuditAdvisories(advisories, allowlist, level, today) {
4
+ const minimum = AUDIT_LEVELS.indexOf(level)
5
+ const failures = []
6
+ const waived = []
7
+ const stale = []
8
+ for (const advisory of advisories) {
9
+ if (AUDIT_LEVELS.indexOf(advisory.severity) < minimum) continue
10
+ const githubEntry = Object.hasOwn(allowlist, advisory.github_advisory_id)
11
+ ? allowlist[advisory.github_advisory_id]
12
+ : undefined
13
+ const numericEntry = Object.hasOwn(allowlist, String(advisory.id))
14
+ ? allowlist[String(advisory.id)]
15
+ : undefined
16
+ const entry = githubEntry ?? numericEntry
17
+ if (!entry) failures.push(advisory)
18
+ else if (entry.expires < today) stale.push({ advisory, entry })
19
+ else waived.push({ advisory, entry })
20
+ }
21
+ return { failures, waived, stale }
22
+ }
@@ -0,0 +1,5 @@
1
+ export function cruiseWorkspaceSelection(root, cwdOnly, discover) {
2
+ if (typeof cwdOnly !== 'boolean')
3
+ throw new TypeError('cwdOnly must be a validated boolean')
4
+ return cwdOnly ? [root] : discover(root)
5
+ }
@@ -0,0 +1 @@
1
+ export const DEFAULT_CRUISE_SOURCES = ['src', 'app', 'server', 'lib']
@@ -0,0 +1,18 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { MAX_CRUISE_DEPTH } from './maxCruiseDepth.mjs'
4
+ import { SKIPPED_CRUISE_DIRECTORIES } from './skippedCruiseDirectories.mjs'
5
+
6
+ export function findCruiseWorkspaces(root, depth = 0) {
7
+ const found = []
8
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- root starts at the invoking project's cwd and recurses through directory entries.
9
+ if (existsSync(resolve(root, 'tsconfig.json'))) found.push(root)
10
+ if (depth >= MAX_CRUISE_DEPTH) return found
11
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- The selected project is read recursively; isDirectory excludes symlink entries below.
12
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
13
+ if (!entry.isDirectory() || SKIPPED_CRUISE_DIRECTORIES.has(entry.name))
14
+ continue
15
+ found.push(...findCruiseWorkspaces(resolve(root, entry.name), depth + 1))
16
+ }
17
+ return found
18
+ }
@@ -0,0 +1,18 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { dirname, resolve } from 'node:path'
4
+ import { cwd, execPath } from 'node:process'
5
+
6
+ /** Resolve a Node CLI from the consumer, including hoisted workspace installs. */
7
+ export function localNodeToolCommand(name, directory = cwd()) {
8
+ const require = createRequire(resolve(directory, 'package.json'))
9
+ const manifestPath = require.resolve(`${name}/package.json`)
10
+ // The manifest belongs to the explicitly selected, installed tool.
11
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
12
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
13
+ const entry =
14
+ typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.[name]
15
+ if (typeof entry !== 'string')
16
+ throw new Error(`No installed CLI entry for ${name}`)
17
+ return [execPath, resolve(dirname(manifestPath), entry)]
18
+ }
@@ -0,0 +1 @@
1
+ export const MAX_CRUISE_DEPTH = 3
@@ -0,0 +1,16 @@
1
+ import { AUDIT_LEVELS } from './auditLevels.mjs'
2
+
3
+ export function parseAuditArguments(args) {
4
+ const levelIndex = args.indexOf('--level')
5
+ const fileIndex = args.indexOf('--file')
6
+ const level =
7
+ levelIndex === -1 ? 'moderate' : (args[levelIndex + 1] ?? 'moderate')
8
+ const file =
9
+ fileIndex === -1
10
+ ? '.baseline-advisories.json'
11
+ : (args[fileIndex + 1] ?? '.baseline-advisories.json')
12
+ if (!AUDIT_LEVELS.includes(level)) {
13
+ throw new Error(`--level must be one of ${AUDIT_LEVELS.join(', ')}.`)
14
+ }
15
+ return { level, file }
16
+ }
@@ -0,0 +1,30 @@
1
+ import { resolve } from 'node:path'
2
+
3
+ export function parseCruiseArguments(args, root) {
4
+ const remaining = []
5
+ let cwdOnly = false
6
+ for (const argument of args) {
7
+ if (argument === '--cwd-only') {
8
+ if (cwdOnly) throw new Error('Duplicate --cwd-only option')
9
+ cwdOnly = true
10
+ } else {
11
+ remaining.push(argument)
12
+ }
13
+ }
14
+ const configIndex = remaining.indexOf('--config')
15
+ const configPath = resolve(
16
+ root,
17
+ configIndex === -1
18
+ ? '.dependency-cruiser.cjs'
19
+ : (remaining[configIndex + 1] ?? ''),
20
+ )
21
+ const sources = (
22
+ configIndex === -1
23
+ ? remaining
24
+ : [
25
+ ...remaining.slice(0, configIndex),
26
+ ...remaining.slice(configIndex + 2),
27
+ ]
28
+ ).filter(Boolean)
29
+ return { configPath, sources, cwdOnly }
30
+ }
@@ -0,0 +1,11 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+
4
+ export function presentCruiseSources(workspace, sources) {
5
+ const present = []
6
+ for (const directory of sources) {
7
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- Source paths are selected by the invoking CLI; this call only probes their existence.
8
+ if (existsSync(resolve(workspace, directory))) present.push(directory)
9
+ }
10
+ return present
11
+ }
@@ -0,0 +1,28 @@
1
+ import { readFile } from 'node:fs/promises'
2
+
3
+ export async function readAuditAllowlist(path) {
4
+ let raw
5
+ try {
6
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
7
+ raw = await readFile(path, 'utf8')
8
+ } catch {
9
+ return {}
10
+ }
11
+ let parsed
12
+ try {
13
+ parsed = JSON.parse(raw)
14
+ } catch {
15
+ throw new Error('Invalid advisory allowlist JSON.')
16
+ }
17
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
18
+ throw new Error('Advisory allowlist must be an object.')
19
+ }
20
+ for (const [id, entry] of Object.entries(parsed)) {
21
+ if (!entry?.reason || !entry?.expires) {
22
+ throw new Error(
23
+ `allowlist entry ${id} needs both \`reason\` and \`expires\`.`,
24
+ )
25
+ }
26
+ }
27
+ return parsed
28
+ }
@@ -0,0 +1,18 @@
1
+ import { validateAuditReport } from './validateAuditReport.mjs'
2
+
3
+ export function readAuditReport(result) {
4
+ if (
5
+ result.error ||
6
+ result.signal ||
7
+ (result.status !== 0 && result.status !== 1)
8
+ ) {
9
+ throw new Error('Could not complete pnpm audit.')
10
+ }
11
+ let report
12
+ try {
13
+ report = JSON.parse(result.stdout)
14
+ } catch {
15
+ throw new Error('pnpm audit did not return JSON.')
16
+ }
17
+ return validateAuditReport(report)
18
+ }
@@ -0,0 +1,18 @@
1
+ import { resolve } from 'node:path'
2
+ import ts from 'typescript'
3
+ import { throwCruiseConfigDiagnostic } from './throwCruiseConfigDiagnostic.mjs'
4
+
5
+ export function readCruiseCompilerOptions(configPath) {
6
+ const parsed = ts.getParsedCommandLineOfConfigFile(
7
+ resolve(configPath),
8
+ {},
9
+ {
10
+ ...ts.sys,
11
+ onUnRecoverableConfigFileDiagnostic: throwCruiseConfigDiagnostic,
12
+ },
13
+ )
14
+ if (!parsed)
15
+ throw new Error(`Cannot read TypeScript configuration: ${configPath}`)
16
+ if (parsed.errors.length > 0) throwCruiseConfigDiagnostic(parsed.errors[0])
17
+ return parsed.options
18
+ }
@@ -0,0 +1,40 @@
1
+ import { isAbsolute, resolve } from 'node:path'
2
+
3
+ export function rebaseCruisePaths(options) {
4
+ if (options.paths === undefined) return undefined
5
+ // TypeScript preserves the declaring config's origin in this internal field.
6
+ // Never substitute process.cwd() when a compiler omits that metadata.
7
+ const origin = options.baseUrl ?? options.pathsBasePath
8
+ if (typeof origin !== 'string' || !isAbsolute(origin)) {
9
+ throw new Error(
10
+ 'Unsupported TypeScript paths origin: an absolute baseUrl or pathsBasePath is required',
11
+ )
12
+ }
13
+ if (
14
+ options.paths === null ||
15
+ typeof options.paths !== 'object' ||
16
+ Array.isArray(options.paths)
17
+ ) {
18
+ throw new Error('TypeScript paths must be an alias map')
19
+ }
20
+ const paths = Object.create(null)
21
+ for (const [alias, targets] of Object.entries(options.paths)) {
22
+ if (!Array.isArray(targets) || targets.length === 0) {
23
+ throw new Error(
24
+ `TypeScript paths targets must be a nonempty array: ${alias}`,
25
+ )
26
+ }
27
+ paths[alias] = []
28
+ for (const target of targets) {
29
+ if (typeof target !== 'string' || target.length === 0) {
30
+ throw new Error(
31
+ `TypeScript paths target must be a nonempty string: ${alias}`,
32
+ )
33
+ }
34
+ paths[alias].push(resolve(origin, target))
35
+ }
36
+ }
37
+ return options.baseUrl === undefined
38
+ ? { paths }
39
+ : { baseUrl: options.baseUrl, paths }
40
+ }
@@ -0,0 +1,28 @@
1
+ export function reportAuditOutcome(advisories, outcome, level) {
2
+ for (const { advisory, entry } of outcome.waived) {
3
+ console.log(
4
+ `waived ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
5
+ `${advisory.module_name} (expires ${entry.expires})\n ${entry.reason}`,
6
+ )
7
+ }
8
+ for (const { advisory, entry } of outcome.stale) {
9
+ console.error(
10
+ `EXPIRED ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
11
+ `${advisory.module_name} (expired ${entry.expires})\n ${entry.reason}\n` +
12
+ ' Re-check it, then renew the entry or remove it.',
13
+ )
14
+ }
15
+ for (const advisory of outcome.failures) {
16
+ console.error(
17
+ `FAIL ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
18
+ `${advisory.module_name} ${advisory.vulnerable_versions}\n` +
19
+ ` patched in ${advisory.patched_versions} - ${advisory.url}\n` +
20
+ ` via ${(advisory.findings?.[0]?.paths ?? []).slice(0, 2).join(', ')}`,
21
+ )
22
+ }
23
+ console.log(
24
+ `\nbaseline-audit: ${advisories.length} advisories, gate at ${level}: ` +
25
+ `${outcome.failures.length} unwaived, ${outcome.stale.length} expired, ${outcome.waived.length} waived.`,
26
+ )
27
+ return outcome.failures.length + outcome.stale.length > 0 ? 1 : 0
28
+ }
@@ -0,0 +1,13 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { pnpmCommand } from './pnpmCommand.mjs'
3
+ import { readAuditReport } from './readAuditReport.mjs'
4
+
5
+ export function runPackageAudit() {
6
+ const [pnpm, ...args] = pnpmCommand()
7
+ return readAuditReport(
8
+ spawnSync(pnpm, [...args, 'audit', '--json'], {
9
+ encoding: 'utf8',
10
+ maxBuffer: 64 * 1024 * 1024,
11
+ }),
12
+ )
13
+ }
@@ -0,0 +1,11 @@
1
+ export function runSynchronousCruise(operation, configPath) {
2
+ const result = operation(configPath)
3
+ if (
4
+ result !== null &&
5
+ (typeof result === 'object' || typeof result === 'function') &&
6
+ typeof result.then === 'function'
7
+ ) {
8
+ throw new TypeError('withCruiseTsconfig requires a synchronous operation')
9
+ }
10
+ return result
11
+ }
@@ -0,0 +1,12 @@
1
+ export const SKIPPED_CRUISE_DIRECTORIES = new Set([
2
+ 'node_modules',
3
+ 'dist',
4
+ 'build',
5
+ 'coverage',
6
+ 'target',
7
+ '.git',
8
+ '.next',
9
+ '.nuxt',
10
+ '.output',
11
+ '.astro',
12
+ ])
@@ -0,0 +1,8 @@
1
+ import { spawnSync } from 'node:child_process'
2
+
3
+ export function spawnCruise(command, args, workspace, configPath) {
4
+ return spawnSync(command, [...args, '--ts-config', configPath], {
5
+ cwd: workspace,
6
+ stdio: 'inherit',
7
+ })
8
+ }
@@ -0,0 +1,5 @@
1
+ import ts from 'typescript'
2
+
3
+ export function throwCruiseConfigDiagnostic(diagnostic) {
4
+ throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
5
+ }
@@ -0,0 +1,105 @@
1
+ import { AUDIT_LEVELS } from './auditLevels.mjs'
2
+
3
+ export function validateAuditReport(report) {
4
+ if (
5
+ report === null ||
6
+ typeof report !== 'object' ||
7
+ Array.isArray(report) ||
8
+ 'error' in report
9
+ ) {
10
+ throw new Error('pnpm audit returned an error or invalid report.')
11
+ }
12
+ if (
13
+ report.advisories === null ||
14
+ typeof report.advisories !== 'object' ||
15
+ Array.isArray(report.advisories)
16
+ ) {
17
+ throw new Error('pnpm audit report is missing its advisory map.')
18
+ }
19
+ const metadata = report.metadata
20
+ if (
21
+ metadata === null ||
22
+ typeof metadata !== 'object' ||
23
+ Array.isArray(metadata)
24
+ ) {
25
+ throw new Error('pnpm audit report is missing metadata.')
26
+ }
27
+ const counts = metadata.vulnerabilities
28
+ if (counts === null || typeof counts !== 'object' || Array.isArray(counts)) {
29
+ throw new Error('pnpm audit report is missing vulnerability counts.')
30
+ }
31
+ for (const key of [
32
+ 'dependencies',
33
+ 'devDependencies',
34
+ 'optionalDependencies',
35
+ 'totalDependencies',
36
+ ]) {
37
+ if (!Number.isInteger(metadata[key]) || metadata[key] < 0)
38
+ throw new Error('Invalid audit dependency counts.')
39
+ }
40
+ for (const key of Object.keys(counts)) {
41
+ if (!AUDIT_LEVELS.includes(key))
42
+ throw new Error('Unknown audit vulnerability count severity.')
43
+ }
44
+ const observed = Object.create(null)
45
+ for (const level of AUDIT_LEVELS) {
46
+ if (!Number.isInteger(counts[level]) || counts[level] < 0)
47
+ throw new Error('Invalid audit vulnerability counts.')
48
+ observed[level] = 0
49
+ }
50
+ for (const advisory of Object.values(report.advisories)) {
51
+ if (
52
+ advisory === null ||
53
+ typeof advisory !== 'object' ||
54
+ Array.isArray(advisory)
55
+ ) {
56
+ throw new Error('Invalid audit advisory.')
57
+ }
58
+ if (
59
+ !AUDIT_LEVELS.includes(advisory.severity) ||
60
+ typeof advisory.module_name !== 'string' ||
61
+ !advisory.module_name ||
62
+ !['number', 'string'].includes(typeof advisory.id)
63
+ ) {
64
+ throw new Error('Invalid audit advisory identity or severity.')
65
+ }
66
+ if (
67
+ advisory.github_advisory_id !== undefined &&
68
+ typeof advisory.github_advisory_id !== 'string'
69
+ ) {
70
+ throw new Error('Invalid GitHub advisory identity.')
71
+ }
72
+ for (const key of ['title', 'url', 'vulnerable_versions']) {
73
+ if (typeof advisory[key] !== 'string')
74
+ throw new Error('Incomplete audit advisory.')
75
+ }
76
+ if (
77
+ !Object.hasOwn(advisory, 'patched_versions') ||
78
+ (advisory.patched_versions !== null &&
79
+ typeof advisory.patched_versions !== 'string')
80
+ ) {
81
+ throw new Error('Invalid patched-version metadata.')
82
+ }
83
+ if (!Array.isArray(advisory.findings))
84
+ throw new Error('Incomplete audit dependency findings.')
85
+ for (const finding of advisory.findings) {
86
+ if (
87
+ finding === null ||
88
+ typeof finding !== 'object' ||
89
+ !Array.isArray(finding.paths)
90
+ ) {
91
+ throw new Error('Incomplete audit dependency paths.')
92
+ }
93
+ for (const path of finding.paths) {
94
+ if (typeof path !== 'string')
95
+ throw new Error('Invalid audit dependency path.')
96
+ }
97
+ }
98
+ observed[advisory.severity] += 1
99
+ }
100
+ for (const level of AUDIT_LEVELS) {
101
+ if (observed[level] !== counts[level])
102
+ throw new Error('Audit advisory counts do not match metadata.')
103
+ }
104
+ return report
105
+ }
@@ -0,0 +1,5 @@
1
+ export declare function withCruiseTsconfig<Result>(
2
+ configPath: string,
3
+ operation: (configPath: string) => Result,
4
+ options?: { readonly requirePaths?: boolean },
5
+ ): Result
@@ -0,0 +1,42 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { closeSync, openSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { dirname, join, resolve } from 'node:path'
4
+ import { readCruiseCompilerOptions } from './readCruiseCompilerOptions.mjs'
5
+ import { rebaseCruisePaths } from './rebaseCruisePaths.mjs'
6
+ import { runSynchronousCruise } from './runSynchronousCruise.mjs'
7
+
8
+ export function withCruiseTsconfig(
9
+ configPath,
10
+ operation,
11
+ { requirePaths = false } = {},
12
+ ) {
13
+ const original = resolve(configPath)
14
+ const compilerOptions = rebaseCruisePaths(readCruiseCompilerOptions(original))
15
+ if (!compilerOptions) {
16
+ if (requirePaths)
17
+ throw new Error(`No TypeScript paths reachable from ${original}`)
18
+ return runSynchronousCruise(operation, original)
19
+ }
20
+ // The same directory preserves TypeScript's implicit include location.
21
+ const generated = join(
22
+ dirname(original),
23
+ `.baseline-depcruise-${randomUUID()}.json`,
24
+ )
25
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- A random filename stays beside the parsed tsconfig; wx rejects preexisting paths.
26
+ const descriptor = openSync(generated, 'wx', 0o600)
27
+ try {
28
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- descriptor is the numeric fd from the exclusive open above, not a filename.
29
+ writeFileSync(
30
+ descriptor,
31
+ JSON.stringify({ extends: original, compilerOptions }),
32
+ )
33
+ return runSynchronousCruise(operation, generated)
34
+ } finally {
35
+ try {
36
+ closeSync(descriptor)
37
+ } finally {
38
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- This filename was created by the successful exclusive open and is cleaned in finally.
39
+ unlinkSync(generated)
40
+ }
41
+ }
42
+ }
package/jscpd.json CHANGED
@@ -10,7 +10,8 @@
10
10
  "astro",
11
11
  "rust",
12
12
  "dart",
13
- "swift"
13
+ "swift",
14
+ "go"
14
15
  ],
15
16
  "gitignore": true,
16
17
  "ignore": [
@@ -24,7 +25,11 @@
24
25
  "**/*.freezed.dart",
25
26
  "**/.build/**",
26
27
  "**/build/**",
27
- "**/.dart_tool/**"
28
+ "**/.dart_tool/**",
29
+ "**/vendor/**",
30
+ "**/testdata/**",
31
+ "**/*.pb.go",
32
+ "**/*_gen.go"
28
33
  ],
29
34
  "reporters": ["console"]
30
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syntopica/quality-config",
3
- "version": "0.15.0",
3
+ "version": "0.16.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",
@@ -48,7 +48,11 @@
48
48
  "./jscpd": "./jscpd.json",
49
49
  "./commitlint": "./src/commitlint.ts",
50
50
  "./oxlint": "./oxlintrc.json",
51
- "./pnpm-command": "./bin/pnpmCommand.mjs"
51
+ "./pnpm-command": "./bin/pnpmCommand.mjs",
52
+ "./cruise-tsconfig": {
53
+ "types": "./bin/withCruiseTsconfig.d.mts",
54
+ "default": "./bin/withCruiseTsconfig.mjs"
55
+ }
52
56
  },
53
57
  "peerDependencies": {
54
58
  "@commitlint/config-conventional": ">=21.0.0",
@@ -73,16 +77,16 @@
73
77
  },
74
78
  "devDependencies": {
75
79
  "@arethetypeswrong/cli": "^0.18.5",
76
- "@syntopica/eslint-config": "0.10.0",
77
- "@types/node": "^26.6.5",
80
+ "@syntopica/eslint-config": "0.10.1",
81
+ "@types/node": "^26.6.6",
78
82
  "@typescript/native": "npm:typescript@^7.0.2",
79
- "dependency-cruiser": "^18.5.0",
80
- "eslint": "^10.12.0",
81
- "eslint-plugin-regexp": "^3.3.1",
82
- "knip": "^6.41.0",
83
+ "dependency-cruiser": "^18.9.0",
84
+ "eslint": "^10.15.0",
85
+ "eslint-plugin-regexp": "^3.3.3",
86
+ "knip": "^6.47.0",
83
87
  "publint": "^0.3.25",
84
88
  "typescript": "npm:@typescript/typescript6@^6.0.2",
85
- "vitest": "^5.0.3"
89
+ "vitest": "^5.1.1"
86
90
  },
87
91
  "dependencies": {
88
92
  "tinyglobby": "^0.2.17"
@@ -80,7 +80,10 @@ const REPO_SCOPE_RULES: IForbiddenRuleType[] = [
80
80
  comment:
81
81
  'A devDependency imported by shipped code will be missing at runtime for consumers.',
82
82
  from: { path: '^packages/[^/]+/src/', pathNot: '\\.(test|spec)\\.ts$' },
83
- to: { dependencyTypes: ['npm-dev'] },
83
+ to: {
84
+ dependencyTypes: ['npm-dev'],
85
+ dependencyTypesNot: ['type-only', 'npm-peer'],
86
+ },
84
87
  },
85
88
  {
86
89
  name: 'no-deprecated-core',
@@ -70,7 +70,7 @@ export const FRAMEWORK_ENTRIES: Record<
70
70
  },
71
71
  nuxt: {
72
72
  entry: ['app/**/*.vue!', 'server/**/*.ts!', 'nuxt.config.*'],
73
- project: ['app/**/*.{ts,vue}!', 'server/**/*.ts!'],
73
+ project: ['app/**/*.{ts,vue,css}!', 'server/**/*.ts!'],
74
74
  includeEntryExports: false,
75
75
  },
76
76
  // TanStack Start has no index.html and no src/main.tsx: the router is the
@@ -94,7 +94,7 @@ export const FRAMEWORK_ENTRIES: Record<
94
94
  // src/main.tsx, not src/main.ts; keep both extensions so a plain-TS
95
95
  // Tauri frontend also matches.
96
96
  entry: ['src/main.{ts,tsx}!', 'vite.config.*'],
97
- project: ['src/**/*.{ts,tsx}!'],
97
+ project: ['src/**/*.{ts,tsx,css}!'],
98
98
  includeEntryExports: false,
99
99
  },
100
100
  'ts-package': {
@@ -106,12 +106,12 @@ export const FRAMEWORK_ENTRIES: Record<
106
106
  // well was a "Remove redundant entry pattern" hint in both Vite templates.
107
107
  'vite-react': {
108
108
  entry: ['index.html!', 'vite.config.*'],
109
- project: ['src/**/*.{ts,tsx}!'],
109
+ project: ['src/**/*.{ts,tsx,css}!'],
110
110
  includeEntryExports: false,
111
111
  },
112
112
  'vite-vue': {
113
113
  entry: ['index.html!', 'vite.config.*'],
114
- project: ['src/**/*.{ts,vue}!'],
114
+ project: ['src/**/*.{ts,vue,css}!'],
115
115
  includeEntryExports: false,
116
116
  },
117
117
  }
package/src/knip.ts CHANGED
@@ -10,6 +10,7 @@ import { FRAMEWORK_ENTRIES, type KnipFramework } from './knip-framework'
10
10
  import { matchedPresetPatterns } from './matchedPresetPatterns'
11
11
  import { peersOfListedDependencies } from './peersOfListedDependencies'
12
12
  import { PRODUCTION_PROJECT_EXCLUSIONS } from './PRODUCTION_PROJECT_EXCLUSIONS'
13
+ import { readInstalledDependencyNames } from './readInstalledDependencyNames'
13
14
  import { readListedDependencies } from './readListedDependencies'
14
15
  import { runnerDependenciesToIgnore } from './runnerDependenciesToIgnore'
15
16
 
@@ -103,6 +104,9 @@ export const createKnipConfig = (options: {
103
104
  }): KnipConfiguration => {
104
105
  const cwd = options.cwd ?? process.cwd()
105
106
  const hostedPeers = peersOfListedDependencies(cwd)
107
+ const sharedConfigDependencies = new Set(
108
+ readInstalledDependencyNames(cwd, '@syntopica/eslint-config'),
109
+ )
106
110
  const usesSharedEslint = readListedDependencies(cwd).includes(
107
111
  '@syntopica/eslint-config',
108
112
  )
@@ -138,10 +142,15 @@ export const createKnipConfig = (options: {
138
142
  ignoreExportsUsedInFile: true,
139
143
  ignoreBinaries: ['gitleaks', ...(options.ignoreBinaries ?? [])],
140
144
  ignoreDependencies: [
141
- ...runnerDependenciesToIgnore(cwd),
145
+ ...runnerDependenciesToIgnore(cwd).filter(
146
+ (dependency) => !hostedPeers.has(dependency),
147
+ ),
142
148
  ...(FRAMEWORK_RUNTIME_PACKAGES[options.framework] ?? []),
143
149
  ...ESLINT_PEER_DEPENDENCIES.filter(
144
- (dependency) => usesSharedEslint && !hostedPeers.has(dependency),
150
+ (dependency) =>
151
+ usesSharedEslint &&
152
+ !hostedPeers.has(dependency) &&
153
+ !sharedConfigDependencies.has(dependency),
145
154
  ),
146
155
  ...(options.ignoreDependencies ?? []),
147
156
  ],
@@ -0,0 +1,30 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /** Direct runtime dependencies owned by an installed package; unknown metadata gives none. */
5
+ export function readInstalledDependencyNames(
6
+ cwd: string,
7
+ name: string,
8
+ ): string[] {
9
+ try {
10
+ const manifest = JSON.parse(
11
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- a listed dependency's manifest under the project's node_modules
12
+ readFileSync(join(cwd, 'node_modules', name, 'package.json'), 'utf8'),
13
+ ) as { dependencies?: Record<string, unknown> }
14
+ const dependencies = manifest.dependencies
15
+ if (
16
+ !dependencies ||
17
+ typeof dependencies !== 'object' ||
18
+ Array.isArray(dependencies)
19
+ )
20
+ return []
21
+ const names: string[] = []
22
+ for (const [dependency, version] of Object.entries(dependencies)) {
23
+ if (typeof version === 'string' && version.trim().length > 0)
24
+ names.push(dependency)
25
+ }
26
+ return names
27
+ } catch {
28
+ return []
29
+ }
30
+ }