check-workspace-constraints.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 shipped preset compositions travel inside the roster package.
  154. '@deepseek-ai/dsh-agent-presets': ['presets'],
  155. // The Web Host mounts the default-off settings owner independently of each
  156. // Agent-scoped delegation-tool instance.
  157. '@deepseek-ai/dsh-tool-subagent': ['lib/model-selection-settings.js'],
  158. // The JSONL backend resolves its private verification Worker relative to
  159. // import.meta.url; it is shipped without a public package subpath.
  160. '@deepseek-ai/dsh-session-persistence-jsonl': ['lib/worker.cjs'],
  161. // The argv-prefix runner entry ships beside the lib as its own bundle;
  162. // sandbox-local resolves it through the package's ./runner export. tsdown
  163. // also shares its generated FFI code through a hashed runtime chunk.
  164. '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
  165. '@deepseek-ai/dsh-skill-badge': ['assets'],
  166. // Ordinary native containment ships a path-loaded runner and its shared
  167. // runner chunk beside the existing node-pty permission repair.
  168. '@deepseek-ai/dsh-subprocess-local': [
  169. 'lib/runner.js',
  170. 'lib/runner-*.js',
  171. 'scripts/ensure-spawn-helper.mjs',
  172. ],
  173. // tsdown shares the repository/pack code between the lib entry and the bin
  174. // through a hashed chunk. The committed bin.js is the link target pnpm can
  175. // resolve at install time, before the build produces lib/bin.js.
  176. '@deepseek-ai/dsh-experimental-webworker-packer': ['bin.js', 'lib/repository-*.js'],
  177. }
  178. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  179. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  180. }
  181. export function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  182. const declaredPatch = manifest.dsh?.bundle?.patch
  183. const bundleFiles = declaredPatch === undefined ? [] : [declaredPatch.replace(/^\.\//, '')]
  184. const extras = [
  185. ...bundleFiles,
  186. ...(manifest.name ? packageFileExtras[manifest.name] ?? [] : []),
  187. ]
  188. return [
  189. 'lib/index.js',
  190. // Packages with an invariant export publish its runtime as a separate
  191. // bundle; the package-invariant gate validates the source/export pairing.
  192. ...manifest.exports?.['./invariant'] ? ['lib/invariant.js'] : [],
  193. ...manifest.bin ? ['lib/bin.js'] : [],
  194. // Worker-thread packages ship a CJS worker entry; the browser worker
  195. // bundle is an ES module a page loads with `new Worker(type: 'module')`.
  196. // Keyed on the artifact path, like ./client below.
  197. ...exportDefault(manifest, './worker') === './lib/worker.cjs' ? ['lib/worker.cjs'] : [],
  198. ...exportDefault(manifest, './worker') === './lib/worker.js' ? ['lib/worker.js'] : [],
  199. // UI plugin packages ship their browser bundle beside the node lib
  200. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  201. // Keyed on the artifact path, not the subpath name: a package's ./client is
  202. // a browser-safe source channel, not a bundle.
  203. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  204. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  205. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  206. // A store subpath ships its own bundle (single-entry builds; no shared chunk).
  207. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  208. // A surface bundle's startup row is its own bundle: the Loader imports it
  209. // as a row module, so it cannot ride inside the package entry.
  210. ...exportDefault(manifest, './startup') === './lib/startup.js' ? ['lib/startup.js'] : [],
  211. ...extras,
  212. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  213. // browser-safe source channels rehomed off src so plain Node can import
  214. // them without type stripping) publish the emitted JS alongside the
  215. // declarations.
  216. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  217. 'lib/types/**/*.d.ts',
  218. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  219. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  220. : [],
  221. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  222. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  223. : [],
  224. ...hasTypertRemoteNavigation(manifest)
  225. ? ['lib/typert.remote-client.js', 'lib/typert.remote-client.d.ts']
  226. : [],
  227. ]
  228. }
  229. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  230. function hasExportPair(
  231. manifest: PackageManifest,
  232. subpath: string,
  233. types: string,
  234. runtime: string,
  235. ): boolean {
  236. const entry = manifest.exports?.[subpath]
  237. return typeof entry === 'object'
  238. && entry !== null
  239. && entry.types === types
  240. && entry.default === runtime
  241. }
  242. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  243. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  244. const entry = manifest.exports?.[subpath]
  245. if (typeof entry === 'string') return entry
  246. if (typeof entry === 'object' && entry !== null) return entry.default
  247. return undefined
  248. }
  249. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  250. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  251. return Object.keys(manifest.exports ?? {}).some(subpath =>
  252. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  253. }
  254. /** Experimental manifest requirements, including explicit public exceptions. */
  255. export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest): string[] {
  256. if (!experimentalPackageDirectory.test(dir)) return []
  257. const label = manifest.name ?? dir
  258. const errors: string[] = []
  259. if (manifest.name?.startsWith(experimentalPackageNamePrefix) !== true) {
  260. errors.push(`${label}: experimental package name must start with ${JSON.stringify(experimentalPackageNamePrefix)}`)
  261. }
  262. if (isPublicExperimentalPackageDirectory(dir)) {
  263. if (manifest.private === true) errors.push(`${label}: public experimental package must not set "private": true`)
  264. if (manifest.publishConfig?.access !== 'public') {
  265. errors.push(`${label}: public experimental package must set publishConfig.access to "public"`)
  266. }
  267. } else {
  268. if (manifest.private !== true) errors.push(`${label}: experimental package must set "private": true`)
  269. if (manifest.publishConfig !== undefined) errors.push(`${label}: experimental package must omit publishConfig`)
  270. }
  271. return errors
  272. }
  273. function isReleaseMemberDirectory(dir: string): boolean {
  274. return standardReleaseMemberDirectory.test(dir) || isPublicExperimentalPackageDirectory(dir)
  275. }
  276. /**
  277. * Require a dsh-family manifest to carry the workspace version.
  278. *
  279. * The dsh release sequence publishes packages/ and apps/ members and every
  280. * private dsh package on one shared version, written by `release:dsh` and
  281. * shared with the workspace root. This name test is that boundary: it covers
  282. * the family wherever the manifest lives, so apps/ members cannot drift with
  283. * only the release lane noticing.
  284. * @param manifest - the workspace package manifest.
  285. * @param expected - the version every dsh-family manifest must carry (the root's).
  286. * @returns one violation naming the manifest and the expected version, or
  287. * undefined when the manifest is compliant or not in the family.
  288. */
  289. export function checkDshFamilyVersion(manifest: PackageManifest, expected: string | undefined): string | undefined {
  290. const name = manifest.name
  291. if (name !== '@deepseek-ai/dsh' && name?.startsWith('@deepseek-ai/dsh-') !== true) return undefined
  292. if (manifest.version !== expected) {
  293. return `${name}: package.json version must match root version ${expected ?? '(missing)'}`
  294. }
  295. return undefined
  296. }
  297. /**
  298. * Check one workspace manifest against publication and dsh-package policy.
  299. * @param workspace - package directory and parsed manifest.
  300. * @returns path-qualified policy violations.
  301. */
  302. export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): string[] {
  303. const errors = checkExperimentalManifest({ dir, manifest })
  304. const label = manifest.name ?? dir
  305. const familyVersionError = checkDshFamilyVersion(manifest, repositoryVersion)
  306. if (familyVersionError !== undefined) errors.push(familyVersionError)
  307. const isNativePackageDir = dir.startsWith('native/system/packages/')
  308. const isPublicNativePackage = isNativePackageDir
  309. && manifest.name !== undefined
  310. && publicNativePackages.has(manifest.name)
  311. if (isPublicNativePackage) {
  312. if (manifest.private === true) {
  313. errors.push(`${label}: published Landlock package must not set "private": true`)
  314. }
  315. if (manifest.publishConfig?.access !== 'public') {
  316. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  317. }
  318. const expectedDirectory = dir
  319. if (manifest.repository?.type !== 'git'
  320. || manifest.repository.url !== repositoryUrl
  321. || manifest.repository.directory !== expectedDirectory) {
  322. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  323. }
  324. } else if (isReleaseMemberDirectory(dir)) {
  325. // Release members state that they are publishable: npm refuses a private
  326. // package, and the repository field is how a consumer finds the source of
  327. // the package it installed.
  328. //
  329. // Access is per release sequence, not per scope: the vendored framework and
  330. // the Landlock packages publish publicly because outside consumers install
  331. // them, and the dsh family published publicly with its own sequence on
  332. // 2026-08-13. No publish path passes `--access`; each packed manifest declares
  333. // it, and this gate requires every release member to be public.
  334. if (manifest.private === true) {
  335. errors.push(`${label}: release member must not set "private": true`)
  336. }
  337. if (manifest.publishConfig?.access !== 'public') {
  338. errors.push(`${label}: release member must set publishConfig.access to "public"`)
  339. }
  340. if (manifest.repository?.type !== 'git'
  341. || manifest.repository.url !== publishedRepositoryUrl
  342. || manifest.repository.directory !== dir) {
  343. errors.push(`${label}: release member repository must use ${publishedRepositoryUrl} with directory ${dir}`)
  344. }
  345. } else if (!experimentalPackageDirectory.test(dir) && manifest.private !== true) {
  346. errors.push(`${label}: package.json must set "private": true`)
  347. }
  348. if (manifest.name && vendoredPackages.has(manifest.name)) {
  349. return errors
  350. }
  351. if (manifest.name?.startsWith('@deepseek-ai/')) {
  352. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  353. for (const file of manifest.files ?? []) {
  354. if (isForbiddenPublicationFile(file) && !allowedSources.includes(file)) {
  355. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  356. }
  357. }
  358. }
  359. if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && manifest.name?.startsWith('@deepseek-ai/')) {
  360. const expectedFiles = appPackageFiles[manifest.name]
  361. if (expectedFiles === undefined) {
  362. errors.push(`${label}: app package has no publication files policy`)
  363. } else if (!sameStringList(manifest.files, expectedFiles)) {
  364. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  365. }
  366. }
  367. if (isNativePackageDir) {
  368. if (!isPublicNativePackage) {
  369. errors.push(`${label}: unexpected package in the public Landlock package family`)
  370. }
  371. if (manifest.version !== nativeVersion) {
  372. errors.push(`${label}: package.json version must match native workspace version ${nativeVersion ?? '(missing)'}`)
  373. }
  374. }
  375. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  376. const peer = manifest.peerDependencies?.['@deepseek-ai/cordis']
  377. const dev = manifest.devDependencies?.['@deepseek-ai/cordis']
  378. if (!peer) errors.push(`${label}: @deepseek-ai/cordis must be a peerDependency`)
  379. if (!dev) errors.push(`${label}: @deepseek-ai/cordis must also be a devDependency`)
  380. if (peer && dev && peer !== dev) {
  381. errors.push(`${label}: @deepseek-ai/cordis peer (${peer}) and dev (${dev}) ranges must match`)
  382. }
  383. if (manifest.type !== 'module') {
  384. errors.push(`${label}: package.json must set "type": "module"`)
  385. }
  386. if (manifest.main !== 'lib/index.js') {
  387. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  388. }
  389. if (manifest.types !== 'lib/types/index.d.ts') {
  390. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  391. }
  392. const rootExport = manifest.exports?.['.']
  393. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  394. if (rootEntry?.types !== './lib/types/index.d.ts') {
  395. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  396. }
  397. if (rootEntry?.default !== './lib/index.js') {
  398. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  399. }
  400. const invariantRaw = manifest.exports?.['./invariant']
  401. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  402. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  403. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  404. }
  405. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  406. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  407. }
  408. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  409. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  410. }
  411. const expectedFiles = expectedDshPackageFiles(manifest)
  412. if (!sameStringList(manifest.files, expectedFiles)) {
  413. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  414. }
  415. }
  416. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  417. }
  418. /**
  419. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  420. * package.json, and packages may be neither flat nor more deeply nested.
  421. */
  422. function checkHierarchyShape(): string[] {
  423. const errors: string[] = []
  424. const packagesRoot = join(root, 'packages')
  425. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  426. if (!group.isDirectory()) continue
  427. const groupRel = join('packages', group.name)
  428. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  429. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  430. continue
  431. }
  432. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  433. if (!pkg.isDirectory()) continue
  434. if (localArtifactDirs.has(pkg.name)) continue
  435. const pkgRel = join(groupRel, pkg.name)
  436. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  437. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  438. }
  439. }
  440. }
  441. return errors
  442. }
  443. function checkRepositoryVersion(): string[] {
  444. // The root carries the dsh release family's version, so a prerelease such as
  445. // 0.0.1-rc.1 is a valid state between `release:dsh` and its publication.
  446. if (repositoryVersion && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(repositoryVersion)) return []
  447. return ['package.json: version must be X.Y.Z with an optional prerelease segment']
  448. }
  449. /** Dependency sections whose ranges reach a published tarball or a local install. */
  450. const dependencySections = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const
  451. /** Dependency sections present in an installed runtime. */
  452. const runtimeDependencySections = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const
  453. /**
  454. * Prevent an official runtime from requiring a package its release omits.
  455. * @param manifests - release, private experimental, and deployment-root manifests.
  456. * @returns One error for each forbidden runtime dependency.
  457. */
  458. export function checkExperimentalDependencyIsolation(manifests: readonly WorkspaceManifest[]): string[] {
  459. const experimentalNames = new Set(manifests
  460. .filter(entry => experimentalPackageDirectory.test(entry.dir))
  461. .map(entry => entry.manifest.name)
  462. .filter(name => name !== undefined))
  463. const errors: string[] = []
  464. for (const { dir, manifest } of manifests) {
  465. if (!standardReleaseMemberDirectory.test(dir) && dir !== 'python/sdk-runtime') continue
  466. for (const section of runtimeDependencySections) {
  467. for (const name of Object.keys(manifest[section] ?? {})) {
  468. if (!experimentalNames.has(name)) continue
  469. errors.push(`${manifest.name ?? dir}: ${section}.${name} must not reference an experimental package`)
  470. }
  471. }
  472. }
  473. return errors
  474. }
  475. /**
  476. * Require the `workspace:` protocol for every reference to a workspace member.
  477. *
  478. * A hand-written range says nothing about the version the workspace actually
  479. * carries, and `pnpm pack` leaves it alone: `^0.0.1` published from version
  480. * `0.0.2` names a version that does not exist. The protocol makes pack
  481. * substitute the member's real version, so no release step rewrites ranges.
  482. * @param manifests - every workspace manifest.
  483. * @returns One error per reference that names a workspace member without the protocol.
  484. */
  485. function checkWorkspaceProtocol(manifests: readonly WorkspaceManifest[]): string[] {
  486. const members = new Set(manifests.map(entry => entry.manifest.name).filter(name => name !== undefined))
  487. const errors: string[] = []
  488. for (const { dir, manifest } of manifests) {
  489. for (const section of dependencySections) {
  490. for (const [name, range] of Object.entries(manifest[section] ?? {})) {
  491. if (!members.has(name) || range.startsWith('workspace:')) continue
  492. errors.push(`${manifest.name ?? dir}: ${section}.${name} must use the workspace: protocol, got ${range}`)
  493. }
  494. }
  495. }
  496. return errors
  497. }
  498. /** Run the repository constraint gate. */
  499. export function main(): void {
  500. const manifests = workspaceManifests()
  501. const dependencyManifests = [
  502. ...manifests,
  503. { dir: 'python/sdk-runtime', manifest: readJson(join(root, 'python/sdk-runtime/package.json')) },
  504. ]
  505. const errors = [
  506. ...checkRepositoryVersion(),
  507. ...manifests.flatMap(checkWorkspaceManifest),
  508. ...checkWorkspaceProtocol(manifests),
  509. ...checkExperimentalDependencyIsolation(dependencyManifests),
  510. ...checkHierarchyShape(),
  511. ...collectProjectReferenceFaceViolations(root),
  512. ]
  513. if (errors.length > 0) {
  514. console.error(errors.join('\n'))
  515. process.exitCode = 1
  516. }
  517. }
  518. if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()