import { globSync, readFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; const frameworkVariables = new Set([ 'NODE_ENV', 'NEXT_PHASE', 'NEXT_RUNTIME', '__NEXT_PRIVATE_PREBUNDLED_REACT', 'npm_lifecycle_event', 'npm_package_version', 'SystemRoot', 'HOSTNAME', ]); const sourcePaths = [ ...['lib', 'app', 'workers', 'hooks'].map(dir => dir + '/**/*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}'), 'instrumentation.ts', 'middleware.ts', ]; export function referencedEnvironment(root) { const names = new Set(); for (const file of globSync(sourcePaths, { cwd: root, exclude: ['**/node_modules', '**/dist'] })) { const source = readFileSync(join(root, file), 'utf8'); for (const [, name] of source.matchAll(/\bprocess\s*\.\s*env\s*\.\s*([A-Za-z_$][\w$]*)/g)) { if (!frameworkVariables.has(name)) names.add(name); } } return [...names].sort(); } export function missingEnvironment(root) { const example = readFileSync(join(root, '.env.example'), 'utf8'); const declared = new Set([...example.matchAll(/^([A-Za-z_$][\w$]*)=/gm)].map(([, name]) => name)); return referencedEnvironment(root).filter(name => !declared.has(name)); } if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { const missing = missingEnvironment(process.cwd()); if (missing.length) { console.error('.env.example 缺少登记:' + missing.join(', ')); process.exitCode = 1; } }