verify-client-domain-graph.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /**
  2. * Enforce intra-package domain layering inside `packages/client/*\/src/client/`.
  3. * verify-module-graph covers package-level edges; this gate covers the
  4. * directory level: domain directories may import `contract/` and never each
  5. * other, and only the assembly point (`apply.ts` / `index.ts`) may import
  6. * across domains.
  7. *
  8. * Layer model (lower may not import higher):
  9. * 0 contract/ shared contract API (types + slot declarations)
  10. * 1 <domain>/ + service domain implementations (skeleton/, chat/, ...)
  11. * 2 apply.ts, index.ts assembly point and re-export shell
  12. *
  13. * Run directly:
  14. * pnpm exec tsx scripts/verify-client-domain-graph.ts
  15. */
  16. import { globSync, readdirSync, readFileSync, statSync } from 'node:fs'
  17. import { join, posix, resolve, sep } from 'node:path'
  18. const root = resolve(import.meta.dirname, '..')
  19. const CLIENT_DIR = join(root, 'packages/client')
  20. /** Directory names treated as the shared contract layer (importable by all). */
  21. const CONTRACT_DIRS = new Set(['contract'])
  22. /** Top-level client files allowed to import across domains (assembly layer). */
  23. const ASSEMBLY_FILES = new Set(['apply.ts', 'index.ts', 'index.tsx'])
  24. interface Violation { file: string; imported: string; reason: string }
  25. /** Recursively list .ts/.tsx files under dir (relative paths). */
  26. function listSources(dir: string): string[] {
  27. return globSync('**/*.{ts,tsx}', { cwd: dir })
  28. .map(rel => rel.split(sep).join('/'))
  29. .filter(rel => !/\.legacy\./.test(rel.slice(rel.lastIndexOf('/') + 1)))
  30. .sort()
  31. }
  32. /** First path segment of a client-relative file, or '' for top-level files. */
  33. function domainOf(rel: string): string {
  34. const ix = rel.indexOf('/')
  35. return ix === -1 ? '' : rel.slice(0, ix)
  36. }
  37. /**
  38. * Resolve one relative import to a client-directory-relative path.
  39. * @param file - Importing file relative to `src/client`.
  40. * @param specifier - Relative module specifier from that file.
  41. * @returns Normalized path, preserving leading `..` segments outside `src/client`.
  42. */
  43. export function resolveClientImport(file: string, specifier: string): string {
  44. return posix.normalize(posix.join(posix.dirname(file), specifier))
  45. }
  46. function checkPackage(pkgName: string, clientDir: string): Violation[] {
  47. const violations: Violation[] = []
  48. const files = listSources(clientDir)
  49. for (const rel of files) {
  50. const fromDomain = domainOf(rel)
  51. const isAssembly = fromDomain === '' && ASSEMBLY_FILES.has(rel)
  52. if (isAssembly) continue
  53. const source = readFileSync(join(clientDir, rel), 'utf8')
  54. for (const match of source.matchAll(/from\s+['"](\.[^'"]+)['"]/g)) {
  55. const spec = match[1]
  56. if (spec === undefined) continue
  57. const target = resolveClientImport(rel, spec)
  58. if (target === '..' || target.startsWith('../')) continue // package-level rules govern
  59. const toDomain = domainOf(target)
  60. if (toDomain === '' || CONTRACT_DIRS.has(toDomain)) continue // top-level shared file or contract layer
  61. if (fromDomain === toDomain) continue // inside one domain
  62. violations.push({
  63. file: `${pkgName}/src/client/${rel}`,
  64. imported: spec,
  65. reason: fromDomain === ''
  66. ? `top-level non-assembly file imports domain "${toDomain}" (only apply/index may assemble)`
  67. : `domain "${fromDomain}" imports sibling domain "${toDomain}" (route shared API through contract/)`,
  68. })
  69. }
  70. }
  71. return violations
  72. }
  73. function main(): void {
  74. const violations: Violation[] = []
  75. for (const pkg of readdirSync(CLIENT_DIR)) {
  76. const clientDir = join(CLIENT_DIR, pkg, 'src/client')
  77. try {
  78. if (!statSync(clientDir).isDirectory()) continue
  79. } catch {
  80. // No client half in this package — nothing to layer-check.
  81. continue
  82. }
  83. violations.push(...checkPackage(pkg, clientDir))
  84. }
  85. if (violations.length > 0) {
  86. console.error(`verify-client-domain-graph: ${violations.length} violation(s):`)
  87. for (const v of violations) console.error(` ${v.file} -> ${v.imported}\n ${v.reason}`)
  88. process.exitCode = 1
  89. return
  90. }
  91. console.log('verify-client-domain-graph: client domain layering clean.')
  92. }
  93. if (import.meta.filename === resolve(process.argv[1] ?? '')) main()