/* searchDependencies
gather info on dependencies and nested dependencies, search for
package.vigour.plugin info
484255
function searchDependencies (dependencies, root) {
  if (!dependencies) {
    return Promise.resolve([])
  } else {
    var pluginPkgPath
    var pluginPkgPaths = []
    for (var key in dependencies) {
      pluginPkgPath = path.join(root, 'node_modules', key)
      pluginPkgPaths.push(pluginPkgPath)
    }
    return Promise.all(pluginPkgPaths.map(function (pkgRoot) {
      var pkgPath = path.join(pkgRoot, 'package.json')
      return readJSON(pkgPath)
        .then(function (pkg) {
          if (pkg.vigour && pkg.vigour.plugin) {
            return searchDependencies(pkg.dependencies, pkgRoot)
              .then(function (deps) {
                return searchDependencies(pkg.dependencies, root)
                  .then(function (otherDeps) {
                    return deps.concat(otherDeps)
                  })
              })
          } else {
            return false
          }
        })
        .catch(function (reason) {
          return false
        })
    }))
    .then(function (arr) {
      arr = _flatten(arr)
      return pluginPkgPaths.concat(arr.reduce(function (prev, curr) {
        if (curr) {
          prev.push(curr)
        }
        return prev
      }, []))
    })
  }
}
889447
function getProdModules(externalModules, packagePath, dependencyGraph, forceExcludes) {
  const packageJsonPath = path.join(process.cwd(), packagePath);
  const packageJson = require(packageJsonPath);
  const prodModules = [];

  // only process the module stated in dependencies section
  if (!packageJson.dependencies) {
    return [];
  }

  // Get versions of all transient modules
  _.forEach(externalModules, module => {
    let moduleVersion = packageJson.dependencies[module.external];

    if (moduleVersion) {
      prodModules.push(`${module.external}@${moduleVersion}`);

      // Check if the module has any peer dependencies and include them too
      try {
        const modulePackagePath = path.join(
          path.dirname(path.join(process.cwd(), packagePath)),
          'node_modules',
          module.external,
          'package.json'
        );
        const peerDependencies = require(modulePackagePath).peerDependencies;
        if (!_.isEmpty(peerDependencies)) {
          this.options.verbose && this.serverless.cli.log(`Adding explicit peers for dependency ${module.external}`);
          const peerModules = getProdModules.call(this, _.map(peerDependencies, (value, key) => ({ external: key })), packagePath, dependencyGraph, forceExcludes);
          Array.prototype.push.apply(prodModules, peerModules);
        }
      } catch (e) {
        this.serverless.cli.log(`WARNING: Could not check for peer dependencies of ${module.external}`);
      }
    } else {
      if (!packageJson.devDependencies || !packageJson.devDependencies[module.external]) {
        // Add transient dependencies if they appear not in the service's dev dependencies
        const originInfo = _.get(dependencyGraph, 'dependencies', {})[module.origin] || {};
        moduleVersion = _.get(_.get(originInfo, 'dependencies', {})[module.external], 'version');
        if (!moduleVersion) {
          this.serverless.cli.log(`WARNING: Could not determine version of module ${module.external}`);
        }
        prodModules.push(moduleVersion ? `${module.external}@${moduleVersion}` : module.external);
      } else if (packageJson.devDependencies && packageJson.devDependencies[module.external] && !_.includes(forceExcludes, module.external)) {
        // To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check
        // most likely set in devDependencies and should not lead to an error now.
        const ignoredDevDependencies = ['aws-sdk'];

        if (!_.includes(ignoredDevDependencies, module.external)) {
          // Runtime dependency found in devDependencies but not forcefully excluded
          this.serverless.cli.log(`ERROR: Runtime dependency '${module.external}' found in devDependencies. Move it to dependencies or use forceExclude to explicitly exclude it.`);
          throw new this.serverless.classes.Error(`Serverless-webpack dependency error: ${module.external}.`);
        }

        this.options.verbose && this.serverless.cli.log(`INFO: Runtime dependency '${module.external}' found in devDependencies. It has been excluded automatically.`);
      }
    }
  });

  return prodModules;
}
1175296
function getDepends(file, config) {
    var code = fs.readFileSync(file, 'utf8'),
        // only process the first module in file
        meta = ast.parse(code)[0],
        deps = ((meta || {}).dependencies || []).map(function (dep) {
            return idToPath(dep, config);
        });
    return deps;
}
455434
def search_dependencies(self):
        
        result = [self.module.name]
        #First we look at the explicit use references from this module and all
        #its dependencies until the chain terminates.
        stack = self.needs
        while len(stack) > 0:
            module = stack.pop()
            if module in result:
                continue
            
            self.parent.load_dependency(module, True, True, False)
            if module in self.parent.modules:
                for dep in self.parent.modules[module].needs:
                    modname = dep.split(".")[0]
                    if modname not in result:
                        result.append(modname)
                    if modname not in stack:
                        stack.append(modname)

        #Add any incidentals from the automatic construction of code. These can be from
        #executables that use special precision types without importing them or from
        #derived types. Same applies to the local members of this module.
        for ekey, anexec in list(self.executables.items()):
            for dep in anexec.search_dependencies():
                if dep is not None and dep not in result:
                    result.append(dep)

        for member in list(self.members.values()):
            dep = member.dependency()
            if dep is not None and dep not in result:
                result.append(dep)
                        
        return result
512373
function dependentLink (pkg, cb) {
  asyncMap(pkg._resolvedDeps, function (dep, cb) {
    var dependents = path.join(npm.dir, dep.name, dep.version, "dependents")
      , to = path.join(dependents, pkg.name + "@" + pkg.version)
      , from = path.join(npm.dir, pkg.name, pkg.version)
    link(from, to, cb)
  }, cb)
}
707850
function showLinkedDeps() {
  const linkedDeps = getLinkedDeps(packageKeys, packageHash);
  if (linkedDeps.length) {
    logPkgsMsg('Linked', linkedDeps);
  } else {
    log('No linked dependencies found');
  }
}
779118
function mapDependencies(dependencies) {
  var deps;

  deps = (dependencies) ? Object.keys(dependencies) : [];

  return deps.map(function(name) {
    return {
      name: name,
      version: dependencies[name]
    };
  });
}
827439
function listDepsForBook(book) {
    var config = book.getConfig();
    var plugins = config.getPluginDependencies();

    return listDependencies(plugins);
}
134090
function buildDependencyObjectLookup(data, lookup, parentPath) {
  if (lookup == undefined) {
    lookup = {};
  }

  parentPath = parentPath || '';

  for(var k in data.dependencies) {
    var dep = data.dependencies[k];
    depPath = parentPath + '/' + dep.name;

    var lookupKey = 'UNKNOWN'; //If we can't find a key below, something's wrong.
    var depToStore = dep;
    if (dep.name) {
      lookupKey = dep.name + '@' + dep.version
    } else if (dep._from) {
      lookupKey = dep._from;
    } else if (dep.requiredBy) {
      // If we can't find the node_modules folder, we'll get 'requiredBy' instead.
      lookupKey = k + "@" + dep.requiredBy;
      depToStore = extractDep(data.dependencies[k]);
    }

    var existing = lookup[lookupKey];
    if (existing) {
      existing.depPaths.push(depPath);
    } else {
      lookup[lookupKey] = depToStore;
      lookup[lookupKey].depPaths = [depPath];
    }

    buildDependencyObjectLookup(dep, lookup, depPath);
  }
  return lookup;
}
1206512
function forcedByDependencies(filename) {
	if (!/\.ts$/.test(filename)) return null;
	var fs = require('fs');
	var fsp = require('path');
	function loadPackage(dir) {
		var path = fsp.join(dir, 'package.json');
		if (fs.existsSync(path)) return require(path);
		var ndir = fsp.join(dir, '..');
		if (ndir.length < dir.length && !/[\\\/]node_modules$/.test(ndir)) return loadPackage(ndir);
		else return null;
	}
	var pkg = loadPackage(fsp.resolve(fsp.dirname(filename)));
	if (!pkg) return false;
	return Object.keys(pkg.dependencies || {}).indexOf('streamline-runtime') >= 0 ||
		Object.keys(pkg.devDependencies || {}).indexOf('streamline-runtime') >= 0;
}
87372
function fetchPeerDependencies(packageName) {
    const npmProcess = spawn.sync(
        "npm",
        ["show", "--json", packageName, "peerDependencies"],
        { encoding: "utf8" }
    );

    const error = npmProcess.error;

    if (error && error.code === "ENOENT") {
        return null;
    }
    const fetchedText = npmProcess.stdout.trim();

    return JSON.parse(fetchedText || "{}");


}
1129727
function(loader, packageJSON, isRoot){
		var deps = crawl.getDependencyMap(loader, packageJSON, isRoot);

		var dependencies = [];
		for(var name in deps) {
			dependencies.push(deps[name]);
		}

		return dependencies;
	}
791620
function getDepsFromDataObject(data, lookup) {
  var results = {};
  if (categories.length == 0) {
    for(var k in data.dependencies) {
      var dep = extractDep(data.dependencies[k]);
      results[k]=dep;
    }
  }

  if (lookup) {
    for (var i = 0; i < categories.length; i++) {
      var category = categories[i];
      for(var k in data[category]) {
        var spec = k + "@" + data[category][k];

        var specMatch = lookupSpecMatch(lookup, spec);

        // If there is no match in the lookup then this dependency was "deduped"
        if (specMatch) {
          results[k]=specMatch;
        }
      }
    }
  }
  return results;
}
465301
def search_for_vcs(self, dependency):  # type: (VCSDependency) -> List[Package]
        
        if dependency.vcs != "git":
            raise ValueError("Unsupported VCS dependency {}".format(dependency.vcs))

        tmp_dir = Path(mkdtemp(prefix="pypoetry-git-{}".format(dependency.name)))

        try:
            git = Git()
            git.clone(dependency.source, tmp_dir)
            git.checkout(dependency.reference, tmp_dir)
            revision = git.rev_parse(dependency.reference, tmp_dir).strip()

            if dependency.tag or dependency.rev:
                revision = dependency.reference

            directory_dependency = DirectoryDependency(
                dependency.name,
                tmp_dir,
                category=dependency.category,
                optional=dependency.is_optional(),
            )
            for extra in dependency.extras:
                directory_dependency.extras.append(extra)

            package = self.search_for_directory(directory_dependency)[0]

            package.source_type = "git"
            package.source_url = dependency.source
            package.source_reference = revision
        except Exception:
            raise
        finally:
            safe_rmtree(str(tmp_dir))

        return [package]
650548
function dependencies(dependencyObject) {
    'use strict';

    function extractSpecificPath(depPath, loadType) {
        if (typeof depPath === 'object') {
            return depPath[loadType];
        }

        return depPath;
    }

    var depNames, depPaths;

    depNames = Object.keys(dependencyObject);
    depPaths = depNames.map(function (depName) {return dependencyObject[depName]; });

    function init(root, factory) {

        if (typeof module === 'object' && module.exports) {
            // Node/CommonJS
            console.log("NODE MODE");
            factory.apply(root, depPaths.map(function (depPath) {return require(extractSpecificPath(depPath, 'node')); }));
        } else if (typeof define === 'function' && define.amd) {
            // AMD
            console.log("AMD MODE");
            define(depPaths.map(function (depPath) { return extractSpecificPath(depPath, 'browser'); }), factory);
        } else {
            // Browser globals
            console.log("GLOBALS MODE");
            factory.apply(root, depNames.map(function (depName) {return root[depName]; }));
        }
    }

    return { init: init };
}
627551
private static MavenCoordinates findCompileDependency(String zipEntryPath, String groupId) {
		int apiNameIndex = zipEntryPath.indexOf(groupId);
		int extensionIndex = zipEntryPath.lastIndexOf(".jar");
		if (apiNameIndex >= 0 && extensionIndex >= 0) {
			String fileNameWithoutExtension = zipEntryPath.substring(apiNameIndex, extensionIndex);

			String artifactId = fileNameWithoutExtension.substring(0, fileNameWithoutExtension.lastIndexOf("_"));
			String versionId = fileNameWithoutExtension.substring(fileNameWithoutExtension.lastIndexOf("_")+1, fileNameWithoutExtension.length());
			MavenCoordinates coordinates = new MavenCoordinates(groupId, artifactId, versionId);
			System.out.println("Found compile dependency: " + coordinates);
			return coordinates;
		}
		return null;
	}
140031
function getValidVulnerabilities(productRange, details, pkg, depPaths) {
        var results = [];
        if(details != undefined) {
                for(var i = 0; i < details.length; i++) {
                        var detail = details[i];
                        detail.depPaths = depPaths;

                  		// Do we white-list this match?
                        var id = detail.id;
                        if (whitelist && whitelist[id]) {
                            var whitelistEntry = whitelist[id];
                            if (whitelistEntry.dependencyPaths) {
                              for (var whitelistIdx = 0; whitelistIdx < whitelistEntry.dependencyPaths.length; whitelistIdx++) {
                                var wDep = whitelistEntry.dependencyPaths[whitelistIdx];
                                var regex = new RegExp(wDep);
                                detail.depPaths = detail.depPaths.filter(function(dDep) {
                                  if (regex.test(dDep)){
                                    detail.whitelistedPaths = detail.whitelistedPaths || [];
                                    detail.whitelistedPaths.push(dDep);
                                    return false;
                                  }

                                  return true;
                                });
                              }

                              detail["package"] = pkg;
                              whitelistedVulnerabilities.push(detail);
                              if (detail.depPaths.length == 0) {
                                console.log('SKIPPING BECAUSE ALL PATHS MATCHED')
                              }
                            } else {
                              detail["package"] = pkg;
                              whitelistedVulnerabilities.push(detail);
                            }
                        }
                        else {
                          results.push(detail);
                        }
                }
        }
        return results;
}