check-workspace-constraints.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. // dsh-base also ships the win32 shell platform layer the launcher reads.
  112. '@deepseek-ai/dsh-base': ['cordis.patch.yml', 'windows.cordis.patch.yml'],
  113. '@deepseek-ai/dsh-web-app': ['cordis.patch.yml'],
  114. '@deepseek-ai/dsh-headless': ['cordis.patch.yml'],
  115. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  116. '@deepseek-ai/dsh-helper': ['lib/assets'],
  117. // The argv-prefix runner entry ships beside the lib as its own bundle;
  118. // sandbox-local resolves it through the package's ./runner export.
  119. '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js'],
  120. '@deepseek-ai/dsh-skill-badge': ['assets'],
  121. '@deepseek-ai/dsh-subprocess-local': ['scripts/ensure-spawn-helper.mjs'],
  122. '@deepseek-ai/dsh-scripts': [
  123. 'lib/dev/tsdown-config.js',
  124. 'lib/local-plugin-loader-hooks.js',
  125. 'lib/assets',
  126. ],
  127. }
  128. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  129. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  130. }
  131. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  132. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  133. const typeRTRemoteNavigation = hasTypeRTRemoteNavigation(manifest)
  134. return [
  135. 'lib/index.js',
  136. // Every package publishes its invariant ownership companion as a separate
  137. // bundle; the package-invariant gate validates the companion itself.
  138. 'lib/invariant.js',
  139. ...manifest.bin ? ['lib/bin.js'] : [],
  140. ...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
  141. // UI plugin packages ship their browser bundle beside the node lib
  142. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  143. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  144. // a browser-safe source channel, not a bundle.
  145. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  146. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  147. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  148. // web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
  149. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  150. ...extras,
  151. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  152. // browser-safe source channels rehomed off src so plain Node can import
  153. // them without type stripping) publish the emitted JS alongside the
  154. // declarations.
  155. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  156. 'lib/types/**/*.d.ts',
  157. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  158. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  159. : [],
  160. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  161. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  162. : [],
  163. ...typeRTRemoteNavigation
  164. ? [
  165. 'lib/typert.remote-client.js',
  166. 'lib/typert.remote-client.d.ts',
  167. 'lib/typert.remote-client.d.ts.map',
  168. 'src',
  169. ]
  170. : [],
  171. ]
  172. }
  173. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  174. function hasExportPair(
  175. manifest: PackageManifest,
  176. subpath: string,
  177. types: string,
  178. runtime: string,
  179. ): boolean {
  180. const entry = manifest.exports?.[subpath]
  181. return typeof entry === 'object'
  182. && entry !== null
  183. && entry.types === types
  184. && entry.default === runtime
  185. }
  186. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  187. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  188. const entry = manifest.exports?.[subpath]
  189. if (typeof entry === 'string') return entry
  190. if (typeof entry === 'object' && entry !== null) return entry.default
  191. return undefined
  192. }
  193. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  194. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  195. return Object.keys(manifest.exports ?? {}).some(subpath =>
  196. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  197. }
  198. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  199. const errors: string[] = []
  200. const label = manifest.name ?? dir
  201. const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/')
  202. const isPublicLandlockPackage = isLandlockPackageDir
  203. && manifest.name !== undefined
  204. && publicLandlockPackages.has(manifest.name)
  205. if (isPublicLandlockPackage) {
  206. if (manifest.private === true) {
  207. errors.push(`${label}: published Landlock package must not set "private": true`)
  208. }
  209. if (manifest.publishConfig?.access !== 'public') {
  210. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  211. }
  212. const expectedDirectory = dir
  213. if (manifest.repository?.type !== 'git'
  214. || manifest.repository.url !== repositoryUrl
  215. || manifest.repository.directory !== expectedDirectory) {
  216. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  217. }
  218. } else if (manifest.private !== true) {
  219. errors.push(`${label}: package.json must set "private": true`)
  220. }
  221. if (manifest.name && vendoredPackages.has(manifest.name)) {
  222. return errors
  223. }
  224. if (manifest.name?.startsWith('@deepseek-ai/')) {
  225. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  226. const publicationPolicy = { typeRTRemoteNavigation: hasTypeRTRemoteNavigation(manifest) }
  227. for (const file of manifest.files ?? []) {
  228. if (isForbiddenPublicationFile(file, publicationPolicy) && !allowedSources.includes(file)) {
  229. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  230. }
  231. }
  232. }
  233. if (dir.startsWith('apps/') && manifest.name?.startsWith('@deepseek-ai/')) {
  234. const expectedFiles = appPackageFiles[manifest.name]
  235. if (expectedFiles === undefined) {
  236. errors.push(`${label}: app package has no publication files policy`)
  237. } else if (!sameStringList(manifest.files, expectedFiles)) {
  238. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  239. }
  240. }
  241. if (isLandlockPackageDir) {
  242. if (!isPublicLandlockPackage) {
  243. errors.push(`${label}: unexpected package in the public Landlock package family`)
  244. }
  245. if (manifest.version !== landlockVersion) {
  246. errors.push(`${label}: package.json version must match Landlock workspace version ${landlockVersion ?? '(missing)'}`)
  247. }
  248. }
  249. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  250. const peer = manifest.peerDependencies?.cordis
  251. const dev = manifest.devDependencies?.cordis
  252. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  253. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  254. if (peer && dev && peer !== dev) {
  255. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  256. }
  257. if (manifest.version !== repositoryVersion) {
  258. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  259. }
  260. if (manifest.type !== 'module') {
  261. errors.push(`${label}: package.json must set "type": "module"`)
  262. }
  263. if (manifest.main !== 'lib/index.js') {
  264. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  265. }
  266. if (manifest.types !== 'lib/types/index.d.ts') {
  267. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  268. }
  269. const rootExport = manifest.exports?.['.']
  270. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  271. if (rootEntry?.types !== './lib/types/index.d.ts') {
  272. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  273. }
  274. if (rootEntry?.default !== './lib/index.js') {
  275. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  276. }
  277. const invariantRaw = manifest.exports?.['./invariant']
  278. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  279. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  280. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  281. }
  282. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  283. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  284. }
  285. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  286. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  287. }
  288. const expectedFiles = expectedDshPackageFiles(manifest)
  289. if (!sameStringList(manifest.files, expectedFiles)) {
  290. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  291. }
  292. }
  293. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  294. }
  295. /**
  296. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  297. * package.json, and packages may be neither flat nor more deeply nested.
  298. */
  299. function checkHierarchyShape(): string[] {
  300. const errors: string[] = []
  301. const packagesRoot = join(root, 'packages')
  302. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  303. if (!group.isDirectory()) continue
  304. const groupRel = join('packages', group.name)
  305. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  306. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  307. continue
  308. }
  309. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  310. if (!pkg.isDirectory()) continue
  311. if (localArtifactDirs.has(pkg.name)) continue
  312. const pkgRel = join(groupRel, pkg.name)
  313. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  314. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  315. }
  316. }
  317. }
  318. return errors
  319. }
  320. function checkRepositoryVersion(): string[] {
  321. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  322. return ['package.json: version must be stable X.Y.Z']
  323. }
  324. const errors = [
  325. ...checkRepositoryVersion(),
  326. ...workspaceManifests().flatMap(checkWorkspace),
  327. ...checkHierarchyShape(),
  328. ...collectProjectReferenceFaceViolations(root),
  329. ]
  330. if (errors.length > 0) {
  331. console.error(errors.join('\n'))
  332. process.exitCode = 1
  333. }