function getAllReferencedModules(compilation, module, type, includeInitial) {
	const collectedModules = new Set(includeInitial ? [module] : []);
	const visitedModules = new WeakSet([module]);
	const stack = [module];

	while (stack.length > 0) {
		const currentModule = stack.pop();
		if (!currentModule) continue;

		const outgoingConnections =
			compilation.moduleGraph.getOutgoingConnections(currentModule);
		if (outgoingConnections) {
			for (const connection of outgoingConnections) {
				const connectedModule = connection.module;

				// Skip if module has already been visited
				if (!connectedModule || visitedModules.has(connectedModule)) {
					continue;
				}

				// Handle 'initial' type (skipping async blocks)
				if (type === "initial") {
					const parentBlock = compilation.moduleGraph.getParentBlock(
						/** @type {Dependency} */
						(connection.dependency)
					);
					if (parentBlock instanceof AsyncDependenciesBlock) {
						continue;
					}
				}

				// Handle 'external' type (collecting only external modules)
				if (type === "external") {
					if (connection.module instanceof ExternalModule) {
						collectedModules.add(connectedModule);
					}
				} else {
					// Handle 'all' or unspecified types
					collectedModules.add(connectedModule);
				}

				// Add connected module to the stack and mark it as visited
				visitedModules.add(connectedModule);
				stack.push(connectedModule);
			}
		}
	}

	return collectedModules;
}
Helper method to collect all referenced modules recursively.
@param {Compilation} compilation The webpack compilation instance.
@param {Module} module The module to start collecting from.
@param {string} type The type of modules to collect ("initial", "external", or "all").
@param {boolean} includeInitial Should include the referenced module passed
@returns {Set<Module>} Set of collected modules.