package-invariants.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * Package-invariant companion discovery and structural checks.
  3. * The runtime registry stays product-independent; this gate makes ownership
  4. * exhaustive across packages without centralizing package checks.
  5. */
  6. import { existsSync, globSync, readFileSync } from 'node:fs'
  7. import { dirname, relative, resolve, sep } from 'node:path'
  8. import ts from 'typescript'
  9. /** Required explanation marker for an intentionally empty installer. */
  10. const NO_RUNTIME_INVARIANT_MARKER = 'No runtime invariant:'
  11. interface PackageManifest {
  12. name?: string
  13. exports?: Record<string, { types?: string; default?: string } | string | undefined>
  14. files?: string[]
  15. peerDependencies?: Record<string, string>
  16. devDependencies?: Record<string, string>
  17. }
  18. /** One package and the files participating in its invariant publication contract. */
  19. export interface PackageInvariantOwner {
  20. readonly dir: string
  21. readonly manifestPath: string
  22. readonly sourcePath: string
  23. readonly packageName: string
  24. }
  25. /** One gate violation with a repo-relative owner path. */
  26. export interface PackageInvariantViolation {
  27. readonly path: string
  28. readonly message: string
  29. }
  30. /** Discover every package under the repository package tree. */
  31. export function packageInvariantOwners(root: string): PackageInvariantOwner[] {
  32. return globSync('packages/*/*/package.json', { cwd: root })
  33. .map(path => path.split(sep).join('/'))
  34. .sort()
  35. .map((manifestPath) => {
  36. const manifest = readManifest(resolve(root, manifestPath))
  37. if (manifest.name === undefined || manifest.name === '') {
  38. throw new Error(`${manifestPath}: package invariant owner must declare a package name`)
  39. }
  40. const dir = dirname(manifestPath)
  41. return {
  42. dir,
  43. manifestPath,
  44. sourcePath: `${dir}/src/invariant.ts`,
  45. packageName: manifest.name,
  46. }
  47. })
  48. }
  49. /** Return all violations of the package-invariant companion contract. */
  50. export function collectPackageInvariantViolations(root: string): PackageInvariantViolation[] {
  51. const violations: PackageInvariantViolation[] = []
  52. for (const owner of packageInvariantOwners(root)) {
  53. const manifest = readManifest(resolve(root, owner.manifestPath))
  54. checkManifest(owner, manifest, violations)
  55. checkBuild(owner, root, violations)
  56. checkSource(owner, root, violations)
  57. }
  58. return violations
  59. }
  60. function readManifest(path: string): PackageManifest {
  61. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  62. }
  63. function addViolation(
  64. violations: PackageInvariantViolation[],
  65. path: string,
  66. message: string,
  67. ): void {
  68. violations.push({ path, message })
  69. }
  70. function checkManifest(
  71. owner: PackageInvariantOwner,
  72. manifest: PackageManifest,
  73. violations: PackageInvariantViolation[],
  74. ): void {
  75. const invariantExport = manifest.exports?.['./invariant']
  76. if (typeof invariantExport !== 'object'
  77. || invariantExport.types !== './lib/types/invariant.d.ts'
  78. || invariantExport.default !== './lib/invariant.js') {
  79. addViolation(
  80. violations,
  81. owner.manifestPath,
  82. 'exports["./invariant"] must target ./lib/types/invariant.d.ts and ./lib/invariant.js',
  83. )
  84. }
  85. if (!manifest.files?.includes('lib/invariant.js')) {
  86. addViolation(violations, owner.manifestPath, 'files must publish lib/invariant.js')
  87. }
  88. if (owner.packageName === '@deepseek-ai/dsh-invariants') return
  89. if (manifest.peerDependencies?.['@deepseek-ai/dsh-invariants'] !== '^0.0.1') {
  90. addViolation(
  91. violations,
  92. owner.manifestPath,
  93. '@deepseek-ai/dsh-invariants must be a ^0.0.1 peerDependency',
  94. )
  95. }
  96. if (manifest.devDependencies?.['@deepseek-ai/dsh-invariants'] !== 'workspace:^') {
  97. addViolation(
  98. violations,
  99. owner.manifestPath,
  100. '@deepseek-ai/dsh-invariants must also be a workspace:^ devDependency',
  101. )
  102. }
  103. }
  104. function checkBuild(
  105. owner: PackageInvariantOwner,
  106. root: string,
  107. violations: PackageInvariantViolation[],
  108. ): void {
  109. const tsconfigPath = `${owner.dir}/tsconfig.json`
  110. const tsconfig = JSON.parse(readFileSync(resolve(root, tsconfigPath), 'utf8')) as {
  111. references?: Array<{ path?: string }>
  112. }
  113. if (owner.packageName !== '@deepseek-ai/dsh-invariants'
  114. && !tsconfig.references?.some(reference => reference.path === '../../support/invariants')) {
  115. addViolation(
  116. violations,
  117. tsconfigPath,
  118. 'TypeScript project references must include ../../support/invariants',
  119. )
  120. }
  121. const configPath = `${owner.dir}/tsdown.config.ts`
  122. if (!existsSync(resolve(root, configPath))) return
  123. const source = readFileSync(resolve(root, configPath), 'utf8')
  124. if (!source.includes('lib/types/invariant.js')) {
  125. addViolation(violations, configPath, 'package build override must bundle lib/types/invariant.js')
  126. }
  127. }
  128. function checkSource(
  129. owner: PackageInvariantOwner,
  130. root: string,
  131. violations: PackageInvariantViolation[],
  132. ): void {
  133. const absolutePath = resolve(root, owner.sourcePath)
  134. if (!existsSync(absolutePath)) {
  135. addViolation(violations, owner.sourcePath, 'missing package-owned invariant companion')
  136. return
  137. }
  138. const sourceText = readFileSync(absolutePath, 'utf8')
  139. if (sourceText.includes('@generated')) {
  140. addViolation(
  141. violations,
  142. owner.sourcePath,
  143. 'invariant companions must be hand-owned and may not carry @generated markers',
  144. )
  145. }
  146. const sourceFile = ts.createSourceFile(
  147. absolutePath,
  148. sourceText,
  149. ts.ScriptTarget.Latest,
  150. true,
  151. ts.ScriptKind.TS,
  152. )
  153. const constants = topLevelStringConstants(sourceFile)
  154. const registrations: string[] = []
  155. const unresolved: number[] = []
  156. const visit = (node: ts.Node): void => {
  157. if (ts.isCallExpression(node) && isInvariantRegistration(node.expression)) {
  158. const argument = node.arguments[0]
  159. const packageName = argument === undefined ? undefined : stringValue(argument, constants)
  160. if (packageName === undefined) unresolved.push(sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1)
  161. else registrations.push(packageName)
  162. }
  163. ts.forEachChild(node, visit)
  164. }
  165. visit(sourceFile)
  166. for (const line of unresolved) {
  167. addViolation(
  168. violations,
  169. owner.sourcePath,
  170. `line ${line}: ctx.invariants.register package name must resolve to a local string constant`,
  171. )
  172. }
  173. if (registrations.length !== 1 || registrations[0] !== owner.packageName) {
  174. addViolation(
  175. violations,
  176. owner.sourcePath,
  177. `must register exactly its own package name ${JSON.stringify(owner.packageName)}; saw ${JSON.stringify(registrations)}`,
  178. )
  179. }
  180. for (const exportedName of ['name', 'inject', 'apply']) {
  181. if (!hasNamedExport(sourceFile, exportedName)) {
  182. addViolation(violations, owner.sourcePath, `must named-export ${exportedName}`)
  183. }
  184. }
  185. checkInstaller(owner, sourceFile, sourceText, violations)
  186. }
  187. function checkInstaller(
  188. owner: PackageInvariantOwner,
  189. sourceFile: ts.SourceFile,
  190. sourceText: string,
  191. violations: PackageInvariantViolation[],
  192. ): void {
  193. let initializer: ts.Expression | undefined
  194. let declarationStatement: ts.VariableStatement | undefined
  195. for (const statement of sourceFile.statements) {
  196. if (!ts.isVariableStatement(statement)) continue
  197. for (const declaration of statement.declarationList.declarations) {
  198. if (ts.isIdentifier(declaration.name)
  199. && declaration.name.text === 'install'
  200. && declaration.initializer !== undefined) {
  201. initializer = declaration.initializer
  202. declarationStatement = statement
  203. }
  204. }
  205. }
  206. const installer = initializer === undefined ? undefined : installerFunction(initializer)
  207. if (installer === undefined) {
  208. addViolation(violations, owner.sourcePath, 'must declare a local install function for package-owned checks')
  209. return
  210. }
  211. if (ts.isBlock(installer.body) && installer.body.statements.length === 0) {
  212. const declarationText = declarationStatement === undefined
  213. ? ''
  214. : sourceText.slice(declarationStatement.getFullStart(), declarationStatement.getEnd())
  215. if (!declarationText.includes(NO_RUNTIME_INVARIANT_MARKER)) {
  216. addViolation(
  217. violations,
  218. owner.sourcePath,
  219. `empty install function must explain why with a "${NO_RUNTIME_INVARIANT_MARKER}" comment`,
  220. )
  221. }
  222. return
  223. }
  224. const reporter = installer.parameters[1]?.name
  225. if (reporter === undefined || !ts.isIdentifier(reporter)) {
  226. addViolation(violations, owner.sourcePath, 'install function must accept the bound failure reporter as its second parameter')
  227. return
  228. }
  229. if (!usesIdentifier(installer.body, reporter.text)) {
  230. addViolation(violations, owner.sourcePath, 'install function must use its bound failure reporter')
  231. }
  232. }
  233. function usesIdentifier(node: ts.Node, name: string): boolean {
  234. return ts.isIdentifier(node) && node.text === name
  235. || node.getChildren().some(child => usesIdentifier(child, name))
  236. }
  237. function installerFunction(
  238. initializer: ts.Expression,
  239. ): ts.ArrowFunction | ts.FunctionExpression | undefined {
  240. if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) return initializer
  241. if (ts.isCallExpression(initializer)
  242. && ts.isPropertyAccessExpression(initializer.expression)
  243. && ts.isIdentifier(initializer.expression.expression)
  244. && initializer.expression.expression.text === 'Object'
  245. && initializer.expression.name.text === 'assign') {
  246. const target = initializer.arguments[0]
  247. if (target !== undefined && (ts.isArrowFunction(target) || ts.isFunctionExpression(target))) return target
  248. }
  249. return undefined
  250. }
  251. function topLevelStringConstants(sourceFile: ts.SourceFile): ReadonlyMap<string, string> {
  252. const constants = new Map<string, string>()
  253. for (const statement of sourceFile.statements) {
  254. if (!ts.isVariableStatement(statement)) continue
  255. for (const declaration of statement.declarationList.declarations) {
  256. if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
  257. const value = stringValue(declaration.initializer, constants)
  258. if (value !== undefined) constants.set(declaration.name.text, value)
  259. }
  260. }
  261. return constants
  262. }
  263. function stringValue(node: ts.Expression, constants: ReadonlyMap<string, string>): string | undefined {
  264. if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text
  265. if (ts.isIdentifier(node)) return constants.get(node.text)
  266. return undefined
  267. }
  268. function isInvariantRegistration(expression: ts.LeftHandSideExpression): boolean {
  269. return ts.isPropertyAccessExpression(expression)
  270. && expression.name.text === 'register'
  271. && ts.isPropertyAccessExpression(expression.expression)
  272. && expression.expression.name.text === 'invariants'
  273. }
  274. function hasNamedExport(sourceFile: ts.SourceFile, name: string): boolean {
  275. return sourceFile.statements.some((statement) => {
  276. if (!ts.isVariableStatement(statement)
  277. || !statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) return false
  278. return statement.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === name)
  279. })
  280. }
  281. /** Format violations for the command-line gate. */
  282. export function formatPackageInvariantViolation(
  283. root: string,
  284. violation: PackageInvariantViolation,
  285. ): string {
  286. const path = resolve(root, violation.path)
  287. return `${relative(root, path)}: ${violation.message}`
  288. }