index.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /**
  2. * Scoped-context primitive: mint a Cordis context that tags registrations with
  3. * an opaque identity and build routing-only event carriers for that identity.
  4. *
  5. * @module @deepseek-ai/dsh-scope
  6. */
  7. import type { Context, Fiber } from 'cordis'
  8. import { Context as CordisContext } from 'cordis'
  9. /** An opaque, identity-compared scope key. */
  10. export type ScopeKey = object
  11. /** Context tag written by {@link createScope}. */
  12. const kScope = Symbol('dsh.scope')
  13. declare const ScopedBrand: unique symbol
  14. /**
  15. * A routing-only event receiver built by {@link scopeTarget}. The type
  16. * parameter records the subject type for dispatch checking; the carrier does
  17. * not expose the subject's properties. Event payloads carry the real subject.
  18. */
  19. export type Scoped<T extends object> = object & { readonly [ScopedBrand]: T }
  20. /** The key associated with each carrier. Presence distinguishes an unkeyed carrier from a non-carrier. */
  21. const carrierKeys = new WeakMap<object, ScopeKey | undefined>()
  22. /** A minted registration scope and its quiescent disposal boundaries. */
  23. export interface Scope {
  24. /** Context through which scope-owned registrations are made. */
  25. ctx: Context
  26. /** Exact Cordis disposer, used when nesting this scope in an ordered composite effect. */
  27. rawDispose: () => Promise<void> | void
  28. /** Dispose every scope-owned registration; racing calls await the same completion. */
  29. dispose(): Promise<void>
  30. }
  31. /** Follow a Cordis fiber through asynchronous teardown even if its raw disposer was already claimed. */
  32. async function quiesceFiber(fiber: Fiber): Promise<void> {
  33. await Promise.resolve(fiber.dispose())
  34. while (fiber.inertia !== undefined) await fiber.inertia
  35. }
  36. /** Shared no-op plugin used as the backing scope fiber. */
  37. function scope(): void {}
  38. /**
  39. * Mint a scope under `ctx`. The scoped context inherits the minting plugin's
  40. * dependency surface and owns every registration made through it.
  41. * @param ctx - active context whose dependency surface the scope inherits.
  42. * @param key - opaque identity used for listener routing.
  43. * @returns the scoped context and exact/shared disposal boundaries.
  44. */
  45. export function createScope(ctx: Context, key: ScopeKey): Scope {
  46. const fiber = ctx.plugin(scope)
  47. const scoped: Context = fiber.ctx.extend({ [kScope]: key })
  48. let disposing: Promise<void> | undefined
  49. return {
  50. ctx: scoped,
  51. rawDispose: fiber.dispose,
  52. dispose: () => (disposing ??= quiesceFiber(fiber)),
  53. }
  54. }
  55. /**
  56. * Read the nearest scope tag inherited by a context.
  57. * @param ctx - context to inspect.
  58. * @returns its scope key, or `undefined` for an unscoped context.
  59. */
  60. export function scopeOf(ctx: Context): ScopeKey | undefined {
  61. return (ctx as Context & { [kScope]?: ScopeKey })[kScope]
  62. }
  63. /**
  64. * Build an opaque receiver that preserves the base filter, admits untagged
  65. * listeners globally, and admits tagged listeners only for a matching key.
  66. * @param base - subject or service whose existing Cordis filter is preserved.
  67. * @param key - routed scope identity, or `undefined` for an unscoped subject.
  68. * @returns a carrier whose subject remains available only through event arguments.
  69. */
  70. export function scopeTarget<T extends object>(base: T, key: ScopeKey | undefined): Scoped<T> {
  71. const baseFilter = (base as { [CordisContext.filter]?: (ctx: Context) => boolean })[CordisContext.filter]
  72. const carrier = {
  73. [CordisContext.filter](ctx: Context): boolean {
  74. if (baseFilter !== undefined && !baseFilter.call(base, ctx)) return false
  75. const tag = scopeOf(ctx)
  76. return tag === undefined || tag === key
  77. },
  78. }
  79. carrierKeys.set(carrier, key)
  80. return carrier as unknown as Scoped<T>
  81. }
  82. /**
  83. * Test whether a value is a scope carrier.
  84. * @param value - dispatch receiver to inspect.
  85. * @returns whether {@link scopeTarget} created it.
  86. */
  87. export function isScopeCarrier(value: unknown): value is Scoped<object> {
  88. return typeof value === 'object' && value !== null && carrierKeys.has(value)
  89. }
  90. /**
  91. * Read a carrier's routing key.
  92. * @param value - dispatch receiver to inspect.
  93. * @returns the carrier key, or `undefined` for an unkeyed/non-carrier value.
  94. */
  95. export function carrierKeyOf(value: unknown): ScopeKey | undefined {
  96. if (!isScopeCarrier(value)) return undefined
  97. return carrierKeys.get(value)
  98. }