cloud / internal-packages / installer / test / fake-cloudflare.mjsmain at aacbc74
// A FAKE CLOUDFLARE for the domain wizard's end-to-end test: one world of pretend/world.js (OAuth,
// the API calls the wizard makes, the dashboard pages it links to), in memory, over Node http.
// The same module runs deployed as the pretend Cloudflare (pretend/worker.js); what it answers,
// and why, is written there.
// const cf = await startFakeCloudflare({ port, user, accounts, taken }) → { origin, state, close }
import http from "node:http";
import { handle, newWorld } from "../pretend/world.js";
export async function startFakeCloudflare({
port = 0,
user = { email: "ada@example.com", first: "Ada", last: "Lovelace" },
accounts = [],
taken = [],
} = {}) {
const state = newWorld({ user, accounts, taken });
const server = http.createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const method = req.method || "GET";
const request = new Request(`http://${req.headers.host}${req.url}`, {
method,
headers: Object.entries(req.headers).flatMap(([k, v]) =>
v === undefined ? [] : [[k, Array.isArray(v) ? v.join(", ") : v]],
),
body: method === "GET" || method === "HEAD" ? undefined : Buffer.concat(chunks),
});
try {
// quoteNeeds "paid": the test takes Workers Paid away to get the answer for "no payment method"
const answer = await handle(state, request, { testControls: true, quoteNeeds: "paid" });
res.writeHead(answer.status, Object.fromEntries(answer.headers));
res.end(Buffer.from(await answer.arrayBuffer()));
} catch (error) {
res.writeHead(500, { "content-type": "text/plain" });
res.end(String(error?.stack || error));
}
});
await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));
return {
origin: `http://127.0.0.1:${server.address().port}`,
state,
close: () => new Promise((resolve) => server.close(resolve)),
};
}