check-workspace-constraints.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. import { hasTypeRTRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
  10. import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
  11. const root = resolve(import.meta.dirname, '..')
  12. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  13. // (the group dirs — core/llm/bash/… — are pure containers with no manifest).
  14. const workspaceGlobs = [
  15. { dir: 'vendor', depth: 1 },
  16. { dir: 'packages', depth: 2 },
  17. { dir: 'native', depth: 1 },
  18. { dir: 'native/landlock-run/packages', depth: 1 },
  19. { dir: 'apps', depth: 1 },
  20. ] as const
  21. const vendoredPackages = new Set([
  22. 'cordis',
  23. 'cosmokit',
  24. 'schemastery',
  25. '@cordisjs/plugin-loader',
  26. '@cordisjs/plugin-include',
  27. '@cordisjs/plugin-group',
  28. '@cordisjs/plugin-timer',
  29. '@cordisjs/plugin-hmr',
  30. '@cordisjs/plugin-logger-console',
  31. ])
  32. const publicLandlockPackages = new Set([
  33. '@deepseek-ai/node-addon-landlock-run',
  34. '@deepseek-ai/node-addon-landlock-run-linux-arm64',
  35. '@deepseek-ai/node-addon-landlock-run-linux-x64',
  36. ])
  37. /** Deliberate source payloads whose exact bytes are part of the package's audit surface. */
  38. const publicationSourceAllowlist: Readonly<Record<string, readonly string[]>> = {
  39. '@deepseek-ai/node-addon-landlock-run': ['src/main.c'],
  40. }
  41. const repositoryUrl = 'git+https://github.com/deepseek-harness/deepseek-harness.git'
  42. const localArtifactDirs = new Set(['node_modules'])
  43. const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
  44. '@deepseek-ai/dsh': ['lib/*.js', 'config'],
  45. '@deepseek-ai/dsh-frontend': ['dist'],
  46. }
  47. /** The subset of package.json fields this constraint check cares about. */
  48. interface PackageManifest {
  49. name?: string
  50. version?: string
  51. private?: boolean
  52. type?: string
  53. main?: string
  54. types?: string
  55. bin?: string | Record<string, string>
  56. exports?: Record<
  57. string,
  58. | string
  59. | {
  60. types?: string
  61. default?: string
  62. }
  63. | null
  64. | undefined
  65. >
  66. files?: string[]
  67. publishConfig?: { access?: string }
  68. repository?: { type?: string; url?: string; directory?: string }
  69. peerDependencies?: Record<string, string>
  70. devDependencies?: Record<string, string>
  71. }
  72. /** One workspace manifest and its repo-relative path. */
  73. interface WorkspaceManifest {
  74. dir: string
  75. manifest: PackageManifest
  76. }
  77. function readJson(path: string): PackageManifest {
  78. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  79. }
  80. const rootManifest = readJson(join(root, 'package.json'))
  81. const repositoryVersion = rootManifest.version
  82. const landlockWorkspaceManifest = readJson(join(root, 'native/landlock-run/package.json'))
  83. const landlockVersion = landlockWorkspaceManifest.version
  84. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  85. function packageDirs(base: string, depth: number): string[] {
  86. if (depth === 1) {
  87. return readdirSync(join(root, base), { withFileTypes: true })
  88. .filter(entry => entry.isDirectory())
  89. .filter(entry => !localArtifactDirs.has(entry.name))
  90. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  91. .map(entry => `${base}/${entry.name}`)
  92. }
  93. return readdirSync(join(root, base), { withFileTypes: true })
  94. .filter(entry => entry.isDirectory())
  95. .filter(entry => !localArtifactDirs.has(entry.name))
  96. .flatMap(group => packageDirs(`${base}/${group.name}`, depth - 1))
  97. }
  98. function workspaceManifests(): WorkspaceManifest[] {
  99. const manifests: WorkspaceManifest[] = [
  100. { dir: '.', manifest: rootManifest },
  101. ]
  102. for (const { dir: base, depth } of workspaceGlobs) {
  103. for (const dir of packageDirs(base, depth)) {
  104. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  105. }
  106. }
  107. return manifests
  108. }
  109. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  110. // Profile bundles publish their dsh.bundle.patch layer beside the lib.
  111. '@deepseek-ai/dsh-base': ['cordis.patch.yml'],
  112. '@deepseek-ai/dsh-web-app': ['cordis.patch.yml'],
  113. '@deepseek-ai/dsh-headless': ['cordis.patch.yml'],
  114. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  115. '@deepseek-ai/dsh-helper': ['lib/assets'],
  116. '@deepseek-ai/dsh-skill-badge': ['assets'],
  117. '@deepseek-ai/dsh-subprocess-local': ['scripts/ensure-spawn-helper.mjs'],
  118. '@deepseek-ai/dsh-scripts': [
  119. 'lib/dev/tsdown-config.js',
  120. 'lib/local-plugin-loader-hooks.js',
  121. 'lib/assets',
  122. ],
  123. }
  124. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  125. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  126. }
  127. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  128. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  129. const typeRTRemoteNavigation = hasTypeRTRemoteNavigation(manifest)
  130. return [
  131. 'lib/index.js',
  132. // Every package publishes its invariant ownership companion as a separate
  133. // bundle; the package-invariant gate validates the companion itself.
  134. 'lib/invariant.js',
  135. ...manifest.bin ? ['lib/bin.js'] : [],
  136. ...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
  137. // UI plugin packages ship their browser bundle beside the node lib
  138. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  139. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  140. // a browser-safe source channel, not a bundle.
  141. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  142. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  143. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  144. // web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
  145. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  146. ...extras,
  147. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  148. // browser-safe source channels rehomed off src so plain Node can import
  149. // them without type stripping) publish the emitted JS alongside the
  150. // declarations.
  151. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  152. 'lib/types/**/*.d.ts',
  153. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  154. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  155. : [],
  156. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  157. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  158. : [],
  159. ...typeRTRemoteNavigation
  160. ? [
  161. 'lib/typert.remote-client.js',
  162. 'lib/typert.remote-client.d.ts',
  163. 'lib/typert.remote-client.d.ts.map',
  164. 'src',
  165. ]
  166. : [],
  167. ]
  168. }
  169. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  170. function hasExportPair(
  171. manifest: PackageManifest,
  172. subpath: string,
  173. types: string,
  174. runtime: string,
  175. ): boolean {
  176. const entry = manifest.exports?.[subpath]
  177. return typeof entry === 'object'
  178. && entry !== null
  179. && entry.types === types
  180. && entry.default === runtime
  181. }
  182. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  183. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  184. const entry = manifest.exports?.[subpath]
  185. if (typeof entry === 'string') return entry
  186. if (typeof entry === 'object' && entry !== null) return entry.default
  187. return undefined
  188. }
  189. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  190. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  191. return Object.keys(manifest.exports ?? {}).some(subpath =>
  192. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  193. }
  194. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  195. const errors: string[] = []
  196. const label = manifest.name ?? dir
  197. const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/')
  198. const isPublicLandlockPackage = isLandlockPackageDir
  199. && manifest.name !== undefined
  200. && publicLandlockPackages.has(manifest.name)
  201. if (isPublicLandlockPackage) {
  202. if (manifest.private === true) {
  203. errors.push(`${label}: published Landlock package must not set "private": true`)
  204. }
  205. if (manifest.publishConfig?.access !== 'public') {
  206. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  207. }
  208. const expectedDirectory = dir
  209. if (manifest.repository?.type !== 'git'
  210. || manifest.repository.url !== repositoryUrl
  211. || manifest.repository.directory !== expectedDirectory) {
  212. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  213. }
  214. } else if (manifest.private !== true) {
  215. errors.push(`${label}: package.json must set "private": true`)
  216. }
  217. if (manifest.name && vendoredPackages.has(manifest.name)) {
  218. return errors
  219. }
  220. if (manifest.name?.startsWith('@deepseek-ai/')) {
  221. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  222. const publicationPolicy = { typeRTRemoteNavigation: hasTypeRTRemoteNavigation(manifest) }
  223. for (const file of manifest.files ?? []) {
  224. if (isForbiddenPublicationFile(file, publicationPolicy) && !allowedSources.includes(file)) {
  225. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  226. }
  227. }
  228. }
  229. if (dir.startsWith('apps/') && manifest.name?.startsWith('@deepseek-ai/')) {
  230. const expectedFiles = appPackageFiles[manifest.name]
  231. if (expectedFiles === undefined) {
  232. errors.push(`${label}: app package has no publication files policy`)
  233. } else if (!sameStringList(manifest.files, expectedFiles)) {
  234. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  235. }
  236. }
  237. if (isLandlockPackageDir) {
  238. if (!isPublicLandlockPackage) {
  239. errors.push(`${label}: unexpected package in the public Landlock package family`)
  240. }
  241. if (manifest.version !== landlockVersion) {
  242. errors.push(`${label}: package.json version must match Landlock workspace version ${landlockVersion ?? '(missing)'}`)
  243. }
  244. }
  245. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  246. const peer = manifest.peerDependencies?.cordis
  247. const dev = manifest.devDependencies?.cordis
  248. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  249. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  250. if (peer && dev && peer !== dev) {
  251. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  252. }
  253. if (manifest.version !== repositoryVersion) {
  254. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  255. }
  256. if (manifest.type !== 'module') {
  257. errors.push(`${label}: package.json must set "type": "module"`)
  258. }
  259. if (manifest.main !== 'lib/index.js') {
  260. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  261. }
  262. if (manifest.types !== 'lib/types/index.d.ts') {
  263. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  264. }
  265. const rootExport = manifest.exports?.['.']
  266. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  267. if (rootEntry?.types !== './lib/types/index.d.ts') {
  268. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  269. }
  270. if (rootEntry?.default !== './lib/index.js') {
  271. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  272. }
  273. const invariantRaw = manifest.exports?.['./invariant']
  274. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  275. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  276. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  277. }
  278. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  279. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  280. }
  281. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  282. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  283. }
  284. const expectedFiles = expectedDshPackageFiles(manifest)
  285. if (!sameStringList(manifest.files, expectedFiles)) {
  286. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  287. }
  288. }
  289. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  290. }
  291. /**
  292. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  293. * package.json, and packages may be neither flat nor more deeply nested.
  294. */
  295. function checkHierarchyShape(): string[] {
  296. const errors: string[] = []
  297. const packagesRoot = join(root, 'packages')
  298. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  299. if (!group.isDirectory()) continue
  300. const groupRel = join('packages', group.name)
  301. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  302. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  303. continue
  304. }
  305. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  306. if (!pkg.isDirectory()) continue
  307. if (localArtifactDirs.has(pkg.name)) continue
  308. const pkgRel = join(groupRel, pkg.name)
  309. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  310. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  311. }
  312. }
  313. }
  314. return errors
  315. }
  316. function checkRepositoryVersion(): string[] {
  317. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  318. return ['package.json: version must be stable X.Y.Z']
  319. }
  320. const errors = [
  321. ...checkRepositoryVersion(),
  322. ...workspaceManifests().flatMap(checkWorkspace),
  323. ...checkHierarchyShape(),
  324. ...collectProjectReferenceFaceViolations(root),
  325. ]
  326. if (errors.length > 0) {
  327. console.error(errors.join('\n'))
  328. process.exitCode = 1
  329. }