invariant.spec.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Runtime invariant companion: the 'slots/changed' emission-order audit —
  3. * a fired key must already carry a bumped version (emission follows the
  4. * applied mutation), bogus payloads fail loud, foreign events pass.
  5. */
  6. import { Context } from 'cordis'
  7. import { describe, expect, it } from 'vitest'
  8. import InvariantService from '@deepseek-ai/dsh-invariants'
  9. import * as RuntimeInvariant from '../src/invariant.ts'
  10. import { SlotsService } from '../src/client/slots.ts'
  11. async function setup(): Promise<Context> {
  12. const ctx = new Context()
  13. await ctx.plugin(InvariantService, { enabled: true })
  14. await ctx.plugin(RuntimeInvariant).await()
  15. return ctx
  16. }
  17. const emit = (ctx: Context, event: string, ...args: unknown[]): void => {
  18. ;(ctx.emit as (event: string, ...args: unknown[]) => void)(event, ...args)
  19. }
  20. describe('runtime slots/changed invariant', () => {
  21. it('passes foreign events and a legitimate mutation-then-emission sequence', async () => {
  22. const ctx = await setup()
  23. expect(() => { emit(ctx, 'unrelated/event', 'x') }).not.toThrow()
  24. await ctx.plugin(SlotsService).await() // fiber must reach ACTIVE — the audit reads strict ctx.get
  25. // A real registration bumps the version first and re-emits through
  26. // onMutate — the audit sees version > 0 and stays quiet. (Erased call:
  27. // the typed register face rides the wave-1 ui-slots types.)
  28. const slots = ctx.slots as unknown as { register(options: object, component: unknown): () => void }
  29. expect(() => slots.register({ name: 'root' }, () => null)).not.toThrow()
  30. })
  31. it('fails loud on a missing key and on an emission with no applied mutation', async () => {
  32. const ctx = await setup()
  33. expect(() => { emit(ctx, 'slots/changed', '') }).toThrow(/without a slot key/)
  34. expect(() => { emit(ctx, 'slots/changed', 42) }).toThrow(/without a slot key/)
  35. await ctx.plugin(SlotsService).await()
  36. // Hand-emitted key that never saw a mutation: version 0 → violation.
  37. expect(() => { emit(ctx, 'slots/changed', 'never-mutated') })
  38. .toThrow(/before any mutation bumped its version/)
  39. })
  40. it('stays quiet when no slots service is mounted (nothing to audit against)', async () => {
  41. const ctx = await setup()
  42. expect(() => { emit(ctx, 'slots/changed', 'any-key') }).not.toThrow()
  43. })
  44. })