test-invariants.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. /** Eager Vite module-glob expansion used by the Vitest setup file. */
  14. glob<TModule>(pattern: string, options: { eager: true }): Record<string, 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. /** Every package companion, discovered eagerly so coverage observes each registration. */
  25. export const testInvariantCompanions: Readonly<Record<string, TestInvariantCompanion>> =
  26. import.meta.glob<TestInvariantCompanion>('../packages/*/*/src/invariant.ts', { eager: true })
  27. /** Manual-topology suites whose names cannot follow the focused invariant convention. */
  28. const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
  29. '/packages/support/invariants/tests/service.spec.ts',
  30. '/packages/examples/agent-spine-demo/tests/agent-core.spec.ts',
  31. ] as const
  32. interface InvariantHost {
  33. readonly fibers: readonly PluginFiber[]
  34. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  35. readonly ready: Promise<void>
  36. }
  37. type PluginFiber = ReturnType<RegistryService['plugin']>
  38. const hosts = new WeakMap<Context, InvariantHost>()
  39. // eslint-disable-next-line @typescript-eslint/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  40. const originalPlugin = RegistryService.prototype.plugin
  41. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  42. const testPath = expect.getState().testPath ?? ''
  43. if (usesManualInvariantTree(testPath)) return originalPlugin.call(this, plugin, config, getOuterStack)
  44. const root = this.ctx.root
  45. const host = hosts.get(root) ?? startInvariantHost(root)
  46. const callback = this.resolve(plugin)
  47. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  48. if (existing !== undefined) {
  49. return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
  50. }
  51. const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
  52. // A root-level await is the test's composition boundary. Nested plugin
  53. // fibers must not await their own companion parent through the global host.
  54. if (this.ctx !== root) return fiber
  55. return joinInvariantStartup(fiber, host.ready)
  56. }
  57. /**
  58. * Detect focused suites that construct service selection or companion lifecycle explicitly.
  59. * @param testPath - absolute or repo-relative Vitest file path.
  60. * @returns whether the global invariant host must leave the root untouched.
  61. */
  62. export function usesManualInvariantTree(testPath: string): boolean {
  63. const normalized = testPath.replaceAll('\\', '/')
  64. if (/\/packages\/[^/]+\/[^/]+\/tests\/[^/]*invariant[^/]*\.spec\.ts$/.test(normalized)) return true
  65. return MANUAL_INVARIANT_TEST_EXCEPTIONS.some(path => normalized.endsWith(path))
  66. }
  67. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  68. /**
  69. * Select the package companions that an ordinary test root must register.
  70. * Package tests receive their owner's checks; the dedicated topology test
  71. * receives every owner so coverage and exhaustive runtime registration remain
  72. * independently enforced.
  73. * @param testPath - absolute or repo-relative normalized Vitest file path.
  74. * @returns sorted `import.meta.glob` keys for companions to mount.
  75. */
  76. export function testInvariantCompanionPaths(testPath: string): string[] {
  77. const normalized = testPath.replaceAll('\\', '/')
  78. const allPaths = Object.keys(testInvariantCompanions).sort()
  79. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  80. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  81. if (owner === null) return []
  82. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  83. if (testInvariantCompanions[companionPath] === undefined) {
  84. throw new Error(`test invariants: package test has no companion at ${companionPath}`)
  85. }
  86. return [companionPath]
  87. }
  88. function startInvariantHost(root: Context): InvariantHost {
  89. const fibers: PluginFiber[] = []
  90. const byCallback = new Map<unknown, PluginFiber>()
  91. const mount = (plugin: Plugin, config?: unknown): void => {
  92. const fiber = originalPlugin.call(root.registry, plugin, config)
  93. const callback = root.registry.resolve(plugin)
  94. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  95. fibers.push(fiber)
  96. byCallback.set(callback, fiber)
  97. }
  98. mount(InvariantService, { enabled: true })
  99. const testPath = expect.getState().testPath ?? ''
  100. const companionPaths = testInvariantCompanionPaths(testPath)
  101. for (const path of companionPaths) {
  102. const companion = testInvariantCompanions[path]
  103. if (companion === undefined) {
  104. throw new Error(`test invariants: selected companion vanished at ${path}`)
  105. }
  106. if (!companion.inject.includes('invariants')) {
  107. throw new Error(`test invariants: ${path} must inject the invariant service`)
  108. }
  109. mount(companion)
  110. }
  111. const [serviceFiber, ...companionFibers] = fibers
  112. if (serviceFiber === undefined) throw new Error('test invariants: service fiber was not mounted')
  113. // A companion is initially PENDING on the invariant service, and Cordis
  114. // Fiber.await() only joins work already in flight. Wait for the service to
  115. // activate its dependants before joining their startup and failures.
  116. const ready = serviceFiber.await()
  117. .then(() => Promise.all(companionFibers.map(fiber => fiber.await())))
  118. .then(() => undefined)
  119. const host = { fibers, byCallback, ready }
  120. hosts.set(root, host)
  121. return host
  122. }
  123. function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
  124. const readiness = fiber.await().then(async (loaded) => {
  125. await invariantReady
  126. return loaded
  127. })
  128. const joined = Object.create(fiber) as PluginFiber
  129. joined.then = readiness.then.bind(readiness)
  130. return joined
  131. }