Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

1.1 KB
Raw Blame
// Leaf contract shared by route handlers and the dispatch table so built-in
// routes do not form a circular ESM import with ./table.ts.
import type { IncomingMessage, ServerResponse } from "node:http";
import type { json, readBody } from "../harness/http.ts";
import type { RequestAuth } from "../request-auth.ts";

export const PASS: unique symbol = Symbol("route.pass");

export interface RouteContext {
  req: IncomingMessage;
  res: ServerResponse;
  url: URL;
  path: string;
  method: string;
  auth: RequestAuth;
  json: typeof json;
  readBody: typeof readBody;
}

/** Resolve with PASS to decline; anything else means the request was answered. */
export type RouteHandler = (ctx: RouteContext) => Promise<typeof PASS | void>;

/** True means stop routing. A handler that wrote a response but returned PASS still counts as answered. */
export async function dispatchRoutes(routes: readonly RouteHandler[], ctx: RouteContext): Promise<boolean> {
  for (const route of routes) {
    const out = await route(ctx);
    if (out !== PASS || ctx.res.headersSent || ctx.res.writableEnded) return true;
  }
  return false;
}