/*
attempt to resolve a dependency by name (supports parental hierarchy)
@param moduleName (string): the qualified name that the module can be located by in the container
@returns the module that is being resolved
435469
function resolve (moduleName, callback) {
                logger.trace('resolving: ' + moduleName);

                if (is.regexp(moduleName)) {
                    var modules = resolveTasks.filterMatchingRegistrations(moduleName, context)
                        .map(function (moduleNameText) {
                            return resolveOne(moduleNameText, moduleNameText);
                        })

                    if (is.function(callback)) {
                        callback(null, modules);
                    } else {
                        return modules;
                    }
                }

                return resolveOne(moduleName, moduleName, callback);
            }
171602
function(moduleName, deps, callback) {
  //if (moduleName === "jquery/selector") { debugger; }
  if (!deps && !callback) {
    return;
  }

  // Allow deps to be optional.
  if (!callback && typeof deps === "function") {
    callback = deps;
    deps = undefined;
  }

  // Ensure dependencies is never falsey.
  deps = deps || [];

  // Normalize the dependencies.
  deps = deps.map(function(dep) {
    if (dep.indexOf("./") === -1) {
      return dep;
    }

    // Take off the last path.
    var normalize = moduleName.split("/").slice(0, -1).join("/");

    //console.log(normalize, dep, define.join(normalize, dep));
    return define.join(normalize, dep);
  });

  // Attach to the module map.
  define.map[moduleName] = {
    moduleName: moduleName,
    deps: deps,
    callback: callback
  };
}
816374
public List<Dependency> getModuleAncestors(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {
        final Client client = getClient();
        final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactAncestors(moduleName, moduleVersion));
        final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_TEST_PARAM, "true")
                .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

        client.destroy();
        if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
            final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors", moduleName, moduleVersion);
            if(LOG.isErrorEnabled()) {
                LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
            }
            throw new GrapesCommunicationException(message, response.getStatus());
        }

        return response.getEntity(new GenericType<List<Dependency>>(){});
    }
903903
public function getModule($moduleName) {
        $moduleName = strtolower($moduleName);
        if (isset(self::$_modules[$moduleName])) {
            return self::$_modules[$moduleName];
        } else {
            try {
                return $this->loadModule($moduleName);
            }
            catch (\Exception $e) {
                throw new ModuleException("Cannot find requested module: $moduleName");
            }
        }
    }
1009798
public function isOperational($moduleName) {
    	if(!array_key_exists($moduleName, $this->modules_list)) {
    		if($module = fw\Module::getModuleByName($moduleName)) {
    			if($module instanceof DependentInterface) {
    				if($module->validatePrerequisites()) {
    					$this->modules_list[$moduleName] = TRUE;
    					return true;
    				} else {
    					// Do not cache the result,
    					// as they could change by the next call to the method
    					return false;
    				}
    			}
    			else {
    				$this->modules_list[$moduleName] = TRUE;
    				return true;
    			}
    		}
    		else {
    			$this->modules_list[$moduleName] = FALSE;
    		}
    	}
    	return $this->modules_list[$moduleName];
    	
    }
1074303
protected function resolveDepsRecursive($module, $version, \ArrayObject $resolved){
    
        $module = strtolower($module);
        
        // replace if exists with lower version number
        if($resolved->offsetExists($module)){
            $new = new SoftwareVersion($version);
        
            // remember the greatest versions
            if($new->isGt($resolved[$module])){
                unset($resolved[$module]);
                $resolved[$module] = $version;
            }
        } else{
            $resolved[$module] = $version;
        }
        
        // ask for deps
        $deps = $this->getModuleDeps($module);
        
        if (array_key_exists($module, $deps)) {
            throw new \Exception(
                sprintf('Invalid dependency for module %s: dependency cannot point to self', $module));
        }
    
        foreach ($deps as $name => $depVersion){
    
            // make sure the same module doesn't get resolved again
            if(!$resolved->offsetExists($name)){
                $this->resolveDepsRecursive($name, $depVersion, $resolved);
            }
        }
        
        if ($resolved[$module] == $version) {
            unset($resolved[$module]);
            $resolved[$module] = $version;
        }
    }
405897
function resolveModuleName(base, name) {
	var stack = base.split('/');
	stack.pop();
	name.split('/').forEach(function(segment, i) {
		if ( segment == '..' ) {
			stack.pop();
		} else if ( segment === '.' ) {
			// ignore
		} else {
			if ( i === 0 ) {
				stack = [];
			}
			stack.push(segment);
		}
	});
	return stack.join('/');
}
349456
public DependencyResult resolveDependencies(GAV a, String scope) throws DependencyResolutionException {
        DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(scope);

        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(new Dependency(new DefaultArtifact(a.toString()), JavaScopes.COMPILE));
        collectRequest.setRepositories(remoteRepositories);

        DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);

        return resolveDependencies(dependencyRequest);
    }
735374
function resolve() {
	var parts,
		flg,
		len,
		str,
		i;

	// CASE 1: this module is loaded from a global path...
	len = gpaths.length;
	for ( i = 0; i < len; i++ ) {
		str = dir.substring( 0, gpaths[ i ].length );
		if ( str === gpaths[ i ] ) {
			// We are loaded from a global path. Resort to finding the nearest `package.json` walking up from the current working directory...
			str = pkgdir();
			if ( str ) {
				return str;
			}
			flg = true;
		}
	}
	// CASE 2: this module is a local module dependency; in which case, split on `node_modules`...
	parts = dir.split( path.sep+'node_modules' );
	if ( parts.length > 1 ) {
		// We are a nested module. Assume that the top-level node module directory is the application root...
		return parts[ 0 ];
	}
	// CASE 3: possibly a git submodule, copy and paste, or some other dependency pattern; in which case, find the nearest `package.json` walking up from the current working directory...
	if ( !flg ) {
		str = pkgdir();
		if ( str ) {
			return str;
		}
	}
	// CASE 4: nothing worked. Just use the main module...
	return path.dirname( require.main.filename );
}
1248875
function resolveInitializer(moduleName) {
  var module = require(moduleName, null, null, true);
  if (!module) {
    throw new Error(moduleName + ' must export an initializer.');
  }
  var initializer = module['default'];
  if (!initializer.name) {
    initializer.name = moduleName.slice(moduleName.lastIndexOf('/') + 1);
  }
  return initializer;
}
1336997
public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) {
        final DbModule module = moduleHandler.getModule(moduleId);
        final DbOrganization organization = moduleHandler.getOrganization(module);
        filters.setCorporateFilter(new CorporateFilter(organization));

        final DependencyReport report = new DependencyReport(moduleId);
        final List<String> done = new ArrayList<String>();
        for(final DbModule submodule: DataUtils.getAllSubmodules(module)){
            done.add(submodule.getId());
        }

        addModuleToReport(report, module, filters, done, 1);

        return report;
    }
1218104
function _requireModule(rootPath, name) {
  let modulePath = _normalizeRequire(rootPath, name),
    moduleRes;
  try {
    moduleRes = require(modulePath);
  } catch (e) {
    if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(name) !== -1) {
      try {
        moduleRes = require(name);
      } catch (e) {
        if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf(name) !== -1) {
          throw "NOT_FOUND";
        }
        throw e;
      }
    } else {
      throw e;
    }
  }
  return moduleRes;
}
178097
public function addDependency($moduleName, $dependency)
    {
        if (!isset($this->moduleNames[$dependency])) {
            throw new RuntimeException(sprintf(
                'The module "%s" does not exist in the graph.',
                $dependency
            ));
        }

        if (!isset($this->moduleNames[$moduleName])) {
            throw new RuntimeException(sprintf(
                'The module "%s" does not exist in the graph.',
                $moduleName
            ));
        }

        if (null !== ($path = $this->getPath($dependency, $moduleName))) {
            $last = array_pop($path);

            throw new CyclicDependencyException(sprintf(
                'A cyclic dependency was discovered between the modules "%s" '.
                'and "%s". Please check the "override" keys defined in these '.
                'modules.',
                implode('", "', $path),
                $last
            ));
        }

        $this->dependencies[$moduleName][$dependency] = true;
    }
532892
@Override
    protected ResolutionResult resolveDependencies(String projectFolder, String topLevelFolder, Set<String> paketDependenciesFiles) {
        boolean installSuccess = true;
        Collection<DependencyInfo> dependencies = new ArrayList<>();
        List<String> excludes = new LinkedList<>();
        if (paketRunPreStep) {
            File paket = new File(topLevelFolder + Constants.FORWARD_SLASH + PAKET_EXE);
            if (StringUtils.isNotEmpty(this.paketPath)) {
                paket = new File(this.paketPath);
            } else if (!paket.exists()) {
                paket = null;
            }
            installSuccess = !executePreparationStep(topLevelFolder, paket);
        }
        if (installSuccess) {
            String paketLockPath = topLevelFolder + Constants.FORWARD_SLASH + PAKET_LOCK;
            File paketLockFile = new File(paketLockPath);
            if (paketLockFile.exists()) {
                logger.debug("Found paket.lock file: {}", paketLockPath);
                Map<String, List<String>> groupToDirectDependenciesMap = getGroupToDirectDependencies(paketDependenciesFiles.iterator().next());
                if (groupToDirectDependenciesMap != null && !groupToDirectDependenciesMap.keySet().isEmpty()) {
                    Collection<AbstractPaketDependencyCollector> paketDependencyCollectors = new LinkedList<>();
                    for(String groupName : groupToDirectDependenciesMap.keySet()) {
                        if (groupName.equals(MAIN)) {
                            paketDependencyCollectors.add(new MainGroupPaketDependencyCollector(groupToDirectDependenciesMap.get(MAIN), this.paketIgnoredGroups));
                        } else {
                            paketDependencyCollectors.add(new GroupPaketDependencyCollector(groupToDirectDependenciesMap.get(groupName), this.paketIgnoredGroups, groupName));
                        }
                    }
                    logger.info("Start collecting paket dependencies");
                    paketDependencyCollectors.forEach(paketDependencyCollector -> {
                        Collection<AgentProjectInfo> prjectInfo = paketDependencyCollector.collectDependencies(topLevelFolder);
                        dependencies.addAll(prjectInfo.iterator().next().getDependencies());
                    });
                }

                // ignore all the nupkg files in order to not scan them again
                if (!dependencies.isEmpty()) {
                    if (this.ignoreSourceFiles) {
                        excludes.addAll(normalizeLocalPath(projectFolder, topLevelFolder,extensionPattern(PAKET_EXTENSIONS) , null));
                    } else {
                        excludes.addAll(normalizeLocalPath(projectFolder, topLevelFolder, extensionPattern(PAKET_EXTENSIONS), Constants.PACKAGES));
                    }
                }
            } else {
                logger.warn("Could not find paket.lock file in {}. Please execute 'paket install' first.", topLevelFolder);
            }
        } else {
            logger.warn("'paket install' command failed");
        }
        return new ResolutionResult(dependencies, excludes, getDependencyType(), topLevelFolder);
    }
624940
function (moduleName) {
            var requiresModule = createModule(moduleName);
            var mods = requiresModule.getNormalizedModules();
            Utils.each(mods, function (m) {
                m.undef();
            });
        }
407535
public void addModuleToExport(final String moduleName) {

        if (m_modulesToExport == null) {
            m_modulesToExport = new HashSet<String>();
        }
        m_modulesToExport.add(moduleName);
    }
168659
public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {
        final Client client = getClient();
        final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));
        final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true")
                .queryParam(ServerAPI.SCOPE_TEST_PARAM, "true")
                .queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())
                .queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())
                .queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())
                .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

        client.destroy();
        if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
            final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors ", moduleName, moduleVersion);
            if(LOG.isErrorEnabled()) {
                LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
            }
            throw new GrapesCommunicationException(message, response.getStatus());
        }

        return response.getEntity(new GenericType<List<Dependency>>(){});
    }