for each dependency, link this pkg into the proper "dependent" folder
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)
}
176724
function depends (targets) {
    debug('Depends: start parse dependencies');
    targets = prepare.targets(targets).filter(directories);
    debug('Depends: target : ' + targets);
    targets.forEach(parse_node_module);
}
140622
def set_dependencies(analysis, dependencies, path):
    

    for toc in (analysis.binaries, analysis.datas):
        for i, tpl in enumerate(toc):
            if not tpl[1] in dependencies.keys():
                logger.info("Adding dependency %s located in %s" % (tpl[1], path))
                dependencies[tpl[1]] = path
            else:
                dep_path = get_relative_path(path, dependencies[tpl[1]])
                logger.info("Referencing %s to be a dependecy for %s, located in %s" % (tpl[1], path, dep_path))
                analysis.dependencies.append((":".join((dep_path, tpl[0])), tpl[1], "DEPENDENCY"))
                toc[i] = (None, None, None)
        # Clean the list
        toc[:] = [tpl for tpl in toc if tpl != (None, None, None)]
806011
function attachHMRServer({httpServer, path, packagerServer}) {
  let client = null;

  function disconnect() {
    client = null;
    packagerServer.setHMRFileChangeListener(null);
  }

  // For the give platform and entry file, returns a promise with:
  //   - The full list of dependencies.
  //   - The shallow dependencies each file on the dependency list has
  //   - Inverse shallow dependencies map
  function getDependencies(platform, bundleEntry) {
    return packagerServer.getDependencies({
      platform: platform,
      dev: true,
      hot: true,
      entryFile: bundleEntry,
    }).then(response => {
      const {getModuleId} = response;

      // for each dependency builds the object:
      // `{path: '/a/b/c.js', deps: ['modA', 'modB', ...]}`
      return Promise.all(Object.values(response.dependencies).map(dep => {
        return dep.getName().then(depName => {
          if (dep.isAsset() || dep.isJSON()) {
            return Promise.resolve({path: dep.path, deps: []});
          }
          return packagerServer.getShallowDependencies({
            platform: platform,
            dev: true,
            hot: true,
            entryFile: dep.path
          })
            .then(deps => {
              return {
                path: dep.path,
                name: depName,
                deps,
              };
            });
        });
      }))
      .then(deps => {
        // list with all the dependencies' filenames the bundle entry has
        const dependenciesCache = response.dependencies.map(dep => dep.path);

        // map from module name to path
        const moduleToFilenameCache = Object.create(null);
        deps.forEach(dep => {
          moduleToFilenameCache[dep.name] = dep.path;
        });

        // map that indicates the shallow dependency each file included on the
        // bundle has
        const shallowDependencies = Object.create(null);
        deps.forEach(dep => {
          shallowDependencies[dep.path] = dep.deps;
        });

        // map from module name to the modules' dependencies the bundle entry
        // has
        const dependenciesModulesCache = Object.create(null);
        response.dependencies.forEach(dep => {
          dependenciesModulesCache[getModuleId(dep)] = dep;
        });


        const inverseDependenciesCache = Object.create(null);
        const inverseDependencies = getInverseDependencies(response);
        for (const [module, dependents] of inverseDependencies) {
          inverseDependenciesCache[getModuleId(module)] =
            Array.from(dependents).map(getModuleId);
        }

        return {
          dependenciesCache,
          dependenciesModulesCache,
          shallowDependencies,
          inverseDependenciesCache,
          resolutionResponse: response,
        };
      });
    });
  }

  const WebSocketServer = require('ws').Server;
  const wss = new WebSocketServer({
    server: httpServer,
    path: path,
  });

  wss.on('connection', ws => {
    const params = querystring.parse(url.parse(ws.upgradeReq.url).query);

    getDependencies(params.platform, params.bundleEntry)
      .then(({
        dependenciesCache,
        dependenciesModulesCache,
        shallowDependencies,
        inverseDependenciesCache,
      }) => {
        client = {
          ws,
          platform: params.platform,
          bundleEntry: params.bundleEntry,
          dependenciesCache,
          dependenciesModulesCache,
          shallowDependencies,
          inverseDependenciesCache,
        };

        packagerServer.setHMRFileChangeListener((type, filename) => {
          if (!client) {
            return;
          }

          const blacklisted = blacklist.find(blacklistedPath =>
            filename.indexOf(blacklistedPath) !== -1
          );

          if (blacklisted) {
            return;
          }

          client.ws.send(JSON.stringify({type: 'update-start'}));
          const promise = type === 'delete'
            ? Promise.resolve()
            : packagerServer.getShallowDependencies({
                entryFile: filename,
                platform: client.platform,
                dev: true,
                hot: true,
              }).then(deps => {
                if (!client) {
                  return [];
                }

                // if the file dependencies have change we need to invalidate the
                // dependencies caches because the list of files we need to send
                // to the client may have changed
                const oldDependencies = client.shallowDependencies[filename];
                if (arrayEquals(deps, oldDependencies)) {
                  // Need to create a resolution response to pass to the bundler
                  // to process requires after transform. By providing a
                  // specific response we can compute a non recursive one which
                  // is the least we need and improve performance.
                  return packagerServer.getDependencies({
                    platform: client.platform,
                    dev: true,
                    hot: true,
                    entryFile: filename,
                    recursive: true,
                  }).then(response => {
                    const module = packagerServer.getModuleForPath(filename);

                    return response.copy({dependencies: [module]});
                  });
                }

                // if there're new dependencies compare the full list of
                // dependencies we used to have with the one we now have
                return getDependencies(client.platform, client.bundleEntry)
                  .then(({
                    dependenciesCache: depsCache,
                    dependenciesModulesCache: depsModulesCache,
                    shallowDependencies: shallowDeps,
                    inverseDependenciesCache: inverseDepsCache,
                    resolutionResponse,
                  }) => {
                    if (!client) {
                      return {};
                    }

                    // build list of modules for which we'll send HMR updates
                    const modulesToUpdate = [packagerServer.getModuleForPath(filename)];
                    Object.keys(depsModulesCache).forEach(module => {
                      if (!client.dependenciesModulesCache[module]) {
                        modulesToUpdate.push(depsModulesCache[module]);
                      }
                    });

                    // Need to send modules to the client in an order it can
                    // process them: if a new dependency graph was uncovered
                    // because a new dependency was added, the file that was
                    // changed, which is the root of the dependency tree that
                    // will be sent, needs to be the last module that gets
                    // processed. Reversing the new modules makes sense
                    // because we get them through the resolver which returns
                    // a BFS ordered list.
                    modulesToUpdate.reverse();

                    // invalidate caches
                    client.dependenciesCache = depsCache;
                    client.dependenciesModulesCache = depsModulesCache;
                    client.shallowDependencies = shallowDeps;
                    client.inverseDependenciesCache = inverseDepsCache;

                    return resolutionResponse.copy({
                      dependencies: modulesToUpdate
                    });
                  });
              })
              .then((resolutionResponse) => {
                if (!client) {
                  return;
                }

                // make sure the file was modified is part of the bundle
                if (!client.shallowDependencies[filename]) {
                  return;
                }

                const httpServerAddress = httpServer.address();

                // Sanitize the value from the HTTP server
                let packagerHost = 'localhost';
                if (httpServer.address().address &&
                    httpServer.address().address !== '::' &&
                    httpServer.address().address !== '') {
                  packagerHost = httpServerAddress.address;
                }

                return packagerServer.buildBundleForHMR({
                  entryFile: client.bundleEntry,
                  platform: client.platform,
                  resolutionResponse,
                }, packagerHost, httpServerAddress.port);
              })
              .then(bundle => {
                if (!client || !bundle || bundle.isEmpty()) {
                  return;
                }

                return JSON.stringify({
                  type: 'update',
                  body: {
                    modules: bundle.getModulesIdsAndCode(),
                    inverseDependencies: client.inverseDependenciesCache,
                    sourceURLs: bundle.getSourceURLs(),
                    sourceMappingURLs: bundle.getSourceMappingURLs(),
                  },
                });
              })
              .catch(error => {
                // send errors to the client instead of killing packager server
                let body;
                if (error.type === 'TransformError' ||
                    error.type === 'NotFoundError' ||
                    error.type === 'UnableToResolveError') {
                  body = {
                    type: error.type,
                    description: error.description,
                    filename: error.filename,
                    lineNumber: error.lineNumber,
                  };
                } else {
                  console.error(error.stack || error);
                  body = {
                    type: 'InternalError',
                    description: 'react-packager has encountered an internal error, ' +
                      'please check your terminal error output for more details',
                  };
                }

                return JSON.stringify({type: 'error', body});
              })
              .then(update => {
                if (!client || !update) {
                  return;
                }

                client.ws.send(update);
              });

          promise.then(() => {
            client.ws.send(JSON.stringify({type: 'update-done'}));
          });
        });

        client.ws.on('error', e => {
          console.error('[Hot Module Replacement] Unexpected error', e);
          disconnect();
        });

        client.ws.on('close', () => disconnect());
      })
    .catch(err => {
      throw err;
    });
  });
}
328883
def bootstrap():
    ""
    # Link files shared by subprojects
    debian = path("debian")
    debian.exists() or debian.makedirs()

    for shared in ("debian/changelog", "LICENSE"):
        path(shared).exists() or (path("..") / shared).link(shared)

    build()
235821
function resolveNames(pkg, parentName) {
    var external = [];
    _.forEach(pkg.assetNames, function (name) {
      if (!_.isString(name)) {
        return;
      }
      var base = path.normalize(name).split('/')[0];
      if (_.indexOf(newAssetsNames, base) < 0) {
        return;
      }
      if (pkg.name === base) {
        return;
      }
      var a = assets[_.indexOf(newAssetsNames, base)];
      if (a.type === 'package') {
        if (parentName !== a.name) {
          external = external.concat(resolveNames(a, parentName));
        }
      } else if (a.type === 'folder') {
        if (name !== base) {
          external.push(name);
        }
      } else {
        external.push(a.name);
      }
    });
    return _.uniq(external);
  }
119477
function installGitDependencies(options, cb) {
  var libsassPath = './src/libsass';

  if (process.env.LIBSASS_EXT || options.libsassExt) {
    cb();
  } else if (fs.access) { // node 0.12+, iojs 1.0.0+
    fs.access(libsassPath, fs.R_OK, function(err) {
      err && err.code === 'ENOENT' ? initSubmodules(cb) : cb();
    });
  } else { // node < 0.12
    fs.exists(libsassPath, function(exists) {
      exists ? cb() : initSubmodules(cb);
    });
  }
}
489406
function (pkg, cb) {
  var auto = npm.config.get("update-dependents")
  if (!auto) {
    autoUpdate = function (_, cb) { return cb() }
    return log.verbose(
      "update-dependents disabled by config", "update-dependents", cb)
  }
  pkg = pkg && pkg._data || pkg
  if (auto === "always") {
    return npm.commands["update-dependents"]([pkg], cb)
  }
  readInstalled(pkg.name, function (er, inst) {
    if (er) return cb(er)
    var versions = Object.keys(inst[pkg.name])
                   .filter(function (v) { return v !== pkg.version })
                   .sort(semver.sort)
      , maxHave = versions.pop()
    if (!maxHave) return cb()
    if (!semver.gt(pkg.version, maxHave)) return log.verbose(
      "downgrade, not updating dependencencies", "update-dependents", cb)
    npm.commands["update-dependents"]([pkg], cb)
  })
}
530587
function collectDependencies(module) {
    let paths = [];
    function pathsToAcceptingModules(path, root) {
      const requiredMe = parents[root.filename];
      if (module.hot._selfAccepted) {
        paths.push(path.concat(root.filename));
        return;
      }
      if (module.hot._selfDeclined) {
        return;
      }
      for (let next in requiredMe) {
        let parentHotRuntime = requiredMe[next].hot;
        if (parentHotRuntime._acceptedDependencies[root.filename]) {
          paths.push(path.concat(root.filename));
          continue;
        }
        if (parentHotRuntime._declinedDependencies[root.filename]) {
          continue;
        }
        pathsToAcceptingModules(path.concat(root.filename), requiredMe[next]);
      }
    }
    pathsToAcceptingModules([], module);
    return paths;
  }
393424
function processLinked(deps, processed) {
      if(_.isEmpty(deps)) {
        return;
      }
      if(!processed) {
        processed = _.clone(deps);
      }

      var newDeps = {};
      var promise = when.resolve();
      _.each(deps, function(version, link) {
        promise = promise.then(function() {
          var pkgPath = path.resolve(nodeModulesDir, link, 'package.json');
          if (!fs.existsSync(pkgPath)) { throw new Error('Invalid package at '+pkgPath); }
          var linkPackage = require(pkgPath);

          if(!_.isEmpty(linkPackage.peerDependencies)) {
            //Install OR link peer dependencies
            self.log.verbose("Installing peer dependencies " +
              JSON.stringify(_.keys(linkPackage.peerDependencies)) + " from "
              + linkPackage.name + "@" + linkPackage.version + " into " + cwd);
          }

          return self.installWorkspaceDependencies(cwd, linkPackage.peerDependencies, workspaceDescriptor, installed)
          .then(function(newResults) {
            _.extend(newDeps, newResults.linked);
          });
        });
      });

      return promise.then(function() {
        var diff = _.omit(newDeps, _.keys(processed));
        //update the global list
        var newProcessed = _.extend({}, processed, diff);
        //process only new links
        return processLinked(diff, newProcessed);
      });
    }
1097283
async function resolveDependencies(rootFolder) {
    const includeFile = path.join(rootFolder, constants.INCLUDE_FILE);
    const includeJson = fs.readJsonSync(includeFile, 'utf8');
    await recDependencies(includeJson.dependencies, true);
    return depencyList;
}
453805
function loadPaths (pkg) {
  const name = pkg.name
  const file = pkg.path
  return resolveFile(tmp, path.join(name, file)).then(entry => ({
    entry: entry,
    package: path.join(tmp, 'node_modules', name, 'package.json')
  }))
}
969128
def install_update_deps(self):
        
        logger.debug("")
        self._ctx.installed(self.name)

        # are there any dependencies?
        depfile = os.path.join(self.repo_dir, '_upkg', 'depends')
        logger.debug("depfile? %s", depfile)
        if os.path.exists(depfile):
            logger.debug("Found depends file at %s", depfile)
            deps = open(depfile, 'r')
            dep = deps.readline()
            while dep:
                dep = dep.strip()
                logger.debug("depends: %s", dep)
                self._ctx.add_dep(nice_pkg_name(os.path.basename(dep)), dep)
                dep = deps.readline()
            deps.close()

        for rep in self._ctx.deps_needed:
            repo = Repo(url=rep)
            if repo.installed:
                repo.update()
            else:
                repo.install()
403237
async function buildDirectDependentTree() {
  const dependents = new Map();

  for (const packageName of await _list()) {
    dependents.set(packageName, new Set());
  }

  for (const packageName of await _list()) {
    for (const dep of tree.get(packageName)) {
      dependents.get(dep).add(packageName);
    }
  }

  return dependents;
}
532131
function bundleDTS() {
    const DST_PATH = path.join(__dirname, '..', config.dir.pkg);
    const TYPE_DEF_FILE = path.join(DST_PATH, config.dir.types, config.main.bundle_d_ts);
    const SRC_DEF_FILE = path.join(__dirname, '..', config.dir.built, config.main.basename + '-all.d.ts');

    let src = '\ufeff' + banner('.d.ts', config.main.basename) + fs.readFileSync(SRC_DEF_FILE).toString()
            .replace(/^\ufeff/gm, '')
            .replace(/\r\n/gm, '\n')
    ;

    const refPathInfo = [];
    const refPathDefs = src.match(/<reference path="[\s\S]*?"/g);

    if (null != refPathDefs) {
        refPathDefs.forEach((refpath) => {
            const filePath = refpath.match(/("|')[\s\S]*?("|')/)[0].replace(/("|')/g, '');
            const fileName = path.basename(filePath);
            refPathInfo.push({
                refpath: refpath,
                path: filePath,
                file: fileName,
            });
        });
        refPathInfo.forEach((target) => {
            src = src.replace(target.refpath, '<reference path="' + target.file + '"');
        });
        // remove '_dev.dependencies.d.ts' reference.
        src = src.replace(/\/\/\/ <reference path="_dev.dependencies.d.ts"[\s\S]*?\n/g, '');
    }

    if (!fs.existsSync(path.join(DST_PATH, config.dir.types))) {
        fs.mkdirSync(path.join(DST_PATH, config.dir.types));
    }
    fs.writeFileSync(TYPE_DEF_FILE, src);
}
244564
function lookForExternalDependenciesRES( _def, resources, depFile ) {
  if ( !_def ) return;
  try {
    const def = convertExternalDependencyDefinition( _def );
    for ( const dep of Object.keys( def ) ) {
      if ( def[ dep ] === "" ) {
        // `res: { "bob/foo.png": "" }` is equivalent to
        // `res: { "bob/foo.png": "bob/foo.png" }`
        def[ dep ] = dep;
      }
      const
      srcDep = Project.srcOrLibPath( `mod/${dep}` ) ||
        Project.srcOrLibPath( dep );
      if ( !srcDep ) {
        Fatal.fire(
          `Unable to find dependency file "${dep}" nor "mod/${dep}"!`,
          depFile.getAbsoluteFilePath()
        );
      }
      resources[ srcDep ] = Project.wwwPath( def[ dep ] );
    }
  } catch ( ex ) {
    Fatal.fire(
      `Unable to parse RES dependencies: ${JSON.stringify(_def)}!\n${ex}`,
      depFile
    );
  }
}
1240665
function buildDependencyTreeFromSources(filenames, sourcesObject) {
  const orgnizedFlat = {};

  // build tree object
  filenames.forEach(sourceFileName => {
    orgnizedFlat[sourceFileName] = {
      path: sourceFileName,
      source: sourcesObject[sourceFileName],
      dependencies: buildDependencyTreeFromSources(allImportPaths(sourcesObject[sourceFileName]), sourcesObject),
    };
  });

  // return organized object
  return orgnizedFlat;
}