Shared components left in route folders, and duplicate component names. An exception needs a reason and an expiry date.
Add "Shared component checks" from ntent to this repo.
Fetch https://ntent.app/r/f/check-stray-components as plain text. Write it verbatim to scripts/check-stray-components.mjs. Then make exactly these edits and no others: Point CONFIG at this repo’s route and shared-component directories if they are not src/app and src/components.
Then check it: Import a private component from a second route and the check tells you to promote it. Allowlist it and the reason and date print on every run afterwards, rather than the finding disappearing. Backdate the entry and it fails.Reads https://ntent.app/r/f/check-stray-components
Read the code
check-stray-components.mjsscripts/check-stray-components.mjs
521 lines
#!/usr/bin/env node
/**
* Design-system drift gate: a reusable component should not live inside one
* route's private folder.
*
* Two separate checks, because they fail differently.
*
* CHECK 1, REUSE. A component defined under a route's private folder
* (src/app/**\/_components/) but imported by two or more other places is
* shared in practice while living somewhere private by name. The next person
* looking for it will not find it, and will write a second one.
*
* CHECK 2, DUPLICATES. The same component name defined in two or more files.
* This is the worse failure, because there is no single source at all, and
* check 1 cannot see it: check 1 works by counting importers, and two
* copy-pasted components have zero importers each. In an earlier repo a row
* component was defined twice, in two different sheets, with the same anatomy
* and the same explanatory comment pasted into both. Every gate was green.
*
* Neither check is a proof. Both are prompts for a human decision: promote it,
* or add it to ALLOWLIST with a reason and a date. The reason is the point. An
* allowlist entry with no explanation becomes permanent within a month, so the
* allowlist is a mechanism rather than a courtesy: both fields are required,
* every accepted entry prints on every run, and the date is enforced. The
* obvious implementation, `if (ALLOWLIST[name]) continue`, is that same warning
* written into the code: skipped in silence, with a reason nothing ever reads.
*
* WHAT IT DOES NOT PROVE. That the components it passes are well factored, or
* that an accepted exception is still a good idea. It proves that every
* exception has a name, a reason and a date somebody agreed to.
*
* Usage:
* node scripts/check-stray-components.mjs report, always exit 0
* node scripts/check-stray-components.mjs --check exit 1 on anything unaccepted
* node scripts/check-stray-components.mjs --check src/a.tsx block only on findings that involve these files
*
* EXIT CODES. 0 clean, 1 findings or a broken allowlist, 2 read nothing.
*
* An allowlist entry with no reason, no date or a date that is not YYYY-MM-DD is
* exit 1, in either mode, and it blocks. It used to be exit 2, which the
* pre-commit hook treats as a note ("nothing to read"), so the one thing an
* allowlist that demands reasons exists to stop was let through with a note.
* Exit 2 is kept for the scan reading no .tsx/.jsx file at all: that is a check
* pointed at the wrong place (or at Vue, Svelte or Astro), and "ok. 0
* components" would read as a pass.
*
* Exit 0 with paths given and none of them a file this reads is a commit with
* nothing to check. It says so on stdout and in NTENT_UNCHECKED_FILE (see
* noteUnchecked), which is how the hook keeps it off its passed list.
*/
import { appendFileSync, readFileSync, readdirSync, statSync, existsSync } from 'node:fs'
import { join, basename, dirname, normalize, relative, resolve, sep } from 'node:path'
// ---------------------------------------------------------------- CONFIG ---
const CONFIG = {
// Folders whose components are meant to be private to one route or feature.
// A component here that gets shared is the drift this catches.
privateDirs: ['src/app', 'src/features'],
// Where a promoted component belongs.
sharedDir: 'src/components',
// Everything scanned for imports, to count who uses what.
scanDirs: ['src'],
ignoreDirs: ['node_modules', '.next', 'dist', 'build', '.git'],
// Names that look like components but are compositions, not primitives.
// A page or a layout is not something you promote.
compositionSuffixes: ['Page', 'Layout', 'Template', 'Provider', 'Boundary', 'Route'],
// Files that re-export or catalogue rather than consume. An index barrel
// importing something is not evidence of reuse.
barrelNames: ['index.ts', 'index.tsx'],
// Next's file conventions. What these export is the route's own entry, named
// Loading or Error or NotFound in every route by design, so it is neither a
// component to promote nor a duplicate: eight routes with a loading.tsx are
// not eight copies of one component.
specialFiles: ['page', 'layout', 'loading', 'error', 'global-error', 'not-found', 'template', 'default', 'route'],
// Files that neither define a component worth sharing nor show one being
// reused. A story's `export const Primary = () => <Row />` reads as a
// component named Primary, and a story importing Row is not a second user.
ignoreFiles: [/\.stories\.[jt]sx?$/, /\.story\.[jt]sx?$/, /\.(test|spec)\.[jt]sx?$/, /(^|[\\/])__tests__[\\/]/],
// Non-relative import prefixes that point into the repo. Anything else that
// is not relative is a package, and a package's Row is not ours.
aliases: { '@/': 'src/', '~/': 'src/' },
}
/**
* Intentional exceptions. Every entry carries WHY this is genuinely local and
* WHEN it stops being acceptable, because "nobody has got round to it" is not a
* reason and an exception with no date never leaves.
*
* Both fields are enforced rather than requested. An entry missing either one
* stops the script dead, and every accepted entry is printed on every run: an
* exception nobody sees again is a permanent one.
*/
const ALLOWLIST = {
// InvoiceRow: {
// reason:
// 'Bound to the billing fixtures and the invoice status enum, not a tenant-neutral ' +
// 'primitive. Shared by the list and the detail drawer on purpose so the two never drift.',
// until: '2026-06-30',
// },
}
// --------------------------------------------------------------- HELPERS ---
function walk(dir, acc = []) {
let entries
try {
entries = readdirSync(dir)
} catch {
return acc
}
for (const entry of entries) {
if (CONFIG.ignoreDirs.includes(entry)) continue
const full = join(dir, entry)
if (statSync(full).isDirectory()) walk(full, acc)
else if (/\.(tsx|jsx)$/.test(entry)) acc.push(full)
else if (UNREADABLE.test(entry)) unreadable.push(full)
}
return acc
}
// Component formats this checker has no reader for. Kept so an empty run can
// name them instead of reporting a pass.
const UNREADABLE = /\.(vue|svelte|astro)$/
const unreadable = []
const isIgnoredFile = (file) => CONFIG.ignoreFiles.some((re) => re.test(file))
const isSpecialFile = (file) => CONFIG.specialFiles.includes(basename(file).replace(/\.[jt]sx?$/, ''))
/**
* Component names declared in a file. Matches the four shapes people write:
* export function X, export const X = , function X, const X = , where X is
* PascalCase. Non-exported declarations are included on purpose: check 2 needs
* them, since a copy-pasted component is usually not exported.
*/
function componentsDeclaredIn(file) {
if (isIgnoredFile(file) || isSpecialFile(file)) return new Map()
const text = readFileSync(file, 'utf8')
const found = new Map() // name -> exported?
const patterns = [
{ re: /export\s+(?:default\s+)?function\s+([A-Z][A-Za-z0-9]*)/g, exported: true },
{ re: /export\s+const\s+([A-Z][A-Za-z0-9]*)\s*[:=]/g, exported: true },
{ re: /^\s*function\s+([A-Z][A-Za-z0-9]*)/gm, exported: false },
{ re: /^\s*const\s+([A-Z][A-Za-z0-9]*)\s*[:=]\s*(?:\(|function|React\.memo|forwardRef)/gm, exported: false },
]
for (const { re, exported } of patterns) {
re.lastIndex = 0
let m
while ((m = re.exec(text))) {
const name = m[1]
if (CONFIG.compositionSuffixes.some((s) => name.endsWith(s))) continue
if (!found.has(name) || exported) found.set(name, exported)
}
}
// Only count it as a component if the file actually renders JSX. A PascalCase
// const in a plain .ts helper is a type or a constant, not a component.
if (!/<[A-Za-z]/.test(text)) return new Map()
return found
}
/**
* The component a file default-exports, or null. `export default function X`,
* `export default X`, or, failing both, the only component the file declares:
* `const Card = ...; export default memo(Card)` is read that way.
*/
function defaultComponentOf(file, declared) {
const text = readFileSync(file, 'utf8')
const direct =
/export\s+default\s+(?:async\s+)?function\s+([A-Z][A-Za-z0-9]*)/.exec(text)?.[1] ??
/export\s+default\s+(?:[A-Za-z.]+\()?([A-Z][A-Za-z0-9]*)\)?\s*;?\s*$/m.exec(text)?.[1]
if (direct && declared.has(direct)) return direct
return declared.size === 1 && /export\s+default\b/.test(text) ? [...declared.keys()][0] : null
}
/**
* Every import in a file: where from, which names it takes, and what it calls
* the default. A dynamic import() and next/dynamic's `import('./X')` take the
* default. Side-effect imports (`import './x.css'`) have no clause and are not
* matched, because the clause cannot hold a quote.
*/
function importsIn(file) {
const text = readFileSync(file, 'utf8')
const found = []
const re = /import\s+(?:type\s+)?([\w$\s,{}*]+?)\s*from\s*['"]([^'"]+)['"]/g
let m
while ((m = re.exec(text))) {
const clause = m[1]
const named = [...(/\{([^}]*)\}/.exec(clause)?.[1] ?? '').split(',')]
.map((part) => part.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0].trim())
.filter((n) => /^[A-Z]/.test(n))
const hasDefault = /^\s*[A-Za-z_$][\w$]*\s*(?:,|$)/.test(clause) && !/^\s*(?:\{|\*)/.test(clause)
found.push({ spec: m[2], named, hasDefault })
}
for (const d of text.matchAll(/import\(\s*['"]([^'"]+)['"]\s*\)/g)) {
found.push({ spec: d[1], named: [], hasDefault: true })
}
return found
}
/**
* The scanned file an import path points at, or null. Relative paths and the
* configured aliases are resolved the way a bundler would, trying the usual
* extensions and an index file. A path that is neither is a package.
*/
function resolveImport(from, spec, known) {
let base
if (spec.startsWith('.')) base = join(dirname(from), spec)
else {
const alias = Object.keys(CONFIG.aliases).find((a) => spec.startsWith(a))
if (!alias) return null
base = CONFIG.aliases[alias] + spec.slice(alias.length)
}
base = normalize(base)
const exts = ['.tsx', '.jsx']
for (const c of [base, ...exts.map((e) => base + e), ...exts.map((e) => join(base, 'index' + e))]) {
if (known.has(c)) return c
}
return null
}
function isPrivate(file) {
return CONFIG.privateDirs.some((d) => file.startsWith(d + sep) || file.startsWith(d + '/'))
}
/** Reason text, wrapped so a long one stays readable in a terminal. */
function wrap(text, width = 72) {
const lines = []
let line = ''
for (const word of String(text).split(/\s+/)) {
if (line && line.length + word.length + 1 > width) {
lines.push(line)
line = word
} else {
line = line ? `${line} ${word}` : word
}
}
if (line) lines.push(line)
return lines
}
/**
* Refuse to run on a malformed allowlist. Exit 1, so it blocks: a finding is
* something in the codebase, and this is the check's own config being wrong,
* but exit 2 means "read nothing" to the hook and ends up a note, which lets
* the commit through. Failing loudly here is the difference between an
* allowlist and a place things go to disappear.
*/
function validateAllowlist() {
for (const [name, rec] of Object.entries(ALLOWLIST)) {
if (!rec || !rec.reason || !rec.until) {
console.error(`\n Allowlist entry "${name}" has no reason or no until date.`)
console.error(` An entry without both is permanent, and "nobody has got round to`)
console.error(` it" is not a reason. Add both, or delete the entry and do the work.\n`)
process.exit(1)
}
// Dates are compared as strings, so the format is load-bearing. 'soon' or
// '1 June' would sort as never expired and the entry would be permanent
// while looking dated.
if (!/^\d{4}-\d{2}-\d{2}$/.test(rec.until)) {
console.error(`\n Allowlist entry "${name}" has until: "${rec.until}".`)
console.error(` It has to be YYYY-MM-DD. Anything else never expires.\n`)
process.exit(1)
}
}
}
/**
* The pre-commit hook points NTENT_UNCHECKED_FILE at a file and reads one line
* of reason back from it, so it can list this gate as having read nothing.
* Unset, this does nothing, and a run by hand prints what it always did.
*/
function noteUnchecked(reason) {
const file = process.env.NTENT_UNCHECKED_FILE
if (!file) return
try {
appendFileSync(file, reason + '\n')
} catch {
// The hook falls back to what it knew before.
}
}
// ------------------------------------------------------------------ MAIN ---
function main() {
const strict = process.argv.includes('--check')
// What the pre-commit hook triggers on, asked of the checker so that moving
// these dirs moves the gate with it instead of leaving it on src/.
if (process.argv.includes('--print-config')) {
for (const dir of [...CONFIG.scanDirs, ...CONFIG.privateDirs, CONFIG.sharedDir]) console.log(`watchDir\t${dir}`)
process.exit(0)
}
const today = new Date().toISOString().slice(0, 10)
validateAllowlist()
const files = CONFIG.scanDirs.filter(existsSync).flatMap((d) => walk(d)).map((f) => normalize(f))
// Paths on the command line are the files being committed. The scan is still
// the whole repo, because who imports a component is a fact about every file,
// but only a finding that involves one of these blocks the commit.
const staged = process.argv
.slice(2)
.filter((a) => !a.startsWith('--'))
.map((p) => relative(process.cwd(), resolve(p)))
const touches = (file) => staged.includes(file)
// A scan that read no file checked nothing, and "ok. 0 component(s) across 0
// files" reads like a pass. Say what was looked for and what to change.
if (!files.length) {
const kinds = [...new Set(unreadable.map((f) => f.slice(f.lastIndexOf('.'))))].sort()
const missing = CONFIG.scanDirs.filter((d) => !existsSync(d))
console.log(
`components: could not check. Read 0 .tsx/.jsx files under ${CONFIG.scanDirs.join(', ')}.\n` +
(missing.length ? ` ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist here.\n` : '') +
(unreadable.length
? ` It found ${unreadable.length} ${kinds.join(', ')} file(s) there, and does not read them: this checker reads\n` +
` React components only.\n`
: '') +
` Set CONFIG.scanDirs (and privateDirs) to where your React components live, or drop this check.`,
)
process.exit(2)
}
// name -> [files that declare it]
const declaredIn = new Map()
const declaredBy = new Map() // file -> Map(name -> exported?)
const known = new Set(files)
for (const file of files) {
const declared = componentsDeclaredIn(file)
declaredBy.set(file, declared)
for (const [name] of declared) {
if (!declaredIn.has(name)) declaredIn.set(name, [])
declaredIn.get(name).push(file)
}
}
// name -> [files that import it], excluding barrels and the declaring file.
//
// An import counts when its PATH points at the file that declares the name,
// not when the name merely matches. A name match counted `import { Row } from
// 'some-lib'` as a user of the private Row, and missed `import Tile from
// './Row'` because the default import carries no name to match.
const importedBy = new Map()
const addUser = (name, file) => {
if (!importedBy.has(name)) importedBy.set(name, new Set())
importedBy.get(name).add(file)
}
for (const file of files) {
if (CONFIG.barrelNames.includes(basename(file)) || isIgnoredFile(file)) continue
for (const { spec, named, hasDefault } of importsIn(file)) {
const target = resolveImport(file, spec, known)
if (target) {
if (target === file) continue
const declared = declaredBy.get(target)
for (const name of named) if (declared.has(name)) addUser(name, file)
if (hasDefault) {
const name = defaultComponentOf(target, declared)
if (name) addUser(name, file)
}
} else if (!spec.startsWith('.')) {
// An alias this file does not know (tsconfig paths, say) cannot be
// resolved, so fall back to the last segment of the path agreeing with
// the declaring file's name. A package named for a component does not.
const last = spec.split('/').pop().replace(/\.[jt]sx?$/, '')
for (const name of named) {
for (const site of declaredIn.get(name) ?? []) {
const stem = basename(site).replace(/\.[jt]sx?$/, '')
const owner = stem === 'index' ? basename(dirname(site)) : stem
if (owner === last && site !== file) addUser(name, file)
}
}
}
}
}
const findings = []
const accepted = [] // allowlisted, and printed every run rather than skipped
// CHECK 1: private but reused.
for (const [name, sites] of declaredIn) {
if (sites.length !== 1) continue // handled by check 2
const home = sites[0]
if (!isPrivate(home)) continue
const users = [...(importedBy.get(name) ?? [])]
if (users.length >= 2) {
if (ALLOWLIST[name]) {
accepted.push({ kind: 'REUSED-BUT-PRIVATE', name, where: rel(home) })
continue
}
findings.push({
kind: 'REUSED-BUT-PRIVATE',
name,
involves: [home, ...users],
detail:
` defined in ${rel(home)}\n` +
` imported by ${users.length}: ${users.map(rel).join(', ')}\n` +
` fix: move it to ${CONFIG.sharedDir}/, or add it to ALLOWLIST with the\n` +
` reason it is genuinely local to one route, and a date`,
})
}
}
// CHECK 2: defined more than once.
for (const [name, sites] of declaredIn) {
if (sites.length < 2) continue
if (ALLOWLIST[name]) {
accepted.push({ kind: 'DEFINED-TWICE', name, where: sites.map(rel).join(', ') })
continue
}
findings.push({
kind: 'DEFINED-TWICE',
name,
involves: sites,
detail:
` defined in ${sites.length} files: ${sites.map(rel).join(', ')}\n` +
` There is no single source for this component. Copy-paste is the worse\n` +
` failure: the two copies will drift and nobody will notice.\n` +
` fix: keep one, in ${CONFIG.sharedDir}/, and import it in both places`,
})
}
// Staged paths narrow what blocks. A repo with old duplicates would
// otherwise refuse every commit that touched any component (5 of 74 blocked
// edits in the field study); what is left over is counted, not hidden.
let outside = 0
if (staged.length) {
if (!staged.some((f) => known.has(f))) {
console.log(
`components: nothing staged is a file this reads (.tsx/.jsx under ${CONFIG.scanDirs.join(', ')}), so nothing to check for this commit.`,
)
noteUnchecked('nothing staged is a file it reads')
process.exit(0)
}
for (let i = findings.length - 1; i >= 0; i--) {
if (!findings[i].involves.some(touches)) {
findings.splice(i, 1)
outside++
}
}
}
const debtNote = outside
? ` note: ${outside} finding(s) involve no staged file, not blocking this commit. Run without paths to see them.\n`
: ''
// -------------------------------------------------------------- REPORT ---
// Accepted exceptions print FIRST, on every run, whether or not anything else
// was found. This is the half that used to be a silent `continue`: an
// exception you never see again is one nobody will ever remove.
let expired = 0
if (accepted.length) {
console.log(`\n Accepted, each with a reason and a date:\n`)
for (const a of accepted) {
const rec = ALLOWLIST[a.name]
console.log(` [known] ${a.name} ${a.kind}, until ${rec.until}`)
console.log(` ${a.where}`)
for (const line of wrap(rec.reason, 66)) console.log(` ${line}`)
if (today > rec.until) {
expired++
console.log(` PAST ITS DATE. Do the work, or agree a new date and write`)
console.log(` down what changed. Moving the date on its own is how an`)
console.log(` exception becomes permanent.`)
}
console.log()
}
}
// An entry that matched nothing is dead config. The drift it accepted is gone,
// or the name changed, and either way the entry now accepts nothing while
// reading as an agreed exception. Printed, not fatal: deleting it is the work.
const unused = Object.keys(ALLOWLIST).filter((name) => !accepted.some((a) => a.name === name))
if (unused.length) {
console.log(` Allowlist entries that matched nothing this run:\n`)
for (const name of unused) {
console.log(` [stale] ${name}`)
console.log(` Nothing here is that component any more. Delete the entry,`)
console.log(` so the allowlist keeps meaning what it says.`)
console.log()
}
}
if (!findings.length && !expired) {
if (accepted.length) {
console.log(
` components: none new. ${accepted.length} accepted, listed above with a reason and a date.\n`,
)
} else {
console.log(`components: ok. ${declaredIn.size} component(s) across ${files.length} files.`)
}
if (debtNote) console.log(debtNote)
process.exit(0)
}
if (findings.length) {
if (!accepted.length && !unused.length) console.log()
console.log(` components: ${findings.length} finding(s)\n`)
for (const f of findings) {
console.log(` ${f.kind} ${f.name}`)
console.log(f.detail)
console.log()
}
console.log(` These are prompts for a decision, not proofs. Promote, or allowlist`)
console.log(` with a reason AND a date in ${rel('scripts/check-stray-components.mjs')}.`)
console.log()
}
// An expired entry counts as unaccepted, because that is what it is. The two
// numbers are separate so nobody reads a long accepted list as a clean run.
console.log(
` components: ${findings.length + expired} unaccepted, ${accepted.length - expired} accepted.\n`,
)
if (debtNote) console.log(debtNote)
process.exit(strict ? 1 : 0)
}
function rel(f) {
return relative(process.cwd(), f)
}
main()
How to tell it works: Import a private component from a second route and the check tells you to promote it. Allowlist it and the reason and date print on every run afterwards, rather than the finding disappearing. Backdate the entry and it fails.