Copied from Bundler
166533
def which(executable)
      if File.file?(executable) && File.executable?(executable)
        executable
      elsif ENV['PATH']
        path = ENV['PATH'].split(File::PATH_SEPARATOR).find do |p|
          abs_path = File.join(p, executable)
          File.file?(abs_path) && File.executable?(abs_path)
        end
        path && File.expand_path(executable, path)
      end
    end
248864
function bundle () {
    var didError = false
    const outStream = fs.createWriteStream(outFile)
    const bStream = w.bundle()

    bStream.on('error', function (err) {
      console.error('[bundle]', String(err))
      didError = true
      outStream.end('console.error(' + JSON.stringify(String(err)) + ')')
    })

    // if we're not splitting vendor files, include them in the bundle
    if (!shouldSplitVendor && vendorFiles.length) {
      multistream(vendorFiles.map(createReadStream).concat(bStream))
        .pipe(outStream)
    } else {
      bStream.pipe(outStream)
    }

    outStream.on('error', function (err) {
      console.error('[bundle]', err)
    })

    outStream.on('close', function () {
      if (verbose && !didError) {
        // TODO: also display size of vendor files
        console.error(
          '[bundle] %d bytes written to %s (%s seconds)',
          bytes, outFile, (time / 1000).toFixed(2)
        )
      }
    })
  }
725832
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();
    }
  }
134565
function BundleFile() {

  var location = getTempFileName('.browserify.js');

  function write(content) {
    fs.writeFileSync(location, content);
  }

  function exists() {
    return fs.existsSync(location);
  }

  function remove() {
    if (exists()) {
      fs.unlinkSync(location);
    }
  }

  function touch() {
    if (!exists()) {
      write('');
    }
  }


  // API

  this.touch = touch;

  this.update = write;
  this.remove = remove;

  this.location = location;
}
411918
function bundlePureJS() {
    const SRC_PATH = path.join(__dirname, '..', config.dir.src, config.dir.script);

    // source
    const src = fs.readFileSync(path.join(SRC_PATH, config.main.basename + '.js')).toString();
    const bundleSrc = '\ufeff' + banner('.js', config.main.basename) + src
            .replace(/^\ufeff/gm, '')
            .replace(/\r\n/gm, '\n')
    ;
    fs.writeFileSync(path.join(DST_PATH, config.main.basename + '.js'), bundleSrc);

    // d.ts
    const dts = fs.readFileSync(path.join(SRC_PATH, config.main.bundle_d_ts)).toString();
    const bundleDTS = '\ufeff' + banner('.d.ts', config.main.basename) + dts
            .replace(/^\ufeff/gm, '')
            .replace(/\r\n/gm, '\n')
    ;
    if (!fs.existsSync(path.join(DST_PATH, config.dir.types))) {
        fs.mkdirSync(path.join(DST_PATH, config.dir.types));
    }
    fs.writeFileSync(path.join(DST_PATH, config.dir.types, config.main.bundle_d_ts), bundleDTS);
}
192717
def bundle(self, app, results_dir):
    
    assert(isinstance(app, BundleCreate.App))

    bundle_dir = self.get_bundle_dir(app.id, results_dir)
    self.context.log.debug('creating {}'.format(os.path.relpath(bundle_dir, get_buildroot())))

    safe_mkdir(bundle_dir, clean=True)

    classpath = OrderedSet()

    # Create symlinks for both internal and external dependencies under `lib_dir`. This is
    # only needed when not creating a deployjar
    lib_dir = os.path.join(bundle_dir, self.LIBS_DIR)
    if not app.deployjar:
      os.mkdir(lib_dir)
      consolidated_classpath = self.context.products.get_data('consolidated_classpath')
      classpath.update(ClasspathProducts.create_canonical_classpath(
        consolidated_classpath,
        app.target.closure(bfs=True, **self._target_closure_kwargs),
        lib_dir,
        internal_classpath_only=False,
        excludes=app.binary.deploy_excludes,
      ))

    bundle_jar = os.path.join(bundle_dir, '{}.jar'.format(app.binary.basename))
    with self.monolithic_jar(app.binary, bundle_jar,
                             manifest_classpath=classpath) as jar:
      self.add_main_manifest_entry(jar, app.binary)

      # Make classpath complete by adding the monolithic jar.
      classpath.update([jar.path])

    if app.binary.shading_rules:
      for jar_path in classpath:
        # In case `jar_path` is a symlink, this is still safe, shaded jar will overwrite jar_path,
        # original file `jar_path` linked to remains untouched.
        # TODO run in parallel to speed up
        self.shade_jar(shading_rules=app.binary.shading_rules, jar_path=jar_path)

    self.symlink_bundles(app, bundle_dir)

    return bundle_dir
343117
function build() {
    const p = pending = new Emitter()
    buffer = bundler.toString()

    if (p !== pending) return
    pending.emit('ready', null, pending = false)
  }
807413
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) {
  var l = []
    , usedBuiltIns = npmTree._builtIns
    , len = 0;
  delete npmTree._builtIns;

  // 1. construct the global namespace object
  l.push("window." + ns + " = {data:{}, path:{}};");

  // 2. attach path code to the namespace object so that require.js can efficiently resolve paths
  l.push('\n// include npm::path');
  var pathCode = read(join(builtInDir, 'path.posix.js'));
  l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));');

  // 3. pull in serialized data
  Object.keys(o.data).forEach(function (name) {
    return l.push(ns + ".data." + name + " = " + o.data[name] + ";");
  });

  // 4. attach require code
  var config = {
    namespace : ns
  , domains   : Object.keys(o.domains) // TODO: remove npm from here
  , arbiters  : o.arbiters
  , logging   : o.logLevel
  , npmTree   : npmTree
  , builtIns  : builtIns
  , slash     : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client
  };

  l.push(anonWrap(read(join(dir, 'require.js'))
    .replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version)
    .replace(/REQUIRECONFIG/, JSON.stringify(config))
  ));

  // 5. include CommonJS compatible code in the order they have to be defined
  var defineWrap = function (exportName, domain, code) {
    return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});";
  };

  // 6. harvest function splits code into app and non-app code and defineWraps
  var harvest = function (onlyMain) {
    codeList.forEach(function (pair) {
      var dom = pair[0]
        , file = pair[1]
        , basename = file.split('.')[0];
      if ((dom === 'app') !== onlyMain) {
        return;
      }
      var code = before(compile(join(o.domains[dom], file)));
      l.push(defineWrap(basename, dom, code));
    });
  };

  // 7.a) include required builtIns
  l.push("\n// node builtins\n");
  len = l.length;
  usedBuiltIns.forEach(function (b) {
    if (b === 'path') { // already included
      return;
    }
    l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js'))));
  });
  if (l.length === len) {
    l.pop();
  }

  // 7.b) include modules not on the app domain
  l.push("\n// shared code\n");
  len = l.length;
  harvest(false);
  if (l.length === len) {
    l.pop();
  }

  // 7.c) include modules on the app domain, and wait for domloader if set
  l.push("\n// app code - safety wrapped\n\n");
  domload(harvest(true));

  // 8. use a closure to encapsulate the private internal data and APIs
  return anonWrap(l.join('\n'));
}
1020168
def bundler_fetcher
      # Bundler versions 1.10.0 moves AnonymizableURI to Source::Rubygems::Remote
      # See https://github.com/bundler/bundler/pull/3476
      if defined?(Bundler::Source::Rubygems::Remote)
        remote = Bundler::Source::Rubygems::Remote.new(Gem.sources.first.uri)
      else
        remote = Gem.sources.first.uri
      end
      Bundler::Fetcher.new(remote)
    end
1086104
def undo_bundler
      clean_env = nil
      Bundler.with_clean_env do
        clean_env = ENV.to_hash
      end
      ENV.replace(clean_env)
    end
843716
function visitBundle(file) {
        if (visitedIndexes[file]) {
            return;
        }
        visitedIndexes[file] = true;
        // walk deps
        var bundle = manifest.bundles[manifest.indexes[file]];
        bundle.data.forEach(function(module) {
            Object.keys(module.deps).forEach(function(key) {
                var value = module.deps[key];
                if (visitedIndexes.hasOwnProperty(value)) {
                    visitBundle(value);
                }
            });
        });
    }
262642
function bundleJsFiles () {
  return concat(jsFiles)
    .then((output) => {
      const uglified = UglifyJS.minify(output)
      if (uglified.error) {
        throw new Error(uglified.error)
      }
      return uglified.code
    })
}
71270
function createBundleRendererCreator (
  createRenderer
) {
  return function createBundleRenderer (
    bundle,
    rendererOptions
  ) {
    if ( rendererOptions === void 0 ) rendererOptions = {};

    var files, entry, maps;
    var basedir = rendererOptions.basedir;

    // load bundle if given filepath
    if (
      typeof bundle === 'string' &&
      /\.js(on)?$/.test(bundle) &&
      path$2.isAbsolute(bundle)
    ) {
      if (fs.existsSync(bundle)) {
        var isJSON = /\.json$/.test(bundle);
        basedir = basedir || path$2.dirname(bundle);
        bundle = fs.readFileSync(bundle, 'utf-8');
        if (isJSON) {
          try {
            bundle = JSON.parse(bundle);
          } catch (e) {
            throw new Error(("Invalid JSON bundle file: " + bundle))
          }
        }
      } else {
        throw new Error(("Cannot locate bundle file: " + bundle))
      }
    }

    if (typeof bundle === 'object') {
      entry = bundle.entry;
      files = bundle.files;
      basedir = basedir || bundle.basedir;
      maps = createSourceMapConsumers(bundle.maps);
      if (typeof entry !== 'string' || typeof files !== 'object') {
        throw new Error(INVALID_MSG)
      }
    } else if (typeof bundle === 'string') {
      entry = '__vue_ssr_bundle__';
      files = { '__vue_ssr_bundle__': bundle };
      maps = {};
    } else {
      throw new Error(INVALID_MSG)
    }

    var renderer = createRenderer(rendererOptions);

    var run = createBundleRunner(
      entry,
      files,
      basedir,
      rendererOptions.runInNewContext
    );

    return {
      renderToString: function (context, cb) {
        var assign;

        if (typeof context === 'function') {
          cb = context;
          context = {};
        }

        var promise;
        if (!cb) {
          ((assign = createPromiseCallback(), promise = assign.promise, cb = assign.cb));
        }

        run(context).catch(function (err) {
          rewriteErrorTrace(err, maps);
          cb(err);
        }).then(function (app) {
          if (app) {
            renderer.renderToString(app, context, function (err, res) {
              rewriteErrorTrace(err, maps);
              cb(err, res);
            });
          }
        });

        return promise
      },

      renderToStream: function (context) {
        var res = new PassThrough();
        run(context).catch(function (err) {
          rewriteErrorTrace(err, maps);
          // avoid emitting synchronously before user can
          // attach error listener
          process.nextTick(function () {
            res.emit('error', err);
          });
        }).then(function (app) {
          if (app) {
            var renderStream = renderer.renderToStream(app, context);

            renderStream.on('error', function (err) {
              rewriteErrorTrace(err, maps);
              res.emit('error', err);
            });

            // relay HTMLStream special events
            if (rendererOptions && rendererOptions.template) {
              renderStream.on('beforeStart', function () {
                res.emit('beforeStart');
              });
              renderStream.on('beforeEnd', function () {
                res.emit('beforeEnd');
              });
            }

            renderStream.pipe(res);
          }
        });

        return res
      }
    }
  }
}
980054
def write_merged_lockfiles(without: [])
      unless external_lockfile?
        copy_bundler_env
        return
      end

      # handle external lockfile
      Tempfile.open(".appbundler-gemfile", app_dir) do |t|
        t.puts "source 'https://rubygems.org'"

        locked_gems = {}

        gemfile_lock_specs.each do |s|
          # next if SHITLIST.include?(s.name)
          spec = safe_resolve_local_gem(s)
          next if spec.nil?

          case s.source
          when Bundler::Source::Path
            locked_gems[spec.name] = %Q{gem "#{spec.name}", path: "#{spec.gem_dir}"}
          when Bundler::Source::Rubygems
            # FIXME: should add the spec.version as a gem requirement below
            locked_gems[spec.name] = %Q{gem "#{spec.name}", "= #{spec.version}"}
          when Bundler::Source::Git
            raise "FIXME: appbundler needs a patch to support Git gems"
          else
            raise "appbundler doens't know this source type"
          end
        end

        seen_gems = {}

        t.puts "# GEMS FROM GEMFILE:"

        requested_dependencies(without).each do |dep|
          next if SHITLIST.include?(dep.name)
          if locked_gems[dep.name]
            t.puts locked_gems[dep.name]
          else
            string = %Q{gem "#{dep.name}", #{requirement_to_str(dep.requirement)}}
            string << %Q{, platform: #{dep.platforms}} unless dep.platforms.empty?
            t.puts string
          end
          seen_gems[dep.name] = true
        end

        t.puts "# GEMS FROM LOCKFILE: "

        locked_gems.each do |name, line|
          next if SHITLIST.include?(name)
          next if seen_gems[name]
          t.puts line
        end

        t.close
        puts IO.read(t.path) # debugging
        Dir.chdir(app_dir) do
          FileUtils.rm_f "#{app_dir}/Gemfile.lock"
          Bundler.with_clean_env do
            so = Mixlib::ShellOut.new("bundle lock", env: { "BUNDLE_GEMFILE" => t.path })
            so.run_command
            so.error!
          end
          FileUtils.mv t.path, "#{app_dir}/Gemfile"
        end
      end
      "#{app_dir}/Gemfile"
    end
304239
def _render_bundle(bundle_name):
    
    try:
        bundle = get_bundles()[bundle_name]
    except KeyError:
        raise ImproperlyConfigured("Bundle '%s' is not defined" % bundle_name)

    if bundle.use_bundle:
        return _render_file(bundle.bundle_type, bundle.get_url(), attrs=({'media':bundle.media} if bundle.media else {}))

    # Render files individually
    bundle_files = []

    for bundle_file in bundle.files:
        if bundle_file.precompile_in_debug:
            bundle_files.append(_render_file(bundle_file.bundle_type, bundle_file.precompile_url, attrs=({'media':bundle_file.media} if bundle.media else {})))
        else:
            bundle_files.append(_render_file(bundle_file.file_type, bundle_file.file_url, attrs=({'media':bundle_file.media} if bundle.media else {})))

    return '\n'.join(bundle_files)
1271538
function bundleJavascript() {
  const bundleEntryPath = path.resolve(__dirname, '..', 'dist', 'static', 'hierplane.js');
  const bundlePath = path.resolve(__dirname, '..', 'dist', 'static', 'hierplane.bundle.js');

  // Put together our "bundler", which uses browserify
  const browserifyOpts = {
    entries: [ bundleEntryPath ],
    standalone: 'hierplane'
  };

  // If we're watching or changes, enable watchify
  if (isWatchTarget) {
    // These are required for watchify
    browserifyOpts.packageCache = {};
    browserifyOpts.cache = {};

    // Enable the plugin
    browserifyOpts.plugin = [ watchify ];
  };

  // Construct the bundler
  const bundler = browserify(browserifyOpts);

  // Make an inline function which writes out the bundle, so that we can invoke it whenever
  // an update is detected if the watch target is being executed.
  const writeBundle = () => {
    console.log(chalk.cyan(`bundling ${chalk.magenta(path.relative(execArgs.cwd, bundleEntryPath))}`));
    bundler.bundle().pipe(fs.createWriteStream(bundlePath))
    console.log(chalk.green(`wrote ${chalk.magenta(path.relative(execArgs.cwd, bundlePath))}`));
  };

  // Write out the bundle once
  writeBundle();

  // If we're supposed to watch for changes, write out the bundle whenever they occur
  if (isWatchTarget) {
    bundler.on('update', writeBundle);
  }
}
503998
function patchBundle(bundle: Bundle, delta: DeltaBundle): Bundle {
  const map = new Map(bundle.modules);

  for (const [key, value] of delta.modified) {
    map.set(key, value);
  }

  for (const [key, value] of delta.added) {
    map.set(key, value);
  }

  for (const key of delta.deleted) {
    map.delete(key);
  }

  const modules = Array.from(map.entries());

  return {
    pre: bundle.pre,
    post: bundle.post,
    modules,
  };
}