334 lines
12 KiB
TypeScript
334 lines
12 KiB
TypeScript
/**
|
|
* Package-invariant companion discovery and structural checks.
|
|
* The runtime registry stays product-independent; this gate makes ownership
|
|
* exhaustive across packages without centralizing package checks.
|
|
*/
|
|
|
|
import { existsSync, globSync, readFileSync } from 'node:fs'
|
|
import { dirname, relative, resolve, sep } from 'node:path'
|
|
import ts from 'typescript'
|
|
|
|
interface PackageManifest {
|
|
name?: string
|
|
exports?: Record<string, { types?: string; default?: string } | string | undefined>
|
|
files?: string[]
|
|
peerDependencies?: Record<string, string>
|
|
devDependencies?: Record<string, string>
|
|
}
|
|
|
|
/** One package and the files participating in its invariant publication contract. */
|
|
export interface PackageInvariantOwner {
|
|
readonly dir: string
|
|
readonly manifestPath: string
|
|
readonly sourcePath: string
|
|
readonly packageName: string
|
|
}
|
|
|
|
/** One gate violation with a repo-relative owner path. */
|
|
export interface PackageInvariantViolation {
|
|
readonly path: string
|
|
readonly message: string
|
|
}
|
|
|
|
/** Discover every package under the repository package tree. */
|
|
export function packageInvariantOwners(root: string): PackageInvariantOwner[] {
|
|
return globSync('packages/*/*/package.json', { cwd: root })
|
|
.map(path => path.split(sep).join('/'))
|
|
.sort()
|
|
.map((manifestPath) => {
|
|
const manifest = readManifest(resolve(root, manifestPath))
|
|
if (manifest.name === undefined || manifest.name === '') {
|
|
throw new Error(`${manifestPath}: package invariant owner must declare a package name`)
|
|
}
|
|
const dir = dirname(manifestPath)
|
|
return {
|
|
dir,
|
|
manifestPath,
|
|
sourcePath: `${dir}/src/invariant.ts`,
|
|
packageName: manifest.name,
|
|
}
|
|
})
|
|
}
|
|
|
|
/** Return all violations of the package-invariant companion contract. */
|
|
export function collectPackageInvariantViolations(root: string): PackageInvariantViolation[] {
|
|
const violations: PackageInvariantViolation[] = []
|
|
const observedPluginNames = new Map<string, PackageInvariantOwner>()
|
|
for (const owner of packageInvariantOwners(root)) {
|
|
const manifest = readManifest(resolve(root, owner.manifestPath))
|
|
checkManifest(owner, manifest, violations)
|
|
checkBuild(owner, root, violations)
|
|
for (const pluginName of checkSource(owner, root, violations)) {
|
|
const existing = observedPluginNames.get(pluginName)
|
|
if (existing === undefined) {
|
|
observedPluginNames.set(pluginName, owner)
|
|
} else {
|
|
addViolation(
|
|
violations,
|
|
owner.sourcePath,
|
|
`name-based plugin invariant ${JSON.stringify(pluginName)} is already owned by ${JSON.stringify(existing.packageName)}`,
|
|
)
|
|
}
|
|
}
|
|
}
|
|
return violations
|
|
}
|
|
|
|
function readManifest(path: string): PackageManifest {
|
|
return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
|
|
}
|
|
|
|
function addViolation(
|
|
violations: PackageInvariantViolation[],
|
|
path: string,
|
|
message: string,
|
|
): void {
|
|
violations.push({ path, message })
|
|
}
|
|
|
|
function checkManifest(
|
|
owner: PackageInvariantOwner,
|
|
manifest: PackageManifest,
|
|
violations: PackageInvariantViolation[],
|
|
): void {
|
|
const invariantExport = manifest.exports?.['./invariant']
|
|
if (typeof invariantExport !== 'object'
|
|
|| invariantExport.types !== './lib/types/invariant.d.ts'
|
|
|| invariantExport.default !== './lib/invariant.js') {
|
|
addViolation(
|
|
violations,
|
|
owner.manifestPath,
|
|
'exports["./invariant"] must target ./lib/types/invariant.d.ts and ./lib/invariant.js',
|
|
)
|
|
}
|
|
if (!manifest.files?.includes('lib/invariant.js')) {
|
|
addViolation(violations, owner.manifestPath, 'files must publish lib/invariant.js')
|
|
}
|
|
if (owner.packageName === '@deepseek-ai/dsh-invariants') return
|
|
if (manifest.peerDependencies?.['@deepseek-ai/dsh-invariants'] !== '^0.0.1') {
|
|
addViolation(
|
|
violations,
|
|
owner.manifestPath,
|
|
'@deepseek-ai/dsh-invariants must be a ^0.0.1 peerDependency',
|
|
)
|
|
}
|
|
if (manifest.devDependencies?.['@deepseek-ai/dsh-invariants'] !== 'workspace:^') {
|
|
addViolation(
|
|
violations,
|
|
owner.manifestPath,
|
|
'@deepseek-ai/dsh-invariants must also be a workspace:^ devDependency',
|
|
)
|
|
}
|
|
}
|
|
|
|
function checkBuild(
|
|
owner: PackageInvariantOwner,
|
|
root: string,
|
|
violations: PackageInvariantViolation[],
|
|
): void {
|
|
const tsconfigPath = `${owner.dir}/tsconfig.json`
|
|
const tsconfig = JSON.parse(readFileSync(resolve(root, tsconfigPath), 'utf8')) as {
|
|
references?: Array<{ path?: string }>
|
|
}
|
|
if (owner.packageName !== '@deepseek-ai/dsh-invariants'
|
|
&& !tsconfig.references?.some(reference => reference.path === '../../support/invariants')) {
|
|
addViolation(
|
|
violations,
|
|
tsconfigPath,
|
|
'TypeScript project references must include ../../support/invariants',
|
|
)
|
|
}
|
|
|
|
const configPath = `${owner.dir}/tsdown.config.ts`
|
|
if (!existsSync(resolve(root, configPath))) return
|
|
const source = readFileSync(resolve(root, configPath), 'utf8')
|
|
if (!source.includes('lib/types/invariant.js')) {
|
|
addViolation(violations, configPath, 'package build override must bundle lib/types/invariant.js')
|
|
}
|
|
}
|
|
|
|
function checkSource(
|
|
owner: PackageInvariantOwner,
|
|
root: string,
|
|
violations: PackageInvariantViolation[],
|
|
): string[] {
|
|
const absolutePath = resolve(root, owner.sourcePath)
|
|
if (!existsSync(absolutePath)) {
|
|
addViolation(violations, owner.sourcePath, 'missing package-owned invariant companion')
|
|
return []
|
|
}
|
|
const sourceText = readFileSync(absolutePath, 'utf8')
|
|
if (sourceText.includes('@generated')) {
|
|
addViolation(
|
|
violations,
|
|
owner.sourcePath,
|
|
'invariant companions must be hand-owned and may not carry @generated markers',
|
|
)
|
|
}
|
|
|
|
const sourceFile = ts.createSourceFile(
|
|
absolutePath,
|
|
sourceText,
|
|
ts.ScriptTarget.Latest,
|
|
true,
|
|
ts.ScriptKind.TS,
|
|
)
|
|
const constants = topLevelStringConstants(sourceFile)
|
|
const registrations: string[] = []
|
|
const unresolved: number[] = []
|
|
const visit = (node: ts.Node): void => {
|
|
if (ts.isCallExpression(node) && isInvariantRegistration(node.expression)) {
|
|
const argument = node.arguments[0]
|
|
const packageName = argument === undefined ? undefined : stringValue(argument, constants)
|
|
if (packageName === undefined) unresolved.push(sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1)
|
|
else registrations.push(packageName)
|
|
}
|
|
ts.forEachChild(node, visit)
|
|
}
|
|
visit(sourceFile)
|
|
|
|
for (const line of unresolved) {
|
|
addViolation(
|
|
violations,
|
|
owner.sourcePath,
|
|
`line ${line}: ctx.invariants.register package name must resolve to a local string constant`,
|
|
)
|
|
}
|
|
if (registrations.length !== 1 || registrations[0] !== owner.packageName) {
|
|
addViolation(
|
|
violations,
|
|
owner.sourcePath,
|
|
`must register exactly its own package name ${JSON.stringify(owner.packageName)}; saw ${JSON.stringify(registrations)}`,
|
|
)
|
|
}
|
|
for (const exportedName of ['name', 'inject', 'apply']) {
|
|
if (!hasNamedExport(sourceFile, exportedName)) {
|
|
addViolation(violations, owner.sourcePath, `must named-export ${exportedName}`)
|
|
}
|
|
}
|
|
checkInstaller(owner, sourceFile, violations)
|
|
return nameOnlyObservedPlugins(sourceFile)
|
|
}
|
|
|
|
function nameOnlyObservedPlugins(sourceFile: ts.SourceFile): string[] {
|
|
const names: string[] = []
|
|
const visit = (node: ts.Node): void => {
|
|
if (ts.isCallExpression(node)
|
|
&& ts.isIdentifier(node.expression)
|
|
&& node.expression.text === 'observePluginInvariant') {
|
|
const contract = node.arguments[2]
|
|
if (contract !== undefined && ts.isObjectLiteralExpression(contract)) {
|
|
let hasExactPlugin = false
|
|
let name: string | undefined
|
|
for (const property of contract.properties) {
|
|
if (!ts.isPropertyAssignment(property)) continue
|
|
const key = ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)
|
|
? property.name.text
|
|
: undefined
|
|
if (key === 'plugin') hasExactPlugin = true
|
|
if (key === 'name') name = stringValue(property.initializer, new Map())
|
|
}
|
|
if (!hasExactPlugin && name !== undefined) names.push(name)
|
|
}
|
|
}
|
|
ts.forEachChild(node, visit)
|
|
}
|
|
visit(sourceFile)
|
|
return names
|
|
}
|
|
|
|
function checkInstaller(
|
|
owner: PackageInvariantOwner,
|
|
sourceFile: ts.SourceFile,
|
|
violations: PackageInvariantViolation[],
|
|
): void {
|
|
let initializer: ts.Expression | undefined
|
|
for (const statement of sourceFile.statements) {
|
|
if (!ts.isVariableStatement(statement)) continue
|
|
for (const declaration of statement.declarationList.declarations) {
|
|
if (ts.isIdentifier(declaration.name)
|
|
&& declaration.name.text === 'install'
|
|
&& declaration.initializer !== undefined) initializer = declaration.initializer
|
|
}
|
|
}
|
|
const installer = initializer === undefined ? undefined : installerFunction(initializer)
|
|
if (installer === undefined) {
|
|
addViolation(violations, owner.sourcePath, 'must declare a local install function for package-owned checks')
|
|
return
|
|
}
|
|
if (ts.isBlock(installer.body) && installer.body.statements.length === 0) {
|
|
addViolation(violations, owner.sourcePath, 'install function must contain a package-owned invariant check')
|
|
}
|
|
const reporter = installer.parameters[1]?.name
|
|
if (reporter === undefined || !ts.isIdentifier(reporter)) {
|
|
addViolation(violations, owner.sourcePath, 'install function must accept the bound failure reporter as its second parameter')
|
|
return
|
|
}
|
|
if (!usesIdentifier(installer.body, reporter.text)) {
|
|
addViolation(violations, owner.sourcePath, 'install function must use its bound failure reporter')
|
|
}
|
|
}
|
|
|
|
function usesIdentifier(node: ts.Node, name: string): boolean {
|
|
return ts.isIdentifier(node) && node.text === name
|
|
|| node.getChildren().some(child => usesIdentifier(child, name))
|
|
}
|
|
|
|
function installerFunction(
|
|
initializer: ts.Expression,
|
|
): ts.ArrowFunction | ts.FunctionExpression | undefined {
|
|
if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) return initializer
|
|
if (ts.isCallExpression(initializer)
|
|
&& ts.isPropertyAccessExpression(initializer.expression)
|
|
&& ts.isIdentifier(initializer.expression.expression)
|
|
&& initializer.expression.expression.text === 'Object'
|
|
&& initializer.expression.name.text === 'assign') {
|
|
const target = initializer.arguments[0]
|
|
if (target !== undefined && (ts.isArrowFunction(target) || ts.isFunctionExpression(target))) return target
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
function topLevelStringConstants(sourceFile: ts.SourceFile): ReadonlyMap<string, string> {
|
|
const constants = new Map<string, string>()
|
|
for (const statement of sourceFile.statements) {
|
|
if (!ts.isVariableStatement(statement)) continue
|
|
for (const declaration of statement.declarationList.declarations) {
|
|
if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
|
|
const value = stringValue(declaration.initializer, constants)
|
|
if (value !== undefined) constants.set(declaration.name.text, value)
|
|
}
|
|
}
|
|
return constants
|
|
}
|
|
|
|
function stringValue(node: ts.Expression, constants: ReadonlyMap<string, string>): string | undefined {
|
|
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text
|
|
if (ts.isIdentifier(node)) return constants.get(node.text)
|
|
return undefined
|
|
}
|
|
|
|
function isInvariantRegistration(expression: ts.LeftHandSideExpression): boolean {
|
|
return ts.isPropertyAccessExpression(expression)
|
|
&& expression.name.text === 'register'
|
|
&& ts.isPropertyAccessExpression(expression.expression)
|
|
&& expression.expression.name.text === 'invariants'
|
|
}
|
|
|
|
function hasNamedExport(sourceFile: ts.SourceFile, name: string): boolean {
|
|
return sourceFile.statements.some((statement) => {
|
|
if (!ts.isVariableStatement(statement)
|
|
|| !statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) return false
|
|
return statement.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === name)
|
|
})
|
|
}
|
|
|
|
/** Format violations for the command-line gate. */
|
|
export function formatPackageInvariantViolation(
|
|
root: string,
|
|
violation: PackageInvariantViolation,
|
|
): string {
|
|
const path = resolve(root, violation.path)
|
|
return `${relative(root, path)}: ${violation.message}`
|
|
}
|