All files / src/internal/core instance-resolver.mts

79.76% Statements 134/168
65.03% Branches 93/143
76.92% Functions 20/26
79.76% Lines 134/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817                                                                                268x 268x 268x 268x 268x 268x 268x 268x 268x                                               836x                                               151x                                                                               987x             987x 3x     984x         984x     987x   13x 13x 13x                     987x 450x 450x     444x 444x 444x         444x 3x   441x     6x 6x           6x               540x                     520x       520x                                                     990x 990x       3x 987x         3x       3x           3x 3x                   984x   984x 984x     984x             984x                               6x                                                                 6x 6x     6x   6x                                         540x       540x       540x 540x 540x     540x 72x                   468x                   468x 125x   343x       468x           468x     468x                   540x     540x   93x 93x 45x   48x 48x 48x 48x             540x 468x       468x 468x 468x           468x                                                                               540x 540x 540x                               72x         72x                   72x           72x         72x                           72x                               448x 448x       448x     448x 134x               448x     448x                         20x 20x 20x       20x                                   468x 20x               448x                                                 1746x     857x 106x         106x 3x     103x   103x       854x 854x   854x   854x 103x           834x                   889x                                       540x   540x       168x     168x 168x 168x       168x 168x                 168x                 23x                     23x                 167x       167x       32x   540x                                                        
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { ScopedContainer } from '../../container/scoped-container.mjs'
import type { IContainer } from '../../interfaces/container.interface.mjs'
import type {
  AnyInjectableType,
  InjectionTokenType,
} from '../../token/injection-token.mjs'
import type { Registry } from '../../token/registry.mjs'
import type { ServiceInitializationContext } from '../context/service-initialization-context.mjs'
import type { IHolderStorage } from '../holder/holder-storage.interface.mjs'
import type { InstanceHolder } from '../holder/instance-holder.mjs'
import type { LifecycleEventBus } from '../lifecycle/lifecycle-event-bus.mjs'
 
import { InjectableScope } from '../../enums/index.mjs'
import { DIError, DIErrorCode } from '../../errors/index.mjs'
import {
  FactoryInjectionToken,
  InjectionToken,
} from '../../token/injection-token.mjs'
import {
  getCurrentResolutionContext,
  withResolutionContext,
} from '../context/resolution-context.mjs'
import { InstanceStatus } from '../holder/instance-holder.mjs'
import { CircularDetector } from '../lifecycle/circular-detector.mjs'
import { NameResolver } from './name-resolver.mjs'
import { ScopeTracker } from './scope-tracker.mjs'
import { ServiceInitializer } from './service-initializer.mjs'
import { ServiceInvalidator } from './service-invalidator.mjs'
import { TokenResolver } from './token-resolver.mjs'
 
/**
 * Resolves instances from tokens, handling caching, creation, and scope rules.
 *
 * Uses unified storage for both singleton and request-scoped services.
 * Coordinates with ServiceInitializer for actual service creation.
 * Integrates ScopeTracker for automatic scope upgrades.
 */
export class InstanceResolver {
  constructor(
    private readonly registry: Registry,
    private readonly storage: IHolderStorage,
    private readonly serviceInitializer: ServiceInitializer,
    private readonly tokenResolver: TokenResolver,
    private readonly nameResolver: NameResolver,
    private readonly scopeTracker: ScopeTracker,
    private readonly serviceInvalidator: ServiceInvalidator,
    private readonly eventBus: LifecycleEventBus,
    private readonly logger: Console | null = null,
  ) {}
 
  // ============================================================================
  // PUBLIC RESOLUTION METHODS
  // ============================================================================
 
  /**
   * Resolves an instance for the given token and arguments.
   * This method is used for singleton and transient services.
   *
   * @param token The injection token
   * @param args Optional arguments
   * @param contextContainer The container to use for creating context
   * @param requestStorage Optional request storage (for scope upgrades)
   * @param requestId Optional request ID (for scope upgrades)
   */
  async resolveInstance(
    token: AnyInjectableType,
    args: any,
    contextContainer: IContainer,
    requestStorage?: IHolderStorage,
    requestId?: string,
  ): Promise<[undefined, any] | [DIError]> {
    return this.resolveWithStorage(
      token,
      args,
      contextContainer,
      this.storage,
      undefined,
      requestStorage,
      requestId,
    )
  }
 
  /**
   * Resolves a request-scoped instance for a ScopedContainer.
   * The service will be stored in the ScopedContainer's request storage.
   *
   * @param token The injection token
   * @param args Optional arguments
   * @param scopedContainer The ScopedContainer that owns the request context
   */
  async resolveRequestScopedInstance(
    token: AnyInjectableType,
    args: any,
    scopedContainer: ScopedContainer,
  ): Promise<[undefined, any] | [DIError]> {
    return this.resolveWithStorage(
      token,
      args,
      scopedContainer.getParent(),
      scopedContainer.getParent().getStorage(),
      scopedContainer,
      scopedContainer.getStorage(),
      scopedContainer.getRequestId(),
    )
  }
 
  // ============================================================================
  // UNIFIED RESOLUTION (Storage Strategy Pattern)
  // ============================================================================
 
  /**
   * Unified resolution method that works with any IHolderStorage.
   * This eliminates duplication between singleton and request-scoped resolution.
   *
   * IMPORTANT: The check-and-store logic is carefully designed to avoid race conditions.
   * The storage check and holder creation must happen synchronously (no awaits between).
   *
   * @param token The injection token
   * @param args Optional arguments
   * @param contextContainer The container for context
   * @param storage The storage strategy to use
   * @param scopedContainer Optional scoped container for request-scoped services
   * @param requestStorage Optional request storage (for scope upgrades)
   * @param requestId Optional request ID (for scope upgrades)
   */
  private async resolveWithStorage(
    token: AnyInjectableType,
    args: any,
    contextContainer: IContainer,
    storage: IHolderStorage,
    scopedContainer?: ScopedContainer,
    requestStorage?: IHolderStorage,
    requestId?: string,
  ): Promise<[undefined, any] | [DIError]> {
    // Step 1: Resolve token and prepare instance name
    const [err, data] = await this.resolveTokenAndPrepareInstanceName(
      token,
      args,
      contextContainer,
      requestId,
      scopedContainer,
    )
    if (err) {
      return [err]
    }
 
    const { instanceName, validatedArgs, realToken, scope } = data!
 
    // Step 2: Check for existing holder SYNCHRONOUSLY (no await between check and store)
    // This is critical for preventing race conditions with concurrent resolution
    const getResult =
      storage.get(instanceName) ?? requestStorage?.get(instanceName) ?? null
 
    // Create getHolder function for circular dependency detection
    const getHolder = (name: string): InstanceHolder | undefined => {
      // Check both storages
      const result = storage.get(name)
      Eif (result && result[0] === undefined && result[1]) {
        return result[1]
      }
      if (requestStorage) {
        const reqResult = requestStorage.get(name)
        if (reqResult && reqResult[0] === undefined && reqResult[1]) {
          return reqResult[1]
        }
      }
      return undefined
    }
 
    if (getResult !== null) {
      const [error, holder] = getResult
      if (!error && holder) {
        // Found existing holder - wait for it to be ready
        // Try to get waiterHolder from resolution context if available
        const resolutionCtx = getCurrentResolutionContext()
        const waiterHolder = resolutionCtx?.waiterHolder
        const readyResult = await this.waitForInstanceReady(
          holder,
          waiterHolder,
          getHolder,
        )
        if (readyResult[0]) {
          return [readyResult[0]]
        }
        return [undefined, readyResult[1]!.instance]
      }
      // Handle error states (destroying, etc.)
      Eif (error) {
        const handledResult = await this.handleStorageError(
          instanceName,
          error,
          holder,
          storage,
        )
        Iif (handledResult) {
          return handledResult
        }
      }
    }
 
    // Step 3: Create new instance and store it
    // NOTE: Holder is stored synchronously inside createAndStoreInstance before any await
    const [createError, holder] = await this.createAndStoreInstance(
      instanceName,
      realToken,
      validatedArgs,
      contextContainer,
      storage,
      scopedContainer,
      requestStorage,
      requestId,
      scope,
    )
    Iif (createError) {
      return [createError]
    }
 
    return [undefined, holder!.instance]
  }
 
  /**
   * Internal method to resolve token args and create instance name.
   * Handles factory token resolution and validation.
   */
  private async resolveTokenAndPrepareInstanceName(
    token: AnyInjectableType,
    args: any,
    contextContainer: IContainer,
    requestId?: string,
    scopedContainer?: ScopedContainer,
  ): Promise<
    | [
        undefined,
        {
          instanceName: string
          validatedArgs: any
          actualToken: InjectionTokenType
          realToken: InjectionToken<any, any>
          scope: InjectableScope
        },
      ]
    | [DIError]
  > {
    const [err, { actualToken, validatedArgs }] =
      this.tokenResolver.validateAndResolveTokenArgs(token, args)
    if (
      err instanceof DIError &&
      err.code === DIErrorCode.TokenValidationError
    ) {
      return [err]
    } else if (
      err instanceof DIError &&
      err.code === DIErrorCode.FactoryTokenNotResolved &&
      actualToken instanceof FactoryInjectionToken
    ) {
      this.logger?.log(
        `[InstanceResolver]#resolveTokenAndPrepareInstanceName() Factory token not resolved, resolving it`,
      )
      // Create a simple factory context for resolving the factory token
      const factoryCtx = {
        inject: async (t: any, a?: any) =>
          (scopedContainer ?? contextContainer).get(t, a),
        container: scopedContainer ?? contextContainer,
        addDestroyListener: () => {},
      }
      await actualToken.resolve(factoryCtx as any)
      return this.resolveTokenAndPrepareInstanceName(
        token,
        undefined,
        contextContainer,
        requestId,
        scopedContainer,
      )
    }
 
    // Get the real token for registry lookup
    const realToken = this.tokenResolver.getRealToken(actualToken)
    // Get scope from registry
    const record = this.registry.get(realToken)
    const scope = record.scope
 
    // Generate instance name with requestId if needed
    const instanceName = this.nameResolver.generateInstanceName(
      actualToken,
      validatedArgs,
      requestId,
      scope,
    )
 
    return [
      undefined,
      { instanceName, validatedArgs, actualToken, realToken, scope },
    ]
  }
 
  /**
   * Handles storage error states (destroying, error, etc.).
   * Returns a result if handled, null if should proceed with creation.
   */
  private async handleStorageError(
    instanceName: string,
    error: DIError,
    holder: InstanceHolder | undefined,
    storage: IHolderStorage,
  ): Promise<[undefined, any] | [DIError] | null> {
    switch (error.code) {
      case DIErrorCode.InstanceDestroying:
        // Wait for destruction then retry
        this.logger?.log(
          `[InstanceResolver] Instance ${instanceName} is being destroyed, waiting...`,
        )
        if (holder?.destroyPromise) {
          await holder.destroyPromise
        }
        // Re-check after destruction
        const newResult = storage.get(instanceName)
        if (newResult !== null && !newResult[0]) {
          // Create getHolder for circular dependency detection
          const getHolder = (name: string): InstanceHolder | undefined => {
            const result = storage.get(name)
            return result && result[0] === undefined && result[1]
              ? result[1]
              : undefined
          }
          const readyResult = await this.waitForInstanceReady(
            newResult[1]!,
            undefined,
            getHolder,
          )
          if (readyResult[0]) {
            return [readyResult[0]]
          }
          return [undefined, readyResult[1]!.instance]
        }
        return null // Proceed with creation
 
      default:
        // For error states, remove the failed holder from storage so we can retry
        Eif (holder) {
          this.logger?.log(
            `[InstanceResolver] Removing failed instance ${instanceName} from storage to allow retry`,
          )
          storage.delete(instanceName)
        }
        return null // Proceed with creation
    }
  }
 
  /**
   * Creates a new instance and stores it using the provided storage strategy.
   * This unified method replaces instantiateServiceFromRegistry and createRequestScopedInstance.
   *
   * For transient services, the instance is created but not stored (no caching).
   */
  private async createAndStoreInstance<Instance>(
    instanceName: string,
    realToken: InjectionToken<Instance, any>,
    args: any,
    contextContainer: IContainer,
    storage: IHolderStorage,
    scopedContainer?: ScopedContainer,
    requestStorage?: IHolderStorage,
    requestId?: string,
    scope?: InjectableScope,
  ): Promise<[undefined, InstanceHolder<Instance>] | [DIError]> {
    this.logger?.log(
      `[InstanceResolver]#createAndStoreInstance() Creating instance for ${instanceName}`,
    )
 
    Iif (!this.registry.has(realToken)) {
      return [DIError.factoryNotFound(realToken.name.toString())]
    }
 
    const record = this.registry.get<Instance, any>(realToken)
    const { type, scope: recordScope } = record
    const serviceScope = scope || recordScope
 
    // For transient services, don't use storage locking - create directly
    if (serviceScope === InjectableScope.Transient) {
      return this.createTransientInstance(
        instanceName,
        record,
        args,
        contextContainer,
        scopedContainer,
        requestStorage,
        requestId,
      )
    }
    Iif (serviceScope === InjectableScope.Request && !requestStorage) {
      return [
        DIError.initializationError(
          `Request storage is required for request-scoped services`,
          instanceName,
        ),
      ]
    }
 
    let storageToUse: IHolderStorage
    if (serviceScope === InjectableScope.Request) {
      storageToUse = requestStorage!
    } else {
      storageToUse = storage
    }
 
    // Create holder in "Creating" state
    const [deferred, holder] = storageToUse.createHolder<Instance>(
      instanceName,
      type,
      new Set(),
    )
    // Store holder immediately (for lock mechanism)
    storageToUse.set(instanceName, holder)
 
    // Create context for service initialization
    const ctx = this.createServiceInitializationContext(
      scopedContainer ?? contextContainer,
      instanceName,
      serviceScope,
      holder.deps,
      realToken,
      requestStorage,
      requestId,
    )
 
    holder.destroyListeners = ctx.getDestroyListeners()
 
    // Create getHolder function for resolution context
    const getHolder = (name: string): InstanceHolder | undefined => {
      // Check both storages
      const result = storage.get(name)
      if (result && result[0] === undefined && result[1]) {
        return result[1]
      }
      Eif (requestStorage) {
        const reqResult = requestStorage.get(name)
        Eif (reqResult && reqResult[0] === undefined && reqResult[1]) {
          return reqResult[1]
        }
      }
      return undefined
    }
 
    // Start async instantiation within resolution context for circular dependency detection
    withResolutionContext(holder, getHolder, () => {
      this.serviceInitializer
        .instantiateService(ctx, record, args)
        .then(async (result: [undefined, Instance] | [DIError]) => {
          const [error, instance] =
            result.length === 2 ? result : [result[0], undefined]
          const newScope = record.scope
          const newName = this.nameResolver.generateInstanceName(
            realToken,
            args,
            requestId,
            newScope,
          )
          await this.handleInstantiationResult(
            newName,
            holder,
            ctx,
            deferred,
            newScope,
            error,
            instance,
            scopedContainer,
            requestStorage,
            requestId,
          )
        })
        .catch(async (error: Error) => {
          const newScope = record.scope
          const newName = this.nameResolver.generateInstanceName(
            realToken,
            args,
            requestId,
            newScope,
          )
 
          await this.handleInstantiationError(
            newName,
            holder,
            deferred,
            newScope,
            error,
          )
        })
        .catch(() => {
          // Suppress unhandled rejections from the async chain.
          // Errors are communicated to awaiters via deferred.reject() which
          // rejects holder.creationPromise. This catch is a safety net for
          // any errors that might occur in the error handling itself.
        })
    })
 
    // Wait for instance to be ready
    // Use resolution context to get waiterHolder if available
    const resolutionCtx = getCurrentResolutionContext()
    const waiterHolder = resolutionCtx?.waiterHolder
    return this.waitForInstanceReady(holder, waiterHolder, getHolder)
  }
 
  /**
   * Creates a transient instance without storage or locking.
   * Each call creates a new instance.
   */
  private async createTransientInstance<Instance>(
    instanceName: string,
    record: any,
    args: any,
    contextContainer: IContainer,
    scopedContainer?: ScopedContainer,
    requestStorage?: IHolderStorage,
    requestId?: string,
  ): Promise<[undefined, InstanceHolder<Instance>] | [DIError]> {
    this.logger?.log(
      `[InstanceResolver]#createTransientInstance() Creating transient instance for ${instanceName}`,
    )
 
    // Create a temporary holder for resolution context (transient instances can still have deps)
    const ctx = this.createServiceInitializationContext(
      scopedContainer ?? contextContainer,
      instanceName,
      InjectableScope.Transient,
      new Set(),
      record.originalToken,
      requestStorage,
      requestId,
    )
 
    const [error, instance] = await this.serviceInitializer.instantiateService(
      ctx,
      record,
      args,
    )
 
    Iif (error) {
      return [error]
    }
 
    // Create a temporary holder for the result
    const tempHolder: InstanceHolder<Instance> = {
      status: InstanceStatus.Created,
      name: instanceName,
      instance: instance as Instance,
      creationPromise: null,
      destroyPromise: null,
      type: record.type,
      scope: InjectableScope.Transient,
      deps: ctx.dependencies,
      destroyListeners: ctx.getDestroyListeners(),
      createdAt: Date.now(),
      waitingFor: new Set(),
    }
 
    return [undefined, tempHolder]
  }
 
  /**
   * Handles successful service instantiation.
   */
  private async handleInstantiationSuccess(
    instanceName: string,
    holder: InstanceHolder<any>,
    ctx: ServiceInitializationContext,
    deferred: any,
    instance: any,
    _scopedContainer?: ScopedContainer,
    requestStorage?: IHolderStorage,
    _requestId?: string,
  ): Promise<void> {
    holder.instance = instance
    holder.status = InstanceStatus.Created
 
    // Set up dependency subscriptions for event-based invalidation
    // Determine which storage to use for subscriptions
    const storageForSubscriptions = requestStorage || this.storage
 
    // Set up subscriptions via ServiceInvalidator
    if (ctx.dependencies.size > 0) {
      this.serviceInvalidator.setupDependencySubscriptions(
        instanceName,
        ctx.dependencies,
        storageForSubscriptions,
        holder,
      )
    }
 
    this.logger?.log(
      `[InstanceResolver] Instance ${instanceName} created successfully`,
    )
    deferred.resolve([undefined, instance])
  }
 
  /**
   * Handles service instantiation errors.
   */
  private async handleInstantiationError(
    instanceName: string,
    holder: InstanceHolder<any>,
    deferred: any,
    scope: InjectableScope,
    error: any,
  ): Promise<void> {
    holder.status = InstanceStatus.Error
    holder.instance = error instanceof DIError ? error : DIError.unknown(error)
    this.logger?.error(
      `[InstanceResolver] Instance ${instanceName} creation failed:`,
      error,
    )
    deferred.reject(error instanceof DIError ? error : DIError.unknown(error))
  }
 
  /**
   * Handles instantiation result (success or error).
   */
  private async handleInstantiationResult(
    instanceName: string,
    holder: InstanceHolder<any>,
    ctx: ServiceInitializationContext,
    deferred: any,
    scope: InjectableScope,
    error: any,
    instance: any,
    scopedContainer?: ScopedContainer,
    requestStorage?: IHolderStorage,
    requestId?: string,
  ): Promise<void> {
    if (error) {
      await this.handleInstantiationError(
        instanceName,
        holder,
        deferred,
        scope,
        error,
      )
    } else {
      await this.handleInstantiationSuccess(
        instanceName,
        holder,
        ctx,
        deferred,
        instance,
        scopedContainer,
        requestStorage,
        requestId,
      )
    }
  }
 
  /**
   * Waits for an instance holder to be ready and returns the appropriate result.
   *
   * @param holder The holder to wait for
   * @param waiterHolder Optional holder that is doing the waiting (for circular dependency detection)
   * @param getHolder Optional function to retrieve holders by name (required if waiterHolder is provided)
   */
  private async waitForInstanceReady<T>(
    holder: InstanceHolder<T>,
    waiterHolder?: InstanceHolder,
    getHolder?: (name: string) => InstanceHolder | undefined,
  ): Promise<[undefined, InstanceHolder<T>] | [DIError]> {
    switch (holder.status) {
      case InstanceStatus.Creating: {
        // Check for circular dependency before waiting
        if (waiterHolder && getHolder) {
          const cycle = CircularDetector.detectCycle(
            waiterHolder.name,
            holder.name,
            getHolder,
          )
          if (cycle) {
            return [DIError.circularDependency(cycle)]
          }
 
          Eif (process.env.NODE_ENV !== 'production') {
            // Track the waiting relationship
            waiterHolder.waitingFor.add(holder.name)
          }
        }
 
        try {
          await holder.creationPromise
        } finally {
          Eif (process.env.NODE_ENV !== 'production') {
            // Clean up the waiting relationship
            if (waiterHolder) {
              waiterHolder.waitingFor.delete(holder.name)
            }
          }
        }
 
        // Recursively check after creation completes
        return this.waitForInstanceReady(holder, waiterHolder, getHolder)
      }
 
      case InstanceStatus.Destroying:
        return [DIError.instanceDestroying(holder.name)]
 
      case InstanceStatus.Error:
        return [holder.instance as unknown as DIError]
 
      case InstanceStatus.Created:
        return [undefined, holder]
 
      default:
        // @ts-expect-error Maybe we will use this in the future
        return [DIError.instanceNotFound(holder?.name ?? 'unknown')]
    }
  }
 
  /**
   * Creates a ServiceInitializationContext for service instantiation.
   */
  private createServiceInitializationContext(
    container: IContainer,
    serviceName: string,
    scope: InjectableScope,
    deps: Set<string>,
    serviceToken: InjectionToken<any, any>,
    requestStorage?: IHolderStorage,
    requestId?: string,
  ): ServiceInitializationContext {
    const destroyListeners: Array<() => void> = []
 
    return {
      inject: async (token: any, args?: any) => {
        // Track dependency and check for scope upgrade
        const actualToken =
          typeof token === 'function'
            ? this.tokenResolver.normalizeToken(token)
            : token
        const realToken = this.tokenResolver.getRealToken(actualToken)
        const depRecord = this.registry.get(realToken)
        const depScope = depRecord.scope
 
        // Generate dependency name - if dependency is Request-scoped and we have requestId, use it
        const dependencyRequestId =
          depScope === InjectableScope.Request ? requestId : undefined
        const finalDepName = this.nameResolver.generateInstanceName(
          actualToken,
          args,
          dependencyRequestId,
          depScope,
        )
 
        // Check if current service needs scope upgrade
        // If current service is Singleton and dependency is Request, upgrade current service
        if (
          scope === InjectableScope.Singleton &&
          depScope === InjectableScope.Request &&
          requestStorage &&
          requestId
        ) {
          // Check and perform scope upgrade for current service
          // Use the dependency name with requestId for the check
          const [needsUpgrade, newServiceName] =
            this.scopeTracker.checkAndUpgradeScope(
              serviceName,
              scope,
              finalDepName,
              depScope,
              serviceToken,
              this.storage,
              requestStorage,
              requestId,
            )
 
          Eif (needsUpgrade && newServiceName) {
            // Service was upgraded - update the service name in context
            // The holder will be moved to request storage by ScopeTracker
            // For now, we continue with the current resolution
            // Future resolutions will use the new name
          }
        }
 
        // Track dependency
        deps.add(finalDepName)
 
        // Resolve dependency
        // Resolution context is automatically used by the injectors system for circular dependency detection
        return container.get(token, args)
      },
      container,
      addDestroyListener: (listener: () => void) => {
        destroyListeners.push(listener)
      },
      getDestroyListeners: () => destroyListeners,
      serviceName,
      dependencies: deps,
      scope,
      trackDependency: (name: string, depScope: InjectableScope) => {
        deps.add(name)
        // Check for scope upgrade
        if (
          scope === InjectableScope.Singleton &&
          depScope === InjectableScope.Request &&
          requestStorage &&
          requestId
        ) {
          this.scopeTracker.checkAndUpgradeScope(
            serviceName,
            scope,
            name,
            depScope,
            serviceToken,
            this.storage,
            requestStorage,
            requestId,
          )
        }
      },
    }
  }
}