check-workspace-constraints.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 { pathToFileURL } from 'node:url'
  10. import { isPublicExperimentalPackageDirectory } from './experimental-package-policy.ts'
  11. import { hasTypertRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
  12. import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
  13. const root = resolve(import.meta.dirname, '..')
  14. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  15. // (the group dirs — core/llm/shell/… — are pure containers with no manifest).
  16. const workspaceGlobs = [
  17. { dir: 'vendor', depth: 1 },
  18. { dir: 'packages', depth: 2 },
  19. { dir: 'native', depth: 1 },
  20. { dir: 'native/system/packages', depth: 1 },
  21. { dir: 'apps', depth: 1 },
  22. ] as const
  23. const vendoredPackages = new Set([
  24. '@deepseek-ai/cordis',
  25. '@deepseek-ai/cosmokit',
  26. '@deepseek-ai/schemastery',
  27. '@deepseek-ai/cordis-plugin-loader',
  28. '@deepseek-ai/cordis-plugin-include',
  29. '@deepseek-ai/cordis-plugin-group',
  30. '@deepseek-ai/cordis-plugin-timer',
  31. '@deepseek-ai/cordis-plugin-hmr',
  32. '@deepseek-ai/cordis-plugin-logger-console',
  33. ])
  34. const publicNativePackages = new Set([
  35. '@deepseek-ai/node-addon-system',
  36. '@deepseek-ai/node-addon-system-darwin-arm64',
  37. '@deepseek-ai/node-addon-system-darwin-x64',
  38. '@deepseek-ai/node-addon-system-linux-arm64',
  39. '@deepseek-ai/node-addon-system-linux-x64',
  40. ])
  41. /** Deliberate source payloads whose exact bytes are part of the package's audit surface. */
  42. const publicationSourceAllowlist: Readonly<Record<string, readonly string[]>> = {
  43. '@deepseek-ai/node-addon-system': ['src/main.c', 'src/flock.c'],
  44. }
  45. const repositoryUrl = 'git+https://github.com/deepseek-harness/deepseek-harness.git'
  46. /**
  47. * Source home the published packages point consumers at. It differs from
  48. * {@link repositoryUrl}, which the Landlock packages keep because npm resolves
  49. * their trusted publishing against the repository that runs the workflow.
  50. */
  51. const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harness.git'
  52. /** Packages that participate in the experimental policy. */
  53. const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/
  54. /** npm namespace reserved for experimental packages. */
  55. const experimentalPackageNamePrefix = '@deepseek-ai/dsh-experimental-'
  56. /** Ordinary directories whose packages this repository publishes: one release member each. */
  57. const standardReleaseMemberDirectory = /^(?:packages\/(?!experimental\/)[^/]+\/[^/]+|apps\/(?!desktop(?:-host)?$)[^/]+|vendor\/[^/]+)$/
  58. /** Installable application assembled by electron-builder rather than published to npm. */
  59. const desktopApplicationDirectory = 'apps/desktop'
  60. const localArtifactDirs = new Set(['node_modules'])
  61. const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
  62. '@deepseek-ai/dsh': ['lib/*.js'],
  63. '@deepseek-ai/dsh-desktop-host': [
  64. 'lib/index.js',
  65. 'config/desktop.cordis.patch.yml',
  66. ],
  67. // Sourcemaps stay out by payload policy; the worker-preview surface
  68. // (dist/preview.html and dist/preview/) backs private experimental
  69. // packages and is not published.
  70. '@deepseek-ai/dsh-web-frontend': ['dist', '!dist/**/*.map', '!dist/preview.html', '!dist/preview'],
  71. }
  72. /** The subset of package.json fields this constraint check cares about. */
  73. export interface PackageManifest {
  74. name?: string
  75. version?: string
  76. private?: boolean
  77. type?: string
  78. main?: string
  79. types?: string
  80. bin?: string | Record<string, string>
  81. exports?: Record<
  82. string,
  83. | string
  84. | {
  85. types?: string
  86. default?: string
  87. }
  88. | null
  89. | undefined
  90. >
  91. files?: string[]
  92. publishConfig?: { access?: string }
  93. repository?: { type?: string; url?: string; directory?: string }
  94. peerDependencies?: Record<string, string>
  95. devDependencies?: Record<string, string>
  96. dependencies?: Record<string, string>
  97. optionalDependencies?: Record<string, string>
  98. dsh?: {
  99. bundle?: {
  100. patch?: string
  101. }
  102. }
  103. }
  104. /** One workspace manifest and its repo-relative path. */
  105. export interface WorkspaceManifest {
  106. dir: string
  107. manifest: PackageManifest
  108. }
  109. function readJson(path: string): PackageManifest {
  110. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  111. }
  112. const rootManifest = readJson(join(root, 'package.json'))
  113. const repositoryVersion = rootManifest.version
  114. const nativeWorkspaceManifest = readJson(join(root, 'native/system/package.json'))
  115. const nativeVersion = nativeWorkspaceManifest.version
  116. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  117. function packageDirs(base: string, depth: number): string[] {
  118. if (depth === 1) {
  119. return readdirSync(join(root, base), { withFileTypes: true })
  120. .filter(entry => entry.isDirectory())
  121. .filter(entry => !localArtifactDirs.has(entry.name))
  122. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  123. .map(entry => `${base}/${entry.name}`)
  124. }
  125. return readdirSync(join(root, base), { withFileTypes: true })
  126. .filter(entry => entry.isDirectory())
  127. .filter(entry => !localArtifactDirs.has(entry.name))
  128. .flatMap(group => packageDirs(`${base}/${group.name}`, depth - 1))
  129. }
  130. function workspaceManifests(): WorkspaceManifest[] {
  131. const manifests: WorkspaceManifest[] = [
  132. { dir: '.', manifest: rootManifest },
  133. ]
  134. for (const { dir: base, depth } of workspaceGlobs) {
  135. for (const dir of packageDirs(base, depth)) {
  136. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  137. }
  138. }
  139. return manifests
  140. }
  141. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  142. // Statically linked client libraries keep their stylesheets next to the emitted
  143. // JavaScript, which imports them by relative path: the compile shell runs
  144. // them through its own CSS pipeline, so the sheets are published artifacts.
  145. // The glob covers whichever sheets a package emits; sourcemaps stay
  146. // unpublished, as everywhere else in the repository.
  147. '@deepseek-ai/dsh-client-ui-primitives': ['lib/**/*.css'],
  148. '@deepseek-ai/dsh-client-ui-dockkit': ['lib/**/*.css'],
  149. '@deepseek-ai/dsh-client-web': ['lib/**/*.css'],
  150. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  151. // The CPython side ships as source .py files, published as-is rather than built.
  152. '@deepseek-ai/dsh-experimental-code-runtime-python': ['py/**/*.py'],
  153. // The isolated Node bootstrap is a separately launched bundle.
  154. '@deepseek-ai/dsh-code-runtime-node': ['lib/process.js'],
  155. // The shipped preset compositions travel inside the roster package.
  156. '@deepseek-ai/dsh-agent-presets': ['presets'],
  157. // The Web Host mounts the default-off settings owner independently of each
  158. // Agent-scoped delegation-tool instance.
  159. '@deepseek-ai/dsh-tool-subagent': ['lib/model-selection-settings.js'],
  160. // The JSONL backend resolves its private verification Worker relative to
  161. // import.meta.url; it is shipped without a public package subpath.
  162. '@deepseek-ai/dsh-session-persistence-jsonl': ['lib/worker.cjs'],
  163. // The argv-prefix runner entry ships beside the lib as its own bundle;
  164. // sandbox-local resolves it through the package's ./runner export. tsdown
  165. // also shares its generated FFI code through a hashed runtime chunk.
  166. '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
  167. '@deepseek-ai/dsh-skill-badge': ['assets'],
  168. '@deepseek-ai/dsh-subprocess': ['lib/control.js'],
  169. // Ordinary native containment ships a path-loaded runner and its shared
  170. // runner chunk beside the existing node-pty permission repair.
  171. '@deepseek-ai/dsh-subprocess-local': [
  172. 'lib/runner.js',
  173. 'lib/runner-*.js',
  174. 'scripts/ensure-spawn-helper.mjs',
  175. ],
  176. // tsdown shares the repository/pack code between the lib entry and the bin
  177. // through a hashed chunk. The committed bin.js is the link target pnpm can
  178. // resolve at install time, before the build produces lib/bin.js.
  179. '@deepseek-ai/dsh-experimental-webworker-packer': ['bin.js', 'lib/repository-*.js'],
  180. // The headless entry and its startup row share the JSON projection code
  181. // through a hashed tsdown chunk; both import it by relative path.
  182. '@deepseek-ai/dsh-headless': ['lib/json-stream-*.js'],
  183. }
  184. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  185. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  186. }
  187. export function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  188. const declaredPatch = manifest.dsh?.bundle?.patch
  189. const bundleFiles = declaredPatch === undefined ? [] : [declaredPatch.replace(/^\.\//, '')]
  190. const extras = [
  191. ...bundleFiles,
  192. ...(manifest.name ? packageFileExtras[manifest.name] ?? [] : []),
  193. ]
  194. return [
  195. 'lib/index.js',
  196. // Packages with an invariant export publish its runtime as a separate
  197. // bundle; the package-invariant gate validates the source/export pairing.
  198. ...manifest.exports?.['./invariant'] ? ['lib/invariant.js'] : [],
  199. ...manifest.bin ? ['lib/bin.js'] : [],
  200. // Worker-thread packages ship a CJS worker entry; the browser worker
  201. // bundle is an ES module a page loads with `new Worker(type: 'module')`.
  202. // Keyed on the artifact path, like ./client below.
  203. ...exportDefault(manifest, './worker') === './lib/worker.cjs' ? ['lib/worker.cjs'] : [],
  204. ...exportDefault(manifest, './worker') === './lib/worker.js' ? ['lib/worker.js'] : [],
  205. // UI plugin packages ship their browser bundle beside the node lib
  206. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  207. // Keyed on the artifact path, not the subpath name: a package's ./client is
  208. // a browser-safe source channel, not a bundle.
  209. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  210. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  211. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  212. // A store subpath ships its own bundle (single-entry builds; no shared chunk).
  213. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  214. // A surface bundle's startup row is its own bundle: the Loader imports it
  215. // as a row module, so it cannot ride inside the package entry.
  216. ...exportDefault(manifest, './startup') === './lib/startup.js' ? ['lib/startup.js'] : [],
  217. ...extras,
  218. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  219. // browser-safe source channels rehomed off src so plain Node can import
  220. // them without type stripping) publish the emitted JS alongside the
  221. // declarations.
  222. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  223. 'lib/types/**/*.d.ts',
  224. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  225. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  226. : [],
  227. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  228. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  229. : [],
  230. ...hasTypertRemoteNavigation(manifest)
  231. ? ['lib/typert.remote-client.js', 'lib/typert.remote-client.d.ts']
  232. : [],
  233. ]
  234. }
  235. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  236. function hasExportPair(
  237. manifest: PackageManifest,
  238. subpath: string,
  239. types: string,
  240. runtime: string,
  241. ): boolean {
  242. const entry = manifest.exports?.[subpath]
  243. return typeof entry === 'object'
  244. && entry !== null
  245. && entry.types === types
  246. && entry.default === runtime
  247. }
  248. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  249. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  250. const entry = manifest.exports?.[subpath]
  251. if (typeof entry === 'string') return entry
  252. if (typeof entry === 'object' && entry !== null) return entry.default
  253. return undefined
  254. }
  255. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  256. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  257. return Object.keys(manifest.exports ?? {}).some(subpath =>
  258. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  259. }
  260. /** Experimental manifest requirements, including explicit public exceptions. */
  261. export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest): string[] {
  262. if (!experimentalPackageDirectory.test(dir)) return []
  263. const label = manifest.name ?? dir
  264. const errors: string[] = []
  265. if (manifest.name?.startsWith(experimentalPackageNamePrefix) !== true) {
  266. errors.push(`${label}: experimental package name must start with ${JSON.stringify(experimentalPackageNamePrefix)}`)
  267. }
  268. if (isPublicExperimentalPackageDirectory(dir)) {
  269. if (manifest.private === true) errors.push(`${label}: public experimental package must not set "private": true`)
  270. if (manifest.publishConfig?.access !== 'public') {
  271. errors.push(`${label}: public experimental package must set publishConfig.access to "public"`)
  272. }
  273. } else {
  274. if (manifest.private !== true) errors.push(`${label}: experimental package must set "private": true`)
  275. if (manifest.publishConfig !== undefined) errors.push(`${label}: experimental package must omit publishConfig`)
  276. }
  277. return errors
  278. }
  279. function isReleaseMemberDirectory(dir: string): boolean {
  280. return standardReleaseMemberDirectory.test(dir) || isPublicExperimentalPackageDirectory(dir)
  281. }
  282. /**
  283. * Require a dsh-family manifest to carry the workspace version.
  284. *
  285. * The dsh release sequence publishes packages/ and apps/ members and every
  286. * private dsh package on one shared version, written by `release:dsh` and
  287. * shared with the workspace root. This name test is that boundary: it covers
  288. * the family wherever the manifest lives, so apps/ members cannot drift with
  289. * only the release lane noticing.
  290. * @param manifest - the workspace package manifest.
  291. * @param expected - the version every dsh-family manifest must carry (the root's).
  292. * @returns one violation naming the manifest and the expected version, or
  293. * undefined when the manifest is compliant or not in the family.
  294. */
  295. export function checkDshFamilyVersion(manifest: PackageManifest, expected: string | undefined): string | undefined {
  296. const name = manifest.name
  297. if (name !== '@deepseek-ai/dsh' && name?.startsWith('@deepseek-ai/dsh-') !== true) return undefined
  298. if (manifest.version !== expected) {
  299. return `${name}: package.json version must match root version ${expected ?? '(missing)'}`
  300. }
  301. return undefined
  302. }
  303. /**
  304. * Check one workspace manifest against publication and dsh-package policy.
  305. * @param workspace - package directory and parsed manifest.
  306. * @returns path-qualified policy violations.
  307. */
  308. export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): string[] {
  309. const errors = checkExperimentalManifest({ dir, manifest })
  310. const label = manifest.name ?? dir
  311. const familyVersionError = checkDshFamilyVersion(manifest, repositoryVersion)
  312. if (familyVersionError !== undefined) errors.push(familyVersionError)
  313. const isNativePackageDir = dir.startsWith('native/system/packages/')
  314. const isPublicNativePackage = isNativePackageDir
  315. && manifest.name !== undefined
  316. && publicNativePackages.has(manifest.name)
  317. if (isPublicNativePackage) {
  318. if (manifest.private === true) {
  319. errors.push(`${label}: published Landlock package must not set "private": true`)
  320. }
  321. if (manifest.publishConfig?.access !== 'public') {
  322. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  323. }
  324. const expectedDirectory = dir
  325. if (manifest.repository?.type !== 'git'
  326. || manifest.repository.url !== repositoryUrl
  327. || manifest.repository.directory !== expectedDirectory) {
  328. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  329. }
  330. } else if (isReleaseMemberDirectory(dir)) {
  331. // Release members state that they are publishable: npm refuses a private
  332. // package, and the repository field is how a consumer finds the source of
  333. // the package it installed.
  334. //
  335. // Access is per release sequence, not per scope: the vendored framework and
  336. // the Landlock packages publish publicly because outside consumers install
  337. // them, and the dsh family published publicly with its own sequence on
  338. // 2026-08-13. No publish path passes `--access`; each packed manifest declares
  339. // it, and this gate requires every release member to be public.
  340. if (manifest.private === true) {
  341. errors.push(`${label}: release member must not set "private": true`)
  342. }
  343. if (manifest.publishConfig?.access !== 'public') {
  344. errors.push(`${label}: release member must set publishConfig.access to "public"`)
  345. }
  346. if (manifest.repository?.type !== 'git'
  347. || manifest.repository.url !== publishedRepositoryUrl
  348. || manifest.repository.directory !== dir) {
  349. errors.push(`${label}: release member repository must use ${publishedRepositoryUrl} with directory ${dir}`)
  350. }
  351. } else if (!experimentalPackageDirectory.test(dir) && manifest.private !== true) {
  352. errors.push(`${label}: package.json must set "private": true`)
  353. }
  354. if (manifest.name && vendoredPackages.has(manifest.name)) {
  355. return errors
  356. }
  357. if (manifest.name?.startsWith('@deepseek-ai/')) {
  358. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  359. for (const file of manifest.files ?? []) {
  360. if (isForbiddenPublicationFile(file) && !allowedSources.includes(file)) {
  361. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  362. }
  363. }
  364. }
  365. if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && manifest.name?.startsWith('@deepseek-ai/')) {
  366. const expectedFiles = appPackageFiles[manifest.name]
  367. if (expectedFiles === undefined) {
  368. errors.push(`${label}: app package has no publication files policy`)
  369. } else if (!sameStringList(manifest.files, expectedFiles)) {
  370. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  371. }
  372. }
  373. if (isNativePackageDir) {
  374. if (!isPublicNativePackage) {
  375. errors.push(`${label}: unexpected package in the public Landlock package family`)
  376. }
  377. if (manifest.version !== nativeVersion) {
  378. errors.push(`${label}: package.json version must match native workspace version ${nativeVersion ?? '(missing)'}`)
  379. }
  380. }
  381. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  382. const peer = manifest.peerDependencies?.['@deepseek-ai/cordis']
  383. const dev = manifest.devDependencies?.['@deepseek-ai/cordis']
  384. if (!peer) errors.push(`${label}: @deepseek-ai/cordis must be a peerDependency`)
  385. if (!dev) errors.push(`${label}: @deepseek-ai/cordis must also be a devDependency`)
  386. if (peer && dev && peer !== dev) {
  387. errors.push(`${label}: @deepseek-ai/cordis peer (${peer}) and dev (${dev}) ranges must match`)
  388. }
  389. if (manifest.type !== 'module') {
  390. errors.push(`${label}: package.json must set "type": "module"`)
  391. }
  392. if (manifest.main !== 'lib/index.js') {
  393. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  394. }
  395. if (manifest.types !== 'lib/types/index.d.ts') {
  396. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  397. }
  398. const rootExport = manifest.exports?.['.']
  399. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  400. if (rootEntry?.types !== './lib/types/index.d.ts') {
  401. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  402. }
  403. if (rootEntry?.default !== './lib/index.js') {
  404. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  405. }
  406. const invariantRaw = manifest.exports?.['./invariant']
  407. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  408. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  409. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  410. }
  411. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  412. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  413. }
  414. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  415. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  416. }
  417. const expectedFiles = expectedDshPackageFiles(manifest)
  418. if (!sameStringList(manifest.files, expectedFiles)) {
  419. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  420. }
  421. }
  422. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  423. }
  424. /**
  425. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  426. * package.json, and packages may be neither flat nor more deeply nested.
  427. */
  428. function checkHierarchyShape(): string[] {
  429. const errors: string[] = []
  430. const packagesRoot = join(root, 'packages')
  431. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  432. if (!group.isDirectory()) continue
  433. const groupRel = join('packages', group.name)
  434. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  435. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  436. continue
  437. }
  438. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  439. if (!pkg.isDirectory()) continue
  440. if (localArtifactDirs.has(pkg.name)) continue
  441. const pkgRel = join(groupRel, pkg.name)
  442. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  443. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  444. }
  445. }
  446. }
  447. return errors
  448. }
  449. function checkRepositoryVersion(): string[] {
  450. // The root carries the dsh release family's version, so a prerelease such as
  451. // 0.0.1-rc.1 is a valid state between `release:dsh` and its publication.
  452. if (repositoryVersion && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(repositoryVersion)) return []
  453. return ['package.json: version must be X.Y.Z with an optional prerelease segment']
  454. }
  455. /** Dependency sections whose ranges reach a published tarball or a local install. */
  456. const dependencySections = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const
  457. /** Dependency sections present in an installed runtime. */
  458. const runtimeDependencySections = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const
  459. /**
  460. * Prevent an official runtime from requiring a package its release omits.
  461. * @param manifests - release, private experimental, and deployment-root manifests.
  462. * @returns One error for each forbidden runtime dependency.
  463. */
  464. export function checkExperimentalDependencyIsolation(manifests: readonly WorkspaceManifest[]): string[] {
  465. const experimentalNames = new Set(manifests
  466. .filter(entry => experimentalPackageDirectory.test(entry.dir))
  467. .map(entry => entry.manifest.name)
  468. .filter(name => name !== undefined))
  469. const errors: string[] = []
  470. for (const { dir, manifest } of manifests) {
  471. if (!standardReleaseMemberDirectory.test(dir) && dir !== 'python/sdk-runtime') continue
  472. for (const section of runtimeDependencySections) {
  473. for (const name of Object.keys(manifest[section] ?? {})) {
  474. if (!experimentalNames.has(name)) continue
  475. errors.push(`${manifest.name ?? dir}: ${section}.${name} must not reference an experimental package`)
  476. }
  477. }
  478. }
  479. return errors
  480. }
  481. /**
  482. * Require the `workspace:` protocol for every reference to a workspace member.
  483. *
  484. * A hand-written range says nothing about the version the workspace actually
  485. * carries, and `pnpm pack` leaves it alone: `^0.0.1` published from version
  486. * `0.0.2` names a version that does not exist. The protocol makes pack
  487. * substitute the member's real version, so no release step rewrites ranges.
  488. * @param manifests - every workspace manifest.
  489. * @returns One error per reference that names a workspace member without the protocol.
  490. */
  491. function checkWorkspaceProtocol(manifests: readonly WorkspaceManifest[]): string[] {
  492. const members = new Set(manifests.map(entry => entry.manifest.name).filter(name => name !== undefined))
  493. const errors: string[] = []
  494. for (const { dir, manifest } of manifests) {
  495. for (const section of dependencySections) {
  496. for (const [name, range] of Object.entries(manifest[section] ?? {})) {
  497. if (!members.has(name) || range.startsWith('workspace:')) continue
  498. errors.push(`${manifest.name ?? dir}: ${section}.${name} must use the workspace: protocol, got ${range}`)
  499. }
  500. }
  501. }
  502. return errors
  503. }
  504. /** Run the repository constraint gate. */
  505. export function main(): void {
  506. const manifests = workspaceManifests()
  507. const dependencyManifests = [
  508. ...manifests,
  509. { dir: 'python/sdk-runtime', manifest: readJson(join(root, 'python/sdk-runtime/package.json')) },
  510. ]
  511. const errors = [
  512. ...checkRepositoryVersion(),
  513. ...manifests.flatMap(checkWorkspaceManifest),
  514. ...checkWorkspaceProtocol(manifests),
  515. ...checkExperimentalDependencyIsolation(dependencyManifests),
  516. ...checkHierarchyShape(),
  517. ...collectProjectReferenceFaceViolations(root),
  518. ]
  519. if (errors.length > 0) {
  520. console.error(errors.join('\n'))
  521. process.exitCode = 1
  522. }
  523. }
  524. if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()