better-effect 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +599 -30
- package/dist/adapters/iti.d.mts +2 -3
- package/dist/adapters/iti.d.mts.map +1 -1
- package/dist/adapters/iti.mjs +2 -2
- package/dist/bun.d.mts +95 -0
- package/dist/bun.d.mts.map +1 -0
- package/dist/bun.mjs +177 -0
- package/dist/bun.mjs.map +1 -0
- package/dist/{context-BUEf1qjL.mjs → context-DSGSqcJj.mjs} +14 -3
- package/dist/context-DSGSqcJj.mjs.map +1 -0
- package/dist/current-request-Bc1YHL0w.mjs +21 -0
- package/dist/current-request-Bc1YHL0w.mjs.map +1 -0
- package/dist/current-request-Dm-QQ3Xr.d.mts +22 -0
- package/dist/current-request-Dm-QQ3Xr.d.mts.map +1 -0
- package/dist/{effect-CK4YZaX0.mjs → effect-W0IQXY8P.mjs} +21 -2
- package/dist/effect-W0IQXY8P.mjs.map +1 -0
- package/dist/{errors-BKcsQ0ip.d.mts → errors-CpHMzPiP.d.mts} +6 -2
- package/dist/errors-CpHMzPiP.d.mts.map +1 -0
- package/dist/hono.d.mts +65 -27
- package/dist/hono.d.mts.map +1 -1
- package/dist/hono.mjs +177 -53
- package/dist/hono.mjs.map +1 -1
- package/dist/{index-CX6iAoCB.d.mts → index-3Bkl-sxS.d.mts} +7 -2
- package/dist/{index-CX6iAoCB.d.mts.map → index-3Bkl-sxS.d.mts.map} +1 -1
- package/dist/{index-B1nH4luq.d.mts → index-C2ed9Ilq.d.mts} +32 -21
- package/dist/index-C2ed9Ilq.d.mts.map +1 -0
- package/dist/{index-GYJ4qm9K.d.mts → index-ClNndn2-.d.mts} +93 -62
- package/dist/index-ClNndn2-.d.mts.map +1 -0
- package/dist/{index-BMdU_Z72.d.mts → index-Cy1VsU-u.d.mts} +2 -3
- package/dist/index-Cy1VsU-u.d.mts.map +1 -0
- package/dist/index.d.mts +6 -7
- package/dist/index.mjs +8 -8
- package/dist/{internal-identity-CbXoZIfw.mjs → internal-identity-BuHBtP0k.mjs} +2 -2
- package/dist/{internal-identity-CbXoZIfw.mjs.map → internal-identity-BuHBtP0k.mjs.map} +1 -1
- package/dist/layer-2kjHVv4N.mjs +343 -0
- package/dist/layer-2kjHVv4N.mjs.map +1 -0
- package/dist/{outcome-CB43bnFW.d.mts → layer-C2OaqTmB.d.mts} +683 -138
- package/dist/layer-C2OaqTmB.d.mts.map +1 -0
- package/dist/next.d.mts +192 -0
- package/dist/next.d.mts.map +1 -0
- package/dist/next.mjs +185 -0
- package/dist/next.mjs.map +1 -0
- package/dist/{node-context-DWsCUBRa.d.mts → node-context-1YEjrU9g.d.mts} +2 -2
- package/dist/{node-context-DWsCUBRa.d.mts.map → node-context-1YEjrU9g.d.mts.map} +1 -1
- package/dist/{node-context-lggRF4bR.mjs → node-context-g3bCcY9t.mjs} +2 -2
- package/dist/{node-context-lggRF4bR.mjs.map → node-context-g3bCcY9t.mjs.map} +1 -1
- package/dist/node.d.mts +11 -6
- package/dist/node.d.mts.map +1 -1
- package/dist/node.mjs +156 -10
- package/dist/node.mjs.map +1 -1
- package/dist/opentelemetry.d.mts +112 -0
- package/dist/opentelemetry.d.mts.map +1 -0
- package/dist/opentelemetry.mjs +871 -0
- package/dist/opentelemetry.mjs.map +1 -0
- package/dist/{registration-drnZk0SY.mjs → registration-Bwe2GbVu.mjs} +8 -2
- package/dist/registration-Bwe2GbVu.mjs.map +1 -0
- package/dist/runtime/explicit.d.mts +2 -2
- package/dist/runtime/explicit.mjs +1 -1
- package/dist/runtime/node.d.mts +3 -3
- package/dist/runtime/node.mjs +2 -2
- package/dist/runtime-qpcVwaz_.mjs +1680 -0
- package/dist/runtime-qpcVwaz_.mjs.map +1 -0
- package/dist/service-CO9VJQYa.mjs +74 -0
- package/dist/service-CO9VJQYa.mjs.map +1 -0
- package/dist/signal-5Rg9bUUe.mjs +52 -0
- package/dist/signal-5Rg9bUUe.mjs.map +1 -0
- package/dist/{standard-services-GBZ32tll.mjs → standard-services-B-iMM_W7.mjs} +39 -19
- package/dist/standard-services-B-iMM_W7.mjs.map +1 -0
- package/dist/standard-services.d.mts +4 -3
- package/dist/standard-services.mjs +3 -2
- package/dist/testing.d.mts +25 -6
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +51 -7
- package/dist/testing.mjs.map +1 -1
- package/dist/types-BFTqCCcw.d.mts +81 -0
- package/dist/types-BFTqCCcw.d.mts.map +1 -0
- package/dist/web-effect-B9hp9jIe.mjs +380 -0
- package/dist/web-effect-B9hp9jIe.mjs.map +1 -0
- package/dist/web.d.mts +56 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +2 -0
- package/package.json +36 -11
- package/dist/context-BUEf1qjL.mjs.map +0 -1
- package/dist/effect-CK4YZaX0.mjs.map +0 -1
- package/dist/errors-BKcsQ0ip.d.mts.map +0 -1
- package/dist/index-B1nH4luq.d.mts.map +0 -1
- package/dist/index-BMdU_Z72.d.mts.map +0 -1
- package/dist/index-GYJ4qm9K.d.mts.map +0 -1
- package/dist/index-heuaRmXR.d.mts +0 -374
- package/dist/index-heuaRmXR.d.mts.map +0 -1
- package/dist/layer-D56fRdLt.mjs +0 -269
- package/dist/layer-D56fRdLt.mjs.map +0 -1
- package/dist/outcome-CB43bnFW.d.mts.map +0 -1
- package/dist/program-metadata-DhQCCirO.mjs +0 -260
- package/dist/program-metadata-DhQCCirO.mjs.map +0 -1
- package/dist/registration-drnZk0SY.mjs.map +0 -1
- package/dist/runtime-CBMrX8Wl.mjs +0 -776
- package/dist/runtime-CBMrX8Wl.mjs.map +0 -1
- package/dist/signal-D2UTcaaG.mjs +0 -105
- package/dist/signal-D2UTcaaG.mjs.map +0 -1
- package/dist/standard-services-GBZ32tll.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"layer-D56fRdLt.mjs","names":["Constructor"],"sources":["../src/service/runtime.ts","../src/service/service.ts","../src/layer/internal.ts","../src/layer/layer.ts"],"sourcesContent":["import { ServiceRuntimeNotConfiguredError } from './errors'\nimport { captureServiceTag } from './tag'\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 captureServiceTag(token)\n const resolver = ServiceRuntime.current()\n\n return await resolver.resolve(token)\n }\n}\n","import { ServiceRuntime } from './runtime'\nimport { registerServiceTag, validateServiceTag } from './tag'\n\nimport type { ServiceRequirement } from '../effect/types'\n\nimport type {\n AnyService,\n AnyServiceToken,\n ServiceClass,\n ServiceContract,\n ServiceIdentity,\n ServiceIdentityTypeId,\n ServiceInstance,\n ServiceRequirements,\n ServiceTag,\n ServiceToken,\n ServiceTokenOf\n} from './types'\n\ntype ServiceTagLiteral<Tag extends string> = string extends Tag\n ? never\n : Tag extends ''\n ? never\n : Tag\n\ninterface ServiceFactory<Self> {\n <const Tag extends string>(\n tag: ServiceTagLiteral<Tag>\n ): (abstract new () => ServiceIdentity<Tag>) & {\n readonly name: string\n readonly serviceTag: Tag\n } & {\n readonly of: Service.FactoryOf<Self, Tag>\n readonly [Symbol.asyncIterator]: (\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ) => AsyncGenerator<ServiceRequirement<Self>, Self, unknown>\n }\n}\n\n/**\n * Declare a class-backed Service with a stable string-literal identity.\n *\n * The returned class is simultaneously the implementation type, the runtime\n * dependency token, and the value yielded by `yield*` in an Effect generator.\n * The explicit self type preserves exact instance inference, while the second\n * call captures the tag as a literal for Layer composition and diagnostics.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(): string {\n * return 'ok'\n * }\n * }\n *\n * const database = yield* Database\n * database.query()\n * ```\n *\n * @typeParam Self The instance type implemented by the declared Service.\n */\nexport function Service<Self>(): ServiceFactory<Self> {\n return function <const Tag extends string>(tag: ServiceTagLiteral<Tag>) {\n validateServiceTag(tag)\n\n abstract class BaseService implements ServiceIdentity<Tag> {\n /** The stable logical identity used by Layers and resolver backends. */\n static readonly serviceTag: Tag = tag\n declare readonly [ServiceIdentityTypeId]: Tag\n\n /**\n * Type-check a structural implementation of this Service.\n *\n * This is an identity helper. It returns the supplied value unchanged\n * and does not invoke a constructor or modify its prototype.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(sql: string): string {\n * return sql\n * }\n * }\n *\n * const database = Database.of({\n * query: (sql) => `Result: ${sql}`\n * })\n *\n * database.query('SELECT 1')\n * // 'Result: SELECT 1'\n * // database is the original object, not an instance of Database\n * ```\n */\n static of(this: void, implementation: ServiceContract<Self & ServiceIdentity<Tag>>): Self {\n // SAFETY: ServiceContract removes only the phantom marker; this boundary restores Self.\n return implementation as Self\n }\n\n /** Resolve this Service from the resolver active in the current runtime. */\n // oxlint-disable-next-line require-yield\n static async *[Symbol.asyncIterator](\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ): AsyncGenerator<ServiceRequirement<Self>, Self, unknown> {\n return await ServiceRuntime.resolve(this)\n }\n }\n\n registerServiceTag(BaseService, tag)\n\n return BaseService\n }\n}\n\n/** Type-level aliases for Service tokens and their instance contracts. */\nexport declare namespace Service {\n /** The widened Service instance constraint. */\n export type Any = AnyService\n\n /** A class-backed Service token with a stable tag and instance contract. */\n export type Token<Tag extends string = string, Instance extends AnyService = any> = ServiceToken<\n Tag,\n Instance\n >\n\n /** A constructible Service class with a stable tag and instance contract. */\n export type Class<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n > = ServiceClass<Tag, Instance>\n\n /** Extract the instance represented by a Service token. */\n export type Instance<T extends AnyServiceToken> = ServiceInstance<T>\n\n /** Extract the stable tag represented by a Service instance. */\n export type Tag<S extends AnyService> = ServiceTag<S>\n\n /** A branded Service instance identity with a stable tag. */\n export type Identity<Tag extends string = string> = ServiceIdentity<Tag>\n\n /** Remove the internal identity marker from a Service implementation contract. */\n export type Contract<S extends AnyService> = ServiceContract<S>\n\n /** Extract the Service token represented by a branded Service instance. */\n export type TokenOf<S extends AnyService> = ServiceTokenOf<S>\n\n /** Declaration bridge for the recursive structural `Service.of` signature. */\n export type FactoryOf<Self, Tag extends string> = (\n this: void,\n implementation: ServiceContract<Self & ServiceIdentity<Tag>>\n ) => Self\n\n /** Extract Effect Service requirements from a Service instance. */\n export type Requirements<S extends AnyService> = ServiceRequirements<S>\n}\n","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 { captureServiceTag } from '../service/tag'\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'\nimport { captureLayerRegistrationTag } from './registration'\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 /** The tag captured before this provider can cross an asynchronous boundary. */\n readonly serviceTag: string\n\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(\n providers.map((provider) =>\n Object.freeze({\n ...provider,\n serviceTag: captureLayerRegistrationTag(provider)\n })\n )\n )\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 serviceTag = captureServiceTag(service)\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 serviceTag,\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 serviceTag = captureServiceTag(service)\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 serviceTag,\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 void captureServiceTag(from)\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 const serviceTag = captureServiceTag(service)\n\n // SAFETY: The public callbacks constrain acquisition and release to the requested Service.\n return new Layer([\n {\n service,\n serviceTag,\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 const serviceTag = captureServiceTag(service)\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 serviceTag,\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 const serviceTag = captureServiceTag(service)\n\n // SAFETY: The generator and release callback are checked against the requested Service.\n return new Layer([\n {\n service,\n serviceTag,\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 const serviceTag = captureServiceTag(service)\n\n // SAFETY: The generator result is normalized to the requested Service at the runtime boundary.\n return new Layer([\n {\n service,\n serviceTag,\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 serviceTag = captureLayerRegistrationTag(provider)\n const existing = providers.get(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(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(captureLayerRegistrationTag(provider), provider)\n }\n\n for (const layer of overrides) {\n for (const provider of layer.providers) {\n providers.set(captureLayerRegistrationTag(provider), 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"],"mappings":";;;;;AAyBA,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;EAClF,kBAAkB,KAAK;EAGvB,OAAO,MAFU,eAAe,QAEZ,CAAC,CAAC,QAAQ,KAAK;CACrC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;ACtBA,SAAgB,UAAsC;CACpD,OAAO,SAAoC,KAA6B;EACtE,mBA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,QAAQ;GACvD,MAAM,WAAW,UAAU,IAAI,UAAU;GAEzC,IAAI,UAAU;IACZ,IAAI,SAAS,YAAY,SACvB,MAAM,IAAI,yBAAyB,SAAS,SAAS,OAAO;IAG9D,MAAM,IAAI,sBAAsB,OAAO;GACzC;GAEA,UAAU,IAAI,YAAY,QAAQ;EACpC;EAIF,OAAO,IAAI,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC,CAAC;CAC1C;;CAGA,OAAO,SAA+B,OAAgC;EACpE,OAAO;CACT;CAoBA,OAAO,SAAS,MAAkB,GAAG,WAAmD;EACtF,MAAM,4BAAY,IAAI,IAA2B;EAEjD,KAAK,MAAM,YAAY,KAAK,WAC1B,UAAU,IAAI,4BAA4B,QAAQ,GAAG,QAAQ;EAG/D,KAAK,MAAM,SAAS,WAClB,KAAK,MAAM,YAAY,MAAM,WAC3B,UAAU,IAAI,4BAA4B,QAAQ,GAAG,QAAQ;EAKjE,OAAO,IAAI,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC,CAAC;CAC1C;AACF;AAIA,OAAO,eAAe,OAAO,SAAS;CACpC,OAAO,MAAM;CACb,UAAU;CACV,YAAY;CACZ,cAAc;AAChB,CAAC;AAED,MAAM,oBAEF,kBAEI;CAEJ,OAAO,QAAQ;AACjB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"outcome-CB43bnFW.d.mts","names":[],"sources":["../src/internal/variance.ts","../src/utils/types.ts","../src/internal/missing-dependencies.ts","../src/layer/metadata.ts","../src/layer/inference.ts","../src/layer/types.ts","../src/layer/layer.ts","../src/layer/backend.ts","../src/layer/errors.ts","../src/runtime/observer.ts","../src/runtime/outcome.ts"],"mappings":";;;KACY,UAAU,WAAW;;KAGrB,UAAU,MAAM,OAAO,MAAM;;;KCJ7B,aAAa,KAAK,IAAI,YAAY;;;KCElC,oBAAoB,gBAAgB;;WAErC,iBAAiB;;;;;cCCP;UAEJ,kBACX,iBAAiB,gBACjB,oBAAoB;WAE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EjB,SAAS;;;KAIR;WACD,SAAS;;WAET,aAAa;;;KAIZ;;WAED;;WAEA"}
|
|
@@ -1,260 +0,0 @@
|
|
|
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 ResourceNotDisposableError, c as ScopeRuntimeNotConfiguredError, i as getDisposeFinalizer, o as ScopeCloseError, s as ScopeClosedError } from "./signal-D2UTcaaG.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
|
-
//#region src/effect/program-metadata.ts
|
|
244
|
-
const programNames = /* @__PURE__ */ new WeakMap();
|
|
245
|
-
/** Return the private diagnostic name attached to a callable Program. */
|
|
246
|
-
const getProgramName = (program) => programNames.get(program);
|
|
247
|
-
/** Attach a name without changing the callable Program facade. */
|
|
248
|
-
const setProgramName = (program, name) => {
|
|
249
|
-
programNames.set(program, name);
|
|
250
|
-
return program;
|
|
251
|
-
};
|
|
252
|
-
/** Copy a source Program's name to a lazily-created derived Program. */
|
|
253
|
-
const inheritProgramName = (source, derived) => {
|
|
254
|
-
const name = getProgramName(source);
|
|
255
|
-
return name === void 0 ? derived : setProgramName(derived, name);
|
|
256
|
-
};
|
|
257
|
-
//#endregion
|
|
258
|
-
export { runScoped as a, Scope as i, inheritProgramName as n, ScopeRuntime as o, setProgramName as r, getProgramName as t };
|
|
259
|
-
|
|
260
|
-
//# sourceMappingURL=program-metadata-DhQCCirO.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"program-metadata-DhQCCirO.mjs","names":[],"sources":["../src/scope/runtime.ts","../src/scope/internal.ts","../src/scope/scope.ts","../src/effect/program-metadata.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","export type ProgramIdentity = (...arguments_: never[]) => void\n\nconst programNames = new WeakMap<ProgramIdentity, string>()\n\n/** Return the private diagnostic name attached to a callable Program. */\nexport const getProgramName = (program: ProgramIdentity): string | undefined =>\n programNames.get(program)\n\n/** Attach a name without changing the callable Program facade. */\nexport const setProgramName = <Program extends ProgramIdentity>(\n program: Program,\n name: string\n): Program => {\n programNames.set(program, name)\n return program\n}\n\n/** Copy a source Program's name to a lazily-created derived Program. */\nexport const inheritProgramName = <Source extends ProgramIdentity, Derived extends ProgramIdentity>(\n source: Source,\n derived: Derived\n): Derived => {\n const name = getProgramName(source)\n\n return name === undefined ? derived : setProgramName(derived, name)\n}\n"],"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,YAAY,OACvB,OACA,SACA,YACwB;CACxB,IAAI;CAEJ,IAAI,gBAAgB;CACpB,IAAI;CAEJ,IAAI;EACF,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AAQ,IAAI,UAAU;EAE5B,OAAO,UAAU,aAAa,QAAQ,KAAK,GAAG,EAC5C,gBAAgB,cAClB,CAAC;CACH;AACF;;;ACzQA,MAAM,+BAAe,IAAI,QAAiC;;AAG1D,MAAa,kBAAkB,YAC7B,aAAa,IAAI,OAAO;;AAG1B,MAAa,kBACX,SACA,SACY;CACZ,aAAa,IAAI,SAAS,IAAI;CAC9B,OAAO;AACT;;AAGA,MAAa,sBACX,QACA,YACY;CACZ,MAAM,OAAO,eAAe,MAAM;CAElC,OAAO,SAAS,KAAA,IAAY,UAAU,eAAe,SAAS,IAAI;AACpE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registration-drnZk0SY.mjs","names":[],"sources":["../src/service/tag.ts","../src/service/errors.ts","../src/layer/errors.ts","../src/layer/registration.ts"],"sourcesContent":["const serviceTags = new WeakMap<object, string>()\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- This boundary validates untrusted JavaScript token values.\nconst isObjectLike = (value: unknown): value is object => value !== null && Object(value) === value\n\n// oxlint-disable-next-line anti-slop/no-object-parameters -- Tokens are validated object-like owners at this internal boundary.\nconst lockServiceTag = (token: object, tag: string): void => {\n const descriptor = Object.getOwnPropertyDescriptor(token, 'serviceTag')\n\n if (descriptor?.configurable === false) {\n if ('value' in descriptor && descriptor.value === tag && descriptor.writable === false) {\n return\n }\n\n if ('value' in descriptor && descriptor.value === tag && descriptor.writable === true) {\n Object.defineProperty(token, 'serviceTag', { writable: false })\n return\n }\n\n throw new TypeError('Service tags must be immutable')\n }\n\n Object.defineProperty(token, 'serviceTag', {\n value: tag,\n writable: false,\n enumerable: descriptor?.enumerable ?? true,\n configurable: false\n })\n}\n\n/** Validate the runtime form of a Service tag without coercing it. */\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Validate the public JavaScript declaration boundary.\nexport const validateServiceTag = (tag: unknown): string => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Reject boxed and object tag aliases instead of coercing them.\n if (typeof tag !== 'string' || tag.length === 0) {\n throw new TypeError('Service tags must be non-empty primitive strings')\n }\n\n return tag\n}\n\n/** Record a declaration tag and make the public static property immutable. */\n// oxlint-disable-next-line anti-slop/no-object-parameters -- The declaration owner is always a class constructor.\nexport const registerServiceTag = (token: object, tag: string): void => {\n const canonicalTag = validateServiceTag(tag)\n const existing = serviceTags.get(token)\n\n if (existing !== undefined) {\n if (existing !== canonicalTag) {\n throw new TypeError('A Service tag cannot be changed after declaration')\n }\n\n return\n }\n\n lockServiceTag(token, canonicalTag)\n serviceTags.set(token, canonicalTag)\n}\n\n/** Capture a token's logical tag once so later mutable aliases cannot drift. */\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Validate unchecked Service tokens at each runtime boundary.\nexport const captureServiceTag = (token: unknown): string => {\n if (!isObjectLike(token)) {\n throw new TypeError('Service tokens must be objects or functions')\n }\n\n const known = serviceTags.get(token)\n\n if (known !== undefined) {\n return known\n }\n\n let prototype = Object.getPrototypeOf(token)\n\n while (isObjectLike(prototype)) {\n const inherited = serviceTags.get(prototype)\n\n if (inherited !== undefined) {\n lockServiceTag(token, inherited)\n serviceTags.set(token, inherited)\n\n return inherited\n }\n\n prototype = Object.getPrototypeOf(prototype)\n }\n\n // SAFETY: The object-like check above limits this assertion to a token-shaped object; the value is validated immediately below.\n const tag = validateServiceTag((token as { readonly serviceTag?: unknown }).serviceTag)\n lockServiceTag(token, tag)\n serviceTags.set(token, tag)\n\n return tag\n}\n","import { captureServiceTag } from './tag'\nimport type { AnyServiceToken } from './types'\n\nconst formatResolutionPath = (path: readonly AnyServiceToken[]): string =>\n path.map((service) => captureServiceTag(service)).join(' → ')\n\n/** Thrown when a Service is accessed without an active runtime resolver. */\nexport class ServiceRuntimeNotConfiguredError extends Error {\n constructor() {\n super('No ServiceResolver is available in the current runtime context')\n\n this.name = 'ServiceRuntimeNotConfiguredError'\n }\n}\n\n/** Thrown when a runtime has no provider for the requested Service tag. */\nexport class ServiceNotFoundError extends Error {\n constructor(readonly service: AnyServiceToken) {\n super(`Service \"${captureServiceTag(service)}\" was not provided`)\n\n this.name = 'ServiceNotFoundError'\n }\n}\n\n/** Thrown when resolving a Service re-enters a Service already in its path. */\nexport class CircularDependencyError extends Error {\n readonly path: readonly AnyServiceToken[]\n\n constructor(path: readonly AnyServiceToken[]) {\n const normalizedPath = Object.freeze([...path])\n\n super(`Circular Service dependency detected:\\n${formatResolutionPath(normalizedPath)}`)\n\n this.name = 'CircularDependencyError'\n this.path = normalizedPath\n }\n}\n\n/** Thrown when a registered Service provider fails during lazy acquisition. */\nexport class ServiceAcquisitionError extends Error {\n override readonly cause: unknown\n\n constructor(\n readonly service: AnyServiceToken,\n resolutionPath: readonly AnyServiceToken[],\n cause: unknown\n ) {\n const normalizedPath = Object.freeze([...resolutionPath])\n\n super(\n `Failed to acquire Service \"${captureServiceTag(service)}\"` +\n (normalizedPath.length > 0\n ? ` while resolving: ${formatResolutionPath(normalizedPath)}`\n : '')\n )\n\n this.name = 'ServiceAcquisitionError'\n this.cause = cause\n this.resolutionPath = normalizedPath\n }\n\n readonly resolutionPath: readonly AnyServiceToken[]\n}\n","import { captureServiceTag } from '../service/tag'\nimport type { AnyServiceToken, ServiceClass } from '../service'\nimport type { ScopeOutcome } from '../scope'\n\ntype LayerCause = Extract<ScopeOutcome, { readonly status: 'failure' }>['cause']\n\n/** Thrown when a Layer registers the same Service tag more than once. */\nexport class DuplicateServiceError extends Error {\n constructor(readonly service: ServiceClass<any>) {\n super(`Duplicate service tag \"${captureServiceTag(service)}\"`)\n\n this.name = 'DuplicateServiceError'\n }\n}\n\n/** Thrown when one Service tag is associated with incompatible constructors. */\nexport class ServiceTagCollisionError extends Error {\n constructor(\n readonly existing: AnyServiceToken,\n readonly incoming: AnyServiceToken\n ) {\n super(\n `Service tag \"${captureServiceTag(incoming)}\" is already associated with \"${existing.name}\" ` +\n `and cannot be associated with \"${incoming.name}\"`\n )\n\n this.name = 'ServiceTagCollisionError'\n }\n}\n\n/** Thrown when a backend fails while registering a Layer provider. */\nexport class LayerRegistrationError extends Error {\n constructor(\n readonly service: ServiceClass<any> | undefined,\n readonly registrationCause: LayerCause,\n readonly cleanupCause?: LayerCause\n ) {\n super(\n service\n ? `Failed to register service \"${captureServiceTag(service)}\"`\n : 'Failed to build Layer',\n {\n cause: registrationCause\n }\n )\n\n this.name = 'LayerRegistrationError'\n }\n}\n\n/** Thrown when one or more Layer-owned resources fail during disposal. */\nexport class LayerDisposeError extends Error {\n constructor(readonly causes: readonly unknown[]) {\n super(`Failed to dispose Layer (${causes.length} error${causes.length === 1 ? '' : 's'})`)\n\n this.name = 'LayerDisposeError'\n }\n}\n\n/** Thrown when a Layer generator yields a value other than a Service requirement. */\nexport class LayerGeneratorYieldError extends Error {\n constructor(readonly service: ServiceClass<any>) {\n super(`Layer.gen(\"${captureServiceTag(service)}\") yielded an unsupported value`)\n\n this.name = 'LayerGeneratorYieldError'\n }\n}\n","import { captureServiceTag, validateServiceTag } from '../service/tag'\n\nimport type { LayerRegistration } from './types'\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Validate unchecked registrations at the adapter boundary.\nconst validateRegistrationTag = (service: unknown, registrationTag: unknown): string => {\n const tokenTag = captureServiceTag(service)\n\n if (registrationTag === undefined) {\n return tokenTag\n }\n\n const canonicalTag = validateServiceTag(registrationTag)\n\n if (canonicalTag !== tokenTag) {\n throw new TypeError('Layer registration tag does not match its Service token')\n }\n\n return canonicalTag\n}\n\n/** Capture and validate the logical identity carried by a backend registration. */\nexport const captureLayerRegistrationTag = (registration: LayerRegistration): string => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Reject forged registrations before reading their fields.\n if (typeof registration !== 'object' || registration === null) {\n throw new TypeError('Layer registrations must be objects')\n }\n\n return validateRegistrationTag(registration.service, registration.serviceTag)\n}\n\n/** Detach a registration from mutable caller-owned objects at the backend boundary. */\nexport const normalizeLayerRegistration = (registration: LayerRegistration): LayerRegistration => {\n const service = registration.service\n const registrationTag = registration.serviceTag\n const acquire = registration.acquire\n const serviceTag = validateRegistrationTag(service, registrationTag)\n\n return Object.freeze({\n service,\n serviceTag,\n acquire\n })\n}\n"],"mappings":";AAAA,MAAM,8BAAc,IAAI,QAAwB;AAGhD,MAAM,gBAAgB,UAAoC,UAAU,QAAQ,OAAO,KAAK,MAAM;AAG9F,MAAM,kBAAkB,OAAe,QAAsB;CAC3D,MAAM,aAAa,OAAO,yBAAyB,OAAO,YAAY;CAEtE,IAAI,YAAY,iBAAiB,OAAO;EACtC,IAAI,WAAW,cAAc,WAAW,UAAU,OAAO,WAAW,aAAa,OAC/E;EAGF,IAAI,WAAW,cAAc,WAAW,UAAU,OAAO,WAAW,aAAa,MAAM;GACrF,OAAO,eAAe,OAAO,cAAc,EAAE,UAAU,MAAM,CAAC;GAC9D;EACF;EAEA,MAAM,IAAI,UAAU,gCAAgC;CACtD;CAEA,OAAO,eAAe,OAAO,cAAc;EACzC,OAAO;EACP,UAAU;EACV,YAAY,YAAY,cAAc;EACtC,cAAc;CAChB,CAAC;AACH;;AAIA,MAAa,sBAAsB,QAAyB;CAE1D,IAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,GAC5C,MAAM,IAAI,UAAU,kDAAkD;CAGxE,OAAO;AACT;;AAIA,MAAa,sBAAsB,OAAe,QAAsB;CACtE,MAAM,eAAe,mBAAmB,GAAG;CAC3C,MAAM,WAAW,YAAY,IAAI,KAAK;CAEtC,IAAI,aAAa,KAAA,GAAW;EAC1B,IAAI,aAAa,cACf,MAAM,IAAI,UAAU,mDAAmD;EAGzE;CACF;CAEA,eAAe,OAAO,YAAY;CAClC,YAAY,IAAI,OAAO,YAAY;AACrC;;AAIA,MAAa,qBAAqB,UAA2B;CAC3D,IAAI,CAAC,aAAa,KAAK,GACrB,MAAM,IAAI,UAAU,6CAA6C;CAGnE,MAAM,QAAQ,YAAY,IAAI,KAAK;CAEnC,IAAI,UAAU,KAAA,GACZ,OAAO;CAGT,IAAI,YAAY,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