|
| 1 | +import { NextRequest } from 'next/server' |
| 2 | +import { markInternalRequest } from '@/lib/api/server/routes/internal-request' |
| 3 | +import { V2_ROUTES } from '@/lib/api/server/routes/v2-route-table.generated' |
| 4 | + |
| 5 | +/** |
| 6 | + * A `fetch` that answers the server's own v2 requests in-process. |
| 7 | + * |
| 8 | + * The embedded CLI and the agent-cli engines are typed v2 clients. Pointing them at |
| 9 | + * the server's URL made every tool call a network round trip through the proxy, |
| 10 | + * API-key authentication, the abuse rate limits, and the proxy body ceiling — a |
| 11 | + * grep over one block definition cost seconds and tripped the per-key limit. This |
| 12 | + * transport resolves the request's path against the generated route table and |
| 13 | + * invokes the route handler directly, with the request marked internal so |
| 14 | + * admission authenticates it but does not rate-limit it. Contracts, use cases, |
| 15 | + * presenters, and error envelopes are untouched: the handler that runs is the one |
| 16 | + * the network path would run. |
| 17 | + * |
| 18 | + * Anything outside the v2 table falls through to real `fetch`. |
| 19 | + */ |
| 20 | + |
| 21 | +type RouteHandler = ( |
| 22 | + request: NextRequest, |
| 23 | + context: { params: Promise<Record<string, string>> } |
| 24 | +) => Promise<Response> |
| 25 | + |
| 26 | +interface CompiledRoute { |
| 27 | + regex: RegExp |
| 28 | + params: string[] |
| 29 | + /** Literal segments — a more specific pattern wins over a parameterized one. */ |
| 30 | + literals: number |
| 31 | + load: () => Promise<object> |
| 32 | +} |
| 33 | + |
| 34 | +interface MatchedRoute { |
| 35 | + params: Record<string, string> |
| 36 | + literals: number |
| 37 | + load: () => Promise<object> |
| 38 | +} |
| 39 | + |
| 40 | +const COMPILED: CompiledRoute[] = V2_ROUTES.map((route) => { |
| 41 | + const params: string[] = [] |
| 42 | + let literals = 0 |
| 43 | + const source = route.pattern |
| 44 | + .split('/') |
| 45 | + .map((segment) => { |
| 46 | + const param = /^\{(.+)\}$/.exec(segment) |
| 47 | + if (!param?.[1]) { |
| 48 | + literals += 1 |
| 49 | + return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') |
| 50 | + } |
| 51 | + params.push(param[1]) |
| 52 | + return '([^/]+)' |
| 53 | + }) |
| 54 | + .join('/') |
| 55 | + return { regex: new RegExp(`^${source}$`), params, literals, load: route.load } |
| 56 | +}) |
| 57 | + |
| 58 | +export function matchV2Route(pathname: string): MatchedRoute | null { |
| 59 | + let best: MatchedRoute | null = null |
| 60 | + for (const route of COMPILED) { |
| 61 | + const match = route.regex.exec(pathname) |
| 62 | + if (!match) continue |
| 63 | + if (best && best.literals >= route.literals) continue |
| 64 | + const params: Record<string, string> = {} |
| 65 | + route.params.forEach((name, index) => { |
| 66 | + params[name] = decodeURIComponent(match[index + 1] ?? '') |
| 67 | + }) |
| 68 | + best = { params, literals: route.literals, load: route.load } |
| 69 | + } |
| 70 | + return best |
| 71 | +} |
| 72 | + |
| 73 | +function requestUrl(input: RequestInfo | URL): URL { |
| 74 | + if (typeof input === 'string') return new URL(input) |
| 75 | + if (input instanceof URL) return input |
| 76 | + return new URL(input.url) |
| 77 | +} |
| 78 | + |
| 79 | +export function createInProcessTransport(): typeof fetch { |
| 80 | + return async (input, init) => { |
| 81 | + const url = requestUrl(input) |
| 82 | + const method = (init?.method ?? 'GET').toUpperCase() |
| 83 | + const matched = url.pathname.startsWith('/api/v2/') ? matchV2Route(url.pathname) : null |
| 84 | + if (!matched) return fetch(input, init) |
| 85 | + const handler = Reflect.get(await matched.load(), method) |
| 86 | + if (typeof handler !== 'function') return fetch(input, init) |
| 87 | + const request = new NextRequest(url, { |
| 88 | + method, |
| 89 | + headers: init?.headers, |
| 90 | + body: init?.body ?? null, |
| 91 | + signal: init?.signal ?? undefined, |
| 92 | + }) |
| 93 | + markInternalRequest(request) |
| 94 | + return (handler as RouteHandler)(request, { params: Promise.resolve(matched.params) }) |
| 95 | + } |
| 96 | +} |
0 commit comments