index.ts 4.3 KB

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