better-effect 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +337 -88
  2. package/dist/adapters/iti.d.mts +2 -3
  3. package/dist/adapters/iti.d.mts.map +1 -1
  4. package/dist/adapters/iti.mjs +2 -2
  5. package/dist/bun.d.mts +75 -23
  6. package/dist/bun.d.mts.map +1 -1
  7. package/dist/bun.mjs +170 -33
  8. package/dist/bun.mjs.map +1 -1
  9. package/dist/{context-BphfFUMO.mjs → context-DSGSqcJj.mjs} +12 -3
  10. package/dist/context-DSGSqcJj.mjs.map +1 -0
  11. package/dist/{current-request-DDKNyymv.mjs → current-request-Bc1YHL0w.mjs} +3 -2
  12. package/dist/{current-request-DDKNyymv.mjs.map → current-request-Bc1YHL0w.mjs.map} +1 -1
  13. package/dist/{current-request-CIU7AHhF.d.mts → current-request-Dm-QQ3Xr.d.mts} +4 -4
  14. package/dist/current-request-Dm-QQ3Xr.d.mts.map +1 -0
  15. package/dist/{effect-CPdV7Yv8.mjs → effect-W0IQXY8P.mjs} +21 -2
  16. package/dist/effect-W0IQXY8P.mjs.map +1 -0
  17. package/dist/{errors-BKcsQ0ip.d.mts → errors-CpHMzPiP.d.mts} +6 -2
  18. package/dist/errors-CpHMzPiP.d.mts.map +1 -0
  19. package/dist/hono.d.mts +63 -27
  20. package/dist/hono.d.mts.map +1 -1
  21. package/dist/hono.mjs +111 -45
  22. package/dist/hono.mjs.map +1 -1
  23. package/dist/{index-CCi07kUw.d.mts → index-3Bkl-sxS.d.mts} +7 -2
  24. package/dist/{index-CCi07kUw.d.mts.map → index-3Bkl-sxS.d.mts.map} +1 -1
  25. package/dist/{index-cXgyMa0v.d.mts → index-C2ed9Ilq.d.mts} +32 -7
  26. package/dist/index-C2ed9Ilq.d.mts.map +1 -0
  27. package/dist/{index-BodMy6rO.d.mts → index-ClNndn2-.d.mts} +93 -63
  28. package/dist/index-ClNndn2-.d.mts.map +1 -0
  29. package/dist/{index-DAKn0qHk.d.mts → index-Cy1VsU-u.d.mts} +2 -4
  30. package/dist/index-Cy1VsU-u.d.mts.map +1 -0
  31. package/dist/index.d.mts +6 -8
  32. package/dist/index.mjs +8 -9
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/{internal-identity-CbXoZIfw.mjs → internal-identity-BuHBtP0k.mjs} +2 -2
  35. package/dist/{internal-identity-CbXoZIfw.mjs.map → internal-identity-BuHBtP0k.mjs.map} +1 -1
  36. package/dist/layer-2kjHVv4N.mjs +343 -0
  37. package/dist/layer-2kjHVv4N.mjs.map +1 -0
  38. package/dist/layer-C2OaqTmB.d.mts +987 -0
  39. package/dist/layer-C2OaqTmB.d.mts.map +1 -0
  40. package/dist/next.d.mts +102 -26
  41. package/dist/next.d.mts.map +1 -1
  42. package/dist/next.mjs +157 -40
  43. package/dist/next.mjs.map +1 -1
  44. package/dist/{node-context-DczjAcrX.d.mts → node-context-1YEjrU9g.d.mts} +2 -2
  45. package/dist/{node-context-DczjAcrX.d.mts.map → node-context-1YEjrU9g.d.mts.map} +1 -1
  46. package/dist/{node-context-Ca18oNSg.mjs → node-context-g3bCcY9t.mjs} +2 -2
  47. package/dist/{node-context-Ca18oNSg.mjs.map → node-context-g3bCcY9t.mjs.map} +1 -1
  48. package/dist/node.d.mts +11 -6
  49. package/dist/node.d.mts.map +1 -1
  50. package/dist/node.mjs +156 -10
  51. package/dist/node.mjs.map +1 -1
  52. package/dist/opentelemetry.d.mts +20 -2
  53. package/dist/opentelemetry.d.mts.map +1 -1
  54. package/dist/opentelemetry.mjs +423 -5
  55. package/dist/opentelemetry.mjs.map +1 -1
  56. package/dist/{registration-drnZk0SY.mjs → registration-Bwe2GbVu.mjs} +8 -2
  57. package/dist/registration-Bwe2GbVu.mjs.map +1 -0
  58. package/dist/runtime/explicit.d.mts +2 -2
  59. package/dist/runtime/explicit.mjs +1 -1
  60. package/dist/runtime/node.d.mts +3 -3
  61. package/dist/runtime/node.mjs +2 -2
  62. package/dist/runtime-qpcVwaz_.mjs +1680 -0
  63. package/dist/runtime-qpcVwaz_.mjs.map +1 -0
  64. package/dist/service-CO9VJQYa.mjs +74 -0
  65. package/dist/service-CO9VJQYa.mjs.map +1 -0
  66. package/dist/{signal-nfgFyNCk.mjs → signal-5Rg9bUUe.mjs} +2 -2
  67. package/dist/{signal-nfgFyNCk.mjs.map → signal-5Rg9bUUe.mjs.map} +1 -1
  68. package/dist/{standard-services-vnGIafkS.mjs → standard-services-B-iMM_W7.mjs} +38 -4
  69. package/dist/standard-services-B-iMM_W7.mjs.map +1 -0
  70. package/dist/standard-services.d.mts +4 -4
  71. package/dist/standard-services.mjs +3 -3
  72. package/dist/testing.d.mts +25 -7
  73. package/dist/testing.d.mts.map +1 -1
  74. package/dist/testing.mjs +51 -7
  75. package/dist/testing.mjs.map +1 -1
  76. package/dist/{types-oihI-ESv.d.mts → types-BFTqCCcw.d.mts} +32 -5
  77. package/dist/types-BFTqCCcw.d.mts.map +1 -0
  78. package/dist/web-effect-B9hp9jIe.mjs +380 -0
  79. package/dist/web-effect-B9hp9jIe.mjs.map +1 -0
  80. package/dist/web.d.mts +22 -13
  81. package/dist/web.d.mts.map +1 -1
  82. package/dist/web.mjs +1 -1
  83. package/package.json +10 -16
  84. package/dist/context-BphfFUMO.mjs.map +0 -1
  85. package/dist/current-request-CIU7AHhF.d.mts.map +0 -1
  86. package/dist/disposable-CP-Q2H3l.mjs +0 -57
  87. package/dist/disposable-CP-Q2H3l.mjs.map +0 -1
  88. package/dist/effect-CPdV7Yv8.mjs.map +0 -1
  89. package/dist/errors-BKcsQ0ip.d.mts.map +0 -1
  90. package/dist/index-AiKM71-u.d.mts +0 -376
  91. package/dist/index-AiKM71-u.d.mts.map +0 -1
  92. package/dist/index-BodMy6rO.d.mts.map +0 -1
  93. package/dist/index-DAKn0qHk.d.mts.map +0 -1
  94. package/dist/index-cXgyMa0v.d.mts.map +0 -1
  95. package/dist/layer-D16GKxuX.mjs +0 -269
  96. package/dist/layer-D16GKxuX.mjs.map +0 -1
  97. package/dist/observer-9nhbL7Pr.d.mts +0 -68
  98. package/dist/observer-9nhbL7Pr.d.mts.map +0 -1
  99. package/dist/outcome-DI8LPIQ4.d.mts +0 -387
  100. package/dist/outcome-DI8LPIQ4.d.mts.map +0 -1
  101. package/dist/program-metadata-BxjGkT17.mjs +0 -260
  102. package/dist/program-metadata-BxjGkT17.mjs.map +0 -1
  103. package/dist/registration-drnZk0SY.mjs.map +0 -1
  104. package/dist/runtime-C_55ofnL.mjs +0 -791
  105. package/dist/runtime-C_55ofnL.mjs.map +0 -1
  106. package/dist/standard-services-vnGIafkS.mjs.map +0 -1
  107. package/dist/types-oihI-ESv.d.mts.map +0 -1
  108. package/dist/web-Bq3MfMrj.mjs +0 -147
  109. package/dist/web-Bq3MfMrj.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-qpcVwaz_.mjs","names":["SCOPE_SUCCESS"],"sources":["../src/scope/runtime.ts","../src/scope/internal.ts","../src/scope/scope.ts","../src/layer/map-layer-backend.ts","../src/effect/program-metadata.ts","../src/runtime/observer.ts","../src/runtime/outcome.ts","../src/runtime/task.ts","../src/runtime/executor.ts","../src/layer/resolution.ts","../src/runtime/execution.ts","../src/layer/runtime.ts","../src/runtime/runtime.ts"],"sourcesContent":["import { ScopeRuntimeNotConfiguredError } from './errors'\n\nimport { RuntimeContextNotConfiguredError } from '../runtime/errors'\n\nimport type { Scope } from './scope'\n\nimport {\n activeRuntimeContextStorage,\n currentRuntimeContext,\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext\n} from '../runtime/context'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nconst scopeStorages = new WeakMap<object, RuntimeContextStorage>()\n\n/** Bridges the current Scope through async execution context. */\nexport class ScopeRuntime {\n /** Supply a Scope while invoking a callback. */\n static run<A>(\n scope: Scope,\n program: () => A,\n storage: RuntimeContextStorage = scopeStorages.get(scope) ?? activeRuntimeContextStorage()\n ): A {\n scopeStorages.set(scope, storage)\n\n const current = getRuntimeContext(storage)\n const context = makeRuntimeContext(\n current?.resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal,\n current\n )\n\n return runRuntimeContext(storage, context, program)\n }\n\n /** Return the Scope active in the current execution context. */\n static current(): Scope {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch (cause) {\n if (cause instanceof RuntimeContextNotConfiguredError) {\n throw new ScopeRuntimeNotConfiguredError()\n }\n\n throw cause\n }\n\n if (!context.scope) {\n throw new ScopeRuntimeNotConfiguredError()\n }\n\n return context.scope\n }\n\n /** Associate a Runtime-owned Scope with its context storage. */\n static bind(scope: Scope, storage: RuntimeContextStorage): void {\n scopeStorages.set(scope, storage)\n }\n}\n","import { ScopeCloseError } from './errors'\n\nimport { ScopeRuntime } from './runtime'\n\nimport type { CloseableScope, Scope } from './scope'\n\nimport {\n runRuntimeContext,\n type CompleteRuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from './types'\n\ntype ScopePreFinalizer = (outcome: ScopeOutcome) => MaybePromise<void>\n\ntype ScopeImplementation = {\n readonly addPreFinalizer: (finalizer: ScopePreFinalizer) => void\n}\n\nconst scopeImplementations = new WeakMap<object, ScopeImplementation>()\n\n/** Register the private implementation hook used by lifecycle primitives. */\nexport const registerScopeImplementation = (\n scope: CloseableScope,\n implementation: ScopeImplementation\n): void => {\n scopeImplementations.set(scope, implementation)\n}\n\n/** Register work that must run before attached child Scopes close. */\nexport const addScopePreFinalizer = (scope: Scope, finalizer: ScopePreFinalizer): void => {\n const implementation = scopeImplementations.get(scope)\n\n if (!implementation) {\n throw new TypeError('Scope does not support internal pre-finalizers')\n }\n\n implementation.addPreFinalizer(finalizer)\n}\n\nexport type OutcomeClassifier<A> = (value: A) => ScopeOutcome\n\nexport type RunScopedOptions<A> = {\n readonly classify: OutcomeClassifier<A>\n readonly onOutcome?: (outcome: ScopeOutcome) => void\n readonly onCleanupFailure?: (diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>\n readonly contextStorage?: RuntimeContextStorage\n readonly context?: CompleteRuntimeContext\n}\n\nconst notifyCleanupFailure = async (\n observer: ((diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>) | undefined,\n diagnostic: CleanupFailureDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Cleanup diagnostics are best effort and never affect the primary result.\n }\n}\n\nexport const runScoped = async <A>(\n scope: CloseableScope,\n program: () => A | PromiseLike<A>,\n options: RunScopedOptions<Awaited<A>>\n): Promise<Awaited<A>> => {\n let value!: Awaited<A>\n\n let programFailed = false\n let programFailure: unknown\n\n try {\n const run = () => ScopeRuntime.run(scope, program, options.contextStorage)\n\n value = await (options.context && options.contextStorage\n ? runRuntimeContext(options.contextStorage, options.context, run)\n : run())\n } catch (cause) {\n programFailed = true\n programFailure = cause\n }\n\n let outcome: ScopeOutcome\n let outcomeStatus: ScopeOutcome['status']\n\n if (programFailed) {\n outcome = {\n status: 'failure',\n cause: programFailure\n }\n outcomeStatus = 'failure'\n } else {\n try {\n outcome = options.classify(value)\n // Read the discriminant before cleanup so a throwing classifier or proxy is a program failure.\n outcomeStatus = outcome.status\n } catch (cause) {\n programFailed = true\n programFailure = cause\n outcome = {\n status: 'failure',\n cause\n }\n outcomeStatus = 'failure'\n }\n }\n\n options.onOutcome?.(outcome)\n\n let cleanupFailed = false\n let cleanupFailure: unknown\n\n try {\n await scope.close(outcome)\n } catch (cause) {\n cleanupFailed = true\n cleanupFailure = cause\n }\n\n if (cleanupFailed) {\n const error =\n cleanupFailure instanceof ScopeCloseError\n ? cleanupFailure\n : new ScopeCloseError([cleanupFailure])\n\n await notifyCleanupFailure(options.onCleanupFailure, {\n outcome,\n error\n })\n\n cleanupFailure = error\n }\n\n if (programFailed) {\n throw programFailure\n }\n\n if (outcomeStatus === 'failure') {\n return value\n }\n\n if (cleanupFailed) {\n throw cleanupFailure\n }\n\n return value\n}\n","import { ResourceNotDisposableError, ScopeCloseError, ScopeClosedError } from './errors'\n\nimport { getDisposeFinalizer } from './disposable'\n\nimport { registerScopeImplementation, runScoped } from './internal'\n\nimport { ScopeRuntime } from './runtime'\n\nimport type { DisposableResource, MaybePromise, ScopeFinalizer, ScopeOutcome } from './types'\n\n/**\n * Non-owning lifecycle context for finalizers and child Scopes.\n *\n * A Scope can register cleanup and create children, but it cannot close\n * itself. Use `Scope.make()` or `Scope.run()` when your code owns the Scope.\n */\nexport interface Scope {\n /** Register a finalizer that runs when the owning Scope closes. */\n addFinalizer(finalizer: ScopeFinalizer): void\n\n /** Acquire a resource and register its outcome-aware release callback. */\n acquire<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n ): Promise<R>\n\n /** Register an already-acquired disposable resource. */\n add<R extends DisposableResource>(resource: R): Promise<R>\n\n /** Create a child Scope owned by this Scope. */\n fork(): CloseableScope\n}\n\n/** A Scope whose owner is responsible for calling `close()`. */\nexport interface CloseableScope extends Scope {\n /** Close the Scope and run children and finalizers in child-first LIFO order. */\n close(outcome?: ScopeOutcome): Promise<void>\n}\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass ScopeImpl implements CloseableScope {\n private readonly children = new Set<ScopeImpl>()\n\n private readonly finalizers: ScopeFinalizer[] = []\n\n private readonly preFinalizers: ScopeFinalizer[] = []\n\n private closePromise: Promise<void> | undefined\n\n private closeOutcome: ScopeOutcome | undefined\n\n constructor(private parent?: ScopeImpl) {\n registerScopeImplementation(this, {\n addPreFinalizer: (finalizer) => this.addPreFinalizer(finalizer)\n })\n }\n\n fork(): CloseableScope {\n this.assertOpen()\n\n const child = new ScopeImpl(this)\n\n this.children.add(child)\n\n return child\n }\n\n addFinalizer(finalizer: ScopeFinalizer): void {\n this.assertOpen()\n\n this.finalizers.push(finalizer)\n }\n\n async acquire<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n ): Promise<R> {\n this.assertOpen()\n\n const resource = await acquire()\n\n try {\n this.addFinalizer((outcome) => release(resource, outcome))\n\n return resource\n } catch (scopeFailure) {\n try {\n await release(resource, this.closeOutcome ?? SCOPE_SUCCESS)\n } catch (releaseFailure) {\n throw new AggregateError(\n [scopeFailure, releaseFailure],\n 'Scope closed while acquiring a resource and immediate cleanup also failed'\n )\n }\n\n throw scopeFailure\n }\n }\n\n async add<R extends DisposableResource>(resource: R): Promise<R> {\n const finalizer = getDisposeFinalizer(resource)\n\n if (!finalizer) {\n throw new ResourceNotDisposableError()\n }\n\n try {\n this.addFinalizer(finalizer)\n\n return resource\n } catch (scopeFailure) {\n try {\n await finalizer(this.closeOutcome ?? SCOPE_SUCCESS)\n } catch (releaseFailure) {\n throw new AggregateError(\n [scopeFailure, releaseFailure],\n 'Scope closed while adding a disposable resource and cleanup also failed'\n )\n }\n\n throw scopeFailure\n }\n }\n\n close(outcome: ScopeOutcome = SCOPE_SUCCESS): Promise<void> {\n if (this.closePromise) {\n return this.closePromise\n }\n\n this.closeOutcome = outcome\n this.closePromise = Promise.resolve().then(() => this.closeWithRuntime(outcome))\n\n return this.closePromise\n }\n\n private async closeWithRuntime(outcome: ScopeOutcome): Promise<void> {\n let started = false\n\n try {\n await ScopeRuntime.run(this, () => {\n started = true\n return this.closeInternal(outcome)\n })\n } catch (storageFailure) {\n if (started) {\n throw storageFailure\n }\n\n // Context propagation cannot prevent direct Scope cleanup.\n try {\n await this.closeInternal(outcome)\n } catch (cleanupFailure) {\n const cleanupCauses =\n cleanupFailure instanceof ScopeCloseError ? cleanupFailure.causes : [cleanupFailure]\n\n throw new ScopeCloseError([storageFailure, ...cleanupCauses])\n }\n\n throw storageFailure\n }\n }\n\n private async closeInternal(outcome: ScopeOutcome): Promise<void> {\n const failures: unknown[] = []\n\n const preFinalizers = this.preFinalizers.splice(0)\n\n for (let index = preFinalizers.length - 1; index >= 0; index--) {\n const finalizer = preFinalizers[index]\n\n if (!finalizer) {\n continue\n }\n\n try {\n await finalizer(outcome)\n } catch (cause) {\n failures.push(cause)\n }\n }\n\n const children = [...this.children]\n\n this.children.clear()\n\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n\n if (!child) {\n continue\n }\n\n try {\n await child.close(outcome)\n } catch (cause) {\n if (cause instanceof ScopeCloseError) {\n failures.push(...cause.causes)\n } else {\n failures.push(cause)\n }\n }\n }\n\n for (let index = this.finalizers.length - 1; index >= 0; index--) {\n const finalizer = this.finalizers[index]\n\n if (!finalizer) {\n continue\n }\n\n try {\n await finalizer(outcome)\n } catch (cause) {\n failures.push(cause)\n }\n }\n\n this.finalizers.length = 0\n\n this.detach()\n\n if (failures.length > 0) {\n throw new ScopeCloseError(failures)\n }\n }\n\n private detach(): void {\n const parent = this.parent\n\n if (!parent) {\n return\n }\n\n parent.children.delete(this)\n this.parent = undefined\n }\n\n private assertOpen(): void {\n if (this.closePromise) {\n throw new ScopeClosedError()\n }\n }\n\n private addPreFinalizer(finalizer: ScopeFinalizer): void {\n this.assertOpen()\n this.preFinalizers.push(finalizer)\n }\n}\n\nexport const Scope = {\n /** Create an owned, initially open Scope. */\n make(): CloseableScope {\n return new ScopeImpl()\n },\n\n /** Return the non-owning Scope available in the current execution context. */\n current(): Scope {\n return ScopeRuntime.current()\n },\n\n /** Run a callback with an existing Scope supplied as the current context. */\n provide<A>(scope: Scope, program: () => A): A {\n return ScopeRuntime.run(scope, program)\n },\n\n /** Resolve the current Scope through `yield* Scope` inside an Effect. */\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, Scope, unknown> {\n return ScopeRuntime.current()\n },\n\n /**\n * Run a program in a newly owned Scope.\n *\n * Scope is independent from `better-result`, so returned values—including\n * `Result.err`—close this Scope with a successful outcome. Result-aware\n * outcome classification belongs to `Runtime.run`.\n *\n * @example\n * ```ts\n * await Scope.run(async (scope) => {\n * const connection = await scope.acquire(connect, (connection) => connection.close())\n * return connection.query()\n * })\n * ```\n */\n run<A>(program: (scope: Scope) => A | PromiseLike<A>): Promise<Awaited<A>> {\n const scope = new ScopeImpl()\n\n return runScoped(scope, () => program(scope), {\n classify: () => SCOPE_SUCCESS\n })\n }\n} as const\n\n/** Type-level aliases for Scope ownership, outcomes, and cleanup contracts. */\nexport declare namespace Scope {\n /** A Scope whose owner is responsible for calling `close()`. */\n export type Closeable = CloseableScope\n\n /** The outcome supplied to Scope finalizers and resource releases. */\n export type Outcome = ScopeOutcome\n\n /** A cleanup callback registered with a Scope. */\n export type Finalizer = ScopeFinalizer\n\n /** A value implementing a JavaScript disposal protocol. */\n export type Disposable = DisposableResource\n}\n","import { assertServiceCompatibility } from './internal-identity'\nimport { captureLayerRegistrationTag, normalizeLayerRegistration } from './registration'\n\nimport { DuplicateServiceError, ServiceTagCollisionError } from './errors'\n\nimport type { LayerBackend, LayerBackendDisposeOptions } from './backend'\nimport type { LayerRegistration } from './types'\n\nimport { ServiceNotFoundError, type AnyServiceToken } from '../service'\nimport { captureServiceTag } from '../service/tag'\n\ntype LayerAcquiredValue = Awaited<ReturnType<LayerRegistration['acquire']>>\n\n/** Native map-backed Layer backend used by Runtime when no adapter is supplied. */\nexport class MapLayerBackend implements LayerBackend {\n private readonly providers = new Map<string, LayerRegistration>()\n\n private readonly instances = new Map<string, LayerAcquiredValue>()\n\n private readonly pending = new Map<string, Promise<LayerAcquiredValue>>()\n\n /** Register a provider, rejecting duplicate or colliding Service tags. */\n register(registration: LayerRegistration): void {\n const normalized = normalizeLayerRegistration(registration)\n const tag = captureLayerRegistrationTag(normalized)\n const existing = this.providers.get(tag)\n\n if (existing) {\n if (existing.service !== normalized.service) {\n throw new ServiceTagCollisionError(existing.service, normalized.service)\n }\n\n throw new DuplicateServiceError(normalized.service)\n }\n\n this.providers.set(tag, normalized)\n }\n\n /** Resolve and cache a provider instance by Service tag. */\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n const provider = this.providers.get(tag)\n\n if (!provider) {\n throw new ServiceNotFoundError(token)\n }\n\n const validate = (instance: LayerAcquiredValue): InstanceType<T> => {\n assertServiceCompatibility(token, provider.service, instance)\n\n // SAFETY: The provider and requested token share a tag, and compatibility checks verify the registered members before restoring the token-specific instance type.\n return instance as InstanceType<T>\n }\n\n const cached = this.instances.get(tag)\n\n if (cached !== undefined) {\n return validate(cached)\n }\n\n const pending = this.pending.get(tag)\n\n if (pending) {\n return validate(await pending)\n }\n\n const acquisition = Promise.resolve()\n .then(() => provider.acquire())\n .then((instance) => {\n validate(instance)\n this.instances.set(tag, instance)\n\n return instance\n })\n .finally(() => {\n this.pending.delete(tag)\n })\n\n this.pending.set(tag, acquisition)\n\n return validate(await acquisition)\n }\n\n /** Clear pending acquisitions, cached instances, and provider registrations. */\n async disposeAll(options?: LayerBackendDisposeOptions): Promise<void> {\n const acquisitions = [...this.pending.values()]\n\n if (acquisitions.length > 0) {\n const observePending = options?.onPendingAcquisitions\n\n if (observePending) {\n await observePending(acquisitions)\n }\n\n await Promise.allSettled(acquisitions)\n }\n\n this.instances.clear()\n this.pending.clear()\n this.providers.clear()\n }\n}\n","export type ProgramIdentity = (...arguments_: never[]) => void\n\nconst programNames = new WeakMap<ProgramIdentity, string>()\n\n/** Return the private diagnostic name attached to a callable Program. */\nexport const getProgramName = (program: ProgramIdentity): string | undefined =>\n programNames.get(program)\n\n/** Attach a name without changing the callable Program facade. */\nexport const setProgramName = <Program extends ProgramIdentity>(\n program: Program,\n name: string\n): Program => {\n programNames.set(program, name)\n return program\n}\n\n/** Copy a source Program's name to a lazily-created derived Program. */\nexport const inheritProgramName = <Source extends ProgramIdentity, Derived extends ProgramIdentity>(\n source: Source,\n derived: Derived\n): Derived => {\n const name = getProgramName(source)\n\n return name === undefined ? derived : setProgramName(derived, name)\n}\n","import type { AnyServiceToken } from '../service'\nimport type { Scope } from '../scope'\nimport type { ScopeCloseError, ScopeOutcome } from '../scope'\nimport type { MaybePromise } from '../utils/types'\nimport type { ScopedTaskState } from '../effect/task'\nimport type { RuntimeShutdownReason } from './outcome'\n\n/** Observable Runtime shutdown phase. */\nexport type RuntimeShutdownPhase =\n | 'shutdown-requested'\n | 'quiesce-start'\n | 'quiesce-end'\n | 'drain-start'\n | 'drain-end'\n | 'abort-active'\n | 'release-start'\n | 'release-end'\n | 'shutdown-complete'\n | 'shutdown-failure'\n\n/** Detached metadata for one Runtime shutdown phase. */\nexport type RuntimeShutdownEvent = {\n readonly phase: RuntimeShutdownPhase\n readonly reason: RuntimeShutdownReason\n readonly activeExecutions?: number\n readonly durationMs?: number\n readonly error?: unknown\n}\n\n/** Event emitted after a Service resolution attempt settles. */\nexport type RuntimeServiceResolveEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n /** Runtime execution owner, omitted for warmup and other root activity. */\n readonly executionId?: string\n}\n\n/** Event emitted after a provider acquisition attempt settles. */\nexport type RuntimeServiceAcquireEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n /** Runtime execution owner, omitted for warmup and other root activity. */\n readonly executionId?: string\n}\n\n/** Values supplied to one Runtime execution for diagnostic correlation. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- attributes intentionally accept caller-defined values.\nexport type RuntimeExecutionAttributes = Readonly<Record<string, unknown>>\n\n/** Metadata shared by the start and end events for one execution. */\nexport type RuntimeExecutionMetadata = {\n readonly executionId: string\n readonly name?: string\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- preserve the caller-defined attribute contract.\n readonly attributes?: RuntimeExecutionAttributes\n /** Monotonic host timestamp captured immediately before the Program starts. */\n readonly startedAt: number\n}\n\n/** Event emitted immediately before a program starts in an execution Scope. */\nexport type RuntimeExecutionStartEvent = RuntimeExecutionMetadata & {\n readonly scope: Scope\n}\n\n/** Event emitted after a program and its execution Scope settle. */\nexport type RuntimeExecutionEndEvent = RuntimeExecutionMetadata & {\n readonly scope: Scope\n /** The program outcome used to run execution-scope cleanup. */\n readonly outcome: ScopeOutcome\n /** Execution-scope cleanup failure, without changing the primary program outcome. */\n readonly cleanupFailure?: ScopeCloseError\n /** Monotonic elapsed time for the Program and its execution cleanup. */\n readonly durationMs: number\n}\n\n/** Metadata shared by the start and end events for one Scope-owned task. */\nexport type RuntimeTaskMetadata = {\n readonly taskId: string\n /** The execution that created the task, omitted for root lifecycle tasks. */\n readonly parentExecutionId?: string\n readonly name?: string\n readonly startedAt: number\n}\n\n/** Event emitted immediately before a Scope-owned task starts. */\nexport type RuntimeTaskStartEvent = RuntimeTaskMetadata & {\n readonly state: 'running'\n}\n\n/** Event emitted after a Scope-owned task settles and its child Scope closes. */\nexport type RuntimeTaskEndEvent = RuntimeTaskMetadata & {\n readonly state: Exclude<ScopedTaskState, 'running'>\n /** Child Scope cleanup failure, without changing the task's primary state. */\n readonly cleanupFailure?: ScopeCloseError\n}\n\n/** Event emitted after a Layer provider release callback settles. */\nexport type RuntimeResourceReleaseEvent = {\n readonly service: AnyServiceToken\n readonly outcome: ScopeOutcome\n readonly error?: unknown\n /** Runtime execution owner, omitted for Runtime-root cleanup. */\n readonly executionId?: string\n}\n\n/** Metadata shared by lifecycle-only Layer events. */\nexport type RuntimeLifecycleEventMetadata = {\n readonly kind: 'lifecycle'\n /** Stable identity for one lifecycle entry; no acquired resource is retained. */\n readonly lifecycleId: symbol\n readonly name?: string\n}\n\n/** Event emitted immediately before a lifecycle-only entry is acquired. */\nexport type RuntimeLifecycleStartEvent = RuntimeLifecycleEventMetadata\n\n/** Event emitted after a lifecycle-only entry's acquisition settles. */\nexport type RuntimeLifecycleEndEvent = RuntimeLifecycleEventMetadata & {\n readonly outcome: ScopeOutcome\n readonly error?: unknown\n}\n\n/** Event emitted after a lifecycle-only entry's release callback settles. */\nexport type RuntimeLifecycleReleaseEvent = RuntimeLifecycleEventMetadata & {\n readonly outcome: ScopeOutcome\n readonly error?: unknown\n}\n\n/** Optional best-effort hooks for Runtime lifecycle and resolution events. */\nexport type RuntimeObserver = {\n readonly onServiceResolve?: (event: RuntimeServiceResolveEvent) => MaybePromise<void>\n readonly onServiceAcquire?: (event: RuntimeServiceAcquireEvent) => MaybePromise<void>\n readonly onExecutionStart?: (event: RuntimeExecutionStartEvent) => MaybePromise<void>\n readonly onExecutionEnd?: (event: RuntimeExecutionEndEvent) => MaybePromise<void>\n readonly onTaskStart?: (event: RuntimeTaskStartEvent) => MaybePromise<void>\n readonly onTaskEnd?: (event: RuntimeTaskEndEvent) => MaybePromise<void>\n readonly onResourceRelease?: (event: RuntimeResourceReleaseEvent) => MaybePromise<void>\n readonly onLifecycleStart?: (event: RuntimeLifecycleStartEvent) => MaybePromise<void>\n readonly onLifecycleEnd?: (event: RuntimeLifecycleEndEvent) => MaybePromise<void>\n readonly onLifecycleRelease?: (event: RuntimeLifecycleReleaseEvent) => MaybePromise<void>\n readonly onShutdown?: (event: RuntimeShutdownEvent) => MaybePromise<void>\n}\n\n/** Compose best-effort Runtime observers into one observer. */\nexport const RuntimeObserver = {\n compose: (...observers: readonly RuntimeObserver[]): RuntimeObserver => ({\n onServiceResolve: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, event)\n },\n onServiceAcquire: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\n },\n onExecutionStart: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onExecutionStart, event)\n },\n onExecutionEnd: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onExecutionEnd, event)\n },\n onTaskStart: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onTaskStart, event)\n },\n onTaskEnd: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onTaskEnd, event)\n },\n onResourceRelease: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n },\n onLifecycleStart: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onLifecycleStart, event)\n },\n onLifecycleEnd: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onLifecycleEnd, event)\n },\n onLifecycleRelease: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onLifecycleRelease, event)\n },\n onShutdown: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onShutdown, event)\n }\n })\n}\n\nexport const notifyRuntimeObservers = <Event>(\n observers: readonly RuntimeObserver[],\n select: (observer: RuntimeObserver) => ((event: Event) => MaybePromise<void>) | undefined,\n event: Event\n): void => {\n for (const observer of observers) {\n const callback = select(observer)\n\n if (!callback) {\n continue\n }\n\n try {\n void Promise.resolve(callback(event)).catch(() => {})\n } catch {\n // Observability must never change the Runtime result.\n }\n }\n}\n","import { Err } from 'better-result'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from '../scope'\n\nimport type { LayerDisposeError } from '../layer/errors'\n\nimport type { LayerBackend } from '../layer/backend'\n\nimport type { RuntimeContextStorage } from './context'\n\nimport type { RuntimeExecutionAttributes, RuntimeObserver } from './observer'\n\n/** Metadata explaining why a Runtime shutdown was requested. */\nexport type RuntimeShutdownReason = {\n readonly kind: 'dispose' | 'signal' | 'external-abort' | 'main-settled'\n readonly signal?: 'SIGINT' | 'SIGTERM'\n readonly cause?: unknown\n}\n\n/** Aggregated cleanup information reported during Runtime shutdown. */\nexport type RuntimeShutdownDiagnostic = {\n /** Final outcome supplied to the Runtime root Scope. */\n readonly outcome: ScopeOutcome\n /** Aggregated root-Scope and backend cleanup failure. */\n readonly error: LayerDisposeError\n}\n\n/** Observer notified about cleanup failures without changing primary results. */\nexport type CleanupFailureObserver = (\n diagnostic: CleanupFailureDiagnostic | RuntimeShutdownDiagnostic\n) => MaybePromise<void>\n\n/** Optional Runtime configuration for cleanup diagnostics. */\nexport type RuntimeOptions = {\n /** Backend used to register and resolve the Layer. Defaults to MapLayerBackend. */\n readonly backend?: LayerBackend\n /** Resolve every Layer provider before Runtime.make resolves. */\n readonly warmup?: boolean\n /** Best-effort lifecycle and Service resolution observers. */\n readonly observers?: readonly RuntimeObserver[]\n /** Optional observer for best-effort cleanup diagnostics. */\n readonly onCleanupFailure?: CleanupFailureObserver\n /** Context storage used by Service, Scope and Layer resolution. */\n readonly contextStorage?: RuntimeContextStorage\n /** Optional signal exposed through the RuntimeContext. */\n readonly signal?: AbortSignal\n}\n\n/** Optional signal and diagnostic attributes supplied to one Runtime execution. */\nexport type RuntimeRunOptions = {\n readonly signal?: AbortSignal\n /** Copied once and exposed as a readonly event view. */\n readonly attributes?: RuntimeExecutionAttributes\n}\n\n/** Cooperative shutdown policy for a managed Runtime. */\nexport type RuntimeDisposeOptions = {\n /** Time to let active executions settle before requesting cancellation. */\n readonly gracePeriod?: number\n /** Abort active execution signals after the grace period expires. */\n readonly abortAfterGracePeriod?: boolean\n /** Boundary metadata supplied to Layer quiesce callbacks. */\n readonly reason?: RuntimeShutdownReason\n}\n\n/** Classify only a nominal better-result Err as a failed Runtime outcome. */\nexport const classifyRuntimeOutcome = <A>(value: A): ScopeOutcome => {\n if (value instanceof Err) {\n return {\n status: 'failure',\n cause: value.error\n }\n }\n\n return {\n status: 'success'\n }\n}\n","import { Err } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport { getProgramName, type ProgramIdentity } from '../effect/program-metadata'\nimport type { ScopedTask, ScopedTaskExit, ScopedTaskState } from '../effect/task'\nimport type { EffectError, EffectSuccess, Program } from '../effect/types'\nimport type { AnyService } from '../service'\nimport { addScopePreFinalizer, runScoped } from '../scope/internal'\nimport type {\n CleanupFailureDiagnostic,\n CloseableScope,\n MaybePromise,\n Scope,\n ScopeCloseError,\n ScopeOutcome\n} from '../scope'\n\nimport {\n activeRuntimeContextStorage,\n makeRuntimeContext,\n type CompleteRuntimeContext,\n type RuntimeContext,\n type RuntimeContextStorage\n} from './context'\nimport { RuntimeContextNotConfiguredError } from './errors'\nimport { notifyRuntimeObservers } from './observer'\nimport type { RuntimeObserver, RuntimeTaskEndEvent, RuntimeTaskStartEvent } from './observer'\nimport type { RuntimeTaskInspection } from './types'\nimport { classifyRuntimeOutcome } from './outcome'\nimport { linkAbortSignals, type AbortSignalLink } from './signal'\n\nconst taskSupervisors = new WeakMap<object, RuntimeTaskSupervisor>()\n\n/** Associate one Runtime task supervisor with a Runtime-owned Scope. */\nexport const bindRuntimeTaskSupervisor = (\n scope: Scope,\n supervisor: RuntimeTaskSupervisor\n): void => {\n taskSupervisors.set(scope, supervisor)\n}\n\n/** Return the supervisor associated with the current Runtime-owned Scope. */\nexport const getRuntimeTaskSupervisor = (scope: Scope): RuntimeTaskSupervisor | undefined =>\n taskSupervisors.get(scope)\n\ntype TaskState = Exclude<ScopedTaskState, 'running'>\n\ntype TaskMetadata = {\n readonly taskId: string\n readonly parentExecutionId?: string\n readonly name?: string\n readonly startedAt: number\n}\n\ntype MutableTaskMetadata = {\n taskId: string\n parentExecutionId?: string\n name?: string\n startedAt: number\n}\n\ntype MutableTaskEndEvent = MutableTaskMetadata & {\n state: TaskState\n cleanupFailure?: ScopeCloseError\n}\n\ntype AnyProgram = Program<any, any, AnyService>\n\ntype TaskRecord<Input extends AnyProgram> = {\n readonly metadata: TaskMetadata\n readonly childScope: CloseableScope\n readonly signalLink: AbortSignalLink\n readonly handle: ScopedTaskHandle<EffectSuccess<Input>, EffectError<Input>>\n readonly program: Input\n readonly context: CompleteRuntimeContext\n readonly storage: RuntimeContextStorage\n}\n\nconst defaultInterruptionReason = (): Error => {\n const reason = new Error('Scoped task interrupted')\n reason.name = 'ScopedTaskInterruptedError'\n return reason\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- AbortSignal reasons preserve caller-defined diagnostic values.\nconst signalReason = (signal: AbortSignal): unknown =>\n signal.reason === undefined ? defaultInterruptionReason() : signal.reason\n\nconst taskStateFromExit = <A, E>(exit: ScopedTaskExit<A, E>): TaskState => exit.status\n\nconst copyMetadata = (metadata: TaskMetadata): TaskMetadata => {\n const copy: MutableTaskMetadata = {\n taskId: metadata.taskId,\n startedAt: metadata.startedAt\n }\n\n if (metadata.parentExecutionId !== undefined) {\n copy.parentExecutionId = metadata.parentExecutionId\n }\n\n if (metadata.name !== undefined) {\n copy.name = metadata.name\n }\n\n return Object.freeze(copy)\n}\n\ntype TaskHandleState<A, E> = {\n readonly completion: Promise<ScopedTaskExit<A, E>>\n readonly resolveCompletion: (exit: ScopedTaskExit<A, E>) => void\n currentState: ScopedTaskState\n terminalResult: ResultType<A, E> | undefined\n interruptionReasonValue: unknown\n}\n\nclass ScopedTaskHandle<A, E> implements ScopedTask<A, E> {\n private readonly handleState: TaskHandleState<A, E>\n\n constructor(private readonly controller: AbortController) {\n let resolveCompletion!: (exit: ScopedTaskExit<A, E>) => void\n const completion = new Promise<ScopedTaskExit<A, E>>((resolve) => {\n resolveCompletion = resolve\n })\n this.handleState = {\n completion,\n resolveCompletion,\n currentState: 'running',\n terminalResult: undefined,\n interruptionReasonValue: undefined\n }\n Object.freeze(this)\n }\n\n get state(): ScopedTaskState {\n return this.handleState.currentState\n }\n\n await(): Promise<ResultType<A, E>> {\n return this.handleState.completion.then((exit) => {\n if (exit.status === 'succeeded' || exit.status === 'failed') {\n return this.handleState.terminalResult!\n }\n\n if (exit.status === 'defected') {\n throw exit.cause\n }\n\n throw exit.reason\n })\n }\n\n awaitExit(): Promise<ScopedTaskExit<A, E>> {\n return this.handleState.completion\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Task interruption preserves the caller's arbitrary abort reason.\n interrupt(reason?: unknown): Promise<void> {\n if (this.handleState.currentState !== 'running') {\n return this.handleState.completion.then(() => undefined)\n }\n\n const interruption =\n reason === undefined\n ? (this.handleState.interruptionReasonValue ?? defaultInterruptionReason())\n : reason\n this.handleState.interruptionReasonValue = interruption\n\n if (!this.controller.signal.aborted) {\n this.controller.abort(interruption)\n }\n\n return this.handleState.completion.then(() => undefined)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Linked AbortSignals carry arbitrary caller-defined reasons.\n markInterrupted(reason: unknown): void {\n if (\n this.handleState.currentState === 'running' &&\n this.handleState.interruptionReasonValue === undefined\n ) {\n this.handleState.interruptionReasonValue = reason\n }\n }\n\n isInterrupted(): boolean {\n return this.handleState.interruptionReasonValue !== undefined || this.controller.signal.aborted\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- Task exits preserve arbitrary interruption reasons.\n interruptionReason(signal: AbortSignal): unknown {\n return this.handleState.interruptionReasonValue ?? signalReason(signal)\n }\n\n settle(exit: ScopedTaskExit<A, E>, result?: ResultType<A, E>): void {\n if (this.handleState.currentState !== 'running') {\n return\n }\n\n const terminalExit = Object.freeze(exit)\n this.handleState.currentState = taskStateFromExit(terminalExit)\n this.handleState.terminalResult = result\n this.handleState.resolveCompletion(terminalExit)\n }\n}\n\nconst withCleanupFailure = <A extends object>(\n value: A,\n cleanupFailure: ScopeCloseError | undefined\n): A => {\n if (cleanupFailure === undefined) {\n // SAFETY: `value` already has the requested exit shape; freezing a shallow copy preserves it.\n return Object.freeze({ ...value }) as A\n }\n\n // SAFETY: The added diagnostic property is the only runtime extension of the typed exit shape.\n return Object.freeze({ ...value, cleanupFailure }) as A\n}\n\n/** Runtime-owned supervisor for Scope child tasks. */\nexport class RuntimeTaskSupervisor {\n private readonly tasks = new Map<string, TaskRecord<AnyProgram>>()\n\n constructor(\n private readonly createTaskId: () => string,\n private readonly now: () => number,\n private readonly observers: readonly RuntimeObserver[],\n private readonly onCleanupFailure:\n | ((diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>)\n | undefined\n ) {}\n\n bindScope(scope: Scope): void {\n bindRuntimeTaskSupervisor(scope, this)\n }\n\n inspect(): readonly RuntimeTaskInspection[] {\n return Object.freeze(\n [...this.tasks.values()].map(({ metadata }) =>\n Object.freeze({\n ...copyMetadata(metadata),\n state: 'running' as const\n })\n )\n )\n }\n\n forkScoped<Input extends AnyProgram>(\n program: Input,\n context: CompleteRuntimeContext\n ): ScopedTask<EffectSuccess<Input>, EffectError<Input>> {\n if (!context.resolver || !context.scope) {\n throw new RuntimeContextNotConfiguredError()\n }\n\n const parentScope = context.scope\n const childScope = parentScope.fork()\n const controller = new AbortController()\n const signalLink = linkAbortSignals(context.signal, controller.signal)\n const handle = new ScopedTaskHandle<EffectSuccess<Input>, EffectError<Input>>(controller)\n const metadata = this.makeMetadata(program, context)\n const storage = activeRuntimeContextStorage()\n const record: TaskRecord<Input> = {\n metadata,\n childScope,\n signalLink,\n handle,\n program,\n context,\n storage\n }\n const onAbort = (): void => handle.markInterrupted(signalReason(signalLink.signal))\n\n try {\n addScopePreFinalizer(parentScope, (outcome) =>\n handle.interrupt(outcome.status === 'failure' ? outcome.cause : undefined)\n )\n this.bindScope(childScope)\n this.tasks.set(metadata.taskId, record)\n signalLink.signal.addEventListener('abort', onAbort, { once: true })\n if (signalLink.signal.aborted) {\n onAbort()\n }\n this.notifyStart(metadata)\n } catch (cause) {\n signalLink.signal.removeEventListener('abort', onAbort)\n signalLink.dispose()\n void childScope.close({ status: 'failure', cause }).catch(() => {})\n throw cause\n }\n\n void this.runTask(record, onAbort)\n\n return handle\n }\n\n private makeMetadata(program: ProgramIdentity, context: RuntimeContext): TaskMetadata {\n const metadata: MutableTaskMetadata = {\n taskId: this.createTaskId(),\n startedAt: this.now()\n }\n const name = getProgramName(program)\n\n if (name !== undefined) {\n metadata.name = name\n }\n\n if (context.executionId !== undefined) {\n metadata.parentExecutionId = context.executionId\n }\n\n return Object.freeze(metadata)\n }\n\n private notifyStart(metadata: TaskMetadata): void {\n const event: RuntimeTaskStartEvent = {\n ...copyMetadata(metadata),\n state: 'running'\n }\n notifyRuntimeObservers(this.observers, (observer) => observer.onTaskStart, Object.freeze(event))\n }\n\n private notifyEnd<A, E>(metadata: TaskMetadata, exit: ScopedTaskExit<A, E>): void {\n const event: MutableTaskEndEvent = {\n ...copyMetadata(metadata),\n state: exit.status\n }\n\n if (exit.cleanupFailure !== undefined) {\n event.cleanupFailure = exit.cleanupFailure\n }\n\n const frozenEvent: RuntimeTaskEndEvent = Object.freeze(event)\n\n notifyRuntimeObservers(this.observers, (observer) => observer.onTaskEnd, frozenEvent)\n }\n\n private async runTask<Input extends AnyProgram>(\n record: TaskRecord<Input>,\n onAbort: () => void\n ): Promise<void> {\n let cleanupFailure: ScopeCloseError | undefined\n const onChildCleanupFailure = async (diagnostic: CleanupFailureDiagnostic): Promise<void> => {\n cleanupFailure = diagnostic.error\n\n if (this.onCleanupFailure !== undefined) {\n await this.onCleanupFailure(diagnostic)\n }\n }\n const taskContext = makeRuntimeContext(\n record.context.resolver,\n record.childScope,\n [],\n record.signalLink.signal,\n record.context,\n record.context.executionId,\n record.context.executor\n )\n const classify = (value: ResultType<EffectSuccess<Input>, EffectError<Input>>): ScopeOutcome =>\n record.handle.isInterrupted()\n ? {\n status: 'failure',\n cause: record.handle.interruptionReason(record.signalLink.signal)\n }\n : classifyRuntimeOutcome(value)\n\n let exit: ScopedTaskExit<EffectSuccess<Input>, EffectError<Input>>\n let result: ResultType<EffectSuccess<Input>, EffectError<Input>> | undefined\n\n try {\n if (record.handle.isInterrupted()) {\n await record.childScope.close({\n status: 'failure',\n cause: record.handle.interruptionReason(record.signalLink.signal)\n })\n exit = withCleanupFailure(\n {\n status: 'interrupted' as const,\n reason: record.handle.interruptionReason(record.signalLink.signal)\n },\n cleanupFailure\n )\n } else {\n const childResult = await runScoped(record.childScope, () => record.program(), {\n classify,\n onCleanupFailure: onChildCleanupFailure,\n contextStorage: record.storage,\n context: taskContext\n })\n result = childResult\n\n if (record.handle.isInterrupted()) {\n exit = withCleanupFailure(\n {\n status: 'interrupted' as const,\n reason: record.handle.interruptionReason(record.signalLink.signal)\n },\n cleanupFailure\n )\n } else if (childResult instanceof Err) {\n exit = withCleanupFailure(\n {\n status: 'failed' as const,\n error: childResult.error\n },\n cleanupFailure\n )\n } else {\n exit = withCleanupFailure(\n {\n status: 'succeeded' as const,\n value: childResult.value\n },\n cleanupFailure\n )\n }\n }\n } catch (cause) {\n exit = record.handle.isInterrupted()\n ? withCleanupFailure(\n {\n status: 'interrupted' as const,\n reason: record.handle.interruptionReason(record.signalLink.signal)\n },\n cleanupFailure\n )\n : withCleanupFailure(\n {\n status: 'defected' as const,\n cause\n },\n cleanupFailure\n )\n }\n\n record.signalLink.signal.removeEventListener('abort', onAbort)\n record.signalLink.dispose()\n record.handle.settle(exit, result)\n this.tasks.delete(record.metadata.taskId)\n this.notifyEnd(record.metadata, exit)\n }\n}\n","import { RuntimeContextNotConfiguredError, RuntimeExecutorNotConfiguredError } from './errors'\n\nimport { currentRuntimeContext } from './context'\n\nimport type { ServiceRequirement } from '../effect/types'\nimport type { AnyService } from '../service'\nimport type {\n CompleteExecution,\n CompleteExecutionLayer,\n LayerInput,\n ProvidedEnvironment\n} from '../layer/inference'\nimport type { RuntimeRunOptions } from './outcome'\n\n/* oxlint-disable anti-slop/no-unknown-parameters -- managed cancellation preserves caller-defined reasons. */\n\n/** The value published by one managed execution before its work completes. */\nexport type RuntimeManagedPlan<A> = {\n readonly readiness: A | PromiseLike<A>\n readonly completion: PromiseLike<void>\n readonly cancel?: (reason?: unknown) => PromiseLike<void>\n}\n\n/** A non-owning handle for an execution whose readiness is separate from completion. */\nexport type RuntimeManagedExecution<A> = {\n readonly readiness: Promise<Awaited<A>>\n readonly completion: Promise<void>\n readonly signal: AbortSignal\n readonly run: <B>(program: () => B | PromiseLike<B>) => Promise<Awaited<B>>\n readonly cancel: (reason?: unknown) => Promise<void>\n}\n\n/**\n * A non-owning view of a Runtime that can start isolated executions.\n *\n * The view deliberately contains only execution operations. Runtime disposal,\n * warmup, inspection, backend access and Scope ownership stay on `Runtime`.\n */\nexport interface RuntimeExecutor<in out Provided extends AnyService = any> {\n readonly run: <A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ) => Promise<Awaited<A>>\n\n readonly runWith: <Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ) => Promise<Awaited<A>>\n\n readonly runWithManaged: <Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, RuntimeManagedPlan<A>>,\n options?: RuntimeRunOptions\n ) => RuntimeManagedExecution<A>\n}\n\n/** Yieldable request for the executor active in the current Runtime context. */\nexport interface RuntimeExecutorRequest<Provided extends AnyService> {\n [Symbol.iterator](): Generator<ServiceRequirement<Provided>, RuntimeExecutor<Provided>, unknown>\n [Symbol.asyncIterator](): AsyncGenerator<\n ServiceRequirement<Provided>,\n RuntimeExecutor<Provided>,\n unknown\n >\n}\n\nconst castRuntimeExecutor = <Provided extends AnyService>(\n value: RuntimeExecutor<any>\n): RuntimeExecutor<Provided> => {\n // SAFETY: RuntimeExecutor views are stable references to one Runtime root;\n // this helper only changes the compile-time environment selected by a caller.\n return value as RuntimeExecutor<Provided>\n}\n\nconst currentExecutor = <Provided extends AnyService>(): RuntimeExecutor<Provided> => {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch (cause) {\n if (cause instanceof RuntimeContextNotConfiguredError) {\n throw new RuntimeExecutorNotConfiguredError()\n }\n\n throw cause\n }\n\n if (context.executor === undefined) {\n throw new RuntimeExecutorNotConfiguredError()\n }\n\n return castRuntimeExecutor<Provided>(context.executor)\n}\n\n/** Erase a Runtime executor's concrete environment for contextual storage. */\nexport const eraseRuntimeExecutor = <Provided extends AnyService>(\n executor: RuntimeExecutor<Provided>\n): RuntimeExecutor<AnyService> => castRuntimeExecutor<AnyService>(executor)\n\n/** Create one stable executor view from an existing Runtime execution handle. */\nexport const createRuntimeExecutor = <Provided extends AnyService>(\n executor: RuntimeExecutor<Provided>\n): RuntimeExecutor<Provided> => Object.freeze({ ...executor })\n\n/** Build the yieldable contextual executor request used by `Runtime.executor()`. */\nexport const makeRuntimeExecutorRequest = <\n Provided extends AnyService\n>(): RuntimeExecutorRequest<Provided> => {\n const request: RuntimeExecutorRequest<Provided> = {\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<\n ServiceRequirement<Provided>,\n RuntimeExecutor<Provided>,\n unknown\n > {\n return currentExecutor<Provided>()\n },\n // oxlint-disable-next-line require-yield\n async *[Symbol.asyncIterator](): AsyncGenerator<\n ServiceRequirement<Provided>,\n RuntimeExecutor<Provided>,\n unknown\n > {\n return currentExecutor<Provided>()\n }\n }\n\n return request\n}\n","import { captureServiceTag } from '../service/tag'\n\nimport {\n CircularDependencyError,\n ServiceAcquisitionError,\n ServiceNotFoundError,\n type AnyServiceToken,\n type ServiceResolver\n} from '../service'\n\nimport { getRuntimeContext, makeRuntimeContext, runRuntimeContext } from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nimport {\n notifyRuntimeObservers,\n type RuntimeObserver,\n type RuntimeServiceResolveEvent\n} from '../runtime/observer'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport { ServiceTagCollisionError } from './errors'\n\nconst findCycleStart = (path: readonly AnyServiceToken[], tag: string): number =>\n path.findIndex((current) => captureServiceTag(current) === tag)\n\nconst shouldPreserve = (cause: unknown): boolean =>\n cause instanceof CircularDependencyError ||\n cause instanceof ServiceAcquisitionError ||\n cause instanceof ServiceNotFoundError ||\n cause instanceof ServiceTagCollisionError\n\n/** Wrap a backend with Runtime-local resolution paths and acquisition errors. */\nexport const createResolutionResolver = (\n resolver: ServiceResolver,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage,\n observers: readonly RuntimeObserver[] = []\n): ServiceResolver => {\n const wrapped: ServiceResolver = {\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n const context = getRuntimeContext(storage)\n const path = context?.resolutionPath ?? []\n const cycleStart = findCycleStart(path, tag)\n const resolutionPath = [...path, token]\n\n const notifyResolve = (outcome: ScopeOutcome): void => {\n const event: RuntimeServiceResolveEvent = {\n service: token,\n resolutionPath,\n outcome\n }\n\n if (context?.executionId !== undefined) {\n Object.assign(event, { executionId: context.executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, event)\n }\n\n if (cycleStart >= 0) {\n const error = new CircularDependencyError([...path.slice(cycleStart), token])\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n\n const nextContext = makeRuntimeContext(\n wrapped,\n context?.scope,\n resolutionPath,\n context?.signal,\n context\n )\n\n return await runRuntimeContext(storage, nextContext, async () => {\n try {\n const instance = await resolver.resolve(token)\n notifyResolve({ status: 'success' })\n return instance\n } catch (cause) {\n if (shouldPreserve(cause)) {\n notifyResolve({ status: 'failure', cause })\n throw cause\n }\n\n const error = new ServiceAcquisitionError(token, resolutionPath, cause)\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n })\n }\n }\n\n return wrapped\n}\n","export type RuntimeExecutionIdGenerator = () => string\n\nexport type RuntimeMonotonicClock = () => number\n\n/** Per-Runtime host capabilities used to correlate and time executions. */\nexport type RuntimeExecutionDependencies = {\n readonly createExecutionId: RuntimeExecutionIdGenerator\n readonly now: RuntimeMonotonicClock\n}\n\nexport type RuntimeExecutionDependencyOverrides = {\n readonly createExecutionId?: RuntimeExecutionIdGenerator\n readonly now?: RuntimeMonotonicClock\n}\n\nconst hostMonotonicNow = (): number => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- feature-detect the optional host clock.\n if (typeof globalThis.performance?.now === 'function') {\n const value = globalThis.performance.now()\n\n if (Number.isFinite(value)) {\n return value\n }\n }\n\n const wallClock = Date.now()\n return Number.isFinite(wallClock) ? wallClock : 0\n}\n\nconst makeMonotonicClock = (): RuntimeMonotonicClock => {\n let previous = 0\n\n return () => {\n previous = Math.max(previous, hostMonotonicNow())\n return previous\n }\n}\n\nlet fallbackExecutionSequence = 0\n\nconst makeExecutionIdGenerator = (): RuntimeExecutionIdGenerator => () => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- feature-detect the optional host ID source.\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID()\n }\n\n fallbackExecutionSequence += 1\n\n return `execution-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${fallbackExecutionSequence.toString(36)}`\n}\n\n/** Create isolated execution capabilities for one Runtime handle. */\nexport const makeRuntimeExecutionDependencies = (\n overrides: RuntimeExecutionDependencyOverrides = {}\n): RuntimeExecutionDependencies => ({\n createExecutionId: overrides.createExecutionId ?? makeExecutionIdGenerator(),\n now: overrides.now ?? makeMonotonicClock()\n})\n","import { captureServiceTag } from '../service/tag'\nimport type { AnyService, AnyServiceToken, ServiceResolver } from '../service'\n\nimport { Scope, type CloseableScope } from '../scope'\nimport { runScoped } from '../scope/internal'\nimport { ScopeRuntime } from '../scope/runtime'\n\nimport {\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext,\n type CompleteRuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport {\n createRuntimeExecutor,\n eraseRuntimeExecutor,\n type RuntimeExecutor,\n type RuntimeManagedExecution,\n type RuntimeManagedPlan\n} from '../runtime/executor'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport {\n classifyRuntimeOutcome,\n type CleanupFailureObserver,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic,\n type RuntimeShutdownReason\n} from '../runtime/outcome'\n\nimport { linkAbortSignals, type AbortSignalLink } from '../runtime/signal'\nimport { RuntimeTaskSupervisor } from '../runtime/task'\n\nimport { LayerDisposeError, LayerRegistrationError } from './errors'\nimport { captureLayerRegistrationTag } from './registration'\nimport { getLayerEntries, type LayerLifecycleEntry } from './layer'\n\nimport { createResolutionResolver } from './resolution'\n\nimport { getProgramName } from '../effect/program-metadata'\nimport type { ProgramIdentity } from '../effect/program-metadata'\n\nimport {\n makeRuntimeExecutionDependencies,\n type RuntimeExecutionDependencies,\n type RuntimeExecutionDependencyOverrides\n} from '../runtime/execution'\n\nimport { notifyRuntimeObservers } from '../runtime/observer'\n\nimport type {\n RuntimeExecutionAttributes,\n RuntimeExecutionEndEvent,\n RuntimeExecutionMetadata,\n RuntimeLifecycleEndEvent,\n RuntimeLifecycleReleaseEvent,\n RuntimeLifecycleStartEvent,\n RuntimeObserver,\n RuntimeResourceReleaseEvent,\n RuntimeServiceAcquireEvent,\n RuntimeShutdownEvent\n} from '../runtime/observer'\n\nimport type { RuntimeInspection } from '../runtime/types'\n\nimport type { LayerBackend } from './backend'\n\nimport { MapLayerBackend } from './map-layer-backend'\n\nimport type {\n CompleteExecution,\n CompleteExecutionLayer,\n CompleteInput,\n LayerInput,\n ProvidedEnvironment\n} from './inference'\n\nimport type { LayerRegistration } from './types'\n\nimport type {\n CleanupFailureDiagnostic,\n ScopeCloseError,\n ScopeFinalizer,\n ScopeOutcome\n} from '../scope'\nimport type { MaybePromise } from '../utils/types'\n\ntype LayerProvider = LayerInput['providers'][number]\n\ninterface RuntimeHandleCore<Provided extends AnyService> {\n /** The backend used to resolve this Layer's providers. */\n readonly backend: LayerBackend\n\n /** Run a program in a child Scope of the Layer's root Scope. */\n run<A>(program: CompleteExecution<Provided, A>, options?: RuntimeRunOptions): Promise<Awaited<A>>\n\n /** Run a program with providers owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>>\n\n /** Run a program until its managed completion while exposing earlier readiness. */\n runWithManaged<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, RuntimeManagedPlan<A>>,\n options?: RuntimeRunOptions\n ): RuntimeManagedExecution<A>\n\n /** Resolve every registered provider before accepting normal executions. */\n warmup(): Promise<void>\n\n /** Activate lifecycle-only Layer entries after provider registration and warmup. */\n activateLifecycle(): Promise<void>\n\n /** Return a detached diagnostic snapshot without changing Runtime state. */\n inspect(): RuntimeInspection\n\n /** Stop new executions and release Layer-owned resources. */\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void>\n}\n\n/** Runtime-facing handle that owns a Layer's resources and execution scopes. */\nexport type RuntimeHandle<Provided extends AnyService = any> = RuntimeHandleCore<Provided>\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass RuntimeHandleDisposedError extends Error {\n constructor() {\n super('Cannot run a program using a disposed Layer')\n\n this.name = 'RuntimeHandleDisposedError'\n }\n}\n\nconst normalizeDisposeCauses = (cause: unknown): readonly unknown[] => {\n if (cause instanceof AggregateError) {\n return [...cause.errors]\n }\n\n return [cause]\n}\n\nconst isScopeOutcome = (\n input: RuntimeDisposeOptions | ScopeOutcome | undefined\n): input is ScopeOutcome => input !== undefined && 'status' in input\n\nconst validateDisposeOptions = (options: RuntimeDisposeOptions): void => {\n const { gracePeriod, abortAfterGracePeriod } = options\n\n if (gracePeriod !== undefined && (!Number.isFinite(gracePeriod) || gracePeriod < 0)) {\n throw new RangeError('Runtime dispose gracePeriod must be a finite non-negative number')\n }\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validate untyped public options at the Runtime boundary.\n if (abortAfterGracePeriod !== undefined && typeof abortAfterGracePeriod !== 'boolean') {\n throw new TypeError('Runtime dispose abortAfterGracePeriod must be a boolean')\n }\n}\n\ntype ActiveExecution = {\n readonly promise: Promise<unknown>\n readonly metadata: RuntimeExecutionMetadata\n}\n\ntype RootQuiesceRegistration = {\n readonly quiesce: (reason: RuntimeShutdownReason) => MaybePromise<void>\n started: boolean\n}\n\ntype MutableRuntimeExecutionInspection = {\n executionId: string\n startedAt: number\n name?: string\n}\n\nconst copyExecutionAttributes = (\n attributes: RuntimeExecutionAttributes | undefined\n): RuntimeExecutionAttributes | undefined => {\n if (attributes === undefined) {\n return undefined\n }\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validate JavaScript callers at the Runtime boundary.\n if (typeof attributes !== 'object' || attributes === null) {\n throw new TypeError('Runtime execution attributes must be an object')\n }\n\n return Object.freeze({ ...attributes })\n}\n\ntype MutableRuntimeExecutionMetadata = {\n executionId: string\n startedAt: number\n name?: string\n attributes?: RuntimeExecutionAttributes\n}\n\ntype PreparedExecution = {\n readonly metadata: RuntimeExecutionMetadata\n readonly signalLink: AbortSignalLink\n}\n\nconst prepareExecution = <ProgramValue>(\n program: () => ProgramValue | PromiseLike<ProgramValue>,\n options: RuntimeRunOptions | undefined,\n dependencies: RuntimeExecutionDependencies,\n runtimeSignal: AbortSignal | undefined,\n shutdownSignal: AbortSignal,\n additionalSignal?: AbortSignal\n): PreparedExecution => ({\n metadata: makeExecutionMetadata(program, options?.attributes, dependencies),\n signalLink: linkAbortSignals(runtimeSignal, options?.signal, additionalSignal, shutdownSignal)\n})\n\nconst makeExecutionMetadata = (\n program: ProgramIdentity,\n attributes: RuntimeExecutionAttributes | undefined,\n dependencies: RuntimeExecutionDependencies\n): RuntimeExecutionMetadata => {\n const name = getProgramName(program)\n const copiedAttributes = copyExecutionAttributes(attributes)\n\n const metadata: MutableRuntimeExecutionMetadata = {\n executionId: dependencies.createExecutionId(),\n startedAt: dependencies.now()\n }\n\n if (name !== undefined) {\n metadata.name = name\n }\n\n if (copiedAttributes !== undefined) {\n metadata.attributes = copiedAttributes\n }\n\n return Object.freeze(metadata)\n}\n\nconst executionDuration = (\n metadata: RuntimeExecutionMetadata,\n dependencies: RuntimeExecutionDependencies\n): number => {\n try {\n const elapsed = dependencies.now() - metadata.startedAt\n\n return Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0\n } catch {\n return 0\n }\n}\n\nconst readRuntimeTimestamp = (dependencies: RuntimeExecutionDependencies): number | undefined => {\n try {\n const timestamp = dependencies.now()\n\n return Number.isFinite(timestamp) ? timestamp : undefined\n } catch {\n return undefined\n }\n}\n\nconst makeShutdownReason = (outcome: ScopeOutcome): RuntimeShutdownReason => {\n if (outcome.status === 'failure') {\n return {\n kind: 'main-settled',\n cause: outcome.cause\n }\n }\n\n return { kind: 'main-settled' }\n}\n\nconst notifyShutdownFailure = async (\n observer: CleanupFailureObserver | undefined,\n diagnostic: RuntimeShutdownDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Shutdown diagnostics are best effort and never affect the primary result.\n }\n}\n\nconst releaseLayerResource = async (\n service: LayerProvider['service'],\n release: ScopeFinalizer,\n outcome: ScopeOutcome,\n observers: readonly RuntimeObserver[],\n executionId: string | undefined\n): Promise<void> => {\n try {\n await release(outcome)\n const event: RuntimeResourceReleaseEvent = { service, outcome }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n } catch (cause) {\n const event: RuntimeResourceReleaseEvent = { service, outcome, error: cause }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n throw cause\n }\n}\n\nconst lifecycleEventMetadata = (entry: LayerLifecycleEntry) => ({\n kind: 'lifecycle' as const,\n lifecycleId: entry.id\n})\n\nconst releaseLifecycleResource = async (\n entry: LayerLifecycleEntry,\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Lifecycle resources have no Service contract by design.\n resource: unknown,\n outcome: ScopeOutcome,\n observers: readonly RuntimeObserver[]\n): Promise<void> => {\n const metadata = lifecycleEventMetadata(entry)\n\n try {\n await entry.release(resource, outcome)\n const event: RuntimeLifecycleReleaseEvent = { ...metadata, outcome }\n notifyRuntimeObservers(observers, (observer) => observer.onLifecycleRelease, event)\n } catch (cause) {\n const event: RuntimeLifecycleReleaseEvent = { ...metadata, outcome, error: cause }\n notifyRuntimeObservers(observers, (observer) => observer.onLifecycleRelease, event)\n throw cause\n }\n}\n\nconst bindProviderToScope = (\n provider: LayerProvider,\n scope: CloseableScope,\n contextStorage: RuntimeContextStorage,\n resolver: ServiceResolver,\n observers: readonly RuntimeObserver[],\n executor: RuntimeExecutor<AnyService>,\n ownerExecutionId?: string,\n beforeAcquire?: () => void,\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- the callback crosses the erased Layer provider boundary.\n onAcquired?: (instance: unknown) => void\n): LayerRegistration => ({\n service: provider.service,\n serviceTag: provider.serviceTag,\n\n acquire: () => {\n beforeAcquire?.()\n const current = getRuntimeContext(contextStorage)\n const executionId = current?.executionId ?? ownerExecutionId\n const context = makeRuntimeContext(\n resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal,\n current,\n undefined,\n executor\n )\n\n return runRuntimeContext(contextStorage, context, () =>\n ScopeRuntime.run(\n scope,\n async () => {\n const resolutionPath = current?.resolutionPath ?? [provider.service]\n\n try {\n const instance = provider.acquireWithRelease\n ? (\n await scope.acquire(provider.acquireWithRelease, (acquired, outcome) =>\n releaseLayerResource(\n provider.service,\n acquired.release,\n outcome,\n observers,\n ownerExecutionId\n )\n )\n ).instance\n : provider.release\n ? await scope.acquire(\n () => provider.acquire(),\n (resource, outcome) =>\n releaseLayerResource(\n provider.service,\n (releaseOutcome) => provider.release!(resource, releaseOutcome),\n outcome,\n observers,\n ownerExecutionId\n )\n )\n : await provider.acquire()\n\n onAcquired?.(instance)\n\n const event: RuntimeServiceAcquireEvent = {\n service: provider.service,\n resolutionPath,\n outcome: SCOPE_SUCCESS\n }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\n\n return instance\n } catch (cause) {\n const event: RuntimeServiceAcquireEvent = {\n service: provider.service,\n resolutionPath,\n outcome: {\n status: 'failure',\n cause\n }\n }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\n throw cause\n }\n },\n contextStorage\n )\n )\n }\n})\n\n/** Resolve request-local providers first, then fall back to the Runtime root. */\nclass ExecutionLayerBackend implements LayerBackend {\n private readonly localTags = new Set<string>()\n\n constructor(\n private readonly local: MapLayerBackend,\n private readonly root: LayerBackend\n ) {}\n\n register(registration: LayerRegistration): void {\n this.localTags.add(captureLayerRegistrationTag(registration))\n this.local.register(registration)\n }\n\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n\n if (this.localTags.has(tag)) {\n return await this.local.resolve(token)\n }\n\n return await this.root.resolve(token)\n }\n\n async disposeAll(): Promise<void> {\n await this.local.disposeAll()\n this.localTags.clear()\n }\n}\n\nclass RuntimeHandleImpl<Provided extends AnyService> implements RuntimeHandleCore<Provided> {\n private disposePromise: Promise<void> | undefined\n\n private warmupPromise: Promise<void> | undefined\n\n private readonly executions = new Set<ActiveExecution>()\n\n private readonly rootQuiesces: RootQuiesceRegistration[] = []\n\n private readonly serviceTags: readonly string[]\n\n private readonly shutdownController = new AbortController()\n\n private readonly taskSupervisor: RuntimeTaskSupervisor\n\n private state: RuntimeInspection['state'] = 'active'\n\n private warmupState: RuntimeInspection['warmup'] = 'idle'\n\n constructor(\n readonly backend: LayerBackend,\n private readonly resolver: ServiceResolver,\n private readonly rootScope: CloseableScope,\n private readonly onCleanupFailure: CleanupFailureObserver | undefined,\n private readonly contextStorage: RuntimeContextStorage,\n private readonly signal: AbortSignal | undefined,\n private readonly observers: readonly RuntimeObserver[],\n private readonly services: readonly AnyServiceToken[],\n serviceTags: readonly string[],\n private readonly executionDependencies: RuntimeExecutionDependencies,\n private readonly executor: RuntimeExecutor<AnyService>,\n private readonly lifecycleEntries: readonly LayerLifecycleEntry[]\n ) {\n this.serviceTags = Object.freeze([...serviceTags])\n this.taskSupervisor = new RuntimeTaskSupervisor(\n () => this.executionDependencies.createExecutionId(),\n () => this.executionDependencies.now(),\n this.observers,\n this.onCleanupFailure\n )\n this.taskSupervisor.bindScope(this.rootScope)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- root provider instances are intentionally erased internally.\n registerRootQuiesce(provider: LayerProvider, instance: unknown): void {\n if (provider.quiesce === undefined) {\n return\n }\n\n this.rootQuiesces.push({\n started: false,\n quiesce: (reason) => provider.quiesce!(instance, reason)\n })\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- lifecycle resources are intentionally erased internally.\n private registerLifecycleQuiesce(entry: LayerLifecycleEntry, instance: unknown): void {\n if (entry.quiesce === undefined) {\n return\n }\n\n this.rootQuiesces.push({\n started: false,\n quiesce: (reason) => entry.quiesce!(instance, reason)\n })\n }\n\n assertRootAcquisitionAllowed(): void {\n this.assertActive()\n }\n\n private emitShutdown(event: RuntimeShutdownEvent): void {\n notifyRuntimeObservers(this.observers, (observer) => observer.onShutdown, event)\n }\n\n private async quiesceResources(reason: RuntimeShutdownReason): Promise<readonly unknown[]> {\n const failures: unknown[] = []\n\n for (;;) {\n const registration = [...this.rootQuiesces].reverse().find((candidate) => !candidate.started)\n\n if (registration === undefined) {\n return failures\n }\n\n registration.started = true\n\n try {\n await registration.quiesce(reason)\n } catch (cause) {\n failures.push(cause)\n }\n }\n }\n\n inspect(): RuntimeInspection {\n const tasks = this.taskSupervisor.inspect()\n const executions = Object.freeze(\n [...this.executions].map(({ metadata }) => {\n const inspection: MutableRuntimeExecutionInspection = {\n executionId: metadata.executionId,\n startedAt: metadata.startedAt\n }\n\n if (metadata.name !== undefined) {\n inspection.name = metadata.name\n }\n\n return Object.freeze(inspection)\n })\n )\n\n return Object.freeze({\n state: this.state,\n warmup: this.warmupState,\n activeExecutions: executions.length,\n executions,\n activeTasks: tasks.length,\n tasks,\n services: Object.freeze([...this.serviceTags]),\n shutdownSignalAborted: this.shutdownController.signal.aborted\n })\n }\n\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n let prepared: PreparedExecution\n\n try {\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal\n )\n } catch (cause) {\n return Promise.reject(cause)\n }\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n this.taskSupervisor.bindScope(executionScope)\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n return this.startExecution<Awaited<A>>(prepared.signalLink, prepared.metadata, () =>\n this.runExecution(\n executionScope,\n program,\n this.resolver,\n prepared.signalLink.signal,\n prepared.metadata\n )\n )\n }\n\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n let prepared: PreparedExecution\n\n try {\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal\n )\n } catch (cause) {\n return Promise.reject(cause)\n }\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n this.taskSupervisor.bindScope(executionScope)\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n return this.startExecution<Awaited<A>>(\n prepared.signalLink,\n prepared.metadata,\n async (): Promise<Awaited<A>> => {\n try {\n return await this.runExecution<Awaited<A>>(\n executionScope,\n async (): Promise<Awaited<A>> => {\n for (const provider of layer.providers) {\n backend.register(\n bindProviderToScope(\n provider,\n executionScope,\n this.contextStorage,\n resolver,\n this.observers,\n this.executor,\n prepared.metadata.executionId\n )\n )\n }\n\n return await program()\n },\n resolver,\n prepared.signalLink.signal,\n prepared.metadata\n )\n } finally {\n await localBackend.disposeAll()\n }\n }\n )\n }\n\n runWithManaged<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, RuntimeManagedPlan<A>>,\n options?: RuntimeRunOptions\n ): RuntimeManagedExecution<A> {\n this.assertActive()\n\n const managedController = new AbortController()\n let prepared: PreparedExecution\n\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal,\n managedController.signal\n )\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n this.taskSupervisor.bindScope(executionScope)\n const executionContext = makeRuntimeContext(\n resolver,\n executionScope,\n [],\n prepared.signalLink.signal,\n undefined,\n prepared.metadata.executionId,\n this.executor\n )\n\n let plan: RuntimeManagedPlan<A> | undefined\n let pendingCancel: unknown\n let cancelPromise: Promise<void> | undefined\n let executionPromise!: Promise<void>\n let settled = false\n let resolveReadiness!: (value: Awaited<A>) => void\n let rejectReadiness!: (cause?: unknown) => void\n const readiness = new Promise<Awaited<A>>((resolve, reject) => {\n resolveReadiness = resolve\n rejectReadiness = reject\n })\n void readiness.catch(() => undefined)\n\n const runInExecution = <B>(operation: () => B | PromiseLike<B>): Promise<Awaited<B>> => {\n if (settled) {\n return Promise.reject(new RuntimeHandleDisposedError())\n }\n\n return Promise.resolve(\n runRuntimeContext(this.contextStorage, executionContext, () =>\n ScopeRuntime.run(executionScope, operation, this.contextStorage)\n )\n )\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- preserve caller-defined cancellation reasons.\n const cancel = (reason?: unknown): Promise<void> => {\n if (cancelPromise !== undefined) {\n return cancelPromise\n }\n\n cancelPromise = (async () => {\n pendingCancel = reason === undefined ? new Error('Managed execution cancelled') : reason\n\n if (!managedController.signal.aborted) {\n managedController.abort(pendingCancel)\n }\n\n const currentPlan = plan\n if (currentPlan?.cancel !== undefined) {\n try {\n await currentPlan.cancel(pendingCancel)\n } catch {\n // The execution outcome remains the primary cancellation result.\n }\n }\n\n if (executionPromise !== undefined) {\n await executionPromise.catch(() => undefined)\n }\n })()\n\n return cancelPromise\n }\n\n const run = async (): Promise<void> => {\n try {\n for (const provider of layer.providers) {\n backend.register(\n bindProviderToScope(\n provider,\n executionScope,\n this.contextStorage,\n resolver,\n this.observers,\n this.executor,\n prepared.metadata.executionId\n )\n )\n }\n\n const next = await program()\n plan = next\n\n if (pendingCancel !== undefined) {\n rejectReadiness(pendingCancel)\n await next.cancel?.(pendingCancel)\n throw pendingCancel\n }\n\n try {\n resolveReadiness(await next.readiness)\n } catch (cause) {\n rejectReadiness(cause)\n await next.cancel?.(cause)\n throw cause\n }\n\n return await next.completion\n } catch (cause) {\n rejectReadiness(cause)\n throw cause\n }\n }\n\n executionPromise = this.startExecution<void>(\n prepared.signalLink,\n prepared.metadata,\n async () => {\n try {\n return await this.runExecution(\n executionScope,\n run,\n resolver,\n prepared.signalLink.signal,\n prepared.metadata,\n executionContext\n )\n } finally {\n await localBackend.disposeAll()\n }\n }\n )\n\n void executionPromise.then(\n () => {\n settled = true\n },\n () => {\n settled = true\n }\n )\n void executionPromise.catch(() => undefined)\n\n const signalListener = (): void => {\n void cancel(prepared.signalLink.signal.reason)\n }\n if (!prepared.signalLink.signal.aborted) {\n prepared.signalLink.signal.addEventListener('abort', signalListener, { once: true })\n }\n\n void executionPromise.then(\n () => prepared.signalLink.signal.removeEventListener('abort', signalListener),\n () => prepared.signalLink.signal.removeEventListener('abort', signalListener)\n )\n\n const completion = executionPromise.then(() => undefined)\n void completion.catch(() => undefined)\n\n return Object.freeze({\n readiness,\n completion,\n signal: prepared.signalLink.signal,\n run: runInExecution,\n cancel\n })\n }\n\n warmup(): Promise<void> {\n this.assertActive()\n\n if (this.warmupPromise) {\n return this.warmupPromise\n }\n\n this.warmupState = 'running'\n\n let warmup: Promise<void>\n\n try {\n warmup = runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(\n this.resolver,\n this.rootScope,\n [],\n this.signal,\n undefined,\n undefined,\n this.executor\n ),\n async () => {\n for (const service of this.services) {\n await this.resolver.resolve(service)\n }\n }\n )\n } catch (cause) {\n this.warmupState = 'failed'\n return Promise.reject(cause)\n }\n\n this.warmupPromise = warmup\n\n void warmup.then(\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupState = 'completed'\n this.warmupPromise = undefined\n }\n },\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupState = 'failed'\n this.warmupPromise = undefined\n }\n }\n )\n\n return warmup\n }\n\n activateLifecycle(): Promise<void> {\n this.assertActive()\n\n if (this.lifecycleEntries.length === 0) {\n return Promise.resolve()\n }\n\n return runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(\n this.resolver,\n this.rootScope,\n [],\n this.signal,\n undefined,\n undefined,\n this.executor\n ),\n () =>\n ScopeRuntime.run(this.rootScope, async () => {\n for (const entry of this.lifecycleEntries) {\n const metadata = lifecycleEventMetadata(entry)\n const startEvent: RuntimeLifecycleStartEvent = Object.freeze({ ...metadata })\n notifyRuntimeObservers(\n this.observers,\n (observer) => observer.onLifecycleStart,\n startEvent\n )\n\n try {\n const resource = await this.rootScope.acquire(\n () => entry.acquire(),\n (resource, outcome) =>\n releaseLifecycleResource(entry, resource, outcome, this.observers)\n )\n this.registerLifecycleQuiesce(entry, resource)\n const endEvent: RuntimeLifecycleEndEvent = Object.freeze({\n ...metadata,\n outcome: SCOPE_SUCCESS\n })\n notifyRuntimeObservers(\n this.observers,\n (observer) => observer.onLifecycleEnd,\n endEvent\n )\n } catch (cause) {\n const endEvent: RuntimeLifecycleEndEvent = Object.freeze({\n ...metadata,\n outcome: { status: 'failure', cause },\n error: cause\n })\n notifyRuntimeObservers(\n this.observers,\n (observer) => observer.onLifecycleEnd,\n endEvent\n )\n throw cause\n }\n }\n })\n )\n }\n\n private startExecution<A>(\n signalLink: AbortSignalLink,\n metadata: RuntimeExecutionMetadata,\n run: (metadata: RuntimeExecutionMetadata) => PromiseLike<A>\n ): Promise<A> {\n let resolveExecution!: (value: A | PromiseLike<A>) => void\n let rejectExecution!: (cause?: unknown) => void\n\n const execution = new Promise<A>((resolve, reject) => {\n resolveExecution = resolve\n rejectExecution = reject\n })\n\n const activeExecution: ActiveExecution = { promise: execution, metadata }\n\n this.executions.add(activeExecution)\n\n void execution.then(\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n },\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n }\n )\n\n try {\n const running = run(metadata)\n\n void running.then(\n (value) => {\n resolveExecution(value)\n },\n (cause) => {\n rejectExecution(cause)\n }\n )\n } catch (cause) {\n rejectExecution(cause)\n }\n\n return execution\n }\n\n private runExecution<A>(\n executionScope: CloseableScope,\n program: () => A | PromiseLike<A>,\n resolver: ServiceResolver = this.resolver,\n signal: AbortSignal = this.shutdownController.signal,\n metadata: RuntimeExecutionMetadata,\n executionContext?: CompleteRuntimeContext\n ): Promise<Awaited<A>> {\n let outcome: ScopeOutcome | undefined\n let cleanupFailure: ScopeCloseError | undefined\n const onOutcome = (determinedOutcome: ScopeOutcome): void => {\n outcome = determinedOutcome\n }\n const onExecutionCleanupFailure = async (\n diagnostic: CleanupFailureDiagnostic\n ): Promise<void> => {\n cleanupFailure = diagnostic.error\n\n if (this.onCleanupFailure !== undefined) {\n await this.onCleanupFailure(diagnostic)\n }\n }\n const runOptions = {\n classify: classifyRuntimeOutcome,\n onOutcome,\n onCleanupFailure: onExecutionCleanupFailure\n }\n\n const startEvent = Object.freeze({\n ...metadata,\n scope: executionScope\n })\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, startEvent)\n\n let ended = false\n const notifyEnd = (finalOutcome: ScopeOutcome): void => {\n if (ended) {\n return\n }\n\n ended = true\n const endEvent: RuntimeExecutionEndEvent = {\n ...metadata,\n scope: executionScope,\n outcome: finalOutcome,\n durationMs: executionDuration(metadata, this.executionDependencies)\n }\n\n if (cleanupFailure !== undefined) {\n Object.assign(endEvent, { cleanupFailure })\n }\n\n notifyRuntimeObservers(\n this.observers,\n (observer) => observer.onExecutionEnd,\n Object.freeze(endEvent)\n )\n }\n\n let execution: Promise<Awaited<A>>\n\n try {\n execution = runScoped(executionScope, program, {\n ...runOptions,\n contextStorage: this.contextStorage,\n context:\n executionContext ??\n makeRuntimeContext(\n resolver,\n executionScope,\n [],\n signal,\n undefined,\n metadata.executionId,\n this.executor\n )\n })\n } catch (cause) {\n const failure: ScopeOutcome = {\n status: 'failure',\n cause\n }\n notifyEnd(failure)\n return Promise.reject(cause)\n }\n\n return execution.then(\n (value) => {\n notifyEnd(\n outcome ?? {\n status: 'success'\n }\n )\n return value\n },\n (cause) => {\n notifyEnd(\n outcome ?? {\n status: 'failure',\n cause\n }\n )\n throw cause\n }\n )\n }\n\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n if (this.disposePromise) {\n return this.disposePromise\n }\n\n const outcome =\n isScopeOutcome(input) || input === undefined ? (input ?? SCOPE_SUCCESS) : SCOPE_SUCCESS\n const options = isScopeOutcome(input) || input === undefined ? {} : input\n\n validateDisposeOptions(options)\n const reason = Object.freeze(\n options.reason ??\n (isScopeOutcome(input) ? makeShutdownReason(input) : { kind: 'dispose' as const })\n )\n this.state = 'quiescing'\n let resolveDispose!: () => void\n let rejectDispose!: (cause: unknown) => void\n const disposePromise = new Promise<void>((resolve, reject) => {\n resolveDispose = resolve\n rejectDispose = reject\n })\n this.disposePromise = disposePromise\n this.emitShutdown(\n Object.freeze({\n phase: 'shutdown-requested' as const,\n reason,\n activeExecutions: this.executions.size\n })\n )\n\n void this.performDispose(outcome, options, reason).then(resolveDispose, rejectDispose)\n\n return disposePromise\n }\n\n private async performDispose(\n outcome: ScopeOutcome,\n options: RuntimeDisposeOptions,\n reason: RuntimeShutdownReason\n ): Promise<void> {\n const failures: unknown[] = []\n\n if (this.warmupPromise !== undefined) {\n await Promise.allSettled([this.warmupPromise])\n }\n\n const quiesceStartedAt = readRuntimeTimestamp(this.executionDependencies)\n this.emitShutdown({ phase: 'quiesce-start', reason })\n failures.push(...(await this.quiesceResources(reason)))\n const quiesceEnd: RuntimeShutdownEvent = {\n phase: 'quiesce-end',\n reason\n }\n if (quiesceStartedAt !== undefined) {\n Object.assign(quiesceEnd, {\n durationMs: Math.max(\n 0,\n (readRuntimeTimestamp(this.executionDependencies) ?? quiesceStartedAt) - quiesceStartedAt\n )\n })\n }\n this.emitShutdown(quiesceEnd)\n\n this.state = 'draining'\n const executions = [...this.executions]\n this.emitShutdown({ phase: 'drain-start', reason, activeExecutions: executions.length })\n await this.waitForExecutions(executions, options, reason)\n // A just-admitted execution can finish a root acquisition during drain.\n // Quiesce such late resources before the root Scope is released.\n failures.push(...(await this.quiesceResources(reason)))\n this.emitShutdown({ phase: 'drain-end', reason, activeExecutions: this.executions.size })\n\n this.state = 'releasing'\n this.emitShutdown({ phase: 'release-start', reason })\n try {\n const signalLink = linkAbortSignals(this.signal, this.shutdownController.signal)\n\n try {\n await runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(\n this.resolver,\n this.rootScope,\n [],\n signalLink.signal,\n undefined,\n undefined,\n this.executor\n ),\n () => this.rootScope.close(outcome)\n )\n } finally {\n signalLink.dispose()\n }\n } catch (cause) {\n failures.push(cause)\n }\n\n try {\n await this.backend.disposeAll()\n } catch (cause) {\n failures.push(cause)\n }\n\n this.state = 'disposed'\n\n this.emitShutdown({ phase: 'release-end', reason })\n\n if (failures.length > 0) {\n const error = new LayerDisposeError(failures.flatMap(normalizeDisposeCauses))\n\n this.emitShutdown({ phase: 'shutdown-failure', reason, error })\n\n await notifyShutdownFailure(this.onCleanupFailure, {\n outcome,\n error\n })\n\n throw error\n }\n\n this.emitShutdown({ phase: 'shutdown-complete', reason })\n }\n\n private async waitForExecutions(\n executions: readonly ActiveExecution[],\n options: RuntimeDisposeOptions,\n reason: RuntimeShutdownReason\n ): Promise<void> {\n const settled = Promise.allSettled(executions.map((execution) => execution.promise))\n\n if (options.abortAfterGracePeriod !== true || executions.length === 0) {\n await settled\n return\n }\n\n const gracePeriod = options.gracePeriod ?? 0\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const timedOut = await Promise.race([\n settled.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), gracePeriod)\n })\n ])\n\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n\n if (timedOut && !this.shutdownController.signal.aborted) {\n this.state = 'aborting'\n this.emitShutdown({\n phase: 'abort-active',\n reason,\n activeExecutions: this.executions.size\n })\n this.shutdownController.abort(new Error('Runtime shutdown grace period exceeded'))\n }\n\n await settled\n }\n\n private assertActive(): void {\n if (this.state !== 'active') {\n throw new RuntimeHandleDisposedError()\n }\n }\n}\n\n/** Build a Runtime handle for a complete Layer and register its providers. */\nexport const createRuntimeHandle = async <L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options: RuntimeOptions = {},\n executionOverrides: RuntimeExecutionDependencyOverrides = {},\n providedExecutor?: RuntimeExecutor<ProvidedEnvironment<L>>\n): Promise<RuntimeHandle<ProvidedEnvironment<L>>> => {\n const entries = getLayerEntries(layer)\n const providers = entries.filter((entry): entry is LayerProvider => !isLifecycleEntry(entry))\n const lifecycleEntries = entries.filter(isLifecycleEntry)\n const services = providers.map((provider) => provider.service)\n const serviceTags = providers.map((provider) => captureLayerRegistrationTag(provider))\n const rootScope = Scope.make()\n const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage\n const observers = options.observers ?? []\n const resolver = createResolutionResolver(backend, contextStorage, observers)\n const executionDependencies = makeRuntimeExecutionDependencies(executionOverrides)\n ScopeRuntime.bind(rootScope, contextStorage)\n let handle: RuntimeHandleImpl<ProvidedEnvironment<L>> | undefined\n const pendingRootQuiesces: Array<{ provider: LayerProvider; instance: unknown }> = []\n const executor =\n providedExecutor ??\n createRuntimeExecutor<ProvidedEnvironment<L>>({\n run: (program, runOptions) => handle!.run(program, runOptions),\n runWith: (request, program, runOptions) => handle!.runWith(request, program, runOptions),\n runWithManaged: (request, program, runOptions) =>\n handle!.runWithManaged(request, program, runOptions)\n })\n const contextExecutor = eraseRuntimeExecutor(executor)\n let current: LayerProvider | undefined\n\n try {\n for (const provider of providers) {\n current = provider\n\n await backend.register(\n bindProviderToScope(\n provider,\n rootScope,\n contextStorage,\n resolver,\n observers,\n contextExecutor,\n undefined,\n () => handle?.assertRootAcquisitionAllowed(),\n (instance) => {\n if (handle === undefined) {\n pendingRootQuiesces.push({ provider, instance })\n } else {\n handle.registerRootQuiesce(provider, instance)\n }\n }\n )\n )\n }\n } catch (registrationCause) {\n const outcome: ScopeOutcome = {\n status: 'failure',\n cause: registrationCause\n }\n const cleanupCauses: unknown[] = []\n\n try {\n await runRuntimeContext(\n contextStorage,\n makeRuntimeContext(\n resolver,\n rootScope,\n [],\n options.signal,\n undefined,\n undefined,\n contextExecutor\n ),\n () => rootScope.close(outcome)\n )\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n try {\n await backend.disposeAll()\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n if (cleanupCauses.length > 0) {\n const shutdownError = new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(options.onCleanupFailure, {\n outcome,\n error: shutdownError\n })\n }\n\n const cleanupCause =\n cleanupCauses.length === 1\n ? cleanupCauses[0]\n : cleanupCauses.length > 1\n ? new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n : undefined\n\n throw new LayerRegistrationError(current?.service, registrationCause, cleanupCause)\n }\n\n handle = new RuntimeHandleImpl<ProvidedEnvironment<L>>(\n backend,\n resolver,\n rootScope,\n options.onCleanupFailure,\n contextStorage,\n options.signal,\n observers,\n services,\n serviceTags,\n executionDependencies,\n contextExecutor,\n lifecycleEntries\n )\n\n for (const { provider, instance } of pendingRootQuiesces) {\n handle.registerRootQuiesce(provider, instance)\n }\n\n return handle\n}\n\nconst isLifecycleEntry = (\n entry: LayerProvider | LayerLifecycleEntry\n): entry is LayerLifecycleEntry => 'kind' in entry && entry.kind === 'lifecycle'\n","import type { LayerBackend } from '../layer'\n\nimport { MapLayerBackend } from '../layer/map-layer-backend'\n\nimport { createRuntimeHandle, type RuntimeHandle } from '../layer/runtime'\n\nimport type {\n CompleteExecutionLayer,\n LayerInput,\n CompleteInput,\n ProvidedEnvironment\n} from '../layer/inference'\n\nimport type { CompleteExecution } from '../layer/inference'\n\nimport type { AnyService } from '../service'\n\nimport {\n classifyRuntimeOutcome,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from './outcome'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport type { RuntimeExecutionInspection, RuntimeFor, RuntimeInspection } from './types'\n\nimport type { RuntimeObserver } from './observer'\n\nimport {\n createRuntimeExecutor,\n makeRuntimeExecutorRequest,\n type RuntimeExecutor,\n type RuntimeExecutorRequest,\n type RuntimeManagedPlan\n} from './executor'\n\ntype RuntimeOptionsInput = RuntimeOptions & RuntimeRunOptions\n\ntype RuntimeBackendInput = LayerBackend | RuntimeOptionsInput | undefined\n\ntype RuntimeConfig = {\n readonly backend: LayerBackend\n readonly options: RuntimeOptionsInput\n}\n\nconst isLayerBackend = (value: RuntimeBackendInput): value is LayerBackend =>\n value !== undefined && 'register' in value && 'resolve' in value && 'disposeAll' in value\n\nconst resolveRuntimeConfig = (\n backendOrOptions: RuntimeBackendInput,\n legacyOptions?: RuntimeOptionsInput\n): RuntimeConfig => {\n if (isLayerBackend(backendOrOptions)) {\n return {\n backend: backendOrOptions,\n options: legacyOptions ?? {}\n }\n }\n\n const options = backendOrOptions ?? {}\n\n return {\n backend: options.backend ?? new MapLayerBackend(),\n options\n }\n}\n\n/**\n * Long-lived execution environment backed by a complete Layer.\n *\n * A Runtime owns Layer resources until `dispose()` is called. Each `run()` is\n * isolated in a child Scope, while Layer-scoped resources remain shared.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(loadUser('u1'))\n * await runtime.dispose()\n * ```\n *\n * @typeParam Provided The branded Service instances supplied by the Layer.\n */\nexport class Runtime<Provided extends AnyService = any> {\n readonly executor: RuntimeExecutor<Provided>\n\n private constructor(\n private readonly handle: RuntimeHandle<Provided>,\n executor: RuntimeExecutor<Provided>\n ) {\n this.executor = executor\n }\n\n /**\n * Create a long-lived Runtime that owns its Layer resources.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(program)\n * await runtime.dispose()\n * ```\n */\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static async make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrOptions?: LayerBackend | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>> {\n const { backend, options } = resolveRuntimeConfig(backendOrOptions, legacyOptions)\n let handle!: RuntimeHandle<ProvidedEnvironment<L>>\n const executor = createRuntimeExecutor<ProvidedEnvironment<L>>({\n run: <A>(\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n runOptions?: RuntimeRunOptions\n ) => handle.run(program, runOptions),\n runWith: <Request extends LayerInput, A>(\n request: Request & CompleteExecutionLayer<ProvidedEnvironment<L>, Request>,\n program: CompleteExecution<ProvidedEnvironment<L> | ProvidedEnvironment<Request>, A>,\n runOptions?: RuntimeRunOptions\n ) => handle.runWith(request, program, runOptions),\n runWithManaged: <Request extends LayerInput, A>(\n request: Request & CompleteExecutionLayer<ProvidedEnvironment<L>, Request>,\n program: CompleteExecution<\n ProvidedEnvironment<L> | ProvidedEnvironment<Request>,\n RuntimeManagedPlan<A>\n >,\n runOptions?: RuntimeRunOptions\n ) => handle.runWithManaged(request, program, runOptions)\n })\n handle = await createRuntimeHandle(layer, backend, options, {}, executor)\n const runtime = new Runtime<ProvidedEnvironment<L>>(handle, executor)\n\n try {\n if (options.warmup) {\n await runtime.warmup()\n }\n\n await handle.activateLifecycle()\n } catch (cause) {\n try {\n await runtime.disposeWithOutcome({ status: 'failure', cause })\n } catch {\n // Lifecycle activation remains the primary Runtime.make failure.\n }\n\n throw cause\n }\n\n return runtime\n }\n\n /**\n * Run one program and dispose its Layer resources before resolving.\n *\n * This is convenient for request-style or command-style execution where a\n * Runtime should not outlive the operation.\n */\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptionsInput\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptionsInput\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options: RuntimeOptionsInput,\n program: CompleteExecution<ProvidedEnvironment<L>, A>\n ): Promise<Awaited<A>>\n\n static async run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrProgramOrOptions:\n | LayerBackend\n | RuntimeOptionsInput\n | CompleteExecution<ProvidedEnvironment<L>, A>,\n programOrOptions?: CompleteExecution<ProvidedEnvironment<L>, A> | RuntimeOptionsInput,\n legacyOptions?: RuntimeOptionsInput\n ): Promise<Awaited<A>> {\n let program: CompleteExecution<ProvidedEnvironment<L>, A>\n let backendOrOptions: RuntimeBackendInput\n let options: RuntimeOptionsInput | undefined\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch needs to distinguish a Program callback from configuration.\n if (typeof backendOrProgramOrOptions === 'function') {\n program = backendOrProgramOrOptions\n // SAFETY: The function overload branch establishes that this argument is the optional RuntimeOptions value.\n backendOrOptions = programOrOptions as RuntimeOptionsInput | undefined\n options = undefined\n } else {\n backendOrOptions = backendOrProgramOrOptions\n // SAFETY: The non-function overload branch establishes that this argument is the complete execution callback.\n program = programOrOptions as CompleteExecution<ProvidedEnvironment<L>, A>\n options = legacyOptions\n }\n\n const config = resolveRuntimeConfig(backendOrOptions, options)\n let programOutcome: ScopeOutcome | undefined\n const outcomeObserver: RuntimeObserver = {\n onExecutionEnd: ({ outcome }) => {\n programOutcome = outcome\n }\n }\n const runtimeOptions: RuntimeOptions = {\n ...config.options,\n observers: [outcomeObserver, ...(config.options.observers ?? [])]\n }\n const runtime = await Runtime.make(layer, config.backend, runtimeOptions)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n\n try {\n value = await runtime.runUnchecked(program, config.options)\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Run a callback with a managed Runtime and always dispose it afterward. */\n static use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static async use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>> {\n const runtime = await Runtime.make(layer, options)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n let programOutcome: ScopeOutcome | undefined\n\n try {\n value = await use(runtime)\n programOutcome = classifyRuntimeOutcome(value)\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n programOutcome = {\n status: 'failure',\n cause\n }\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Request the non-owning executor view from the current Runtime context. */\n static executor<Requested extends AnyService>(): RuntimeExecutorRequest<Requested> {\n return makeRuntimeExecutorRequest<Requested>()\n }\n\n /** Resolve every Layer provider and dispose the Runtime if warmup fails. */\n async warmup(): Promise<void> {\n try {\n await this.handle.warmup()\n } catch (cause) {\n try {\n await this.handle.dispose({ status: 'failure', cause })\n } catch {\n // Warmup failure remains the primary error; cleanup is best effort.\n }\n\n throw cause\n }\n }\n\n /** Return a detached diagnostic snapshot without changing Runtime state. */\n inspect(): RuntimeInspection {\n return this.handle.inspect()\n }\n\n /** Run one execution in this Runtime's child Scope. */\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.run(program, options)\n }\n\n /** Run one execution with a Layer owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.runWith(layer, program, options)\n }\n\n private runUnchecked<A>(\n program: () => A | PromiseLike<A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n // SAFETY: One-shot Runtime.run performs the same complete-program validation at its public boundary before using this internal escape hatch.\n return this.handle.run(program as CompleteExecution<Provided, A>, options)\n }\n\n /** Stop new executions and release the Runtime's Layer resources. */\n dispose(options?: RuntimeDisposeOptions): Promise<void>\n\n /** @deprecated Scope outcomes are kept for internal compatibility. */\n dispose(outcome: ScopeOutcome): Promise<void>\n\n dispose(optionsOrOutcome?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n return this.handle.dispose(optionsOrOutcome)\n }\n\n /** Release Runtime-owned resources through JavaScript's async disposal protocol. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose()\n }\n\n private disposeWithOutcome(outcome: ScopeOutcome): Promise<void> {\n return this.handle.dispose(outcome)\n }\n}\n\n/** Type-level aliases for naming Runtime handles and shutdown options. */\nexport declare namespace Runtime {\n /** Name a Runtime type from a concrete Layer. */\n export type For<L extends LayerInput> = RuntimeFor<L>\n\n /** Optional Runtime shutdown configuration. */\n export type Options = RuntimeOptions\n\n /** Optional signal supplied to one managed Runtime execution. */\n export type RunOptions = RuntimeRunOptions\n\n /** Cooperative shutdown policy for a managed Runtime. */\n export type DisposeOptions = RuntimeDisposeOptions\n\n /** Diagnostic reported for aggregated Runtime shutdown cleanup failures. */\n export type ShutdownDiagnostic = RuntimeShutdownDiagnostic\n\n /** Detached diagnostic snapshot returned by `Runtime.inspect()`. */\n export type Inspection = RuntimeInspection\n\n /** Detached diagnostic view of one active execution. */\n export type ExecutionInspection = RuntimeExecutionInspection\n\n /** Non-owning view that can start child Runtime executions. */\n export type Executor<Provided extends AnyService = any> = RuntimeExecutor<Provided>\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,gCAAgB,IAAI,QAAuC;;AAGjE,IAAa,eAAb,MAA0B;;CAExB,OAAO,IACL,OACA,SACA,UAAiC,cAAc,IAAI,KAAK,KAAK,4BAA4B,GACtF;EACH,cAAc,IAAI,OAAO,OAAO;EAEhC,MAAM,UAAU,kBAAkB,OAAO;EACzC,MAAM,UAAU,mBACd,SAAS,UACT,OACA,SAAS,kBAAkB,CAAC,GAC5B,SAAS,QACT,OACF;EAEA,OAAO,kBAAkB,SAAS,SAAS,OAAO;CACpD;;CAGA,OAAO,UAAiB;EACtB,IAAI;EAEJ,IAAI;GACF,UAAU,sBA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GA,OAAO,OAAO,gBAA+B;EAC3C,MAAM,KAAK,QAAQ;CACrB;CAEA,mBAA2B,SAAsC;EAC/D,OAAO,KAAK,OAAO,QAAQ,OAAO;CACpC;AACF"}
@@ -0,0 +1,74 @@
1
+ import { m as validateServiceTag, p as registerServiceTag } from "./registration-Bwe2GbVu.mjs";
2
+ import { l as ServiceRuntime } from "./layer-2kjHVv4N.mjs";
3
+ //#region src/service/service.ts
4
+ /**
5
+ * Declare a class-backed Service with a stable string-literal identity.
6
+ *
7
+ * The returned class is simultaneously the implementation type, the runtime
8
+ * dependency token, and the value yielded by `yield*` in an Effect generator.
9
+ * The explicit self type preserves exact instance inference, while the second
10
+ * call captures the tag as a literal for Layer composition and diagnostics.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * class Database extends Service<Database>()('Database') {
15
+ * query(): string {
16
+ * return 'ok'
17
+ * }
18
+ * }
19
+ *
20
+ * const database = yield* Database
21
+ * database.query()
22
+ * ```
23
+ *
24
+ * @typeParam Self The instance type implemented by the declared Service.
25
+ */
26
+ function Service() {
27
+ return function(tag) {
28
+ validateServiceTag(tag);
29
+ class BaseService {
30
+ /** The stable logical identity used by Layers and resolver backends. */
31
+ static serviceTag = tag;
32
+ /**
33
+ * Type-check a structural implementation of this Service.
34
+ *
35
+ * This is an identity helper. It returns the supplied value unchanged
36
+ * and does not invoke a constructor or modify its prototype.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * class Database extends Service<Database>()('Database') {
41
+ * query(sql: string): string {
42
+ * return sql
43
+ * }
44
+ * }
45
+ *
46
+ * const database = Database.of({
47
+ * query: (sql) => `Result: ${sql}`
48
+ * })
49
+ *
50
+ * database.query('SELECT 1')
51
+ * // 'Result: SELECT 1'
52
+ * // database is the original object, not an instance of Database
53
+ * ```
54
+ */
55
+ static of(implementation) {
56
+ return implementation;
57
+ }
58
+ /** Yield this Service as a runtime token for synchronous factory runners. */
59
+ static *[Symbol.iterator]() {
60
+ return yield this;
61
+ }
62
+ /** Resolve this Service from the resolver active in the current runtime. */
63
+ static async *[Symbol.asyncIterator]() {
64
+ return await ServiceRuntime.resolve(this);
65
+ }
66
+ }
67
+ registerServiceTag(BaseService, tag);
68
+ return BaseService;
69
+ };
70
+ }
71
+ //#endregion
72
+ export { Service as t };
73
+
74
+ //# sourceMappingURL=service-CO9VJQYa.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-CO9VJQYa.mjs","names":[],"sources":["../src/service/service.ts"],"sourcesContent":["import { ServiceRuntime } from './runtime'\nimport { registerServiceTag, validateServiceTag } from './tag'\n\nimport type { ServiceRequirement } from '../effect/types'\n\nimport type {\n AnyService,\n AnyServiceToken,\n ServiceClass,\n ServiceContract,\n ServiceIdentity,\n ServiceIdentityTypeId,\n ServiceInstance,\n ServiceRequirements,\n ServiceTag,\n ServiceToken,\n ServiceTokenOf\n} from './types'\n\ntype ServiceTagLiteral<Tag extends string> = string extends Tag\n ? never\n : Tag extends ''\n ? never\n : Tag\n\ninterface ServiceFactory<Self> {\n <const Tag extends string>(\n tag: ServiceTagLiteral<Tag>\n ): (abstract new () => ServiceIdentity<Tag>) & {\n readonly name: string\n readonly serviceTag: Tag\n } & {\n readonly of: Service.FactoryOf<Self, Tag>\n readonly [Symbol.iterator]: (\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ) => Generator<ServiceRequirement<Self>, Self, unknown>\n readonly [Symbol.asyncIterator]: (\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ) => AsyncGenerator<ServiceRequirement<Self>, Self, unknown>\n }\n}\n\n/**\n * Declare a class-backed Service with a stable string-literal identity.\n *\n * The returned class is simultaneously the implementation type, the runtime\n * dependency token, and the value yielded by `yield*` in an Effect generator.\n * The explicit self type preserves exact instance inference, while the second\n * call captures the tag as a literal for Layer composition and diagnostics.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(): string {\n * return 'ok'\n * }\n * }\n *\n * const database = yield* Database\n * database.query()\n * ```\n *\n * @typeParam Self The instance type implemented by the declared Service.\n */\nexport function Service<Self>(): ServiceFactory<Self> {\n return function <const Tag extends string>(tag: ServiceTagLiteral<Tag>) {\n validateServiceTag(tag)\n\n abstract class BaseService implements ServiceIdentity<Tag> {\n /** The stable logical identity used by Layers and resolver backends. */\n static readonly serviceTag: Tag = tag\n declare readonly [ServiceIdentityTypeId]: Tag\n\n /**\n * Type-check a structural implementation of this Service.\n *\n * This is an identity helper. It returns the supplied value unchanged\n * and does not invoke a constructor or modify its prototype.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(sql: string): string {\n * return sql\n * }\n * }\n *\n * const database = Database.of({\n * query: (sql) => `Result: ${sql}`\n * })\n *\n * database.query('SELECT 1')\n * // 'Result: SELECT 1'\n * // database is the original object, not an instance of Database\n * ```\n */\n static of(this: void, implementation: ServiceContract<Self & ServiceIdentity<Tag>>): Self {\n // SAFETY: ServiceContract removes only the phantom marker; this boundary restores Self.\n return implementation as Self\n }\n\n /** Yield this Service as a runtime token for synchronous factory runners. */\n static *[Symbol.iterator](\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ): Generator<ServiceRequirement<Self>, Self, unknown> {\n // SAFETY: The marker is declaration-only; synchronous factory runners replace it with the resolved instance.\n // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- the runtime token is represented by a phantom requirement yield.\n return (yield this as unknown as ServiceRequirement<Self>) as Self\n }\n\n /** Resolve this Service from the resolver active in the current runtime. */\n // oxlint-disable-next-line require-yield\n static async *[Symbol.asyncIterator](\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ): AsyncGenerator<ServiceRequirement<Self>, Self, unknown> {\n return await ServiceRuntime.resolve(this)\n }\n }\n\n registerServiceTag(BaseService, tag)\n\n return BaseService\n }\n}\n\n/** Type-level aliases for Service tokens and their instance contracts. */\nexport declare namespace Service {\n /** The widened Service instance constraint. */\n export type Any = AnyService\n\n /** A class-backed Service token with a stable tag and instance contract. */\n export type Token<Tag extends string = string, Instance extends AnyService = any> = ServiceToken<\n Tag,\n Instance\n >\n\n /** A constructible Service class with a stable tag and instance contract. */\n export type Class<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n > = ServiceClass<Tag, Instance>\n\n /** Extract the instance represented by a Service token. */\n export type Instance<T extends AnyServiceToken> = ServiceInstance<T>\n\n /** Extract the stable tag represented by a Service instance. */\n export type Tag<S extends AnyService> = ServiceTag<S>\n\n /** A branded Service instance identity with a stable tag. */\n export type Identity<Tag extends string = string> = ServiceIdentity<Tag>\n\n /** Remove the internal identity marker from a Service implementation contract. */\n export type Contract<S extends AnyService> = ServiceContract<S>\n\n /** Extract the Service token represented by a branded Service instance. */\n export type TokenOf<S extends AnyService> = ServiceTokenOf<S>\n\n /** Declaration bridge for the recursive structural `Service.of` signature. */\n export type FactoryOf<Self, Tag extends string> = (\n this: void,\n implementation: ServiceContract<Self & ServiceIdentity<Tag>>\n ) => Self\n\n /** Extract Effect Service requirements from a Service instance. */\n export type Requirements<S extends AnyService> = ServiceRequirements<S>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,UAAsC;CACpD,OAAO,SAAoC,KAA6B;EACtE,mBAAmB,GAAG;EAEtB,MAAe,YAA4C;;GAEzD,OAAgB,aAAkB;;;;;;;;;;;;;;;;;;;;;;;;GA0BlC,OAAO,GAAe,gBAAoE;IAExF,OAAO;GACT;;GAGA,SAAS,OAAO,YAEsC;IAGpD,OAAQ,MAAM;GAChB;;GAIA,eAAe,OAAO,iBAEqC;IACzD,OAAO,MAAM,eAAe,QAAQ,IAAI;GAC1C;EACF;EAEA,mBAAmB,aAAa,GAAG;EAEnC,OAAO;CACT;AACF"}
@@ -1,4 +1,4 @@
1
- import { n as currentRuntimeContext } from "./context-BphfFUMO.mjs";
1
+ import { n as currentRuntimeContext } from "./context-DSGSqcJj.mjs";
2
2
  //#region src/runtime/signal.ts
3
3
  const neverAbortedSignal = new AbortController().signal;
4
4
  /** Link caller, Runtime and shutdown signals without owning the caller's controller. */
@@ -49,4 +49,4 @@ const CurrentAbortSignal = { *[Symbol.iterator]() {
49
49
  //#endregion
50
50
  export { linkAbortSignals as n, CurrentAbortSignal as t };
51
51
 
52
- //# sourceMappingURL=signal-nfgFyNCk.mjs.map
52
+ //# sourceMappingURL=signal-5Rg9bUUe.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"signal-nfgFyNCk.mjs","names":[],"sources":["../src/runtime/signal.ts"],"sourcesContent":["import { currentRuntimeContext } from './context'\n\nconst neverAbortedSignal = new AbortController().signal\n\ntype SignalListener = readonly [AbortSignal, () => void]\n\nexport type AbortSignalLink = {\n readonly signal: AbortSignal\n readonly dispose: () => void\n}\n\n/** Link caller, Runtime and shutdown signals without owning the caller's controller. */\nexport const linkAbortSignals = (\n ...signals: readonly (AbortSignal | undefined)[]\n): AbortSignalLink => {\n const active = signals.filter((signal): signal is AbortSignal => signal !== undefined)\n\n if (active.length === 0) {\n return { signal: neverAbortedSignal, dispose: () => {} }\n }\n\n if (active.length === 1) {\n return { signal: active[0]!, dispose: () => {} }\n }\n\n const controller = new AbortController()\n const listeners: SignalListener[] = []\n let disposed = false\n\n const dispose = (): void => {\n if (disposed) {\n return\n }\n\n disposed = true\n\n for (const [source, listener] of listeners) {\n source.removeEventListener('abort', listener)\n }\n\n listeners.length = 0\n }\n\n const abortFrom = (source: AbortSignal): void => {\n if (controller.signal.aborted) {\n return\n }\n\n controller.abort(source.reason)\n dispose()\n }\n\n for (const source of active) {\n if (source.aborted) {\n abortFrom(source)\n break\n }\n\n const listener = (): void => abortFrom(source)\n listeners.push([source, listener])\n source.addEventListener('abort', listener, { once: true })\n }\n\n return { signal: controller.signal, dispose }\n}\n\n/** Return the current cooperative-cancellation signal. */\nexport const currentAbortSignal = (): AbortSignal =>\n currentRuntimeContext().signal ?? neverAbortedSignal\n\n/** Yieldable access to the signal of the current Runtime execution. */\nexport const CurrentAbortSignal = {\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, AbortSignal, unknown> {\n return currentAbortSignal()\n }\n} as const\n"],"mappings":";;AAEA,MAAM,qBAAqB,IAAI,gBAAgB,CAAC,CAAC;;AAUjD,MAAa,oBACX,GAAG,YACiB;CACpB,MAAM,SAAS,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS;CAErF,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ;EAAoB,eAAe,CAAC;CAAE;CAGzD,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ,OAAO;EAAK,eAAe,CAAC;CAAE;CAGjD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,YAA8B,CAAC;CACrC,IAAI,WAAW;CAEf,MAAM,gBAAsB;EAC1B,IAAI,UACF;EAGF,WAAW;EAEX,KAAK,MAAM,CAAC,QAAQ,aAAa,WAC/B,OAAO,oBAAoB,SAAS,QAAQ;EAG9C,UAAU,SAAS;CACrB;CAEA,MAAM,aAAa,WAA8B;EAC/C,IAAI,WAAW,OAAO,SACpB;EAGF,WAAW,MAAM,OAAO,MAAM;EAC9B,QAAQ;CACV;CAEA,KAAK,MAAM,UAAU,QAAQ;EAC3B,IAAI,OAAO,SAAS;GAClB,UAAU,MAAM;GAChB;EACF;EAEA,MAAM,iBAAuB,UAAU,MAAM;EAC7C,UAAU,KAAK,CAAC,QAAQ,QAAQ,CAAC;EACjC,OAAO,iBAAiB,SAAS,UAAU,EAAE,MAAM,KAAK,CAAC;CAC3D;CAEA,OAAO;EAAE,QAAQ,WAAW;EAAQ;CAAQ;AAC9C;;AAGA,MAAa,2BACX,sBAAsB,CAAC,CAAC,UAAU;;AAGpC,MAAa,qBAAqB,EAEhC,EAAE,OAAO,YAAoD;CAC3D,OAAO,mBAAmB;AAC5B,EACF"}
1
+ {"version":3,"file":"signal-5Rg9bUUe.mjs","names":[],"sources":["../src/runtime/signal.ts"],"sourcesContent":["import { currentRuntimeContext } from './context'\n\nconst neverAbortedSignal = new AbortController().signal\n\ntype SignalListener = readonly [AbortSignal, () => void]\n\nexport type AbortSignalLink = {\n readonly signal: AbortSignal\n readonly dispose: () => void\n}\n\n/** Link caller, Runtime and shutdown signals without owning the caller's controller. */\nexport const linkAbortSignals = (\n ...signals: readonly (AbortSignal | undefined)[]\n): AbortSignalLink => {\n const active = signals.filter((signal): signal is AbortSignal => signal !== undefined)\n\n if (active.length === 0) {\n return { signal: neverAbortedSignal, dispose: () => {} }\n }\n\n if (active.length === 1) {\n return { signal: active[0]!, dispose: () => {} }\n }\n\n const controller = new AbortController()\n const listeners: SignalListener[] = []\n let disposed = false\n\n const dispose = (): void => {\n if (disposed) {\n return\n }\n\n disposed = true\n\n for (const [source, listener] of listeners) {\n source.removeEventListener('abort', listener)\n }\n\n listeners.length = 0\n }\n\n const abortFrom = (source: AbortSignal): void => {\n if (controller.signal.aborted) {\n return\n }\n\n controller.abort(source.reason)\n dispose()\n }\n\n for (const source of active) {\n if (source.aborted) {\n abortFrom(source)\n break\n }\n\n const listener = (): void => abortFrom(source)\n listeners.push([source, listener])\n source.addEventListener('abort', listener, { once: true })\n }\n\n return { signal: controller.signal, dispose }\n}\n\n/** Return the current cooperative-cancellation signal. */\nexport const currentAbortSignal = (): AbortSignal =>\n currentRuntimeContext().signal ?? neverAbortedSignal\n\n/** Yieldable access to the signal of the current Runtime execution. */\nexport const CurrentAbortSignal = {\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, AbortSignal, unknown> {\n return currentAbortSignal()\n }\n} as const\n"],"mappings":";;AAEA,MAAM,qBAAqB,IAAI,gBAAgB,CAAC,CAAC;;AAUjD,MAAa,oBACX,GAAG,YACiB;CACpB,MAAM,SAAS,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS;CAErF,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ;EAAoB,eAAe,CAAC;CAAE;CAGzD,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ,OAAO;EAAK,eAAe,CAAC;CAAE;CAGjD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,YAA8B,CAAC;CACrC,IAAI,WAAW;CAEf,MAAM,gBAAsB;EAC1B,IAAI,UACF;EAGF,WAAW;EAEX,KAAK,MAAM,CAAC,QAAQ,aAAa,WAC/B,OAAO,oBAAoB,SAAS,QAAQ;EAG9C,UAAU,SAAS;CACrB;CAEA,MAAM,aAAa,WAA8B;EAC/C,IAAI,WAAW,OAAO,SACpB;EAGF,WAAW,MAAM,OAAO,MAAM;EAC9B,QAAQ;CACV;CAEA,KAAK,MAAM,UAAU,QAAQ;EAC3B,IAAI,OAAO,SAAS;GAClB,UAAU,MAAM;GAChB;EACF;EAEA,MAAM,iBAAuB,UAAU,MAAM;EAC7C,UAAU,KAAK,CAAC,QAAQ,QAAQ,CAAC;EACjC,OAAO,iBAAiB,SAAS,UAAU,EAAE,MAAM,KAAK,CAAC;CAC3D;CAEA,OAAO;EAAE,QAAQ,WAAW;EAAQ;CAAQ;AAC9C;;AAGA,MAAa,2BACX,sBAAsB,CAAC,CAAC,UAAU;;AAGpC,MAAa,qBAAqB,EAEhC,EAAE,OAAO,YAAoD;CAC3D,OAAO,mBAAmB;AAC5B,EACF"}
@@ -1,4 +1,5 @@
1
- import { n as Service, t as Layer } from "./layer-D16GKxuX.mjs";
1
+ import { t as Layer } from "./layer-2kjHVv4N.mjs";
2
+ import { t as Service } from "./service-CO9VJQYa.mjs";
2
3
  import { Result, TaggedError } from "better-result";
3
4
  //#region src/standard-services/config.ts
4
5
  /** A schema validation failure. Raw source values are intentionally omitted. */
@@ -103,13 +104,46 @@ const makeConfigValue = (spec) => {
103
104
  /** Host-backed raw configuration source and provider token. */
104
105
  var Config = class Config extends Service()("Config") {
105
106
  source;
107
+ values;
106
108
  constructor(source) {
107
109
  super();
108
110
  this.source = source;
111
+ this.values = source;
109
112
  }
110
- /** Read one raw value from the configured source. */
113
+ /** Read one value from the configured source or decoded schema output. */
111
114
  get(key) {
112
- return this.source[key];
115
+ return this.values[key];
116
+ }
117
+ /**
118
+ * Create a schema-bound Config token with a typed `get` accessor.
119
+ *
120
+ * The token validates its source while its Layer is acquired. The accessor then
121
+ * reads the decoded schema output, so its return type follows the selected key.
122
+ */
123
+ static withSchema(schema) {
124
+ class SchemaConfig extends Config {}
125
+ const token = SchemaConfig;
126
+ const acquire = async (source) => {
127
+ const checked = await validate(schema, source);
128
+ if (checked.status === "error") throw checked.error;
129
+ const values = checked.value;
130
+ if (typeof values !== "object" || values === null) throw new TypeError("Config schema output must be an object to use Config.get");
131
+ const config = new Config(source);
132
+ config.values = values;
133
+ return config;
134
+ };
135
+ Object.assign(SchemaConfig, {
136
+ layer: (source) => Layer.make(token, () => acquire(source)),
137
+ layerFromEnv: (options = {}) => Layer.make(token, async () => {
138
+ const loaded = await Result.tryPromise({
139
+ try: () => loadSource(options),
140
+ catch: (cause) => sourceError(options.dotEnvPath, cause)
141
+ });
142
+ if (loaded.status === "error") throw loaded.error;
143
+ return await acquire(loaded.value);
144
+ })
145
+ });
146
+ return token;
113
147
  }
114
148
  /** Create a provider from an already-loaded source. */
115
149
  static layer(source) {
@@ -507,4 +541,4 @@ const LoggerTestLayer = () => LoggerTest.layer();
507
541
  //#endregion
508
542
  export { ConfigValidationError as S, IdGeneratorTestLayer as _, Logger as a, ConfigLive as b, LoggerTestLayer as c, RandomSeeded as d, RandomSeededLayer as f, IdGeneratorTest as g, IdGeneratorLive as h, ClockTestLayer as i, Random as l, IdGeneratorExhaustedError as m, ClockLive as n, LoggerLive as o, IdGenerator as p, ClockTest as r, LoggerTest as s, Clock as t, RandomLive as u, IdGeneratorUnavailableError as v, ConfigSourceError as x, Config as y };
509
543
 
510
- //# sourceMappingURL=standard-services-vnGIafkS.mjs.map
544
+ //# sourceMappingURL=standard-services-B-iMM_W7.mjs.map