invariant.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /** Package-owned scoped-dispatch invariants. @module @deepseek-ai/dsh-scope/invariant */
  2. import type { Context } from 'cordis'
  3. import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  4. import { carrierKeyOf, isScopeCarrier } from '@deepseek-ai/dsh-scope'
  5. import { scopedSubjectResolverFor } from './scoped-events.generated.ts'
  6. const PACKAGE_NAME = '@deepseek-ai/dsh-scope'
  7. /** Cordis companion plugin name. */
  8. export const name = 'scope-invariant'
  9. /** Services required before the companion can register. */
  10. export const inject = ['invariants']
  11. /** Install the scoped-dispatch contribution into its child registration fiber. */
  12. const install: InvariantInstaller = (ctx, fail) => {
  13. ctx.on('internal/dispatch', (_mode, eventName, args, thisArg) => {
  14. const subjectOf = scopedSubjectResolverFor(eventName)
  15. if (subjectOf === undefined) return
  16. if (!isScopeCarrier(thisArg)) {
  17. fail(
  18. `"${eventName}" is a scope-filtered event but was dispatched without a scope carrier — `
  19. + 'pass scopeTarget(base, subject) as the dispatch thisArg (agent events: use agentEvents(ctx, agent))',
  20. )
  21. }
  22. if (subjectOf !== null && carrierKeyOf(thisArg) !== subjectOf(args)) {
  23. fail(
  24. `"${eventName}" was dispatched with a scope carrier keyed to a DIFFERENT subject than its arguments name — `
  25. + 'the carrier key and the event\'s subject must be the same object (use agentEvents(ctx, agent))',
  26. )
  27. }
  28. }, { global: true })
  29. }
  30. /**
  31. * Register the scope invariant companion.
  32. * @param ctx - Cordis context carrying the invariant service.
  33. * @returns the installed registration's disposer after setup succeeds.
  34. */
  35. export const apply = (ctx: Context): Promise<() => void> =>
  36. Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))