Resolve the path to the PubNub web
bundle and transpose the files in
that path into the project's vendor
folder during build time.

@method treeForVendor

@params {Object} vendorTree
The broccoli tree representing vendor files.
165467
function(vendorTree) {
    const pubnubPath = path.dirname(require.resolve('pubnub/dist/web/pubnub.js'));
    const pubnubTree = new Funnel(pubnubPath, {
      src: 'pubnub.js',
      dest: './',
      annotation: 'Funnel (PubNub)'
    });

    return mergeTrees([vendorTree, pubnubTree]);
  }
300646
Node parseInputs() {
    boolean devMode = options.devMode != DevMode.OFF;

    // If old roots exist (we are parsing a second time), detach each of the
    // individual file parse trees.
    externsRoot.detachChildren();
    jsRoot.detachChildren();

    Tracer tracer = newTracer(PassNames.PARSE_INPUTS);
    beforePass(PassNames.PARSE_INPUTS);

    try {
      // Parse externs sources.
      if (options.numParallelThreads > 1) {
        new PrebuildAst(this, options.numParallelThreads).prebuild(externs);
      }
      for (CompilerInput input : externs) {
        Node n = checkNotNull(input.getAstRoot(this));
        if (hasErrors()) {
          return null;
        }
        externsRoot.addChildToBack(n);
      }

      if (options.transformAMDToCJSModules) {
        processAMDModules(moduleGraph.getAllInputs());
      }

      if (options.getLanguageIn().toFeatureSet().has(FeatureSet.Feature.MODULES)
          || options.processCommonJSModules) {

        ModuleResolverFactory moduleResolverFactory = null;

        switch (options.getModuleResolutionMode()) {
          case BROWSER:
            moduleResolverFactory = BrowserModuleResolver.FACTORY;
            break;
          case NODE:
            // processJsonInputs requires a module loader to already be defined
            // so we redefine it afterwards with the package.json inputs
            moduleResolverFactory =
                new NodeModuleResolver.Factory(processJsonInputs(moduleGraph.getAllInputs()));
            break;
          case WEBPACK:
            moduleResolverFactory = new WebpackModuleResolver.Factory(inputPathByWebpackId);
            break;
          case BROWSER_WITH_TRANSFORMED_PREFIXES:
            moduleResolverFactory =
                new BrowserWithTransformedPrefixesModuleResolver.Factory(
                    options.getBrowserResolverPrefixReplacements());
            break;
        }

        this.moduleLoader =
            new ModuleLoader(
                null,
                options.moduleRoots,
                moduleGraph.getAllInputs(),
                moduleResolverFactory,
                ModuleLoader.PathResolver.RELATIVE,
                options.getPathEscaper());
      } else {
        // Use an empty module loader if we're not actually dealing with modules.
        this.moduleLoader = ModuleLoader.EMPTY;
      }

      if (options.getDependencyOptions().needsManagement()) {
        findModulesFromEntryPoints(
            options.getLanguageIn().toFeatureSet().has(Feature.MODULES),
            options.processCommonJSModules);
      } else if (options.needsTranspilationFrom(FeatureSet.ES6_MODULES)
          || options.processCommonJSModules) {
        if (options.getLanguageIn().toFeatureSet().has(Feature.MODULES)) {
          parsePotentialModules(moduleGraph.getAllInputs());
        }

        // Build a map of module identifiers for any input which provides no namespace.
        // These files could be imported modules which have no exports, but do have side effects.
        Map<String, CompilerInput> inputModuleIdentifiers = new HashMap<>();
        for (CompilerInput input : moduleGraph.getAllInputs()) {
          if (input.getKnownProvides().isEmpty()) {
            ModuleLoader.ModulePath modPath =
                moduleLoader.resolve(input.getSourceFile().getOriginalPath());
            inputModuleIdentifiers.put(modPath.toModuleName(), input);
          }
        }

        // Find out if any input attempted to import a module that had no exports.
        // In this case we must force module rewriting to occur on the imported file
        Map<String, CompilerInput> inputsToRewrite = new HashMap<>();
        for (CompilerInput input : moduleGraph.getAllInputs()) {
          for (String require : input.getKnownRequiredSymbols()) {
            if (inputModuleIdentifiers.containsKey(require)
                && !inputsToRewrite.containsKey(require)) {
              inputsToRewrite.put(require, inputModuleIdentifiers.get(require));
            }
          }
        }

        for (CompilerInput input : inputsToRewrite.values()) {
          input.setJsModuleType(CompilerInput.ModuleType.IMPORTED_SCRIPT);
        }
      }

      if (this.moduleLoader != null) {
        this.moduleLoader.setErrorHandler(this);
      }

      orderInputs();

      // If in IDE mode, we ignore the error and keep going.
      if (hasErrors()) {
        return null;
      }

      // Build the AST.
      if (options.numParallelThreads > 1) {
        new PrebuildAst(this, options.numParallelThreads).prebuild(moduleGraph.getAllInputs());
      }

      for (CompilerInput input : moduleGraph.getAllInputs()) {
        Node n = checkNotNull(input.getAstRoot(this));
        if (devMode) {
          runValidityCheck();
          if (hasErrors()) {
            return null;
          }
        }

        // TODO(johnlenz): we shouldn't need to check both isExternExportsEnabled and
        // externExportsPath.
        if (options.sourceMapOutputPath != null
            || options.isExternExportsEnabled()
            || options.externExportsPath != null
            || !options.replaceStringsFunctionDescriptions.isEmpty()) {

          // Annotate the nodes in the tree with information from the
          // input file. This information is used to construct the SourceMap.
          SourceInformationAnnotator sia =
              new SourceInformationAnnotator(
                  input.getName(), options.devMode != DevMode.OFF);
          NodeTraversal.traverse(this, n, sia);
        }

        if (NodeUtil.isFromTypeSummary(n)) {
          input.setIsExtern();
          externsRoot.addChildToBack(n);
        } else {
          jsRoot.addChildToBack(n);
        }
      }

      if (hasErrors()) {
        return null;
      }
      return externAndJsRoot;
    } finally {
      afterPass(PassNames.PARSE_INPUTS);
      stopTracer(tracer, PassNames.PARSE_INPUTS);
    }
  }
942052
function findRoot(root) {
  var pkg;
  root = root.split(path.sep);
  while(!pkg && root.length > 1) {
    var cur = root.join(path.sep);
    if(fs.existsSync(path.join(cur, "package.json"))) {
      return cur;
    }
    root.pop();
  }
}
1111357
protected void addPackageTreeLinks(Content contentTree) {
        //Do nothing if only unnamed package is used
        if (isUnnamedPackage()) {
            return;
        }
        if (!classesonly) {
            Content span = HtmlTree.SPAN(HtmlStyle.packageHierarchyLabel,
                    getResource("doclet.Package_Hierarchies"));
            contentTree.addContent(span);
            HtmlTree ul = new HtmlTree(HtmlTag.UL);
            ul.addStyle(HtmlStyle.horizontal);
            int i = 0;
            for (PackageDoc pkg : packages) {
                // If the package name length is 0 or if -nodeprecated option
                // is set and the package is marked as deprecated, do not include
                // the page in the list of package hierarchies.
                if (pkg.name().isEmpty() ||
                        (configuration.nodeprecated && utils.isDeprecated(pkg))) {
                    i++;
                    continue;
                }
                DocPath link = pathString(pkg, DocPaths.PACKAGE_TREE);
                Content li = HtmlTree.LI(getHyperLink(
                        link, new StringContent(pkg.name())));
                if (i < packages.size() - 1) {
                    li.addContent(", ");
                }
                ul.addContent(li);
                i++;
            }
            contentTree.addContent(ul);
        }
    }
531253
function(callback) {
      helpers.walk(buildInfo.srcVendors, function(err, results) {
        if (err) return callback("Error walking files.");    
        callback(null, results);
      });
    }
74836
func importPathFromPath(root, basePath string) string {
	vendorTest := filepath.Join(basePath, "vendor")
	if len(root) > len(vendorTest) && root[:len(vendorTest)] == vendorTest {
		return filepath.ToSlash(root[len(vendorTest)+1:])
	}
	for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
		srcPath := filepath.Join(gopath, "src")
		if strings.HasPrefix(root, srcPath) {
			return filepath.ToSlash(root[len(srcPath)+1:])
		}
	}

	srcPath := filepath.Join(build.Default.GOROOT, "src", "pkg")
	if strings.HasPrefix(root, srcPath) {
		utils.Logger.Warn("Code path should be in GOPATH, but is in GOROOT:", "path", root)
		return filepath.ToSlash(root[len(srcPath)+1:])
	}

	utils.Logger.Error("Unexpected! Code path is not in GOPATH:", "path", root)
	return ""
}
1025147
function getRoot(cwd, filename, smap) {
    var relativePath = path.relative(cwd, filename);

    var segments = relativePath.split('node_modules');

    var sourceRoot = smap.getProperty('sourceRoot') || '/source/' + relativePath;

    if (segments.length <= 1) {
        return sourceRoot;
    } else {
        return sourceRoot
            .replace(/^\/source\//, '/source/' + pathToPackage());
    }

    // it works, somehow ¯\_(ツ)_/¯
    function pathToPackage() {
        var upToNodeModules = segments
            .slice(0, -1)
            .concat('/')
            .join('node_modules');

        var packageName = segments[segments.length - 1]
            .split('/', 2)[1]
            + '/';

        return upToNodeModules + packageName;
    }
}
625857
function packageFilter(pkg, root) {
  pkg.main = pkg.glslify || (
    path.extname(pkg.main || '') !== '.js' &&
    pkg.main
  ) || 'index.glsl'

  return pkg
}
1364169
def vendor!(dir = nil, force = false)
      resolve! if paths.empty?
      dir ||= options[:vendor_dir]
      dir ||= 'vendor' # default
      logger.debug "Vendoring #{paths.length} files to #{dir}"
      paths.collect {|n, p| p }.flatten.each do |path, name, version|
        if index.in_jimhome?(path)
          Jim::Installer.new(path, dir, :shallow => true, :force => force).install
        end
      end
      dir
    end
1068015
function callNativeResolution(request, issuer) {
  if (issuer.endsWith('/')) {
    issuer += 'internal.js';
  }

  try {
    enableNativeHooks = false;

    // Since we would need to create a fake module anyway (to call _resolveLookupPath that
    // would give us the paths to give to _resolveFilename), we can as well not use
    // the {paths} option at all, since it internally makes _resolveFilename create another
    // fake module anyway.
    return Module._resolveFilename(request, makeFakeModule(issuer), false);
  } finally {
    enableNativeHooks = true;
  }
}
1255898
function resolvePackage(packageName) {
    try {
      // First, try to use require.resolve to find the package.
      // We add /package.json and then dirname the result because require.resolve follows the `main`
      // property in package.json to produce a path to a file deep inside the package, and we want
      // the path to the top-level directory.
      // This branch handles packages being symlinked into node_modules, for example with
      // `npm link` or in sku's test cases.
      const result = path.dirname(
        resolve(`${packageName}/package.json`, { paths: [cwd()] }),
      );
      debug(`Resolved ${packageName} to ${result}`);
      return result;
    } catch (error) {
      if (error.code === 'MODULE_NOT_FOUND') {
        const dependencies = getProjectDependencies(fs.readFileSync);

        if (!dependencies[packageName]) {
          // If it's not we can safely return a naive local path, which prevents webpack from
          // throwing config schema errors when this function is used to configure a loader.
          // This branch handles the scenario where we're trying to resolve a design system module because
          // it's in the default list of compilePackages, but it's not actually being used in the project.
          const localPackage = path.join(cwd(), 'node_modules', packageName);
          debug(`Resolved unused package ${packageName} to ${localPackage}`);
          return localPackage;
        }
      }

      // We've gotten this far because the package is listed as a project dependency and can't be
      // resolved, or because the error is not ENOENT. In either case we want to throw.
      throw error;
    }
  }
509329
private function resolveSrc($vendor)
    {
        $src = null;

        /** @var $packages \Composer\Package\CompletePackage[] */
        $packages = $this->repository->getPackages();
        foreach ($packages as $package) {
            if ($vendor == $package->getName()) {
                $autoload = $package->getAutoload();
                $src = current($autoload['psr-0']);

                break;
            }
        }

        if (null === $src) {
            throw new \InvalidArgumentException(sprintf('Vendor "%s" not found', $vendor));
        }

        return $src;
    }
475150
protected void parseVendors(Document doc) {
    // Parse vendors, we will need those.
    // Format: <vendor vendor-id="TGPP" code="10415" name="3GPP" />
    NodeList vendorNodes = doc.getElementsByTagName("vendor");

    for (int v = 0; v < vendorNodes.getLength(); v++) {
      Node vendorNode = vendorNodes.item(v);
      if (vendorNode.getNodeType() == Node.ELEMENT_NODE) {
        Element vendorElement = (Element) vendorNode;

        // Get the Code (number) and ID (string)
        String vendorCode = vendorElement.getAttribute("code");
        String vendorId = vendorElement.getAttribute("vendor-id");

        vendorMap.put(vendorId, vendorCode);
      }
    }
  }
805882
function browserifyBanner (browserify, options) {
  options = options || {};

  if (typeof browserify === "string") {
    // browserify-banner was loaded as a transform, not a plug-in.
    // So return a stream that does nothing.
    return through();
  }

  browserify.on("package", setPackageOption);
  browserify.on("file", setFileOption);
  browserify.on("bundle", wrapBundle);
  browserify.on("reset", wrapBundle);

  /**
   * If the `pkg` option isn't set, then it defaults to the first package that's read
   *
   * @param {object} pkg - The parsed package.json file
   */
  function setPackageOption (pkg) {
    if (!options.pkg) {
      options.pkg = pkg;
    }
  }

  /**
   * If the `file` option isn't set, then it defaults to "banner.txt" in the same directory
   * as the first entry file.  We'll crawl up the directory tree from there if necessary.
   *
   * @param {string} file - The full file path
   */
  function setFileOption (file) {
    if (!options.file) {
      options.file = path.join(path.dirname(file), "banner.txt");
    }
  }

  /**
   * Adds transforms to the Browserify "wrap" pipeline
   */
  function wrapBundle () {
    let wrap = browserify.pipeline.get("wrap");
    let bannerAlreadyAdded = false;
    let banner;

    wrap.push(through(addBannerToBundle));
    if (browserify._options.debug) {
      wrap.push(through(addBannerToSourcemap));
    }

    /**
     * Injects the banner comment block into the Browserify bundle
     */
    function addBannerToBundle (chunk, enc, next) {
      if (!bannerAlreadyAdded) {
        bannerAlreadyAdded = true;
        try {
          banner = getBanner(options);
          this.push(new Buffer(banner));
        }
        catch (e) {
          next(e);
        }
      }
      this.push(chunk);
      next();
    }

    /**
     * Adjusts the sourcemap to account for the banner comment block
     */
    function addBannerToSourcemap (chunk, enc, next) {
      let pushed = false;

      if (banner) {
        // Get the sourcemap, once it exists
        let conv = convertSourcemap.fromSource(chunk.toString("utf8"));
        if (conv) {
          // Offset the sourcemap by the number of lines in the banner
          let offsetMap = offsetSourcemap(conv.toObject(), countLines(banner));
          this.push(new Buffer("\n" + convertSourcemap.fromObject(offsetMap).toComment() + "\n"));
          pushed = true;
        }
      }

      if (!pushed) {
        // This chunk doesn't contain anything for us to modify,
        // so just pass it along as-is
        this.push(chunk);
      }
      next();
    }
  }
}
523847
function resolveNodeModules(pkgpath) {
  let dir = pkgpath;
  let dirs = [];
  let depth = maxFileSystemDepth;
  let parent;
  let nodeModulespath;

  while (true) {
    parent = path.dirname(dir);
    // Stop if we hit max file system depth or root
    // Convert to lowercase to fix problems on Windows
    if (!--depth || parent.toLowerCase() === dir.toLowerCase()) {
      break;
    }

    nodeModulespath = path.resolve(dir, 'node_modules');

    if (exists(nodeModulespath)) dirs.push(nodeModulespath);

    // Walk
    dir = parent;
  }

  return dirs;
}
1193028
function getClosestPackage(modulePath) {
  let root;
  let pkg;

  // Catch findRoot or require errors
  try {
    root = findRoot(modulePath);
    pkg = require(path.join(root, "package.json"));
  } catch (e) {
    return null;
  }

  // If the package.json does not have a name property, try again from
  // one level higher.
  // https://github.com/jsdnxx/find-root/issues/2
  // https://github.com/date-fns/date-fns/issues/264#issuecomment-265128399
  if (!pkg.name) {
    return getClosestPackage(path.resolve(root, ".."));
  }

  return {
    package: pkg,
    path: root
  };
}
574674
function build(importsObj, tree) {
  const modules = {};

  const instantiate = filepath => {
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const mod = tree.modules[filepath];
    const promise = Promise.all(
      Object.entries(mod.deps).map(([key, dep]) => {
        return instantiate(dep.filepath).then(result => [key, result]);
      })
    )
      .then(importsMap => {
        const imports = importsMap.reduce((acc, [key, module]) => {
          acc[key] = module.instance.exports;
          return acc;
        }, {});

        return WebAssembly.instantiate(
          tree.opcodes[filepath],
          Object.assign({}, imports, importsObj)
        );
      })
      .catch(e => {
        // TODO: do some logging here
        throw e;
      });

    modules[filepath] = promise;

    return promise;
  };

  modules[tree.root.filepath] = instantiate(tree.root.filepath);

  return modules[tree.root.filepath];
}