package-invariants.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 rules. */
  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 rules. */
  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'] !== 'workspace:^') {
  90. addViolation(
  91. violations,
  92. owner.manifestPath,
  93. '@deepseek-ai/dsh-invariants must be a workspace:^ 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. if (owner.packageName !== '@deepseek-ai/dsh-invariants'
  111. && !projectReferencesInvariants(root, owner.dir, tsconfigPath)) {
  112. addViolation(
  113. violations,
  114. tsconfigPath,
  115. 'TypeScript project references must include ../../runtime-diagnostics/invariants',
  116. )
  117. }
  118. const configPath = `${owner.dir}/tsdown.config.ts`
  119. if (!existsSync(resolve(root, configPath))) return
  120. const source = readFileSync(resolve(root, configPath), 'utf8')
  121. if (!source.includes('lib/types/invariant.js')) {
  122. addViolation(violations, configPath, 'package build override must bundle lib/types/invariant.js')
  123. }
  124. }
  125. function projectReferencesInvariants(root: string, ownerDir: string, entryPath: string): boolean {
  126. const ownerRoot = resolve(root, ownerDir)
  127. const target = resolve(root, 'packages/runtime-diagnostics/invariants')
  128. const pending = [resolve(root, entryPath)]
  129. const visited = new Set<string>()
  130. while (pending.length > 0) {
  131. const configPath = pending.pop()
  132. if (configPath === undefined) break
  133. if (visited.has(configPath)) continue
  134. visited.add(configPath)
  135. const config = JSON.parse(readFileSync(configPath, 'utf8')) as {
  136. references?: Array<{ path?: string }>
  137. }
  138. for (const reference of config.references ?? []) {
  139. if (reference.path === undefined) continue
  140. const referenced = resolve(dirname(configPath), reference.path)
  141. if (referenced === target) return true
  142. if (!referenced.startsWith(`${ownerRoot}${sep}`)) continue
  143. const childConfig = referenced.endsWith('.json') ? referenced : resolve(referenced, 'tsconfig.json')
  144. if (existsSync(childConfig)) pending.push(childConfig)
  145. }
  146. }
  147. return false
  148. }
  149. function checkSource(
  150. owner: PackageInvariantOwner,
  151. root: string,
  152. violations: PackageInvariantViolation[],
  153. ): void {
  154. const absolutePath = resolve(root, owner.sourcePath)
  155. if (!existsSync(absolutePath)) {
  156. addViolation(violations, owner.sourcePath, 'missing package-owned invariant companion')
  157. return
  158. }
  159. const sourceText = readFileSync(absolutePath, 'utf8')
  160. if (sourceText.includes('@generated')) {
  161. addViolation(
  162. violations,
  163. owner.sourcePath,
  164. 'invariant companions must be hand-owned and may not carry @generated markers',
  165. )
  166. }
  167. const sourceFile = ts.createSourceFile(
  168. absolutePath,
  169. sourceText,
  170. ts.ScriptTarget.Latest,
  171. true,
  172. ts.ScriptKind.TS,
  173. )
  174. const constants = topLevelStringConstants(sourceFile)
  175. const registrations: string[] = []
  176. const unresolved: number[] = []
  177. const mismatchedInstallers: number[] = []
  178. const visit = (node: ts.Node): void => {
  179. if (ts.isCallExpression(node) && isInvariantRegistration(node.expression)) {
  180. const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1
  181. const argument = node.arguments[0]
  182. const packageName = argument === undefined ? undefined : stringValue(argument, constants)
  183. if (packageName === undefined) unresolved.push(line)
  184. else registrations.push(packageName)
  185. const installer = node.arguments[1]
  186. if (installer === undefined || !ts.isIdentifier(installer) || installer.text !== 'install') {
  187. mismatchedInstallers.push(line)
  188. }
  189. }
  190. ts.forEachChild(node, visit)
  191. }
  192. visit(sourceFile)
  193. for (const line of unresolved) {
  194. addViolation(
  195. violations,
  196. owner.sourcePath,
  197. `line ${line}: ctx.invariants.register package name must resolve to a local string constant`,
  198. )
  199. }
  200. for (const line of mismatchedInstallers) {
  201. addViolation(
  202. violations,
  203. owner.sourcePath,
  204. `line ${line}: ctx.invariants.register must use the checked local install function`,
  205. )
  206. }
  207. if (registrations.length !== 1 || registrations[0] !== owner.packageName) {
  208. addViolation(
  209. violations,
  210. owner.sourcePath,
  211. `must register exactly its own package name ${JSON.stringify(owner.packageName)}; saw ${JSON.stringify(registrations)}`,
  212. )
  213. }
  214. for (const exportedName of ['name', 'inject', 'apply']) {
  215. if (!hasNamedExport(sourceFile, exportedName)) {
  216. addViolation(violations, owner.sourcePath, `must named-export ${exportedName}`)
  217. }
  218. }
  219. if (hasDefaultExport(sourceFile)) {
  220. addViolation(violations, owner.sourcePath, 'must not default-export; Loader must retain the companion namespace')
  221. }
  222. checkInstaller(owner, sourceFile, sourceText, violations)
  223. }
  224. function checkInstaller(
  225. owner: PackageInvariantOwner,
  226. sourceFile: ts.SourceFile,
  227. sourceText: string,
  228. violations: PackageInvariantViolation[],
  229. ): void {
  230. let initializer: ts.Expression | undefined
  231. let declarationStatement: ts.VariableStatement | undefined
  232. for (const statement of sourceFile.statements) {
  233. if (!ts.isVariableStatement(statement)) continue
  234. for (const declaration of statement.declarationList.declarations) {
  235. if (ts.isIdentifier(declaration.name)
  236. && declaration.name.text === 'install'
  237. && declaration.initializer !== undefined) {
  238. initializer = declaration.initializer
  239. declarationStatement = statement
  240. }
  241. }
  242. }
  243. const installer = initializer === undefined ? undefined : installerFunction(initializer)
  244. if (installer === undefined) {
  245. addViolation(violations, owner.sourcePath, 'must declare a local install function for package-owned checks')
  246. return
  247. }
  248. if (ts.isBlock(installer.body) && installer.body.statements.length === 0) {
  249. const declarationText = declarationStatement === undefined
  250. ? ''
  251. : sourceText.slice(declarationStatement.getFullStart(), declarationStatement.getEnd())
  252. if (!declarationText.includes(NO_RUNTIME_INVARIANT_MARKER)) {
  253. addViolation(
  254. violations,
  255. owner.sourcePath,
  256. `empty install function must explain why with a "${NO_RUNTIME_INVARIANT_MARKER}" comment`,
  257. )
  258. }
  259. return
  260. }
  261. const reporter = installer.parameters[1]?.name
  262. if (reporter === undefined || !ts.isIdentifier(reporter)) {
  263. addViolation(violations, owner.sourcePath, 'install function must accept the bound failure reporter as its second parameter')
  264. return
  265. }
  266. if (!usesIdentifier(installer.body, reporter.text)) {
  267. addViolation(violations, owner.sourcePath, 'install function must use its bound failure reporter')
  268. }
  269. }
  270. function usesIdentifier(node: ts.Node, name: string): boolean {
  271. return ts.isIdentifier(node) && node.text === name
  272. || node.getChildren().some(child => usesIdentifier(child, name))
  273. }
  274. function installerFunction(
  275. initializer: ts.Expression,
  276. ): ts.ArrowFunction | ts.FunctionExpression | undefined {
  277. if (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer)) return initializer
  278. if (ts.isCallExpression(initializer)
  279. && ts.isPropertyAccessExpression(initializer.expression)
  280. && ts.isIdentifier(initializer.expression.expression)
  281. && initializer.expression.expression.text === 'Object'
  282. && initializer.expression.name.text === 'assign') {
  283. const target = initializer.arguments[0]
  284. if (target !== undefined && (ts.isArrowFunction(target) || ts.isFunctionExpression(target))) return target
  285. }
  286. return undefined
  287. }
  288. function topLevelStringConstants(sourceFile: ts.SourceFile): ReadonlyMap<string, string> {
  289. const constants = new Map<string, string>()
  290. for (const statement of sourceFile.statements) {
  291. if (!ts.isVariableStatement(statement)) continue
  292. for (const declaration of statement.declarationList.declarations) {
  293. if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
  294. const value = stringValue(declaration.initializer, constants)
  295. if (value !== undefined) constants.set(declaration.name.text, value)
  296. }
  297. }
  298. return constants
  299. }
  300. function stringValue(node: ts.Expression, constants: ReadonlyMap<string, string>): string | undefined {
  301. if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text
  302. if (ts.isIdentifier(node)) return constants.get(node.text)
  303. return undefined
  304. }
  305. function isInvariantRegistration(expression: ts.LeftHandSideExpression): boolean {
  306. return ts.isPropertyAccessExpression(expression)
  307. && expression.name.text === 'register'
  308. && ts.isPropertyAccessExpression(expression.expression)
  309. && expression.expression.name.text === 'invariants'
  310. }
  311. function hasNamedExport(sourceFile: ts.SourceFile, name: string): boolean {
  312. return sourceFile.statements.some((statement) => {
  313. if (!ts.isVariableStatement(statement)
  314. || !statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) return false
  315. return statement.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === name)
  316. })
  317. }
  318. function hasDefaultExport(sourceFile: ts.SourceFile): boolean {
  319. return sourceFile.statements.some((statement) => {
  320. if (ts.isExportAssignment(statement)) return true
  321. const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined
  322. if (modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword)) return true
  323. if (!ts.isExportDeclaration(statement) || statement.exportClause === undefined) return false
  324. if (ts.isNamespaceExport(statement.exportClause)) {
  325. return statement.exportClause.name.text === 'default'
  326. }
  327. return statement.exportClause.elements.some(element => element.name.text === 'default')
  328. })
  329. }
  330. /** Format violations for the command-line gate. */
  331. export function formatPackageInvariantViolation(
  332. root: string,
  333. violation: PackageInvariantViolation,
  334. ): string {
  335. const path = resolve(root, violation.path)
  336. return `${relative(root, path)}: ${violation.message}`
  337. }