test-invariants.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. /**
  2. * Vitest-wide invariant host. Ordinary Cordis roots receive the invariant
  3. * service with global enablement plus the current test package's companion.
  4. * One topology test mounts every companion; focused invariant tests own their
  5. * service topology explicitly.
  6. */
  7. import { expect } from 'vitest'
  8. import { RegistryService } from 'cordis'
  9. import type { Context, Plugin } from 'cordis'
  10. import InvariantService from '@deepseek-ai/dsh-invariants'
  11. declare global {
  12. interface ImportMeta {
  13. /** Lazy Vite module-glob expansion used by the Vitest setup file. */
  14. glob<TModule>(pattern: string): Record<string, () => Promise<TModule>>
  15. }
  16. }
  17. /** Loader-safe shape shared by every package invariant companion. */
  18. export interface TestInvariantCompanion {
  19. readonly name: string
  20. readonly inject: readonly string[]
  21. readonly default?: unknown
  22. apply(ctx: Context): Promise<() => void>
  23. }
  24. /**
  25. * Every package companion as a lazy loader keyed by glob path. Ordinary tests
  26. * load only their owner's module; the exhaustive topology test loads and
  27. * executes all of them, so aggregated coverage still observes every
  28. * registration while per-file setup stops importing 168 companions and their
  29. * transitive package sources.
  30. */
  31. export const testInvariantCompanions: Readonly<Record<string, () => Promise<TestInvariantCompanion>>> =
  32. import.meta.glob<TestInvariantCompanion>('../packages/*/*/src/invariant.ts')
  33. /** Manual-topology suites whose names cannot follow the focused invariant convention. */
  34. const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
  35. '/packages/support/invariants/tests/service.spec.ts',
  36. '/packages/examples/agent-spine-demo/tests/agent-core.spec.ts',
  37. ] as const
  38. interface InvariantHost {
  39. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  40. readonly ready: Promise<void>
  41. }
  42. type PluginFiber = ReturnType<RegistryService['plugin']>
  43. const hosts = new WeakMap<Context, InvariantHost>()
  44. // oxlint-disable-next-line typescript/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  45. const originalPlugin = RegistryService.prototype.plugin
  46. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  47. const testPath = expect.getState().testPath ?? ''
  48. if (usesManualInvariantTree(testPath)) return originalPlugin.call(this, plugin, config, getOuterStack)
  49. const root = this.ctx.root
  50. const host = hosts.get(root) ?? startInvariantHost(root)
  51. const callback = this.resolve(plugin)
  52. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  53. if (existing !== undefined) {
  54. return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
  55. }
  56. const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
  57. // A root-level await is the test's composition boundary. Nested plugin
  58. // fibers must not await their own companion parent through the global host.
  59. if (this.ctx !== root) return fiber
  60. return joinInvariantStartup(fiber, host.ready)
  61. }
  62. /**
  63. * Detect focused suites that construct service selection or companion lifecycle explicitly.
  64. * @param testPath - absolute or repo-relative Vitest file path.
  65. * @returns whether the global invariant host must leave the root untouched.
  66. */
  67. export function usesManualInvariantTree(testPath: string): boolean {
  68. const normalized = testPath.replaceAll('\\', '/')
  69. if (/\/packages\/[^/]+\/[^/]+\/tests\/[^/]*invariant[^/]*\.spec\.ts$/.test(normalized)) return true
  70. return MANUAL_INVARIANT_TEST_EXCEPTIONS.some(path => normalized.endsWith(path))
  71. }
  72. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  73. /**
  74. * Select the package companions that an ordinary test root must register.
  75. * Package tests receive their owner's checks; the dedicated topology test
  76. * receives every owner so coverage and exhaustive runtime registration remain
  77. * independently enforced.
  78. * @param testPath - absolute or repo-relative normalized Vitest file path.
  79. * @returns sorted `import.meta.glob` keys for companions to mount.
  80. */
  81. export function testInvariantCompanionPaths(testPath: string): string[] {
  82. const normalized = testPath.replaceAll('\\', '/')
  83. const allPaths = Object.keys(testInvariantCompanions).sort()
  84. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  85. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  86. if (owner === null) return []
  87. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  88. if (testInvariantCompanions[companionPath] === undefined) {
  89. throw new Error(`test invariants: package test has no companion at ${companionPath}`)
  90. }
  91. return [companionPath]
  92. }
  93. function startInvariantHost(root: Context): InvariantHost {
  94. const byCallback = new Map<unknown, PluginFiber>()
  95. const mount = (plugin: Plugin, config?: unknown): PluginFiber => {
  96. const fiber = originalPlugin.call(root.registry, plugin, config)
  97. const callback = root.registry.resolve(plugin)
  98. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  99. byCallback.set(callback, fiber)
  100. return fiber
  101. }
  102. // The service mounts synchronously so the intercepted registration that
  103. // started this host immediately finds its own fiber in byCallback.
  104. // Companions load and mount inside the ready chain (after the service is
  105. // active, so their startup is directly joinable); every joined root plugin
  106. // awaits ready, so none starts ahead of its package checks. Tests plugging
  107. // a companion directly must await an earlier root plugin first — the
  108. // duplicate-mount failure otherwise is loud (owner name already reserved).
  109. const serviceFiber = mount(InvariantService, { enabled: true })
  110. const testPath = expect.getState().testPath ?? ''
  111. const companionPaths = testInvariantCompanionPaths(testPath)
  112. const ready = serviceFiber.await().then(async () => {
  113. const companionFibers = await Promise.all(companionPaths.map(async (path) => {
  114. const load = testInvariantCompanions[path]
  115. if (load === undefined) {
  116. throw new Error(`test invariants: selected companion vanished at ${path}`)
  117. }
  118. const companion = await load()
  119. if (!companion.inject.includes('invariants')) {
  120. throw new Error(`test invariants: ${path} must inject the invariant service`)
  121. }
  122. return mount(companion)
  123. }))
  124. await Promise.all(companionFibers.map(fiber => fiber.await()))
  125. })
  126. const host = { byCallback, ready }
  127. hosts.set(root, host)
  128. return host
  129. }
  130. function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
  131. const readiness = fiber.await().then(async (loaded) => {
  132. await invariantReady
  133. return loaded
  134. })
  135. const joined = Object.create(fiber) as PluginFiber
  136. joined.then = readiness.then.bind(readiness)
  137. return joined
  138. }