|
| 1 | +import type { IncomingMessage, ServerResponse } from 'node:http'; |
| 2 | +import { Buffer } from 'node:buffer'; |
| 3 | +import { createHttpTestServer, type HttpTestServer } from './create-http-test-server.ts'; |
| 4 | +import type { MiniCloudflareDeployment } from '../providers/mini-cloudflare.ts'; |
| 5 | + |
| 6 | +export interface MiniCloudflarePreviewServer { |
| 7 | + readonly origin: string; |
| 8 | + readonly url: string; |
| 9 | + readonly server: HttpTestServer['server']; |
| 10 | + close(): Promise<void>; |
| 11 | +} |
| 12 | + |
| 13 | +export interface ServeMiniCloudflareDeploymentOptions { |
| 14 | + basePath?: string; |
| 15 | +} |
| 16 | + |
| 17 | +export async function serveMiniCloudflareDeployment( |
| 18 | + deployment: MiniCloudflareDeployment, |
| 19 | + options: ServeMiniCloudflareDeploymentOptions = {} |
| 20 | +): Promise<MiniCloudflarePreviewServer> { |
| 21 | + const basePath = normalizeBasePath(options.basePath ?? '/'); |
| 22 | + const server = await createHttpTestServer(async (request, response) => { |
| 23 | + try { |
| 24 | + await proxyToDeployment(deployment, basePath, request, response); |
| 25 | + } catch (error) { |
| 26 | + response.writeHead(500, { |
| 27 | + 'content-type': 'text/plain; charset=utf-8' |
| 28 | + }); |
| 29 | + response.end(error instanceof Error ? error.message : String(error)); |
| 30 | + } |
| 31 | + }); |
| 32 | + |
| 33 | + return { |
| 34 | + origin: server.origin, |
| 35 | + url: `${server.origin}${basePath === '/' ? '/' : `${basePath}/`}`, |
| 36 | + server: server.server, |
| 37 | + close() { |
| 38 | + return server.close(); |
| 39 | + } |
| 40 | + }; |
| 41 | +} |
| 42 | + |
| 43 | +async function proxyToDeployment( |
| 44 | + deployment: MiniCloudflareDeployment, |
| 45 | + basePath: string, |
| 46 | + incoming: IncomingMessage, |
| 47 | + outgoing: ServerResponse |
| 48 | +): Promise<void> { |
| 49 | + const method = incoming.method ?? 'GET'; |
| 50 | + const incomingUrl = new URL(incoming.url ?? '/', 'http://localhost'); |
| 51 | + if (basePath !== '/' && !matchesBasePath(incomingUrl.pathname, basePath)) { |
| 52 | + outgoing.writeHead(404, { |
| 53 | + 'content-type': 'text/plain; charset=utf-8' |
| 54 | + }); |
| 55 | + outgoing.end('Not Found'); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + const target = new URL(stripBasePath(incomingUrl.pathname, basePath), deployment.origin); |
| 60 | + target.search = incomingUrl.search; |
| 61 | + const headers = headersFromIncoming(incoming); |
| 62 | + const body = method === 'GET' || method === 'HEAD' |
| 63 | + ? undefined |
| 64 | + : await readIncomingBody(incoming); |
| 65 | + const request = new Request(target, { |
| 66 | + method, |
| 67 | + headers, |
| 68 | + body, |
| 69 | + duplex: body ? 'half' : undefined |
| 70 | + } as RequestInit & { duplex?: 'half' }); |
| 71 | + |
| 72 | + const response = await deployment.fetch(request); |
| 73 | + const responseHeaders = headersToOutgoing(response.headers); |
| 74 | + outgoing.writeHead(response.status, response.statusText, responseHeaders); |
| 75 | + const responseBody = Buffer.from(await response.arrayBuffer()); |
| 76 | + outgoing.end(responseBody); |
| 77 | +} |
| 78 | + |
| 79 | +function headersFromIncoming(request: IncomingMessage): Headers { |
| 80 | + const headers = new Headers(); |
| 81 | + for (const [name, value] of Object.entries(request.headers)) { |
| 82 | + if (value === undefined) { |
| 83 | + continue; |
| 84 | + } |
| 85 | + if (Array.isArray(value)) { |
| 86 | + for (const item of value) { |
| 87 | + headers.append(name, item); |
| 88 | + } |
| 89 | + } else { |
| 90 | + headers.set(name, value); |
| 91 | + } |
| 92 | + } |
| 93 | + return headers; |
| 94 | +} |
| 95 | + |
| 96 | +function headersToOutgoing(headers: Headers): Record<string, string[]> { |
| 97 | + const outgoing: Record<string, string[]> = {}; |
| 98 | + for (const [name, value] of headers) { |
| 99 | + outgoing[name] = [...(outgoing[name] ?? []), value]; |
| 100 | + } |
| 101 | + return outgoing; |
| 102 | +} |
| 103 | + |
| 104 | +async function readIncomingBody(request: IncomingMessage): Promise<Buffer> { |
| 105 | + const chunks: Buffer[] = []; |
| 106 | + for await (const chunk of request) { |
| 107 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); |
| 108 | + } |
| 109 | + return Buffer.concat(chunks); |
| 110 | +} |
| 111 | + |
| 112 | +function normalizeBasePath(value: string): string { |
| 113 | + const trimmed = value.trim(); |
| 114 | + if (!trimmed || trimmed === '/') { |
| 115 | + return '/'; |
| 116 | + } |
| 117 | + return `/${trimmed.replace(/^\/+|\/+$/g, '')}`; |
| 118 | +} |
| 119 | + |
| 120 | +function matchesBasePath(pathname: string, basePath: string): boolean { |
| 121 | + return pathname === basePath || pathname.startsWith(`${basePath}/`); |
| 122 | +} |
| 123 | + |
| 124 | +function stripBasePath(pathname: string, basePath: string): string { |
| 125 | + if (basePath === '/') { |
| 126 | + return pathname; |
| 127 | + } |
| 128 | + const stripped = pathname.slice(basePath.length); |
| 129 | + return stripped.startsWith('/') ? stripped : `/${stripped}`; |
| 130 | +} |
0 commit comments