check-workspace-constraints.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. const localArtifactDirs = new Set(['node_modules'])
  28. /** The subset of package.json fields this constraint check cares about. */
  29. interface PackageManifest {
  30. name?: string
  31. version?: string
  32. private?: boolean
  33. type?: string
  34. main?: string
  35. types?: string
  36. bin?: string | Record<string, string>
  37. exports?: Record<
  38. string,
  39. | string
  40. | {
  41. types?: string
  42. default?: string
  43. }
  44. | null
  45. | undefined
  46. >
  47. files?: string[]
  48. peerDependencies?: Record<string, string>
  49. devDependencies?: Record<string, string>
  50. }
  51. /** One workspace manifest and its repo-relative path. */
  52. interface WorkspaceManifest {
  53. dir: string
  54. manifest: PackageManifest
  55. }
  56. function readJson(path: string): PackageManifest {
  57. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  58. }
  59. const rootManifest = readJson(join(root, 'package.json'))
  60. const repositoryVersion = rootManifest.version
  61. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  62. function packageDirs(base: string, depth: number): string[] {
  63. if (depth === 1) {
  64. return readdirSync(join(root, base), { withFileTypes: true })
  65. .filter(entry => entry.isDirectory())
  66. .filter(entry => !localArtifactDirs.has(entry.name))
  67. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  68. .map(entry => join(base, entry.name))
  69. }
  70. return readdirSync(join(root, base), { withFileTypes: true })
  71. .filter(entry => entry.isDirectory())
  72. .filter(entry => !localArtifactDirs.has(entry.name))
  73. .flatMap(group => packageDirs(join(base, group.name), depth - 1))
  74. }
  75. function workspaceManifests(): WorkspaceManifest[] {
  76. const manifests: WorkspaceManifest[] = [
  77. { dir: '.', manifest: rootManifest },
  78. ]
  79. for (const { dir: base, depth } of workspaceGlobs) {
  80. for (const dir of packageDirs(base, depth)) {
  81. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  82. }
  83. }
  84. return manifests
  85. }
  86. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  87. '@deepseek-ai/dsh-helper': ['lib/assets'],
  88. '@deepseek-ai/dsh-tui': ['lib/prompt.js'],
  89. '@deepseek-ai/dsh-scripts': [
  90. 'lib/dev/tsdown-config.js',
  91. 'lib/local-plugin-loader-hooks.js',
  92. 'lib/assets',
  93. ],
  94. }
  95. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  96. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  97. }
  98. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  99. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  100. return [
  101. 'lib/index.js',
  102. // Every package publishes its invariant ownership companion as a separate
  103. // bundle; the package-invariant gate validates the companion itself.
  104. 'lib/invariant.js',
  105. ...manifest.bin ? ['lib/bin.js'] : [],
  106. ...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
  107. // UI plugin packages ship their browser bundle beside the node lib
  108. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  109. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  110. // a browser-safe source channel, not a bundle.
  111. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  112. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  113. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  114. // web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
  115. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  116. ...extras,
  117. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  118. // browser-safe source channels rehomed off src so plain Node can import
  119. // them without type stripping) publish the emitted JS alongside the
  120. // declarations.
  121. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  122. 'lib/types/**/*.d.ts',
  123. 'lib/types/**/*.d.ts.map',
  124. 'src',
  125. ]
  126. }
  127. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  128. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  129. const entry = manifest.exports?.[subpath]
  130. if (typeof entry === 'string') return entry
  131. if (typeof entry === 'object' && entry !== null) return entry.default
  132. return undefined
  133. }
  134. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  135. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  136. return Object.keys(manifest.exports ?? {}).some(subpath =>
  137. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  138. }
  139. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  140. const errors: string[] = []
  141. const label = manifest.name ?? dir
  142. if (manifest.private !== true) {
  143. errors.push(`${label}: package.json must set "private": true`)
  144. }
  145. if (manifest.name && vendoredPackages.has(manifest.name)) {
  146. return errors
  147. }
  148. if (manifest.name?.startsWith('@deepseek-ai/dsh-') && manifest.name !== '@deepseek-ai/dsh-root') {
  149. const peer = manifest.peerDependencies?.cordis
  150. const dev = manifest.devDependencies?.cordis
  151. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  152. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  153. if (peer && dev && peer !== dev) {
  154. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  155. }
  156. if (manifest.version !== repositoryVersion) {
  157. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  158. }
  159. if (manifest.type !== 'module') {
  160. errors.push(`${label}: package.json must set "type": "module"`)
  161. }
  162. if (manifest.main !== 'lib/index.js') {
  163. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  164. }
  165. if (manifest.types !== 'lib/types/index.d.ts') {
  166. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  167. }
  168. const rootExport = manifest.exports?.['.']
  169. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  170. if (rootEntry?.types !== './lib/types/index.d.ts') {
  171. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  172. }
  173. if (rootEntry?.default !== './lib/index.js') {
  174. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  175. }
  176. const invariantRaw = manifest.exports?.['./invariant']
  177. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  178. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  179. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  180. }
  181. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  182. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  183. }
  184. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  185. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  186. }
  187. const expectedFiles = expectedDshPackageFiles(manifest)
  188. if (!sameStringList(manifest.files, expectedFiles)) {
  189. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  190. }
  191. }
  192. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  193. }
  194. /**
  195. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  196. * package.json, and packages may be neither flat nor more deeply nested.
  197. */
  198. function checkHierarchyShape(): string[] {
  199. const errors: string[] = []
  200. const packagesRoot = join(root, 'packages')
  201. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  202. if (!group.isDirectory()) continue
  203. const groupRel = join('packages', group.name)
  204. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  205. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  206. continue
  207. }
  208. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  209. if (!pkg.isDirectory()) continue
  210. if (localArtifactDirs.has(pkg.name)) continue
  211. const pkgRel = join(groupRel, pkg.name)
  212. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  213. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  214. }
  215. }
  216. }
  217. return errors
  218. }
  219. function checkRepositoryVersion(): string[] {
  220. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  221. return ['package.json: version must be stable X.Y.Z']
  222. }
  223. const errors = [
  224. ...checkRepositoryVersion(),
  225. ...workspaceManifests().flatMap(checkWorkspace),
  226. ...checkHierarchyShape(),
  227. ]
  228. if (errors.length > 0) {
  229. console.error(errors.join('\n'))
  230. process.exitCode = 1
  231. }