verify-cordis-config.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /**
  2. * Validate Cordis Loader entry metadata and package resolution.
  3. *
  4. * The Loader interpolates only a plugin entry's `config`; expression objects in
  5. * fields such as `disabled` remain truthy data and silently change composition.
  6. * Example configs and the dsh Web composition resolve named plugins from their
  7. * owning workspace manifests. Local example packages must also be in the root
  8. * TypeScript project graph.
  9. */
  10. import { globSync, readFileSync } from 'node:fs'
  11. import { dirname, relative, resolve } from 'node:path'
  12. import * as yaml from 'js-yaml'
  13. import ts from 'typescript'
  14. import { cordisConfigFiles } from './cordis-config-files.ts'
  15. interface JsExpr {
  16. __jsExpr: string
  17. }
  18. interface PackageManifest {
  19. name?: string
  20. dependencies?: Record<string, string>
  21. }
  22. interface PluginReference {
  23. file: string
  24. name: string
  25. }
  26. const root = resolve(import.meta.dirname, '..')
  27. // These example files are overlays consumed by the built dsh app, so their bare
  28. // specifiers resolve from apps/cli rather than the examples workspace.
  29. const appOverlayFiles = new Set([
  30. 'examples/web-cordis/cordis.yml',
  31. ...globSync('examples/mcp-memory/*.cordis.yml', { cwd: root }),
  32. ])
  33. const metadataFields = ['id', 'name', 'group', 'disabled', 'inject', 'intercept', 'isolate'] as const
  34. /** The adaptive directory-picker chooser package (mounts a backend row at boot). */
  35. const CHOOSER_PACKAGE = '@deepseek-ai/dsh-host-directory-picker-auto'
  36. /**
  37. * The backends the chooser mounts by runtime string (mirror of its exported
  38. * `BACKEND_PACKAGES`), invisible to yml-row scanning: a composition mounting
  39. * the chooser must resolve both, or keyless Linux CI (which only ever
  40. * resolves `browse`) hides a dropped `-native` dependency until a macOS boot.
  41. */
  42. const CHOOSER_BACKEND_PACKAGES = [
  43. '@deepseek-ai/dsh-host-directory-picker-native',
  44. '@deepseek-ai/dsh-host-directory-picker-browse',
  45. ]
  46. const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
  47. kind: 'scalar',
  48. resolve: data => typeof data === 'string',
  49. construct: (data: unknown): JsExpr => {
  50. if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string')
  51. return { __jsExpr: data }
  52. },
  53. })
  54. const schema = yaml.JSON_SCHEMA.extend(jsExprType)
  55. const files = cordisConfigFiles(root)
  56. const errors: string[] = []
  57. const pluginReferences: PluginReference[] = []
  58. for (const file of files) {
  59. const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
  60. if (!isUnknownArray(document)) {
  61. errors.push(`${file}: root must be a Loader entry array`)
  62. continue
  63. }
  64. for (let index = 0; index < document.length; index++) {
  65. validateEntry(document[index], file, `[${index}]`)
  66. }
  67. }
  68. errors.push(...validateExampleResolution())
  69. errors.push(...validateAppResolution())
  70. errors.push(...validateSourcePlaneResolution())
  71. if (errors.length > 0) {
  72. console.error('verify-cordis-config: invalid Loader metadata or plugin package resolution:')
  73. for (const error of errors) console.error(`- ${error}`)
  74. process.exitCode = 1
  75. } else {
  76. console.log(`verify-cordis-config: ${files.length} config files passed.`)
  77. }
  78. function validateEntry(value: unknown, file: string, path: string): void {
  79. if (!isRecord(value)) {
  80. errors.push(`${file}${path}: entry must be an object`)
  81. return
  82. }
  83. recordPlugin(value, file)
  84. validateMetadata(value, file, path)
  85. if ((value.group === true || value.name === '@cordisjs/plugin-group') && isUnknownArray(value.config)) {
  86. for (let index = 0; index < value.config.length; index++) {
  87. validateEntry(value.config[index], file, `${path}.config[${index}]`)
  88. }
  89. }
  90. if (isUnknownArray(value.insert)) {
  91. for (let index = 0; index < value.insert.length; index++) {
  92. validateEntry(value.insert[index], file, `${path}.insert[${index}]`)
  93. }
  94. }
  95. if (value.name !== '@cordisjs/plugin-include') return
  96. const config = value.config
  97. if (!isRecord(config) || !isUnknownArray(config.patches)) return
  98. for (let index = 0; index < config.patches.length; index++) {
  99. const patch = config.patches[index]
  100. const patchPath = `${path}.config.patches[${index}]`
  101. if (!isRecord(patch)) continue
  102. recordPlugin(patch, file)
  103. validateMetadata(patch, file, patchPath)
  104. if (!isUnknownArray(patch.insert)) continue
  105. for (let insertIndex = 0; insertIndex < patch.insert.length; insertIndex++) {
  106. validateEntry(patch.insert[insertIndex], file, `${patchPath}.insert[${insertIndex}]`)
  107. }
  108. }
  109. }
  110. function recordPlugin(entry: Record<string, unknown>, file: string): void {
  111. if (typeof entry.name === 'string') pluginReferences.push({ file, name: entry.name })
  112. }
  113. function validateExampleResolution(): string[] {
  114. const violations: string[] = []
  115. const exampleManifest = readManifest('examples/package.json')
  116. const dependencies = exampleManifest.dependencies ?? {}
  117. const localPackages = localPackageDirectories()
  118. const rootReferences = rootProjectReferences()
  119. const exampleReferences = pluginReferences.filter(reference => reference.file.startsWith('examples/') && !appOverlayFiles.has(reference.file))
  120. violations.push(...missingPluginDependencies(exampleReferences, dependencies, 'examples/package.json'))
  121. const requiredPackages = new Set(exampleReferences.map(reference => packageNameFromSpecifier(reference.name)))
  122. const localExamplePackages = new Set([
  123. ...Object.keys(dependencies),
  124. ...[...requiredPackages].filter(packageName => packageName !== undefined),
  125. ])
  126. for (const packageName of localExamplePackages) {
  127. const packageDirectory = localPackages.get(packageName)
  128. if (packageDirectory === undefined || rootReferences.has(packageDirectory)) continue
  129. const repoPath = relative(root, packageDirectory).replaceAll('\\', '/')
  130. violations.push(`tsconfig.json: missing project reference for ${packageName} (${repoPath})`)
  131. }
  132. return violations
  133. }
  134. function validateAppResolution(): string[] {
  135. const violations: string[] = []
  136. // App overlays (and any config left under apps/cli/config) resolve from the
  137. // dsh app's own dependency surface — the profile module fallback mirrors it.
  138. const appDependencies = {
  139. ...readManifest('apps/cli/package.json').dependencies,
  140. // The fallback also links every bundle's own dependencies (healProfilesModuleFallback).
  141. ...Object.fromEntries(globSync('packages/bundle/*/package.json', { cwd: root })
  142. .flatMap(file => Object.entries(readManifest(file).dependencies ?? {}))),
  143. }
  144. const shipped = new Set(globSync('*.cordis.yml', { cwd: resolve(root, 'apps/cli/config') })
  145. .map(file => `apps/cli/config/${file}`))
  146. const appReferences = pluginReferences.filter(reference => shipped.has(reference.file) || appOverlayFiles.has(reference.file))
  147. violations.push(...missingPluginDependencies(appReferences, appDependencies, 'apps/cli/package.json or a bundle manifest'))
  148. // Each bundle's patch rows must resolve from that bundle's own dependencies:
  149. // per-layer resolution anchors on the bundle package directory.
  150. for (const manifestPath of globSync('packages/bundle/*/package.json', { cwd: root })) {
  151. const bundleDir = manifestPath.replace(/\/package\.json$/, '')
  152. const manifest = readManifest(manifestPath)
  153. const references = pluginReferences.filter(reference => reference.file.startsWith(`${bundleDir}/`))
  154. violations.push(...missingPluginDependencies(
  155. // A bundle may mount its own package (the web-app runtime row).
  156. references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name),
  157. manifest.dependencies ?? {},
  158. manifestPath,
  159. ))
  160. }
  161. return violations
  162. }
  163. /**
  164. * Every configured specifier of a local workspace package must resolve through
  165. * the tsconfig `paths` facade to a `.ts`/`.tsx` source file. The `dsh` source
  166. * launch (tsx) and vitest resolve in the source plane; without a `paths` match
  167. * they fall back to package `exports`, which reach built `lib/` — present on a
  168. * built dev tree, absent on a clean one — so a missing mapping boots locally
  169. * yet breaks every clean checkout. Anything but a `.ts`/`.tsx` hit (a `.d.ts`
  170. * or `.js` under built `lib/`) is that artifact-plane fallback, not source.
  171. */
  172. function validateSourcePlaneResolution(): string[] {
  173. const violations: string[] = []
  174. const localPackages = localPackageDirectories()
  175. const config = ts.readConfigFile(resolve(root, 'tsconfig.base.json'), path => ts.sys.readFile(path))
  176. if (config.error !== undefined) {
  177. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  178. }
  179. const { options, errors: optionErrors } = ts.convertCompilerOptionsFromJson(
  180. (config.config as { compilerOptions?: unknown }).compilerOptions,
  181. root,
  182. 'tsconfig.base.json',
  183. )
  184. if (optionErrors.length > 0) {
  185. throw new Error(optionErrors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  186. }
  187. // convertCompilerOptionsFromJson leaves `pathsBasePath` unset, so relative
  188. // `paths` targets resolve against the host's current directory; anchor it to
  189. // the repository root to keep the gate cwd-independent.
  190. const host: ts.ModuleResolutionHost = {
  191. fileExists: path => ts.sys.fileExists(path),
  192. readFile: path => ts.sys.readFile(path),
  193. directoryExists: path => ts.sys.directoryExists(path),
  194. getCurrentDirectory: () => root,
  195. }
  196. const sourceExtensions = new Set<string>([ts.Extension.Ts, ts.Extension.Tsx])
  197. const containingFile = resolve(root, 'scripts/verify-cordis-config.ts')
  198. const locationsBySpecifier = new Map<string, Set<string>>()
  199. for (const reference of pluginReferences) {
  200. const packageName = packageNameFromSpecifier(reference.name)
  201. if (packageName === undefined || !localPackages.has(packageName)) continue
  202. const locations = locationsBySpecifier.get(reference.name) ?? new Set<string>()
  203. locations.add(reference.file)
  204. locationsBySpecifier.set(reference.name, locations)
  205. }
  206. for (const [specifier, locations] of locationsBySpecifier) {
  207. const resolved = ts.resolveModuleName(specifier, containingFile, options, host).resolvedModule
  208. if (resolved !== undefined && sourceExtensions.has(resolved.extension)) continue
  209. violations.push(`${[...locations].join(', ')}: ${specifier} does not resolve to workspace source through tsconfig.base.json paths (add a mapping so the tsx source launch does not depend on built lib/)`)
  210. }
  211. return violations
  212. }
  213. function missingPluginDependencies(
  214. references: readonly PluginReference[],
  215. dependencies: Readonly<Record<string, string>>,
  216. manifestPath: string,
  217. ): string[] {
  218. const requiredPackages = new Map<string, Set<string>>()
  219. const require = (packageName: string, file: string): void => {
  220. const locations = requiredPackages.get(packageName) ?? new Set<string>()
  221. locations.add(file)
  222. requiredPackages.set(packageName, locations)
  223. }
  224. for (const reference of references) {
  225. const packageName = packageNameFromSpecifier(reference.name)
  226. if (packageName === undefined) continue
  227. require(packageName, reference.file)
  228. if (packageName === CHOOSER_PACKAGE) {
  229. for (const backend of CHOOSER_BACKEND_PACKAGES) require(backend, reference.file)
  230. }
  231. }
  232. return [...requiredPackages].flatMap(([packageName, locations]) => packageName in dependencies
  233. ? []
  234. : `${[...locations].join(', ')}: ${packageName} must be declared in ${manifestPath} dependencies`)
  235. }
  236. function readManifest(path: string): PackageManifest {
  237. return JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
  238. }
  239. function localPackageDirectories(): Map<string, string> {
  240. const manifests = globSync(['packages/*/*/package.json', 'vendor/*/package.json'], { cwd: root })
  241. const packages = new Map<string, string>()
  242. for (const manifestPath of manifests) {
  243. const manifest = readManifest(manifestPath)
  244. if (manifest.name !== undefined) packages.set(manifest.name, resolve(root, dirname(manifestPath)))
  245. }
  246. return packages
  247. }
  248. function rootProjectReferences(): Set<string> {
  249. // The root solution references the host and client aggregates (the two
  250. // sides merge cordis Context under the same keys, so one program cannot see
  251. // both — but this BFS only collects reference paths, it never forms a
  252. // program). Seed the solution and follow nested aggregate references to
  253. // collect the covered leaf project set.
  254. const collected = new Set<string>()
  255. const queue = [resolve(root, 'tsconfig.json')]
  256. const seen = new Set<string>()
  257. for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
  258. if (seen.has(file)) continue
  259. seen.add(file)
  260. const config = ts.readConfigFile(file, path => ts.sys.readFile(path))
  261. if (config.error !== undefined) {
  262. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  263. }
  264. const references = (config.config as { references?: Array<{ path?: unknown }> }).references ?? []
  265. for (const reference of references) {
  266. if (typeof reference.path !== 'string') continue
  267. const target = resolve(dirname(file), reference.path)
  268. if (target.endsWith('.json')) queue.push(target)
  269. else collected.add(target)
  270. }
  271. }
  272. return collected
  273. }
  274. function packageNameFromSpecifier(specifier: string): string | undefined {
  275. if (specifier.startsWith('.') || specifier.startsWith('/') || /^[a-z][a-z+.-]*:/i.test(specifier)) return undefined
  276. const segments = specifier.split('/')
  277. if (specifier.startsWith('@')) {
  278. return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : undefined
  279. }
  280. return segments[0] || undefined
  281. }
  282. function validateMetadata(entry: Record<string, unknown>, file: string, path: string): void {
  283. for (const field of metadataFields) {
  284. if (!(field in entry)) continue
  285. const expressionPaths: string[] = []
  286. collectExpressionPaths(entry[field], `${path}.${field}`, expressionPaths)
  287. for (const expressionPath of expressionPaths) errors.push(`${file}${expressionPath}: !!js is not interpolated here`)
  288. }
  289. }
  290. function collectExpressionPaths(value: unknown, path: string, output: string[]): void {
  291. if (isJsExpr(value)) {
  292. output.push(path)
  293. return
  294. }
  295. if (isUnknownArray(value)) {
  296. for (let index = 0; index < value.length; index++) collectExpressionPaths(value[index], `${path}[${index}]`, output)
  297. return
  298. }
  299. if (!isRecord(value)) return
  300. for (const [key, child] of Object.entries(value)) collectExpressionPaths(child, `${path}.${key}`, output)
  301. }
  302. function isJsExpr(value: unknown): value is JsExpr {
  303. return isRecord(value) && typeof value.__jsExpr === 'string'
  304. }
  305. function isRecord(value: unknown): value is Record<string, unknown> {
  306. return value !== null && typeof value === 'object'
  307. }
  308. function isUnknownArray(value: unknown): value is unknown[] {
  309. return Array.isArray(value)
  310. }