check-workspace-constraints.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /**
  2. * Workspace package invariant checks for package-manager-independent quality
  3. * gates.
  4. *
  5. * Run: `tsx scripts/check-workspace-constraints.ts`.
  6. */
  7. import { existsSync, readdirSync, readFileSync } from 'node:fs'
  8. import { join, relative, resolve } from 'node:path'
  9. const root = resolve(import.meta.dirname, '..')
  10. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  11. // (the group dirs — core/llm/bash/… — are pure containers with no manifest).
  12. const workspaceGlobs = [
  13. { dir: 'vendor', depth: 1 },
  14. { dir: 'packages', depth: 2 },
  15. ] as const
  16. const vendoredPackages = new Set([
  17. 'cordis',
  18. 'cosmokit',
  19. 'schemastery',
  20. '@cordisjs/plugin-loader',
  21. '@cordisjs/plugin-include',
  22. '@cordisjs/plugin-group',
  23. '@cordisjs/plugin-timer',
  24. '@cordisjs/plugin-hmr',
  25. '@cordisjs/plugin-logger-console',
  26. ])
  27. /** The subset of package.json fields this constraint check cares about. */
  28. interface PackageManifest {
  29. name?: string
  30. version?: string
  31. private?: boolean
  32. type?: string
  33. main?: string
  34. types?: string
  35. bin?: string | Record<string, string>
  36. exports?: Record<
  37. string,
  38. | {
  39. types?: string
  40. default?: string
  41. }
  42. | undefined
  43. >
  44. files?: string[]
  45. peerDependencies?: Record<string, string>
  46. devDependencies?: Record<string, string>
  47. }
  48. /** One workspace manifest and its repo-relative path. */
  49. interface WorkspaceManifest {
  50. dir: string
  51. manifest: PackageManifest
  52. }
  53. function readJson(path: string): PackageManifest {
  54. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  55. }
  56. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  57. function packageDirs(base: string, depth: number): string[] {
  58. if (depth === 1) {
  59. return readdirSync(join(root, base), { withFileTypes: true })
  60. .filter(entry => entry.isDirectory())
  61. .map(entry => join(base, entry.name))
  62. }
  63. return readdirSync(join(root, base), { withFileTypes: true })
  64. .filter(entry => entry.isDirectory())
  65. .flatMap(group => packageDirs(join(base, group.name), depth - 1))
  66. }
  67. function workspaceManifests(): WorkspaceManifest[] {
  68. const manifests: WorkspaceManifest[] = [
  69. { dir: '.', manifest: readJson(join(root, 'package.json')) },
  70. ]
  71. for (const { dir: base, depth } of workspaceGlobs) {
  72. for (const dir of packageDirs(base, depth)) {
  73. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  74. }
  75. }
  76. return manifests
  77. }
  78. const dshPackageFiles = [
  79. 'lib/index.js',
  80. 'lib/types/**/*.d.ts',
  81. 'lib/types/**/*.d.ts.map',
  82. 'src',
  83. ] as const
  84. const dshBinPackageFiles = [
  85. 'lib/index.js',
  86. 'lib/bin.js',
  87. 'lib/types/**/*.d.ts',
  88. 'lib/types/**/*.d.ts.map',
  89. 'src',
  90. ] as const
  91. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  92. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  93. }
  94. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  95. return manifest.bin ? dshBinPackageFiles : dshPackageFiles
  96. }
  97. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  98. const errors: string[] = []
  99. const label = manifest.name ?? dir
  100. if (manifest.private !== true) {
  101. errors.push(`${label}: package.json must set "private": true`)
  102. }
  103. if (manifest.name && vendoredPackages.has(manifest.name)) {
  104. return errors
  105. }
  106. if (manifest.name?.startsWith('@deepseek-ai/dsh-') && manifest.name !== '@deepseek-ai/dsh-root') {
  107. const peer = manifest.peerDependencies?.cordis
  108. const dev = manifest.devDependencies?.cordis
  109. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  110. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  111. if (peer && dev && peer !== dev) {
  112. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  113. }
  114. if (manifest.version !== '0.0.1') {
  115. errors.push(`${label}: package.json must set "version": "0.0.1"`)
  116. }
  117. if (manifest.type !== 'module') {
  118. errors.push(`${label}: package.json must set "type": "module"`)
  119. }
  120. if (manifest.main !== 'lib/index.js') {
  121. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  122. }
  123. if (manifest.types !== 'lib/types/index.d.ts') {
  124. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  125. }
  126. if (manifest.exports?.['.']?.types !== './lib/types/index.d.ts') {
  127. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  128. }
  129. if (manifest.exports?.['.']?.default !== './lib/index.js') {
  130. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  131. }
  132. const expectedFiles = expectedDshPackageFiles(manifest)
  133. if (!sameStringList(manifest.files, expectedFiles)) {
  134. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  135. }
  136. }
  137. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  138. }
  139. /**
  140. * Enforce the packages/ hierarchy SHAPE: every package lives at exactly
  141. * `packages/<group>/<pkg>`. A group dir is a pure container — it holds packages,
  142. * never sources of its own — so it must NOT carry a package.json, and a package
  143. * must NOT sit directly at the `packages/` root (the old flat layout) nor nest a
  144. * level deeper. The group NAMES are open on purpose: a new group may be added
  145. * without touching this gate, but the depth-2 shape is fixed. This is what keeps
  146. * a stray flat package or an over-nested one from regressing the hierarchy.
  147. */
  148. function checkHierarchyShape(): string[] {
  149. const errors: string[] = []
  150. const packagesRoot = join(root, 'packages')
  151. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  152. if (!group.isDirectory()) continue
  153. const groupRel = join('packages', group.name)
  154. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  155. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  156. continue
  157. }
  158. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  159. if (!pkg.isDirectory()) continue
  160. const pkgRel = join(groupRel, pkg.name)
  161. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  162. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  163. }
  164. }
  165. }
  166. return errors
  167. }
  168. const errors = [...workspaceManifests().flatMap(checkWorkspace), ...checkHierarchyShape()]
  169. if (errors.length > 0) {
  170. console.error(errors.join('\n'))
  171. process.exitCode = 1
  172. }