cloud / scripts / zone-enrollment / only-the-fake.tsmain at aacbc74
// only-the-fake.ts — THE FIXTURE'S ONE WAY OUT: loaded before Alchemy's CLI (`node --import`), it
// replaces `fetch`, so that a call to Cloudflare's API goes to the test's fake
// (FAKE_CLOUDFLARE, an address on 127.0.0.1) and a call to any other address is refused and
// written to REFUSED_CALLS, one line each. Alchemy's own sign-in by environment variables reads
// no other address for the API (2.0.0-beta.87), so the address is replaced here.
import { appendFileSync } from "node:fs";
const API = "https://api.cloudflare.com/client/v4";
const fake = process.env.FAKE_CLOUDFLARE;
const refusedFile = process.env.REFUSED_CALLS;
if (!fake || !/^http:\/\/127\.0\.0\.1:\d+\//.test(fake) || !refusedFile)
throw new Error("only-the-fake.ts needs FAKE_CLOUDFLARE on 127.0.0.1 and REFUSED_CALLS");
const real = globalThis.fetch;
globalThis.fetch = (input, init) => {
const url = input instanceof Request ? input.url : String(input);
// undici's own first fetch, which reaches no network (alchemy/Util/Http1Dispatcher)
if (url.startsWith("data:")) return real(input, init);
if (url === API || url.startsWith(`${API}/`) || url.startsWith(`${API}?`)) {
const there = fake + url.slice(API.length);
return real(input instanceof Request ? new Request(there, input) : there, init);
}
appendFileSync(refusedFile, `${init?.method || "GET"} ${url}\n`);
return Promise.reject(new TypeError(`the fixture reaches the fake alone, not ${url}`));
};