verify-cordis-config.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /**
  2. * Validate Cordis Loader entry metadata and example 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 run from built packages, so every named package must resolve
  7. * from the examples workspace and every local package must 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. const metadataFields = ['id', 'name', 'group', 'disabled', 'inject', 'intercept', 'isolate'] as const
  28. const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
  29. kind: 'scalar',
  30. resolve: data => typeof data === 'string',
  31. construct: (data: unknown): JsExpr => {
  32. if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string')
  33. return { __jsExpr: data }
  34. },
  35. })
  36. const schema = yaml.JSON_SCHEMA.extend(jsExprType)
  37. const files = cordisConfigFiles(root)
  38. const errors: string[] = []
  39. const examplePluginReferences: PluginReference[] = []
  40. for (const file of files) {
  41. const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
  42. if (!isUnknownArray(document)) {
  43. errors.push(`${file}: root must be a Loader entry array`)
  44. continue
  45. }
  46. for (let index = 0; index < document.length; index++) {
  47. validateEntry(document[index], file, `[${index}]`)
  48. }
  49. }
  50. errors.push(...validateExampleResolution())
  51. if (errors.length > 0) {
  52. console.error('verify-cordis-config: invalid Loader metadata or example package resolution:')
  53. for (const error of errors) console.error(`- ${error}`)
  54. process.exitCode = 1
  55. } else {
  56. console.log(`verify-cordis-config: ${files.length} config files passed.`)
  57. }
  58. function validateEntry(value: unknown, file: string, path: string): void {
  59. if (!isRecord(value)) {
  60. errors.push(`${file}${path}: entry must be an object`)
  61. return
  62. }
  63. recordExamplePlugin(value, file)
  64. validateMetadata(value, file, path)
  65. if ((value.group === true || value.name === '@cordisjs/plugin-group') && isUnknownArray(value.config)) {
  66. for (let index = 0; index < value.config.length; index++) {
  67. validateEntry(value.config[index], file, `${path}.config[${index}]`)
  68. }
  69. }
  70. if (value.name !== '@cordisjs/plugin-include') return
  71. const config = value.config
  72. if (!isRecord(config) || !isUnknownArray(config.patches)) return
  73. for (let index = 0; index < config.patches.length; index++) {
  74. const patch = config.patches[index]
  75. const patchPath = `${path}.config.patches[${index}]`
  76. if (!isRecord(patch)) continue
  77. recordExamplePlugin(patch, file)
  78. validateMetadata(patch, file, patchPath)
  79. if (!isUnknownArray(patch.insert)) continue
  80. for (let insertIndex = 0; insertIndex < patch.insert.length; insertIndex++) {
  81. validateEntry(patch.insert[insertIndex], file, `${patchPath}.insert[${insertIndex}]`)
  82. }
  83. }
  84. }
  85. function recordExamplePlugin(entry: Record<string, unknown>, file: string): void {
  86. if (file.startsWith('examples/') && typeof entry.name === 'string') {
  87. examplePluginReferences.push({ file, name: entry.name })
  88. }
  89. }
  90. function validateExampleResolution(): string[] {
  91. const violations: string[] = []
  92. const exampleManifest = readManifest('examples/package.json')
  93. const dependencies = exampleManifest.dependencies ?? {}
  94. const localPackages = localPackageDirectories()
  95. const rootReferences = rootProjectReferences()
  96. const requiredPackages = new Map<string, Set<string>>()
  97. for (const reference of examplePluginReferences) {
  98. const packageName = packageNameFromSpecifier(reference.name)
  99. if (packageName === undefined) continue
  100. const locations = requiredPackages.get(packageName) ?? new Set<string>()
  101. locations.add(reference.file)
  102. requiredPackages.set(packageName, locations)
  103. }
  104. for (const [packageName, locations] of requiredPackages) {
  105. if (!(packageName in dependencies)) {
  106. violations.push(`${[...locations].join(', ')}: ${packageName} must be declared in examples/package.json dependencies`)
  107. }
  108. }
  109. const localExamplePackages = new Set([
  110. ...Object.keys(dependencies),
  111. ...requiredPackages.keys(),
  112. ])
  113. for (const packageName of localExamplePackages) {
  114. const packageDirectory = localPackages.get(packageName)
  115. if (packageDirectory === undefined || rootReferences.has(packageDirectory)) continue
  116. const repoPath = relative(root, packageDirectory).replaceAll('\\', '/')
  117. violations.push(`tsconfig.json: missing project reference for ${packageName} (${repoPath})`)
  118. }
  119. return violations
  120. }
  121. function readManifest(path: string): PackageManifest {
  122. return JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
  123. }
  124. function localPackageDirectories(): Map<string, string> {
  125. const manifests = globSync(['packages/*/*/package.json', 'vendor/*/package.json'], { cwd: root })
  126. const packages = new Map<string, string>()
  127. for (const manifestPath of manifests) {
  128. const manifest = readManifest(manifestPath)
  129. if (manifest.name !== undefined) packages.set(manifest.name, resolve(root, dirname(manifestPath)))
  130. }
  131. return packages
  132. }
  133. function rootProjectReferences(): Set<string> {
  134. // The root solution references the host and client aggregates (the two
  135. // sides merge cordis Context under the same keys, so one program cannot see
  136. // both — but this BFS only collects reference paths, it never forms a
  137. // program). Seed the solution and follow nested aggregate references to
  138. // collect the covered leaf project set.
  139. const collected = new Set<string>()
  140. const queue = [resolve(root, 'tsconfig.json')]
  141. const seen = new Set<string>()
  142. for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
  143. if (seen.has(file)) continue
  144. seen.add(file)
  145. const config = ts.readConfigFile(file, path => ts.sys.readFile(path))
  146. if (config.error !== undefined) {
  147. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  148. }
  149. const references = (config.config as { references?: Array<{ path?: unknown }> }).references ?? []
  150. for (const reference of references) {
  151. if (typeof reference.path !== 'string') continue
  152. const target = resolve(dirname(file), reference.path)
  153. if (target.endsWith('.json')) queue.push(target)
  154. else collected.add(target)
  155. }
  156. }
  157. return collected
  158. }
  159. function packageNameFromSpecifier(specifier: string): string | undefined {
  160. if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('file:')) return undefined
  161. const segments = specifier.split('/')
  162. if (specifier.startsWith('@')) {
  163. return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : undefined
  164. }
  165. return segments[0] || undefined
  166. }
  167. function validateMetadata(entry: Record<string, unknown>, file: string, path: string): void {
  168. for (const field of metadataFields) {
  169. if (!(field in entry)) continue
  170. const expressionPaths: string[] = []
  171. collectExpressionPaths(entry[field], `${path}.${field}`, expressionPaths)
  172. for (const expressionPath of expressionPaths) errors.push(`${file}${expressionPath}: !!js is not interpolated here`)
  173. }
  174. }
  175. function collectExpressionPaths(value: unknown, path: string, output: string[]): void {
  176. if (isJsExpr(value)) {
  177. output.push(path)
  178. return
  179. }
  180. if (isUnknownArray(value)) {
  181. for (let index = 0; index < value.length; index++) collectExpressionPaths(value[index], `${path}[${index}]`, output)
  182. return
  183. }
  184. if (!isRecord(value)) return
  185. for (const [key, child] of Object.entries(value)) collectExpressionPaths(child, `${path}.${key}`, output)
  186. }
  187. function isJsExpr(value: unknown): value is JsExpr {
  188. return isRecord(value) && typeof value.__jsExpr === 'string'
  189. }
  190. function isRecord(value: unknown): value is Record<string, unknown> {
  191. return value !== null && typeof value === 'object'
  192. }
  193. function isUnknownArray(value: unknown): value is unknown[] {
  194. return Array.isArray(value)
  195. }