Wrap `watchify-request` in koa middleware. @param {Object} bundler @return {Function*}
547868
function kw(bundler) {
  assert.equal(typeof bundler, 'object')
  const handler = thenify(wreq(bundler))

  // Koa middleware.
  // @param {Function} next
  // @return {Promise}
  return function *watchifyRequest(next) {
    const ctx = this

    return yield handler(this.req, this.res)
      .then(success)
      .catch(failure)

    function success(res) {
      ctx.response.body = res
    }

    function failure(err) {
      ctx.throw(err)
    }
  }
}
250290
function Bro(bundleFile) {

  var log;

  /**
   * Add bundle file to the list of files in the
   * configuration, right before the first browserified
   * test file and after everything else.
   *
   * That makes sure users can include non-commonJS files
   * prior to the browserified bundle.
   *
   * @param {BundleFile} bundleFile the file containing the browserify bundle
   * @param {Object} config the karma configuration to be updated
   */
  function addBundleFile(bundleFile, config) {

    var files = config.files,
        preprocessors = config.preprocessors;

    // list of patterns using our preprocessor
    var patterns = reduce(preprocessors, function(matched, val, key) {
      if (val.indexOf('browserify') !== -1) {
        matched.push(key);
      }
      return matched;
    }, []);

    // first file being preprocessed
    var file = find(files, function(f) {
      return some(patterns, function(p) {
        return minimatch(f.pattern, p);
      });
    });

    var idx = 0;

    if (file) {
      idx = files.indexOf(file);
    } else {
      log.debug('no matching preprocessed file was found, defaulting to prepend');
    }

    log.debug('add bundle to config.files at position', idx);

    // insert bundle on the correct spot
    files.splice(idx, 0, {
      pattern: bundleFile.location,
      served: true,
      included: true,
      watched: true
    });
  }


  /**
   * The browserify instance that creates the
   * minified bundle and gets added all test files to it.
   */
  var b;


  /**
   * The browserify framework that creates the initial logger and bundle file
   * as well as prepends the bundle file to the karma file configuration.
   */
  function framework(emitter, config, logger) {

    log = logger.create('framework.browserify');

    if (!bundleFile) {
      bundleFile = new BundleFile();
    }

    bundleFile.touch();
    log.debug('created browserify bundle: %s', bundleFile.location);

    b = createBundle(config);

    // TODO(Nikku): hook into karma karmas file update facilities
    // to remove files from the bundle once karma detects the deletion

    // hook into exit for cleanup
    emitter.on('exit', function(done) {
      log.debug('cleaning up');

      if (b.close) {
        b.close();
      }

      bundleFile.remove();
      done();
    });


    // add bundle file to the list of files defined in the
    // configuration. be smart by doing so.
    addBundleFile(bundleFile, config);

    return b;
  }

  framework.$inject = [ 'emitter', 'config', 'logger' ];


  /**
   * Create the browserify bundle
   */
  function createBundle(config) {

    var bopts = config.browserify || {},
        bundleDelay = bopts.bundleDelay || DEFAULT_BUNDLE_DELAY,
        requireName = bopts.externalRequireName || 'require';

    function warn(key) {
      log.warn('Invalid config option: "' + key + 's" should be "' + key + '"');
    }

    forEach([ 'transform', 'plugin' ], function(key) {
      if (bopts[key + 's']) {
        warn(key);
      }
    });

    var browserifyOptions = assign({
      basedir: path.resolve(config.basePath),
      // watchify.args
      cache: {},
      packageCache: {}
    }, omit(bopts, [
      'transform', 'plugin', 'configure', 'bundleDelay'
    ]));

    if ('prebundle' in browserifyOptions) {
      log.warn('The prebundle hook got removed in favor of configure');
    }

    if ('watchify' in browserifyOptions) {
      log.warn('Configure watchify via config.watchify');
    }

    var w = browserify(browserifyOptions);
    w.setMaxListeners(Infinity);

    forEach(bopts.plugin, function(p) {
      // ensure we can pass plugin options as
      // the first parameter
      if (!Array.isArray(p)) {
        p = [ p ];
      }
      w.plugin.apply(w, p);
    });

    forEach(bopts.transform, function(t) {
      // ensure we can pass transform options as
      // the first parameter
      if (!Array.isArray(t)) {
        t = [ t ];
      }
      w.transform.apply(w, t);
    });

    // test if we have a configure function
    if (bopts.configure && typeof bopts.configure === 'function') {
      bopts.configure(w);
    }

    // register rebuild bundle on change
    if (config.autoWatch) {

      if (!watchify) {
        log.error('watchify not found; install it via npm install --save-dev watchify');
        log.error('cannot perform incremental rebuild');

        throw new Error('watchify not found');
      }

      w = watchify(w, config.watchify);

      log.info('registering rebuild (autoWatch=true)');

      w.on('update', function(updated) {

        // we perform an update, karma will trigger one, too
        // because the bundling is deferred only one change will
        // be triggered. Anything else is the result of a
        // raise condition or a problem of watchify firing file
        // changes to late

        log.debug('files changed');
        deferredBundle();
      });

      w.on('log', function(msg) {
        log.info(msg);
      });

      // update bundle file
      w.on('bundled', function(err, content) {
        if (w._builtOnce) {
          bundleFile.update(err ? BUNDLE_ERROR_TPL : content.toString('utf-8'));
          log.info('bundle updated');
        }
      });
    }

    function deferredBundle(cb) {
      if (cb) {
        w.once('bundled', cb);
      }

      rebuild();
    }

    var rebuild = debounce(function rebuild() {

      if (w._bundled) {
        log.debug('resetting bundle');

        var recorded = w._recorded;
        w.reset();

        recorded.forEach(function(e) {
          // we remove missing files on the fly
          // to cope with bundle internals missing
          if (e.file && !fs.existsSync(path.resolve(config.basePath, e.file))) {
            log.debug('removing missing file', e.file);
          } else {
            w.pipeline.write(e);
          }
        });
      }

      w.emit('prebundle', w);

      log.debug('bundling');

      w.bundle(function(err, content) {

        if (err) {
          log.error('bundle error');
          log.error(String(err));
        }

        w.emit('bundled', err, content);
      });
    }, bundleDelay);


    w.bundleFile = function(file, done) {

      var absolutePath = path.resolve(file.path),
          relativePath = path.relative(config.basePath, absolutePath);

      // add file
      log.debug('updating %s in bundle', relativePath);

      // add the file during next prebundle step
      w.once('prebundle', function() {
        w.require('./' + relativePath, { expose: absolutePath });
      });

      deferredBundle(function(err) {
        var stub = 'typeof ' + requireName + ' === "function" && ' + requireName + '("' + escape(absolutePath) + '");';

        done(err, stub);
      });
    };


    /**
     * Wait for the bundle creation to have stabilized (no more additions) and invoke a callback.
     *
     * @param {Function} [callback] invoked with (err, content)
     */
    w.deferredBundle = deferredBundle;

    return w;
  }


  /**
   * A processor that preprocesses commonjs test files which should be
   * delivered via browserify.
   */
  function testFilePreprocessor() {

    return function(content, file, done) {
      b.bundleFile(file, function(err, content) {
        done(content && content.toString());
      });
    };
  }

  testFilePreprocessor.$inject = [ ];


  /**
   * A special preprocessor that builds the main browserify bundle once and
   * passes the bundle contents through on all later preprocessing request.
   */
  function bundlePreprocessor(config) {

    var debug = config.browserify && config.browserify.debug;

    function updateSourceMap(file, content) {
      var map;

      if (debug) {

        map = extractSourceMap(content);

        file.sourceMap = map && map.sourcemap;
      }
    }

    return function(content, file, done) {

      if (b._builtOnce) {
        updateSourceMap(file, content);
        return done(content);
      }

      log.debug('building bundle');

      // wait for the initial bundle to be created
      b.deferredBundle(function(err, content) {

        b._builtOnce = config.autoWatch;

        if (err) {
          return done(BUNDLE_ERROR_TPL);
        }

        content = content.toString('utf-8');
        updateSourceMap(file, content);

        log.info('bundle built');

        done(content);
      });
    };
  }

  bundlePreprocessor.$inject = [ 'config' ];


  // API

  this.framework = framework;

  this.testFilePreprocessor = testFilePreprocessor;
  this.bundlePreprocessor = bundlePreprocessor;
}
1121862
function watch() {
  gulp.watch([appSrc + '/app/**/*.ts', '!' + appSrc + '/app/**/*.spec.ts']).on('change', function (path) {
    console.log('TypeScript file ' + path + ' has been changed. Compiling.');
    gulp.series(inlineTemplate, transpile, updateWatchDist)();
  });
  gulp.watch([appSrc + '/app/**/*.less', appSrc + '/assets/**/*.less']).on('change', function (path) {
    console.log(path + ' has been changed. Updating.');
    gulp.series(() => transpileMinifyLESS(path), updateWatchDist)();
  });
  gulp.watch([appSrc + '/app/**/*.html']).on('change', function (path) {
    console.log(path + ' has been changed. Updating.');
    gulp.series(inlineTemplate, transpile, updateWatchDist)();
  });
}
513670
function(addExtraWatchers) {
  /* Watchers -------------------------------------------------------------- */
  gulp.task('watch', ['serve'], function () {
    gulp.watch(paths.src.es6, ['bundle-js:dev:clean']);
    gulp.watch(paths.src.js, ['bundle-js:dev:clean']);
    gulp.watch(paths.src.styles, ['styles']);
    gulp.watch(paths.src.views, ['tpl-reload']);
    gulp.watch(paths.out.base + '**/*', ['reload']);

    addExtraWatchers && addExtraWatchers(gulp);
  });
}
385968
function watchifyFile(src, out) {
    var opts = assign({}, watchify.args, {
        entries: src,
        standalone: "NavMesh",
        debug: true
    });
    var b = watchify(browserify(opts));
    function bundle() {
        return b.bundle()
            .on('error', gutil.log.bind(gutil, "Browserify Error"))
            .pipe(source(src.replace(/^src\//, '')))
            .pipe(derequire())
            .pipe(gulp.dest(out));
    }
    b.on('update', bundle);
    b.on('log', gutil.log);
    return bundle();
}
925198
function wrap(superagent, Promise) {
  /**
   * Request object similar to superagent.Request, but with end() returning
   * a promise.
   */
  function PromiseRequest() {
    superagent.Request.apply(this, arguments);
  }

  // Inherit form superagent.Request
  PromiseRequest.prototype = Object.create(superagent.Request.prototype);

  /** Send request and get a promise that `end` was emitted */
  PromiseRequest.prototype.end = function(cb) {
    var _end = superagent.Request.prototype.end;
    var self = this;

    return new Promise(function(accept, reject) {
      _end.call(self, function(err, response) {
        if (cb) {
          cb(err, response);
        }

        if (err) {
          err.response = response;
          reject(err);
        } else {
          accept(response);
        }
      });
    });
  };

  /** Provide a more promise-y interface */
  PromiseRequest.prototype.then = function(resolve, reject) {
    var _end = superagent.Request.prototype.end;
    var self = this;

    return new Promise(function(accept, reject) {
      _end.call(self, function(err, response) {
        if (err) {
          err.response = response;
          reject(err);
        } else {
          accept(response);
        }
      });
    }).then(resolve, reject);
  };

  /**
   * Request builder with same interface as superagent.
   * It is convenient to import this as `request` in place of superagent.
   */
  var request = function(method, url) {
    return new PromiseRequest(method, url);
  };

  /** Helper for making an options request */
  request.options = function(url) {
    return request('OPTIONS', url);
  }

  /** Helper for making a head request */
  request.head = function(url, data) {
    var req = request('HEAD', url);
    if (data) {
      req.send(data);
    }
    return req;
  };

  /** Helper for making a get request */
  request.get = function(url, data) {
    var req = request('GET', url);
    if (data) {
      req.query(data);
    }
    return req;
  };

  /** Helper for making a post request */
  request.post = function(url, data) {
    var req = request('POST', url);
    if (data) {
      req.send(data);
    }
    return req;
  };

  /** Helper for making a put request */
  request.put = function(url, data) {
    var req = request('PUT', url);
    if (data) {
      req.send(data);
    }
    return req;
  };

  /** Helper for making a patch request */
  request.patch = function(url, data) {
    var req = request('PATCH', url);
    if (data) {
      req.send(data);
    }
    return req;
  };

  /** Helper for making a delete request */
  request.del = function(url, data) {
    var req = request('DELETE', url);
    if (data) {
      req.send(data);
    }
    return req;
  };

  // Export the request builder
  return request;
}
1228778
function Bundler(file, cb) {

    var bundler = this, bundle,
        watchMsg = format('Watching bundle %s...', chalk.magenta(file));

    // set entry file for this bundler
    options.browserify.entries = [path.join(options.cwd, file)];

    // initiate bundle
    bundle = watchify(browserify(options.browserify), options.watchify);

    /**
     * on update, log to console and bundle
     * @param  {Array} ev  array of event files
     * @return {undefined}
     */
    bundle.on('update', function(ev) {
      log(format('%s File %s updated. Bundling %s ...',
        chalk.yellow('☀'),
        chalk.magenta(path.relative(options.cwd, ev[0])),
        chalk.magenta(file)
      ));
      bundler.outputBundle();
    });

    /**
     * when bundling, log infos to console
     * @param  {String} msg  bundling info
     * @return {undefined}
     */
    bundle.on('log', function(msg) {
      if (options.watch && !watchMsg) {
        log(format('%s Bundled %s %s',
          chalk.green('✓'),
          chalk.magenta(file),
          chalk.gray(msg)
        ));
      }
    });

    /**
     * bundle and transform to stream
     * @return {Object} gulp stream
     */
    this.outputBundle = function() {
      return streamHandler(
        bundle.bundle()
          .on('error', function(err) {
            log(chalk.red(format('✖ Bundling failed for %s %s',
              chalk.magenta(file),
              chalk.gray('(' + String(err) + ')')
            )));
            this.emit('end');
          })
          .pipe(source(file))
          .pipe(buffer())
          .on('end', function() {
            if (!options.watch) {
              bundle.close();
              return cb();
            } else if (watchMsg) {
              log(watchMsg);
              watchMsg = false;
            }
          })
      );
    };

  }
837809
function requestBundles(requestedLangs = navigator.languages) {
    const newLangs = negotiateLanguages(
      requestedLangs, availableLangs, { defaultLocale }
    );

    const bundles = newLangs.map(
      lang => new ResourceBundle(lang, resIds)
    );

    return Promise.resolve(bundles);
  }
692466
function continuousBundle() {
    const bundle = b => b.bundle()
        .on('error', (err) => {
            notifier.notify({
                title: 'Browserify Error',
                message: err.message,
            });
            gutil.log('Browserify Error', err);
        })
        .pipe(source('crudl.js'))
        .pipe(gulp.dest(dist))
        .on('end', () => {
            notifier.notify({
                title: 'Browserify',
                message: 'OK',
            });
        })
    const opts = assign({}, watchify.args, browersifyOptions, { debug: true });
    const bundler = watchify(browserify(opts).transform(babelify.configure(babelifyOptions)));
    bundler.on('update', () => bundle(bundler)); // on any dep update, runs the bundler
    bundler.on('log', gutil.log); // output build logs to terminal

    return bundle(bundler)
}
1342299
function browserifyAnonymousLabeler(bundler) {
  var isValid = bundler && (typeof bundler === 'object') &&
    (typeof bundler.on === 'function') && (typeof bundler.pipeline === 'object');
  if (isValid) {
    bundler.pipeline
      .get('label')
      .push(anonymousLabeler());
  }
  else {
    throw new Error('Expected a browserify bundler instance');
  }
}
132742
function makeRequest(capturedError) {
      req(app)
        .get('/bundle.js')
        .expect(500)
        .end(function(err, res) {
          if (err) {
            done(err);
          }
          assert.ok(capturedError, 'expected error in onerror');
          assert.equal(res.text, capturedError.stack);
          done();
        });
    }
793237
function(self, agent, id, cb) {
  let msg = {action: 'subscribe', id: id};
  agent.request(Constants.KEYWORDS.MASTER_WATCHER, msg, function(err, servers) {
    if(err) {
      logger.error('subscribeRequest request to master with error: %j', err.stack);
      utils.invokeCallback(cb, err);
    }
    let res = [];
    for(let id in servers) {
      res.push(servers[id]);
    }
    addServers(self, res);
    utils.invokeCallback(cb);
  });
}
1299970
function wrapRequestHandler(func) {
  return function handler(req, res, next) {
    try {
      const result = func(req, res, next)
      if (result && result.catch) result.catch(e => next(e))
    } catch(e) {
      next(e)
    }
  }
}
791275
function watch(watchOptions) {

      var watcher = chokidar.watch(watchOptions.dirs, {
        ignoreInitial: true,
        ignored: /[/\\]\./
      });

      watcher.on('add', function(pathFile) {
        onWatcher(pathFile);
      });

      watcher.on('change', function(pathFile) {
        onWatcher(pathFile);
      });

      watcher.on('unlink', function(pathFile) {
        onWatcher(pathFile);
      });

      var updating = false;
      var queued = null;

      function onWatcher(pathFile) {

        if (updating) {
          queued = pathFile;
          return;
        }

        queued = null;
        updating = true;

        return Promise.resolve()
          .then(function() {
            return watchOptions.onFile(pathFile);
          })
          .then(function() {
            return Promise.delay(1000);
          })
          .then(function() {
            updating = false;
            if (queued) {
              return onWatcher(queued);
            }
          });
      }
    }
283395
function bundleUp(bundler) {
  return bundler
    .bundle()
    .on('error', logAndEndStream)
    .pipe(source('ng-redux-dev-tools.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({
      loadMaps: true
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'));
}
550822
function(options, cb) {
    console.log('/watch/request', options);
    publish('/watch/request', options);
    fayeClient.subscribe('/watch/results/' + clientID, cb);
  }
667074
function buildScript(file, watch) {
  var props = {
    entries: [ 'example/_src/jsx/app.js'],
    debug : false,
    transform:  [babelify]
  };

  // watchify() if watch requested, otherwise run browserify() once
  var bundler = watch ? watchify(browserify(props)) : browserify(props);


  function rebundle() {
    var stream = bundler.bundle();
    return stream
      .on('error', handleErrors)
      .pipe(source(file))
      // .pipe(gulp.dest(exampleDir + '/js/'))
      // If you also want to uglify it
      .pipe(buffer())
      // .pipe(uglify())
      .pipe(rename('app.js'))
      .pipe(gulp.dest('example/js/'))
      // .pipe(reload({stream:true}))
  }

  // listen for an update and run rebundle
  bundler.on('update', function() {
    rebundle();
    gutil.log('Rebundle...');
  });

  // run it once the first time buildScript is called
  return rebundle();
}