Files
proxy-bun/api/relay.ts
T
MythEclipseandClaude Opus 4.8 fc69a0e93c refactor: konsolidasi handler ke router.ts + complexity + test coverage
=== DRY Konsolidasi ===
- handleRelay, requireAuth, handleHealth, handleIndex, getClientIP → 1x di src/lib/router.ts
- api/relay.ts, src/worker.ts, src/index.ts jadi thin wrapper

=== Dead exports ===
- 35 dead exports dibersihkan (dari router.ts, worker.ts, relay.ts)
- Duplikasi simbol dari 12 ke 3 (wajar)

=== Keamanan ===
- Default API key sk-dummy-key dihapus — requireAuth return null saat key kosong
- Semua CORS konsisten via getCorsHeaders()

=== Kompleksitas ===
- handleRequest → pecah ke validateRelayTarget, createJsonErrorResponse, dll
- transformAnthropicStream (170 baris) → 4 sub-fungsi (emitInitEvents, emitDoneEvents, etc)
- handleAnthropicMessages → handleUpstreamError, buildStreamHeaders, buildJsonHeaders
- Fix duplicate stream? field di AnthropicRequest interface

=== Test Coverage ===
- Test naik dari 171 ke 248 (+77 test)
- File baru: src/router.test.ts (requireAuth, getClientIP, CORS, health, index)
- File baru: src/relay-integration.test.ts (filterResponseHeaders, shouldSendBody, buildRelayRequest, classifyFetchError, createRelayResponse, normalizeTargetUrl, SSRF, isPrivateIp)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 23:48:16 +07:00

62 lines
1.6 KiB
TypeScript

/**
* Vercel-compatible relay handler (Bun runtime).
*
* Thin wrapper around the shared router in src/lib/router.ts.
* Does NOT call Bun.serve() (Vercel manages the server).
* Does NOT support WebSocket upgrades.
*/
import {
handleRelayPlain,
handleRequest,
getClientIP,
} from "../src/lib/router";
import type { RouterEnv } from "../src/lib/router";
import { getTestPageHtml } from "../src/lib/test-page";
// --- Singletons (survives warm invocations) ----------------------------------
const routerEnv: RouterEnv = {};
/**
* Hybrid handler for Vercel/Node web-api and Bun/Workers runtimes.
*/
async function fetchHandler(req: Request): Promise<Response> {
const url = new URL(req.url);
const clientIP = getClientIP(req);
// Static routes
if (url.pathname === "/health") {
const { handleHealth } = await import("../src/lib/router");
return handleHealth();
}
if (url.pathname === "/docs" || url.pathname === "/test") {
return new Response(getTestPageHtml(), {
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
if (
url.pathname === "/" &&
req.method === "GET" &&
!req.headers.get("x-relay-target")
) {
const { handleIndex } = await import("../src/lib/router");
return handleIndex();
}
// Delegate to shared router (handles AI proxy, model list, relay)
const result = await handleRequest(req, routerEnv, clientIP, {
isWebSocketSupported: false,
skipProxyPool: true,
});
if (result !== undefined) return result;
// Fallback (shouldn't reach here for relay)
return handleRelayPlain(req, routerEnv, clientIP);
}
export default Object.assign(fetchHandler, {
fetch: fetchHandler,
});