/* istanbul ignore next: untestable with Karma
498777
function beforeUnloadHook() {
    // Synchronously check to see if any route hooks want
    // to prevent the current window/tab from closing.
    if (state.routes) {
      var hooks = getRouteHooksForRoutes(state.routes);

      var message = void 0;
      for (var i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) {
        // Passing no args indicates to the user that this is a
        // beforeunload hook. We don't know the next location.
        message = hooks[i]();
      }

      return message;
    }
  }
1358273
function(req, res, next) {
                if (req.headers.accept && req.headers.accept.startsWith('text/html')) {
                  req.url = '/index.html'; // eslint-disable-line no-param-reassign
                }
                next();
              }
532096
function silentHttpError(code, data, message, e) {
    var stack;

    if (Type.isObject(e)) {
        if (e && e.message) {
            message = message + ', ' + e.message;
        }
        stack = e.stack;
        e = null;
    } else if (Type.isString(e)) {
        stack = e;
    } else {
        e = new Error();
        stack = e.stack;
    }

    return toString('SlientHttpError', core.trace(8, 9), message, stack, core.inspect(data), code);
}
241033
function UncaughtExceptionHandler(error) {
    // Call module.exports.crit here so that we can intercept the call in the tests
    module.exports.crit(`Unhandled exception: ${error.message}`);
    module.exports.crit(error.stack.toString());
    process.exit(1);
}
496041
function EvalRoute (ctx, next) {
	let router = this;
	let matched = router.match(router.opts.routerPath || ctx.routerPath || ctx.path, ctx.method);
	/* istanbul ignore else */
	if (ctx.matched) {
		ctx.matched.push.apply(ctx.matched, matched.path);
	} else {
		ctx.matched = matched.path;
	}
	if (matched.route) {
		return this.middleware()(ctx, next);
	} else {
		return Promise.resolve('koaton-no-route');
	}
}
586234
function rewrite(req, res) {

  /* istanbul ignore next: tough to mock fs write error */
  function onError(err) {
    this.conf.removeAllListeners('error');
    this.conf.removeAllListeners('write');
    res.send(err);
  }

  function onWrite() {
    this.conf.removeAllListeners('error');
    this.conf.removeAllListeners('write');
    res.send(null, Constants.OK);
  }

  this.conf.once('error', onError.bind(this));
  this.conf.write(this.conf.getFile(), onWrite.bind(this));
}
142088
function createDone({ meta, emit, test: t, options, same }) {
  return function ondone(result) {
    let test = null;

    /* istanbul ignore if */
    if (same) {
      test = testsCache[t.title];
    } else {
      test = Object.assign({}, t, result, { isPending: false });
    }

    const { reason, ...testObject } = test;

    /* istanbul ignore if */
    if (options.snapshots) {
      testsCache[test.title] = testObject;
      testsCache[test.title].run = false;
    }

    if (test.isRejected) {
      meta.stats.fail += 1;

      test.reason.stack = cleanup(test.reason.stack);
      emit('fail', meta, test);

      /* istanbul ignore if */
      if (options.snapshots) {
        testsCache[test.title].reason = { stack: reason && reason.stack };
      }
    }
    if (test.isFulfilled) {
      if (test.skip) {
        emit('skip', meta, test);
      } else if (test.todo) {
        emit('todo', meta, test);
      } else {
        meta.stats.pass += 1;
        emit('pass', meta, test);
      }
    }

    emit('afterEach', meta, test);
    return test;
  };
}
480606
function callNext() {
			/* istanbul ignore next */
			if (queue.length == 0) return;

			/* istanbul ignore next */
			if (currentInFlight >= opts.concurrency) return;

			const item = queue.shift();

			currentInFlight++;
			handler(item.ctx)
				.then(res => {
					currentInFlight--;
					item.resolve(res);
					callNext();
				})
				.catch(err => {
					currentInFlight--;
					item.reject(err);
					callNext();
				});
		}
1294739
function tryCatchReject(f, x, thisArg, next) {
			try {
				next.become(getHandler(f.call(thisArg, x)));
			} catch(e) {
				next.become(new Rejected(e));
			}
		}
1201684
function (fn, repeatTest = 0, args = []) {
    /**
     * if a new hook gets executed we can assume that all commands should have finised
     * with exception of timeouts where `commandIsRunning` will never be reset but here
     */
    // commandIsRunning = false

    return new Promise((resolve, reject) => {
        try {
            const res = fn.apply(this, args)
            resolve(res)
        } catch (e) {
            if (repeatTest) {
                return resolve(executeSync(fn, --repeatTest, args))
            }

            /**
             * no need to modify stack if no stack available
             */
            if (!e.stack) {
                return reject(e)
            }

            e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
            reject(e)
        }
    })
}
1196280
function clean(post) {
  return reject({
    title: post.title,
    contentFormat: post.contentFormat,
    content: post.content,
    tags: post.tags,
    canonicalUrl: post.canonicalUrl,
    publishStatus: post.publishStatus,
    license: post.license
  });
}
405006
async function crash (reason_, runHooks_, timeout_) {
    const reason = reason_ || 0;
    const runHooks = (typeof runHooks_ !== 'undefined') ? runHooks_ : true
    const timeout = timeout_ || 5000;

    // NOTE: All hooks are stored as promise-returning functions.  This allows
    // this code to be uniform as hell.

    /* Avoid running hooks multiple times */
    const wasCrashed = G.crashed;
    G.crashed = true;

    /* wait for hooks to complete */
    if (runHooks && !wasCrashed) {
        /* Set the timeout */
        setTimeout(crash.bind(null, EXIT_TIMEOUT, false), timeout).unref();

        /* Get all hook promises */
        const promises = G.hooks.map(fn => fn(reason));
        await Promise.settle(promises);
    }

    /* find out the exit code we should use */
    const exitCode = calcExitCode(reason);
    process.exit(exitCode);
}
203779
function isVulnerable (body) {
	// Reject invalid queries
	if (!body) {
		return Promise.resolve(PATTERN_INVALID);
	}
	let isInvalid = false;
	['pattern', 'language'].forEach((f) => {
		if (!body.hasOwnProperty(f) || body[f] === null) {
			isInvalid = true;
		}
	});
	if (isInvalid) {
		return Promise.resolve(PATTERN_INVALID);
	}

	log(`isVulnerable: Connecting to ${dbUrl}`);
	return MongoClient.connect(dbUrl)
		.then((client) => {
			log(`isVulnerable: Connected`);

			const db = client.db(dbName);
			log(`isVulnerable: Got db ${dbName}`);

			return collectionLookup(db.collection(dbLookupCollectionName), {pattern: body.pattern, language: body.language})
				.then((result) => {
					client.close();
					return result;
				})
				.catch((e) => {
					log(`isVulnerable: db error: ${e}`);
					client.close();
					return Promise.resolve(PATTERN_UNKNOWN);
				});
		})
		.catch((e) => {
			log(`isVulnerable: db error: ${e}`);
			return Promise.resolve(PATTERN_UNKNOWN);
		});
}
1155887
function unwrapSync (x) {
  if (!x || (typeof x !== 'object' && typeof x !== 'function')) {
    return x
  }

  const then = x.then
  if (typeof then !== 'function') return x

  let state = constants.PENDING
  let value
  const unwrapValue = y => {
    if (state === constants.PENDING) {
      state = constants.RESOLVED
      value = y
    }
  }
  const unwrapReason = r => {
    if (state === constants.PENDING) {
      state = constants.REJECTED
      value = r
    }
  }
  then.call(x, unwrapValue, unwrapReason)

  if (state === constants.PENDING) {
    state = constants.ASYNC
    throw new UnwrapError(x)
  }

  if (state === constants.RESOLVED) {
    return unwrapSync(value)
  }

  // state === REJECTED
  throw value
}
766710
function wrapReplEval(replServer) {
  const defaultEval = replServer.eval;

  return function(code, context, file, cb) {
    return defaultEval.call(this, code, context, file, (err, result) => {
      if (!result || !result.then) {
        return cb(err, result);
      }

      result.then(resolved => {
        resolvePromises(result, resolved);
        cb(null, resolved);
      }).catch(err => {
        resolvePromises(result, err);

        console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m');
        if (err && err.message) {
          console.log('\x1b[31m' + err.message + '\x1b[0m');
        }

        // Application errors are not REPL errors
        cb(null, err);
      });
    });

    function resolvePromises(promise, resolved) {
      Object.keys(context).forEach(key => {
        // Replace any promise handles in the REPL context with the resolved promise
        if (context[key] === promise) {
          context[key] = resolved;
        }
      });
    }
  };
}
922928
function _isValidProofHandle(handle) {
  if (
    !_isEmpty(handle) &&
    _isObject(handle) &&
    _has(handle, 'uri') &&
    _has(handle, 'hashIdNode')
  ) {
    return true
  }
}
1079468
function cleanUpOldExecutable(next) {
        fs.unlink(nodeCompiler.releasePath, function(err) {
          if (err) {
            if (err.code === 'ENOENT') {
              next();
            } else {
              throw err;
            }
          } else {
            next();
          }
        });
      }