better-effect 0.10.0 → 0.11.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.
- package/README.md +244 -5
- package/dist/adapters/iti.d.mts +3 -4
- package/dist/adapters/iti.d.mts.map +1 -1
- package/dist/adapters/iti.mjs +9 -4
- package/dist/adapters/iti.mjs.map +1 -1
- package/dist/effect-2ZcGZI8A.mjs +513 -0
- package/dist/effect-2ZcGZI8A.mjs.map +1 -0
- package/dist/hono.d.mts +18 -13
- package/dist/hono.d.mts.map +1 -1
- package/dist/hono.mjs +9 -5
- package/dist/hono.mjs.map +1 -1
- package/dist/{index-BafDna0B.d.mts → index-C7Qild0_.d.mts} +158 -28
- package/dist/index-C7Qild0_.d.mts.map +1 -0
- package/dist/{index-DklNCz7w.d.mts → index-DStz0JMN.d.mts} +4 -4
- package/dist/{index-DklNCz7w.d.mts.map → index-DStz0JMN.d.mts.map} +1 -1
- package/dist/{index-CULgSzUw.d.mts → index-heuaRmXR.d.mts} +5 -5
- package/dist/{index-CULgSzUw.d.mts.map → index-heuaRmXR.d.mts.map} +1 -1
- package/dist/{index-C7KX5rAP.d.mts → index-rQhZk3Nt.d.mts} +127 -24
- package/dist/index-rQhZk3Nt.d.mts.map +1 -0
- package/dist/index.d.mts +4 -5
- package/dist/index.mjs +7 -538
- package/dist/index.mjs.map +1 -1
- package/dist/runtime/explicit.d.mts +1 -1
- package/dist/runtime/node.d.mts +1 -1
- package/dist/runtime-DnMn0X0X.mjs +613 -0
- package/dist/runtime-DnMn0X0X.mjs.map +1 -0
- package/dist/scope-GGnmTQck.mjs +245 -0
- package/dist/scope-GGnmTQck.mjs.map +1 -0
- package/dist/{signal-C1bagvrO.mjs → signal-B97cs85Z.mjs} +81 -2
- package/dist/signal-B97cs85Z.mjs.map +1 -0
- package/dist/{standard-services-DW-i4UuA.mjs → standard-services-BFBq-4lo.mjs} +2 -2
- package/dist/{standard-services-DW-i4UuA.mjs.map → standard-services-BFBq-4lo.mjs.map} +1 -1
- package/dist/standard-services.d.mts +2 -2
- package/dist/standard-services.mjs +2 -2
- package/dist/testing.d.mts +198 -2
- package/dist/testing.d.mts.map +1 -0
- package/dist/testing.mjs +976 -2
- package/dist/testing.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/effect-DAMqvegy.mjs +0 -544
- package/dist/effect-DAMqvegy.mjs.map +0 -1
- package/dist/index-BafDna0B.d.mts.map +0 -1
- package/dist/index-C7KX5rAP.d.mts.map +0 -1
- package/dist/map-layer-backend-gal-mcRv.mjs +0 -53
- package/dist/map-layer-backend-gal-mcRv.mjs.map +0 -1
- package/dist/map-layer-backend-rNwfH0Bz.d.mts +0 -42
- package/dist/map-layer-backend-rNwfH0Bz.d.mts.map +0 -1
- package/dist/signal-C1bagvrO.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-DnMn0X0X.mjs","names":[],"sources":["../src/layer/map-layer-backend.ts","../src/runtime/outcome.ts","../src/runtime/observer.ts","../src/layer/resolution.ts","../src/layer/runtime.ts","../src/runtime/runtime.ts"],"sourcesContent":["import { assertServiceCompatibility } from './internal-identity'\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'\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 tag = registration.service.serviceTag\n const existing = this.providers.get(tag)\n\n if (existing) {\n if (existing.service !== registration.service) {\n throw new ServiceTagCollisionError(existing.service, registration.service)\n }\n\n throw new DuplicateServiceError(registration.service)\n }\n\n this.providers.set(tag, registration)\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 = token.serviceTag\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","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 { RuntimeObserver } from './observer'\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 supplied to one managed Runtime execution. */\nexport type RuntimeRunOptions = {\n readonly signal?: AbortSignal\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}\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 type { AnyServiceToken } from '../service'\nimport type { Scope } from '../scope'\nimport type { ScopeOutcome } from '../scope'\nimport type { MaybePromise } from '../utils/types'\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}\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}\n\n/** Event emitted immediately before a program starts in an execution Scope. */\nexport type RuntimeExecutionStartEvent = {\n readonly scope: Scope\n}\n\n/** Event emitted after a program and its execution Scope settle. */\nexport type RuntimeExecutionEndEvent = {\n readonly scope: Scope\n readonly outcome: ScopeOutcome\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}\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 onResourceRelease?: (event: RuntimeResourceReleaseEvent) => 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 onResourceRelease: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, 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 {\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 { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport { ServiceTagCollisionError } from './errors'\n\nconst findCycleStart = (path: readonly AnyServiceToken[], token: AnyServiceToken): number =>\n path.findIndex((current) => current.serviceTag === token.serviceTag)\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 context = getRuntimeContext(storage)\n const path = context?.resolutionPath ?? []\n const cycleStart = findCycleStart(path, token)\n const resolutionPath = [...path, token]\n\n const notifyResolve = (outcome: ScopeOutcome): void => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, {\n service: token,\n resolutionPath,\n outcome\n })\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","import 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 RuntimeContextStorage\n} from '../runtime/context'\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} from '../runtime/outcome'\n\nimport { linkAbortSignals, type AbortSignalLink } from '../runtime/signal'\n\nimport { LayerDisposeError, LayerRegistrationError } from './errors'\n\nimport { createResolutionResolver } from './resolution'\n\nimport { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\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 { ScopeFinalizer, ScopeOutcome } from '../scope'\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 /** Resolve every registered provider before accepting normal executions. */\n warmup(): Promise<void>\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 } = 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\ntype ActiveExecution = {\n readonly promise: Promise<unknown>\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): Promise<void> => {\n try {\n await release(outcome)\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service,\n outcome\n })\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service,\n outcome,\n error: cause\n })\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): LayerRegistration => ({\n service: provider.service,\n\n acquire: () => {\n const current = getRuntimeContext(contextStorage)\n const context = makeRuntimeContext(\n resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal,\n current\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(provider.service, acquired.release, outcome, observers)\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 )\n )\n : await provider.acquire()\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: SCOPE_SUCCESS\n })\n\n return instance\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: {\n status: 'failure',\n cause\n }\n })\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(registration.service.serviceTag)\n this.local.register(registration)\n }\n\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n if (this.localTags.has(token.serviceTag)) {\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 shutdownController = new AbortController()\n\n private state: 'active' | 'disposing' | 'disposed' = 'active'\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 ) {}\n\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n const executionScope = this.rootScope.fork()\n const signalLink = linkAbortSignals(\n this.signal,\n options?.signal,\n this.shutdownController.signal\n )\n\n return this.startExecution<Awaited<A>>(signalLink, () =>\n this.runExecution(executionScope, program, this.resolver, signalLink.signal)\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 const executionScope = this.rootScope.fork()\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n const signalLink = linkAbortSignals(\n this.signal,\n options?.signal,\n this.shutdownController.signal\n )\n\n return this.startExecution<Awaited<A>>(signalLink, 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 )\n )\n }\n\n return await program()\n },\n resolver,\n signalLink.signal\n )\n } finally {\n await localBackend.disposeAll()\n }\n })\n }\n\n warmup(): Promise<void> {\n this.assertActive()\n\n if (this.warmupPromise) {\n return this.warmupPromise\n }\n\n const warmup = runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], this.signal),\n async () => {\n for (const service of this.services) {\n await this.resolver.resolve(service)\n }\n }\n )\n\n this.warmupPromise = warmup\n\n void warmup.then(\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupPromise = undefined\n }\n },\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupPromise = undefined\n }\n }\n )\n\n return warmup\n }\n\n private startExecution<A>(signalLink: AbortSignalLink, run: () => PromiseLike<A>): 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 }\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()\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 ): Promise<Awaited<A>> {\n let outcome!: ScopeOutcome\n const onOutcome = (determinedOutcome: ScopeOutcome): void => {\n outcome = determinedOutcome\n }\n const runOptions = this.onCleanupFailure\n ? {\n classify: classifyRuntimeOutcome,\n onOutcome,\n onCleanupFailure: this.onCleanupFailure\n }\n : {\n classify: classifyRuntimeOutcome,\n onOutcome\n }\n\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, {\n scope: executionScope\n })\n\n const execution = runScoped(executionScope, program, {\n ...runOptions,\n contextStorage: this.contextStorage,\n context: makeRuntimeContext(resolver, executionScope, [], signal)\n })\n\n return execution.then(\n (value) => {\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, {\n scope: executionScope,\n outcome\n })\n return value\n },\n (cause) => {\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, {\n scope: executionScope,\n outcome\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 this.state = 'disposing'\n\n const executions = [...this.executions]\n\n this.disposePromise = this.performDispose(executions, outcome, options)\n\n return this.disposePromise\n }\n\n private async performDispose(\n executions: readonly ActiveExecution[],\n outcome: ScopeOutcome,\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const failures: unknown[] = []\n\n await Promise.allSettled(this.warmupPromise ? [this.warmupPromise] : [])\n await this.waitForExecutions(executions, options)\n\n try {\n const signalLink = linkAbortSignals(this.signal, this.shutdownController.signal)\n\n try {\n await runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], signalLink.signal),\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 if (failures.length > 0) {\n const error = new LayerDisposeError(failures.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(this.onCleanupFailure, {\n outcome,\n error\n })\n\n throw error\n }\n }\n\n private async waitForExecutions(\n executions: readonly ActiveExecution[],\n options: RuntimeDisposeOptions\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.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): Promise<RuntimeHandle<ProvidedEnvironment<L>>> => {\n const rootScope = Scope.make()\n const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage\n const observers = options.observers ?? []\n const resolver = createResolutionResolver(backend, contextStorage, observers)\n ScopeRuntime.bind(rootScope, contextStorage)\n let current: LayerProvider | undefined\n\n try {\n for (const provider of layer.providers) {\n current = provider\n\n await backend.register(\n bindProviderToScope(provider, rootScope, contextStorage, resolver, observers)\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(resolver, rootScope, [], options.signal),\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 return new RuntimeHandleImpl<ProvidedEnvironment<L>>(\n backend,\n resolver,\n rootScope,\n options.onCleanupFailure,\n contextStorage,\n options.signal,\n observers,\n layer.providers.map((provider) => provider.service)\n )\n}\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 { RuntimeFor } from './types'\n\nimport type { RuntimeObserver } from './observer'\n\ntype RuntimeBackendInput = LayerBackend | RuntimeOptions | undefined\n\ntype RuntimeConfig = {\n readonly backend: LayerBackend\n readonly options: RuntimeOptions\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?: RuntimeOptions\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 private constructor(private readonly handle: RuntimeHandle<Provided>) {}\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 const handle = await createRuntimeHandle(layer, backend, options)\n const runtime = new Runtime<ProvidedEnvironment<L>>(handle)\n\n if (options.warmup) {\n await runtime.warmup()\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?: RuntimeOptions\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?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options: RuntimeOptions,\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 | RuntimeOptions\n | CompleteExecution<ProvidedEnvironment<L>, A>,\n programOrOptions?: CompleteExecution<ProvidedEnvironment<L>, A> | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Awaited<A>> {\n let program: CompleteExecution<ProvidedEnvironment<L>, A>\n let backendOrOptions: RuntimeBackendInput\n let options: RuntimeOptions | 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 RuntimeOptions | 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)\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 /** 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 /** 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>(program: () => A | PromiseLike<A>): 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>)\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"],"mappings":";;;;;;;;AAYA,IAAa,kBAAb,MAAqD;CACnD,4BAA6B,IAAI,IAA+B;CAEhE,4BAA6B,IAAI,IAAgC;CAEjE,0BAA2B,IAAI,IAAyC;;CAGxE,SAAS,cAAuC;EAC9C,MAAM,MAAM,aAAa,QAAQ;EACjC,MAAM,WAAW,KAAK,UAAU,IAAI,GAAG;EAEvC,IAAI,UAAU;GACZ,IAAI,SAAS,YAAY,aAAa,SACpC,MAAM,IAAI,yBAAyB,SAAS,SAAS,aAAa,OAAO;GAG3E,MAAM,IAAI,sBAAsB,aAAa,OAAO;EACtD;EAEA,KAAK,UAAU,IAAI,KAAK,YAAY;CACtC;;CAGA,MAAM,QAAmC,OAAoC;EAC3E,MAAM,MAAM,MAAM;EAClB,MAAM,WAAW,KAAK,UAAU,IAAI,GAAG;EAEvC,IAAI,CAAC,UACH,MAAM,IAA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QAAQ,KAAK,OAAO,OAAO;EAEjD,IAAI;EACJ,IAAI,kBAAkB;EACtB,IAAI;EACJ,IAAI;EAEJ,IAAI;GACF,QAAQ,MAAM,IAAI,OAAO;GACzB,iBAAiB,uBAAuB,KAAK;EAC/C,SAAS,OAAO;GACd,kBAAkB;GAClB,mBAAmB;GACnB,iBAAiB;IACf,QAAQ;IACR;GACF;EACF;EAEA,MAAM,UACJ,kBACC;GACC,QAAQ;GACR,OAAO;EACT;EAEF,IAAI;GACF,MAAM,QAAQ,mBAAmB,OAAO;EAC1C,SAAS,iBAAiB;GACxB,IAAI,CAAC,mBAAmB,QAAQ,WAAW,WACzC,MAAM;EAEV;EAEA,IAAI,iBACF,MAAM;EAGR,OAAO;CACT;;CAGA,MAAM,SAAwB;EAC5B,IAAI;GACF,MAAM,KAAK,OAAO,OAAO;EAC3B,SAAS,OAAO;GACd,IAAI;IACF,MAAM,KAAK,OAAO,QAAQ;KAAE,QAAQ;KAAW;IAAM,CAAC;GACxD,QAAQ,CAER;GAEA,MAAM;EACR;CACF;;CAGA,IACE,SACA,SACqB;EACrB,OAAO,KAAK,OAAO,IAAI,SAAS,OAAO;CACzC;;CAGA,QACE,OACA,SACA,SACqB;EACrB,OAAO,KAAK,OAAO,QAAQ,OAAO,SAAS,OAAO;CACpD;CAEA,aAAwB,SAAwD;EAE9E,OAAO,KAAK,OAAO,IAAI,OAAyC;CAClE;CAQA,QAAQ,kBAAwE;EAC9E,OAAO,KAAK,OAAO,QAAQ,gBAAgB;CAC7C;;CAGA,OAAO,OAAO,gBAA+B;EAC3C,MAAM,KAAK,QAAQ;CACrB;CAEA,mBAA2B,SAAsC;EAC/D,OAAO,KAAK,OAAO,QAAQ,OAAO;CACpC;AACF"}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { h as RuntimeContextNotConfiguredError, i as getRuntimeContext, l as makeRuntimeContext, n as currentRuntimeContext, t as activeRuntimeContextStorage, u as runRuntimeContext } from "./context-BUEf1qjL.mjs";
|
|
2
|
+
import { a as getDisposeFinalizer, c as ScopeClosedError, l as ScopeRuntimeNotConfiguredError, o as ResourceNotDisposableError, s as ScopeCloseError } from "./signal-B97cs85Z.mjs";
|
|
3
|
+
//#region src/scope/runtime.ts
|
|
4
|
+
const scopeStorages = /* @__PURE__ */ new WeakMap();
|
|
5
|
+
/** Bridges the current Scope through async execution context. */
|
|
6
|
+
var ScopeRuntime = class {
|
|
7
|
+
/** Supply a Scope while invoking a callback. */
|
|
8
|
+
static run(scope, program, storage = scopeStorages.get(scope) ?? activeRuntimeContextStorage()) {
|
|
9
|
+
scopeStorages.set(scope, storage);
|
|
10
|
+
const current = getRuntimeContext(storage);
|
|
11
|
+
const context = makeRuntimeContext(current?.resolver, scope, current?.resolutionPath ?? [], current?.signal, current);
|
|
12
|
+
return runRuntimeContext(storage, context, program);
|
|
13
|
+
}
|
|
14
|
+
/** Return the Scope active in the current execution context. */
|
|
15
|
+
static current() {
|
|
16
|
+
let context;
|
|
17
|
+
try {
|
|
18
|
+
context = currentRuntimeContext();
|
|
19
|
+
} catch (cause) {
|
|
20
|
+
if (cause instanceof RuntimeContextNotConfiguredError) throw new ScopeRuntimeNotConfiguredError();
|
|
21
|
+
throw cause;
|
|
22
|
+
}
|
|
23
|
+
if (!context.scope) throw new ScopeRuntimeNotConfiguredError();
|
|
24
|
+
return context.scope;
|
|
25
|
+
}
|
|
26
|
+
/** Associate a Runtime-owned Scope with its context storage. */
|
|
27
|
+
static bind(scope, storage) {
|
|
28
|
+
scopeStorages.set(scope, storage);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/scope/internal.ts
|
|
33
|
+
const notifyCleanupFailure = async (observer, diagnostic) => {
|
|
34
|
+
if (!observer) return;
|
|
35
|
+
try {
|
|
36
|
+
await observer(diagnostic);
|
|
37
|
+
} catch {}
|
|
38
|
+
};
|
|
39
|
+
const runScoped = async (scope, program, options) => {
|
|
40
|
+
let value;
|
|
41
|
+
let programFailed = false;
|
|
42
|
+
let programFailure;
|
|
43
|
+
try {
|
|
44
|
+
const run = () => ScopeRuntime.run(scope, program, options.contextStorage);
|
|
45
|
+
value = await (options.context && options.contextStorage ? runRuntimeContext(options.contextStorage, options.context, run) : run());
|
|
46
|
+
} catch (cause) {
|
|
47
|
+
programFailed = true;
|
|
48
|
+
programFailure = cause;
|
|
49
|
+
}
|
|
50
|
+
let outcome;
|
|
51
|
+
let outcomeStatus;
|
|
52
|
+
if (programFailed) {
|
|
53
|
+
outcome = {
|
|
54
|
+
status: "failure",
|
|
55
|
+
cause: programFailure
|
|
56
|
+
};
|
|
57
|
+
outcomeStatus = "failure";
|
|
58
|
+
} else try {
|
|
59
|
+
outcome = options.classify(value);
|
|
60
|
+
outcomeStatus = outcome.status;
|
|
61
|
+
} catch (cause) {
|
|
62
|
+
programFailed = true;
|
|
63
|
+
programFailure = cause;
|
|
64
|
+
outcome = {
|
|
65
|
+
status: "failure",
|
|
66
|
+
cause
|
|
67
|
+
};
|
|
68
|
+
outcomeStatus = "failure";
|
|
69
|
+
}
|
|
70
|
+
options.onOutcome?.(outcome);
|
|
71
|
+
let cleanupFailed = false;
|
|
72
|
+
let cleanupFailure;
|
|
73
|
+
try {
|
|
74
|
+
await scope.close(outcome);
|
|
75
|
+
} catch (cause) {
|
|
76
|
+
cleanupFailed = true;
|
|
77
|
+
cleanupFailure = cause;
|
|
78
|
+
}
|
|
79
|
+
if (cleanupFailed) {
|
|
80
|
+
const error = cleanupFailure instanceof ScopeCloseError ? cleanupFailure : new ScopeCloseError([cleanupFailure]);
|
|
81
|
+
await notifyCleanupFailure(options.onCleanupFailure, {
|
|
82
|
+
outcome,
|
|
83
|
+
error
|
|
84
|
+
});
|
|
85
|
+
cleanupFailure = error;
|
|
86
|
+
}
|
|
87
|
+
if (programFailed) throw programFailure;
|
|
88
|
+
if (outcomeStatus === "failure") return value;
|
|
89
|
+
if (cleanupFailed) throw cleanupFailure;
|
|
90
|
+
return value;
|
|
91
|
+
};
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/scope/scope.ts
|
|
94
|
+
const SCOPE_SUCCESS = Object.freeze({ status: "success" });
|
|
95
|
+
var ScopeImpl = class ScopeImpl {
|
|
96
|
+
parent;
|
|
97
|
+
children = /* @__PURE__ */ new Set();
|
|
98
|
+
finalizers = [];
|
|
99
|
+
closePromise;
|
|
100
|
+
closeOutcome;
|
|
101
|
+
constructor(parent) {
|
|
102
|
+
this.parent = parent;
|
|
103
|
+
}
|
|
104
|
+
fork() {
|
|
105
|
+
this.assertOpen();
|
|
106
|
+
const child = new ScopeImpl(this);
|
|
107
|
+
this.children.add(child);
|
|
108
|
+
return child;
|
|
109
|
+
}
|
|
110
|
+
addFinalizer(finalizer) {
|
|
111
|
+
this.assertOpen();
|
|
112
|
+
this.finalizers.push(finalizer);
|
|
113
|
+
}
|
|
114
|
+
async acquire(acquire, release) {
|
|
115
|
+
this.assertOpen();
|
|
116
|
+
const resource = await acquire();
|
|
117
|
+
try {
|
|
118
|
+
this.addFinalizer((outcome) => release(resource, outcome));
|
|
119
|
+
return resource;
|
|
120
|
+
} catch (scopeFailure) {
|
|
121
|
+
try {
|
|
122
|
+
await release(resource, this.closeOutcome ?? SCOPE_SUCCESS);
|
|
123
|
+
} catch (releaseFailure) {
|
|
124
|
+
throw new AggregateError([scopeFailure, releaseFailure], "Scope closed while acquiring a resource and immediate cleanup also failed");
|
|
125
|
+
}
|
|
126
|
+
throw scopeFailure;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async add(resource) {
|
|
130
|
+
const finalizer = getDisposeFinalizer(resource);
|
|
131
|
+
if (!finalizer) throw new ResourceNotDisposableError();
|
|
132
|
+
try {
|
|
133
|
+
this.addFinalizer(finalizer);
|
|
134
|
+
return resource;
|
|
135
|
+
} catch (scopeFailure) {
|
|
136
|
+
try {
|
|
137
|
+
await finalizer(this.closeOutcome ?? SCOPE_SUCCESS);
|
|
138
|
+
} catch (releaseFailure) {
|
|
139
|
+
throw new AggregateError([scopeFailure, releaseFailure], "Scope closed while adding a disposable resource and cleanup also failed");
|
|
140
|
+
}
|
|
141
|
+
throw scopeFailure;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
close(outcome = SCOPE_SUCCESS) {
|
|
145
|
+
if (this.closePromise) return this.closePromise;
|
|
146
|
+
this.closeOutcome = outcome;
|
|
147
|
+
this.closePromise = Promise.resolve().then(() => this.closeWithRuntime(outcome));
|
|
148
|
+
return this.closePromise;
|
|
149
|
+
}
|
|
150
|
+
async closeWithRuntime(outcome) {
|
|
151
|
+
let started = false;
|
|
152
|
+
try {
|
|
153
|
+
await ScopeRuntime.run(this, () => {
|
|
154
|
+
started = true;
|
|
155
|
+
return this.closeInternal(outcome);
|
|
156
|
+
});
|
|
157
|
+
} catch (storageFailure) {
|
|
158
|
+
if (started) throw storageFailure;
|
|
159
|
+
try {
|
|
160
|
+
await this.closeInternal(outcome);
|
|
161
|
+
} catch (cleanupFailure) {
|
|
162
|
+
const cleanupCauses = cleanupFailure instanceof ScopeCloseError ? cleanupFailure.causes : [cleanupFailure];
|
|
163
|
+
throw new ScopeCloseError([storageFailure, ...cleanupCauses]);
|
|
164
|
+
}
|
|
165
|
+
throw storageFailure;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async closeInternal(outcome) {
|
|
169
|
+
const failures = [];
|
|
170
|
+
const children = [...this.children];
|
|
171
|
+
this.children.clear();
|
|
172
|
+
for (let index = children.length - 1; index >= 0; index--) {
|
|
173
|
+
const child = children[index];
|
|
174
|
+
if (!child) continue;
|
|
175
|
+
try {
|
|
176
|
+
await child.close(outcome);
|
|
177
|
+
} catch (cause) {
|
|
178
|
+
if (cause instanceof ScopeCloseError) failures.push(...cause.causes);
|
|
179
|
+
else failures.push(cause);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (let index = this.finalizers.length - 1; index >= 0; index--) {
|
|
183
|
+
const finalizer = this.finalizers[index];
|
|
184
|
+
if (!finalizer) continue;
|
|
185
|
+
try {
|
|
186
|
+
await finalizer(outcome);
|
|
187
|
+
} catch (cause) {
|
|
188
|
+
failures.push(cause);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
this.finalizers.length = 0;
|
|
192
|
+
this.detach();
|
|
193
|
+
if (failures.length > 0) throw new ScopeCloseError(failures);
|
|
194
|
+
}
|
|
195
|
+
detach() {
|
|
196
|
+
const parent = this.parent;
|
|
197
|
+
if (!parent) return;
|
|
198
|
+
parent.children.delete(this);
|
|
199
|
+
this.parent = void 0;
|
|
200
|
+
}
|
|
201
|
+
assertOpen() {
|
|
202
|
+
if (this.closePromise) throw new ScopeClosedError();
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const Scope = {
|
|
206
|
+
/** Create an owned, initially open Scope. */
|
|
207
|
+
make() {
|
|
208
|
+
return new ScopeImpl();
|
|
209
|
+
},
|
|
210
|
+
/** Return the non-owning Scope available in the current execution context. */
|
|
211
|
+
current() {
|
|
212
|
+
return ScopeRuntime.current();
|
|
213
|
+
},
|
|
214
|
+
/** Run a callback with an existing Scope supplied as the current context. */
|
|
215
|
+
provide(scope, program) {
|
|
216
|
+
return ScopeRuntime.run(scope, program);
|
|
217
|
+
},
|
|
218
|
+
/** Resolve the current Scope through `yield* Scope` inside an Effect. */
|
|
219
|
+
*[Symbol.iterator]() {
|
|
220
|
+
return ScopeRuntime.current();
|
|
221
|
+
},
|
|
222
|
+
/**
|
|
223
|
+
* Run a program in a newly owned Scope.
|
|
224
|
+
*
|
|
225
|
+
* Scope is independent from `better-result`, so returned values—including
|
|
226
|
+
* `Result.err`—close this Scope with a successful outcome. Result-aware
|
|
227
|
+
* outcome classification belongs to `Runtime.run`.
|
|
228
|
+
*
|
|
229
|
+
* @example
|
|
230
|
+
* ```ts
|
|
231
|
+
* await Scope.run(async (scope) => {
|
|
232
|
+
* const connection = await scope.acquire(connect, (connection) => connection.close())
|
|
233
|
+
* return connection.query()
|
|
234
|
+
* })
|
|
235
|
+
* ```
|
|
236
|
+
*/
|
|
237
|
+
run(program) {
|
|
238
|
+
const scope = new ScopeImpl();
|
|
239
|
+
return runScoped(scope, () => program(scope), { classify: () => SCOPE_SUCCESS });
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
//#endregion
|
|
243
|
+
export { runScoped as n, ScopeRuntime as r, Scope as t };
|
|
244
|
+
|
|
245
|
+
//# sourceMappingURL=scope-GGnmTQck.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-GGnmTQck.mjs","names":[],"sources":["../src/scope/runtime.ts","../src/scope/internal.ts","../src/scope/scope.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 } 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\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 { 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 closePromise: Promise<void> | undefined\n\n private closeOutcome: ScopeOutcome | undefined\n\n constructor(private parent?: ScopeImpl) {}\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 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\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"],"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,sBAAsB;EAClC,SAAS,OAAO;GACd,IAAI,iBAAiB,kCACnB,MAAM,IAAI,+BAA+B;GAG3C,MAAM;EACR;EAEA,IAAI,CAAC,QAAQ,OACX,MAAM,IAAI,+BAA+B;EAG3C,OAAO,QAAQ;CACjB;;CAGA,OAAO,KAAK,OAAc,SAAsC;EAC9D,cAAc,IAAI,OAAO,OAAO;CAClC;AACF;;;ACzCA,MAAM,uBAAuB,OAC3B,UACA,eACkB;CAClB,IAAI,CAAC,UACH;CAGF,IAAI;EACF,MAAM,SAAS,UAAU;CAC3B,QAAQ,CAER;AACF;AAEA,MAAa,YAA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8C;EACrD,OAAO,aAAa,QAAQ;CAC9B;;;;;;;;;;;;;;;;CAiBA,IAAO,SAAoE;EACzE,MAAM,QAAQ,IAAI,UAAU;EAE5B,OAAO,UAAU,aAAa,QAAQ,KAAK,GAAG,EAC5C,gBAAgB,cAClB,CAAC;CACH;AACF"}
|
|
@@ -108,6 +108,53 @@ function Service() {
|
|
|
108
108
|
};
|
|
109
109
|
}
|
|
110
110
|
//#endregion
|
|
111
|
+
//#region src/scope/errors.ts
|
|
112
|
+
/** Thrown when Scope context is accessed outside an active Scope execution. */
|
|
113
|
+
var ScopeRuntimeNotConfiguredError = class extends Error {
|
|
114
|
+
constructor() {
|
|
115
|
+
super("No Scope is available in the current execution context");
|
|
116
|
+
this.name = "ScopeRuntimeNotConfiguredError";
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
/** Thrown when a resource or finalizer is added after Scope closure begins. */
|
|
120
|
+
var ScopeClosedError = class extends Error {
|
|
121
|
+
constructor() {
|
|
122
|
+
super("Cannot add resources or finalizers to a closed Scope");
|
|
123
|
+
this.name = "ScopeClosedError";
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
/** Aggregates finalizer failures encountered while closing a Scope. */
|
|
127
|
+
var ScopeCloseError = class extends Error {
|
|
128
|
+
causes;
|
|
129
|
+
constructor(causes) {
|
|
130
|
+
super(`Failed to close Scope (${causes.length} finalizer${causes.length === 1 ? "" : "s"} failed)`);
|
|
131
|
+
this.causes = causes;
|
|
132
|
+
this.name = "ScopeCloseError";
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
/** Thrown when a value has neither Symbol.dispose nor Symbol.asyncDispose. */
|
|
136
|
+
var ResourceNotDisposableError = class extends Error {
|
|
137
|
+
constructor() {
|
|
138
|
+
super("Resource does not implement Symbol.dispose or Symbol.asyncDispose");
|
|
139
|
+
this.name = "ResourceNotDisposableError";
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/scope/disposable.ts
|
|
144
|
+
const SCOPE_SUCCESS = { status: "success" };
|
|
145
|
+
/** Return a Scope finalizer for a value's async or sync disposal protocol. */
|
|
146
|
+
const getDisposeFinalizer = (resource) => {
|
|
147
|
+
const candidate = Object(resource);
|
|
148
|
+
const asyncDispose = candidate[Symbol.asyncDispose];
|
|
149
|
+
if (asyncDispose instanceof Function) return () => asyncDispose.call(resource);
|
|
150
|
+
const dispose = candidate[Symbol.dispose];
|
|
151
|
+
if (dispose instanceof Function) return () => dispose.call(resource);
|
|
152
|
+
};
|
|
153
|
+
/** Dispose a value immediately when it implements a disposal protocol. */
|
|
154
|
+
const disposeResource = (resource) => {
|
|
155
|
+
return getDisposeFinalizer(resource)?.(SCOPE_SUCCESS);
|
|
156
|
+
};
|
|
157
|
+
//#endregion
|
|
111
158
|
//#region src/layer/internal.ts
|
|
112
159
|
const runLayerGenerator = async (service, factory) => {
|
|
113
160
|
const iterator = factory();
|
|
@@ -144,6 +191,8 @@ var Layer = class Layer {
|
|
|
144
191
|
constructor(providers) {
|
|
145
192
|
this.providers = Object.freeze([...providers]);
|
|
146
193
|
}
|
|
194
|
+
/** A stable provider-free Layer for composition roots with no Services. */
|
|
195
|
+
static empty = Object.freeze(new Layer([]));
|
|
147
196
|
static make(service, acquire) {
|
|
148
197
|
const defaultAcquire = () => {
|
|
149
198
|
return new service();
|
|
@@ -162,6 +211,13 @@ var Layer = class Layer {
|
|
|
162
211
|
acquire: normalizedAcquire
|
|
163
212
|
}]);
|
|
164
213
|
}
|
|
214
|
+
/** Alias a source Service under a compatible target contract. */
|
|
215
|
+
static alias(options) {
|
|
216
|
+
const { from, to } = options;
|
|
217
|
+
return Layer.gen(to, async function* () {
|
|
218
|
+
return await ServiceRuntime.resolve(from);
|
|
219
|
+
});
|
|
220
|
+
}
|
|
165
221
|
/** Define a provider with Runtime-root cleanup. */
|
|
166
222
|
static scoped(service, acquire, release) {
|
|
167
223
|
return new Layer([{
|
|
@@ -172,6 +228,23 @@ var Layer = class Layer {
|
|
|
172
228
|
}
|
|
173
229
|
}]);
|
|
174
230
|
}
|
|
231
|
+
/** Define a provider with Runtime-root cleanup through its disposal protocol. */
|
|
232
|
+
static scopedDisposable(service, acquire) {
|
|
233
|
+
const acquireWithRelease = async () => {
|
|
234
|
+
const instance = await acquire();
|
|
235
|
+
const finalizer = getDisposeFinalizer(instance);
|
|
236
|
+
if (!finalizer) throw new ResourceNotDisposableError();
|
|
237
|
+
return {
|
|
238
|
+
instance,
|
|
239
|
+
release: finalizer
|
|
240
|
+
};
|
|
241
|
+
};
|
|
242
|
+
return new Layer([{
|
|
243
|
+
service,
|
|
244
|
+
acquire: async () => (await acquireWithRelease()).instance,
|
|
245
|
+
acquireWithRelease
|
|
246
|
+
}]);
|
|
247
|
+
}
|
|
175
248
|
/** Define a provider whose acquisition can yield contextual Services. */
|
|
176
249
|
static scopedGen(service, factory, release) {
|
|
177
250
|
return new Layer([{
|
|
@@ -214,6 +287,12 @@ var Layer = class Layer {
|
|
|
214
287
|
return new Layer([...providers.values()]);
|
|
215
288
|
}
|
|
216
289
|
};
|
|
290
|
+
Object.defineProperty(Layer, "empty", {
|
|
291
|
+
value: Layer.empty,
|
|
292
|
+
writable: false,
|
|
293
|
+
enumerable: true,
|
|
294
|
+
configurable: false
|
|
295
|
+
});
|
|
217
296
|
const normalizeAcquire = (acquire) => () => {
|
|
218
297
|
return acquire();
|
|
219
298
|
};
|
|
@@ -266,6 +345,6 @@ const CurrentAbortSignal = { *[Symbol.iterator]() {
|
|
|
266
345
|
return currentAbortSignal();
|
|
267
346
|
} };
|
|
268
347
|
//#endregion
|
|
269
|
-
export {
|
|
348
|
+
export { getDisposeFinalizer as a, ScopeClosedError as c, ServiceRuntime as d, defaultRuntimeContextStorage as f, disposeResource as i, ScopeRuntimeNotConfiguredError as l, linkAbortSignals as n, ResourceNotDisposableError as o, Layer as r, ScopeCloseError as s, CurrentAbortSignal as t, Service as u };
|
|
270
349
|
|
|
271
|
-
//# sourceMappingURL=signal-
|
|
350
|
+
//# sourceMappingURL=signal-B97cs85Z.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signal-B97cs85Z.mjs","names":["Constructor"],"sources":["../src/runtime/default.ts","../src/service/runtime.ts","../src/service/service.ts","../src/scope/errors.ts","../src/scope/disposable.ts","../src/layer/internal.ts","../src/layer/layer.ts","../src/runtime/signal.ts"],"sourcesContent":["import { nodeRuntimeContextStorage } from './node'\n\nimport { setDefaultRuntimeContextStorage } from './context'\n\n/** The Node/Bun storage used by the main Runtime entrypoint. */\nexport const defaultRuntimeContextStorage = nodeRuntimeContextStorage\n\nsetDefaultRuntimeContextStorage(defaultRuntimeContextStorage)\n","import { ServiceRuntimeNotConfiguredError } from './errors'\n\nimport { RuntimeContextNotConfiguredError } from '../runtime/errors'\n\nimport {\n currentRuntimeContext,\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext\n} from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { AnyServiceToken } from './types'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\n/** Resolves class-backed Service tokens for a runtime execution. */\nexport interface ServiceResolver {\n /** Resolve a token to its corresponding Service instance. */\n resolve<T extends AnyServiceToken>(token: T): InstanceType<T> | PromiseLike<InstanceType<T>>\n}\n\n/** Provides the resolver context used by Service tokens during execution. */\nexport class ServiceRuntime {\n /**\n * Run a callback with a resolver available to `yield* Service` expressions.\n *\n * The context is scoped to the callback and is restored afterward.\n *\n * @example\n * ```ts\n * const value = ServiceRuntime.run(resolver, () => {\n * return ServiceRuntime.resolve(Database)\n * })\n * ```\n */\n static run<A>(\n resolver: ServiceResolver,\n program: () => A,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage\n ): A {\n const current = getRuntimeContext(storage)\n const context = makeRuntimeContext(\n resolver,\n current?.scope,\n current?.resolver === resolver ? current.resolutionPath : [],\n current?.signal,\n current?.resolver === resolver ? current : undefined\n )\n\n return runRuntimeContext(storage, context, program)\n }\n\n /** Return the resolver active in the current execution context. */\n static current(): ServiceResolver {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch (cause) {\n if (cause instanceof RuntimeContextNotConfiguredError) {\n throw new ServiceRuntimeNotConfiguredError()\n }\n\n throw cause\n }\n\n if (!context.resolver) {\n throw new ServiceRuntimeNotConfiguredError()\n }\n\n return context.resolver\n }\n\n /** Resolve a Service token using the active resolver. */\n static async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const resolver = ServiceRuntime.current()\n\n return await resolver.resolve(token)\n }\n}\n","import { ServiceRuntime } from './runtime'\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.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 if (tag.length === 0) {\n throw new TypeError('Service tags must not be empty')\n }\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 /** 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 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","/** Thrown when Scope context is accessed outside an active Scope execution. */\nexport class ScopeRuntimeNotConfiguredError extends Error {\n constructor() {\n super('No Scope is available in the current execution context')\n\n this.name = 'ScopeRuntimeNotConfiguredError'\n }\n}\n\n/** Thrown when a resource or finalizer is added after Scope closure begins. */\nexport class ScopeClosedError extends Error {\n constructor() {\n super('Cannot add resources or finalizers to a closed Scope')\n\n this.name = 'ScopeClosedError'\n }\n}\n\n/** Aggregates finalizer failures encountered while closing a Scope. */\nexport class ScopeCloseError extends Error {\n constructor(readonly causes: readonly unknown[]) {\n super(\n `Failed to close Scope (${causes.length} finalizer${causes.length === 1 ? '' : 's'} failed)`\n )\n\n this.name = 'ScopeCloseError'\n }\n}\n\n/** Thrown when a value has neither Symbol.dispose nor Symbol.asyncDispose. */\nexport class ResourceNotDisposableError extends Error {\n constructor() {\n super('Resource does not implement Symbol.dispose or Symbol.asyncDispose')\n\n this.name = 'ResourceNotDisposableError'\n }\n}\n","import type { ScopeFinalizer } from './types'\n\nconst SCOPE_SUCCESS = { status: 'success' } as const\n\ntype Disposer = (...args: never[]) => void | PromiseLike<void>\n\ntype DisposableCandidate = {\n [Symbol.dispose]?: Disposer\n\n [Symbol.asyncDispose]?: Disposer\n}\n\n/** Return a Scope finalizer for a value's async or sync disposal protocol. */\nexport const getDisposeFinalizer = <Resource>(resource: Resource): ScopeFinalizer | undefined => {\n // SAFETY: Object() provides a property-bearing view for protocol lookup; each method is checked for callability before invocation.\n const candidate = Object(resource) as DisposableCandidate\n const asyncDispose = candidate[Symbol.asyncDispose]\n\n if (asyncDispose instanceof Function) {\n return () => asyncDispose.call(resource)\n }\n\n const dispose = candidate[Symbol.dispose]\n\n if (dispose instanceof Function) {\n return () => dispose.call(resource)\n }\n\n return undefined\n}\n\n/** Dispose a value immediately when it implements a disposal protocol. */\nexport const disposeResource = <Resource>(resource: Resource): void | PromiseLike<void> => {\n const finalizer = getDisposeFinalizer(resource)\n\n return finalizer?.(SCOPE_SUCCESS)\n}\n","import { LayerGeneratorYieldError } from './errors'\n\nimport type { ServiceRequirement } from '../effect/types'\nimport type { ServiceClass } from '../service'\n\nimport type { LayerGenerator } from './types'\n\nexport const runLayerGenerator = async <\n S extends ServiceClass<any, any>,\n Yield extends ServiceRequirement<unknown>\n>(\n service: S,\n factory: LayerGenerator<S, Yield>\n): Promise<InstanceType<S>> => {\n const iterator = factory()\n\n const state = await iterator.next()\n\n if (!state.done) {\n try {\n // SAFETY: The iterator is closed only to discard an invalid yield; its return value is ignored.\n await iterator.return(undefined as never)\n } finally {\n // oxlint-disable-next-line no-unsafe-finally\n throw new LayerGeneratorYieldError(service)\n }\n }\n\n // SAFETY: The public generator boundary accepts only the requested Service contract.\n return state.value as InstanceType<S>\n}\n","import type { ServiceRequirement } from '../effect/types'\nimport { ServiceRuntime } from '../service'\nimport type { AnyService, ServiceClass, ServiceContract, ServiceRequirements } from '../service'\nimport { ResourceNotDisposableError } from '../scope'\nimport { getDisposeFinalizer } from '../scope/disposable'\n\nimport type { DisposableResource, ScopeFinalizer, ScopeOutcome } from '../scope'\nimport type { Covariant, Invariant } from '../internal/variance'\nimport type { MaybePromise } from '../utils/types'\n\nimport { DuplicateServiceError, ServiceTagCollisionError } from './errors'\nimport { runLayerGenerator } from './internal'\n\nimport type {\n LayerInput,\n CompleteInput,\n LayerResult,\n MergeResult,\n OverrideLayerResult,\n ValidateLayerInput,\n ValidateLayerTuple,\n ValidateOverrides,\n ProvidedEnvironment,\n RequiredEnvironment\n} from './inference'\nimport type { ProviderEntry } from './metadata'\nimport type { LayerGenerator, LayerGeneratorRequirements, LayerRegistration } from './types'\n\ndeclare const LayerTypeId: unique symbol\n\ninterface LayerVariance<in out Provided, out Required> {\n readonly _Provided: Invariant<Provided>\n readonly _Required: Covariant<Required>\n}\n\ntype CapturedLayerAcquisition = {\n readonly instance: unknown\n readonly release: ScopeFinalizer\n}\n\ninterface LayerProvider extends LayerRegistration {\n /** Provider storage deliberately erases the concrete instance type. */\n // oxlint-disable-next-line anti-slop/no-unknown-parameters\n readonly release?: (instance: unknown, outcome: ScopeOutcome) => MaybePromise<void>\n\n /** Capture acquisition-local cleanup without retaining the acquired instance. */\n readonly acquireWithRelease?: () => MaybePromise<CapturedLayerAcquisition>\n}\n\n/** A Service class whose constructor can be called without arguments. */\ntype DefaultConstructibleServiceClass<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n> = ServiceClass<Tag, Instance> & (new () => Instance)\n\ntype IsUnion<Type, Candidate = Type> = Type extends unknown\n ? [Candidate] extends [Type]\n ? false\n : true\n : never\n\ntype InvalidUnionAliasToken = {\n readonly __betterEffectUnionLayerAliasToken: unique symbol\n}\n\ntype RejectUnionAliasToken<Token> = IsUnion<Token> extends true ? InvalidUnionAliasToken : unknown\n\ntype LayerAliasOptions<From extends ServiceClass<any, any>, To extends ServiceClass<any, any>> = {\n readonly from: From\n readonly to: To\n} & RejectUnionAliasToken<From> &\n RejectUnionAliasToken<To> &\n ([ServiceContract<InstanceType<From>>] extends [ServiceContract<InstanceType<To>>]\n ? unknown\n : {\n readonly __betterEffectIncompatibleLayerAlias: unique symbol\n })\n\n/**\n * Declarative collection of Service providers.\n *\n * A Layer describes how to acquire implementations; it does not execute\n * providers until a `Runtime` is created. Use `merge` to compose distinct\n * providers and `override` when replacing an existing provider intentionally.\n *\n * @example\n * ```ts\n * const AppLive = Layer.merge(\n * Layer.succeed(Database, database),\n * Layer.make(UserRepository)\n * )\n *\n * const runtime = await Runtime.make(AppLive, backend)\n * ```\n */\nexport class Layer<\n in out Provided extends AnyService = AnyService,\n out Required extends AnyService = AnyService\n> {\n declare readonly [LayerTypeId]: LayerVariance<Provided, Required>\n\n /** The provider registrations retained by this Layer. */\n readonly providers: readonly LayerProvider[]\n\n private constructor(providers: readonly LayerProvider[]) {\n this.providers = Object.freeze([...providers])\n }\n\n /** A stable provider-free Layer for composition roots with no Services. */\n static readonly empty: Layer<never, never> = Object.freeze(new Layer<never, never>([]))\n\n /** Create a Layer that lazily acquires a Service instance. */\n static make<S extends DefaultConstructibleServiceClass<any, any>>(\n service: S\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n\n static make<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n\n static make<S extends ServiceClass<any, any>>(\n service: S,\n acquire?: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const defaultAcquire = (): InstanceType<S> => {\n // SAFETY: The no-argument overload constrains `service` to a default constructible class.\n const Constructor = service as new () => InstanceType<S>\n\n return new Constructor()\n }\n\n const normalizedAcquire = normalizeAcquire<S>(acquire ?? defaultAcquire)\n\n // SAFETY: Runtime storage erases only the concrete provider metadata; the public constructor result restores its typed provenance.\n return new Layer([\n {\n service,\n acquire: normalizedAcquire\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Create a Layer from an already-constructed Service instance. */\n static succeed<S extends ServiceClass<any, any>>(\n service: S,\n instance: ServiceContract<InstanceType<S>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const normalizedAcquire = normalizeAcquire<S>(() => instance)\n\n // SAFETY: The structural instance has been checked against the requested Service contract.\n return new Layer([\n {\n service,\n acquire: normalizedAcquire\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Alias a source Service under a compatible target contract. */\n static alias<From extends ServiceClass<any, any>, To extends ServiceClass<any, any>>(\n options: LayerAliasOptions<From, To>\n ): LayerResult<\n ProviderEntry<InstanceType<To>, InstanceType<From> | ServiceRequirements<InstanceType<To>>>\n > {\n const { from, to } = options\n\n // Keep alias acquisition in the normal Layer generator path so Runtime supplies the active resolver and resolution diagnostics.\n // oxlint-disable-next-line require-yield\n const alias = Layer.gen(to, async function* () {\n const source = await ServiceRuntime.resolve(from)\n\n // SAFETY: LayerAliasOptions checks that the source implementation satisfies the target contract.\n return source as ServiceContract<InstanceType<To>>\n })\n\n // SAFETY: The alias factory resolves the declared source token before returning the target contract.\n return alias as LayerResult<\n ProviderEntry<InstanceType<To>, InstanceType<From> | ServiceRequirements<InstanceType<To>>>\n >\n }\n\n /** Define a provider with Runtime-root cleanup. */\n static scoped<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>,\n release: (instance: InstanceType<S>, outcome: ScopeOutcome) => MaybePromise<void>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n // SAFETY: The public callbacks constrain acquisition and release to the requested Service.\n return new Layer([\n {\n service,\n acquire: normalizeAcquire<S>(acquire),\n release: (instance, outcome) => {\n // SAFETY: The backend invokes release with the instance acquired for this token.\n return release(instance as InstanceType<S>, outcome)\n }\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Define a provider with Runtime-root cleanup through its disposal protocol. */\n static scopedDisposable<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>> & DisposableResource>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const acquireWithRelease = async (): Promise<CapturedLayerAcquisition> => {\n const instance = await acquire()\n const finalizer = getDisposeFinalizer(instance)\n\n if (!finalizer) {\n throw new ResourceNotDisposableError()\n }\n\n return { instance, release: finalizer }\n }\n\n // SAFETY: The public callback constrains the acquired value and this runtime-only carrier is erased at the Layer boundary.\n return new Layer([\n {\n service,\n acquire: async () => (await acquireWithRelease()).instance,\n acquireWithRelease\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Define a provider whose acquisition can yield contextual Services. */\n static scopedGen<S extends ServiceClass<any, any>, Yield extends ServiceRequirement<unknown>>(\n service: S,\n factory: LayerGenerator<S, Yield>,\n release: (instance: InstanceType<S>, outcome: ScopeOutcome) => MaybePromise<void>\n ): LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>> {\n // SAFETY: The generator and release callback are checked against the requested Service.\n return new Layer([\n {\n service,\n acquire: () => runLayerGenerator(service, factory),\n release: (instance, outcome) => {\n // SAFETY: The backend invokes release with the instance acquired for this token.\n return release(instance as InstanceType<S>, outcome)\n }\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>>\n }\n\n /** Define a provider whose acquisition can yield contextual Services. */\n static gen<S extends ServiceClass<any, any>, Yield extends ServiceRequirement<unknown>>(\n service: S,\n factory: LayerGenerator<S, Yield>\n ): LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>> {\n // SAFETY: The generator result is normalized to the requested Service at the runtime boundary.\n return new Layer([\n {\n service,\n acquire: () => runLayerGenerator(service, factory)\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>>\n }\n\n /** Compose Layers without replacing providers. */\n static merge<const Layers extends readonly LayerInput[]>(\n ...layers: Layers & ValidateLayerTuple<Layers>\n ): MergeResult<Layers> {\n const providers = new Map<string, LayerProvider>()\n\n for (const layer of layers) {\n for (const provider of layer.providers) {\n const service = provider.service\n const existing = providers.get(service.serviceTag)\n\n if (existing) {\n if (existing.service !== service) {\n throw new ServiceTagCollisionError(existing.service, service)\n }\n\n throw new DuplicateServiceError(service)\n }\n\n providers.set(service.serviceTag, provider)\n }\n }\n\n // SAFETY: The heterogeneous provider list is erased only at this internal storage boundary.\n return new Layer([...providers.values()]) as MergeResult<Layers>\n }\n\n /** Mark a Layer composition root as complete without changing its runtime value. */\n static complete<L extends LayerInput>(layer: L & CompleteInput<L>): L {\n return layer\n }\n\n /** Replace providers in a base Layer, using tag identity and compatible contracts. */\n static override<Base extends LayerInput>(\n base: Base & ValidateLayerInput<Base>\n ): OverrideLayerResult<Base, readonly []>\n\n static override<\n Base extends LayerInput,\n const Overrides extends readonly [LayerInput, ...LayerInput[]]\n >(\n base: Base & ValidateLayerInput<Base>,\n ...overrides: Overrides & ValidateOverrides<Base, Overrides>\n ): OverrideLayerResult<Base, Overrides>\n\n static override<Base extends LayerInput, const Overrides extends readonly LayerInput[]>(\n base: Base & ValidateLayerInput<Base>,\n ...overrides: Overrides & ValidateOverrides<Base, Overrides>\n ): OverrideLayerResult<Base, Overrides>\n\n static override(base: LayerInput, ...overrides: readonly LayerInput[]): Layer<any, any> {\n const providers = new Map<string, LayerProvider>()\n\n for (const provider of base.providers) {\n providers.set(provider.service.serviceTag, provider)\n }\n\n for (const layer of overrides) {\n for (const provider of layer.providers) {\n providers.set(provider.service.serviceTag, provider)\n }\n }\n\n // SAFETY: Runtime provider replacement preserves the computed override metadata.\n return new Layer([...providers.values()]) as Layer<any, any>\n }\n}\n\n// TypeScript's `readonly` does not affect the runtime property descriptor. Keep\n// the class field's enumerable behavior while locking the singleton binding.\nObject.defineProperty(Layer, 'empty', {\n value: Layer.empty,\n writable: false,\n enumerable: true,\n configurable: false\n})\n\nconst normalizeAcquire =\n <S extends ServiceClass<any, any>>(\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): (() => MaybePromise<InstanceType<S>>) =>\n () => {\n // SAFETY: ServiceContract removes only the declaration-only identity; runtime values are unchanged.\n return acquire() as MaybePromise<InstanceType<S>>\n }\n\n/** Type-level aliases for inspecting Layer environments and completeness. */\nexport declare namespace Layer {\n /** The widened Layer shape accepted by generic Layer infrastructure. */\n export type Any = LayerInput\n\n /** Extract the branded Service instances provided by a Layer. */\n export type Provided<L extends LayerInput> = ProvidedEnvironment<L>\n\n /** Extract the external Service requirements of a Layer. */\n export type Required<L extends LayerInput> = RequiredEnvironment<L>\n\n /** Extract the Services still missing from a Layer composition. */\n export type Missing<L extends LayerInput> = RequiredEnvironment<L>\n\n /** Validate a Layer's requirements and input shape. */\n export type Complete<L extends LayerInput> = CompleteInput<L>\n}\n","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":";;;;;AAKA,MAAa,+BAA+B;AAE5C,gCAAgC,4BAA4B;;;;ACiB5D,IAAa,iBAAb,MAAa,eAAe;;;;;;;;;;;;;CAa1B,OAAO,IACL,UACA,SACA,UAAiC,8BAC9B;EACH,MAAM,UAAU,kBAAkB,OAAO;EACzC,MAAM,UAAU,mBACd,UACA,SAAS,OACT,SAAS,aAAa,WAAW,QAAQ,iBAAiB,CAAC,GAC3D,SAAS,QACT,SAAS,aAAa,WAAW,UAAU,KAAA,CAC7C;EAEA,OAAO,kBAAkB,SAAS,SAAS,OAAO;CACpD;;CAGA,OAAO,UAA2B;EAChC,IAAI;EAEJ,IAAI;GACF,UAAU,sBAAsB;EAClC,SAAS,OAAO;GACd,IAAI,iBAAiB,kCACnB,MAAM,IAAI,iCAAiC;GAG7C,MAAM;EACR;EAEA,IAAI,CAAC,QAAQ,UACX,MAAM,IAAI,iCAAiC;EAG7C,OAAO,QAAQ;CACjB;;CAGA,aAAa,QAAmC,OAAoC;EAGlF,OAAO,MAFU,eAAe,QAEZ,CAAC,CAAC,QAAQ,KAAK;CACrC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;ACrBA,SAAgB,UAAsC;CACpD,OAAO,SAAoC,KAA6B;EACtE,IAAI,IAAI,WAAW,GACjB,MAAM,IAAI,UAAU,gCAAgC;EAGtD,MAAe,YAA4C;;GAEzD,OAAgB,aAAkB;;;;;;;;;;;;;;;;;;;;;;;;GA0BlC,OAAO,GAAe,gBAAoE;IAExF,OAAO;GACT;;GAIA,eAAe,OAAO,iBAEqC;IACzD,OAAO,MAAM,eAAe,QAAQ,IAAI;GAC1C;EACF;EAEA,OAAO;CACT;AACF;;;;AC7GA,IAAa,iCAAb,cAAoD,MAAM;CACxD,c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,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,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as Layer, u as Service } from "./signal-B97cs85Z.mjs";
|
|
2
2
|
import { Result, TaggedError } from "better-result";
|
|
3
3
|
//#region src/standard-services/config.ts
|
|
4
4
|
/** A schema validation failure. Raw source values are intentionally omitted. */
|
|
@@ -337,4 +337,4 @@ const CurrentRequestLayer = (value) => CurrentRequest.layer(value);
|
|
|
337
337
|
//#endregion
|
|
338
338
|
export { ConfigSourceError as _, CurrentRequest as a, LoggerLive as c, Random as d, RandomLive as f, ConfigLive as g, Config as h, ClockTestLayer as i, LoggerTest as l, RandomSeededLayer as m, ClockLive as n, CurrentRequestLayer as o, RandomSeeded as p, ClockTest as r, Logger as s, Clock as t, LoggerTestLayer as u, ConfigValidationError as v };
|
|
339
339
|
|
|
340
|
-
//# sourceMappingURL=standard-services-
|
|
340
|
+
//# sourceMappingURL=standard-services-BFBq-4lo.mjs.map
|