import type { GetServiceTypeImplementation, IResolvedServiceImplementation, IServiceDescriptor, IServiceImplementationResolver, IServiceTypeResolver, RequestPath, ServiceType, SingleServiceImplementation, } from "../../types/index.js"; import { BaseServiceImplementationResolver } from "../../implementation-resolvers/BaseServiceImplementationResolver.js"; import { fallback } from "../../implementation-resolvers/fallback.js"; export interface IConditionFactory[]> { ( ...args: GetServiceTypeImplementation ): | T | SingleServiceImplementation | IServiceImplementationResolver | Promise< SingleServiceImplementation | IServiceImplementationResolver >; } export class ConditionalServiceImplementationResolver< T, TArgs extends ServiceType[], > extends BaseServiceImplementationResolver { get name(): string { return "conditional(?)"; } constructor( private readonly factory: IConditionFactory, private readonly dependencies: TArgs, ) { super(); } override *resolve( internalGetService: IServiceTypeResolver, descriptor: IServiceDescriptor, requestedBy: IServiceDescriptor | null, requestedPath: RequestPath, mode: "sync" | "async", context: Readonly>, ): Generator, IResolvedServiceImplementation, unknown> { const deps: unknown[] = []; for (const dep of this.dependencies) { deps.push( yield* internalGetService( dep, requestedBy, requestedPath, mode, context, ), ); } const result = this.factory( ...(deps as GetServiceTypeImplementation), ); let implementation: | T | SingleServiceImplementation | IServiceImplementationResolver; if (result instanceof Promise) { yield result.then((impl) => { implementation = impl; }); } else { implementation = result; } implementation = fallback(implementation!); return yield* implementation.resolve( internalGetService, descriptor, requestedBy, requestedPath, mode, context, ); } } export function isConditionalServiceImplementationResolver< T, TArgs extends ServiceType[], >(value: any): value is ConditionalServiceImplementationResolver { return value instanceof ConditionalServiceImplementationResolver; }