capture static method

ContainerSnapshot capture(
  1. DependencyBox box, {
  2. bool fromRoot = true,
})

Captures a complete point-in-time ContainerSnapshot of the container hierarchy starting from the root of box.

Set fromRoot to false to capture only the subtree starting from box.

Implementation

static ContainerSnapshot capture(DependencyBox box, {bool fromRoot = true}) {
  final startBox = fromRoot
      ? (box.root as DependencyBoxImpl)
      : (box as DependencyBoxImpl);

  final scopes = <ScopeSnapshot>[];
  final registrations = <RegistrationSnapshot>[];
  final diagnostics = <DiagnosticNotice>[];

  final visitedBoxes = <DependencyBoxImpl>{};
  final queue = <DependencyBoxImpl>[startBox];

  while (queue.isNotEmpty) {
    final current = queue.removeAt(0);
    if (!visitedBoxes.add(current)) continue;

    final scopeId = _scopeId(current);
    final parentId = current.parent != null
        ? _scopeId(current.parent! as DependencyBoxImpl)
        : null;

    final childrenList = current.children.cast<DependencyBoxImpl>().toList();
    final childIds = childrenList.map(_scopeId).toList();
    queue.addAll(childrenList);

    final scopeSnapshot = ScopeSnapshot(
      id: scopeId,
      name: current.name ?? (current.parent == null ? 'root' : '<unnamed>'),
      depth: current.depth,
      isRoot: current.parent == null,
      isDisposed: current.isDisposed,
      parentId: parentId,
      childIds: childIds,
      directRegistrationCount: current.length,
    );
    scopes.add(scopeSnapshot);

    if (current.isDisposed) {
      diagnostics.add(
        DiagnosticNotice(
          severity: 'warning',
          title: 'Disposed Scope',
          message:
              'Scope "$scopeId" (${scopeSnapshot.name}) is disposed and cannot resolve dependencies.',
          relatedScope: scopeId,
        ),
      );
      continue;
    }

    // Inspect registrations inside this scope
    _inspectScopeRegistrations(
      current,
      scopeId,
      scopeSnapshot.name,
      current.depth,
      registrations,
      diagnostics,
    );
  }

  final rootScopeSnapshot = scopes.firstWhere(
    (s) => s.isRoot,
    orElse: () => scopes.isNotEmpty ? scopes.first : ScopeSnapshot.empty,
  );

  return ContainerSnapshot(
    timestamp: DateTime.now(),
    rootScope: rootScopeSnapshot,
    scopes: scopes,
    registrations: registrations,
    diagnostics: diagnostics,
  );
}