import { beforeEach, describe, expect, mock, test } from "bun:test"; import { scopedTestState } from "./scoped.test-helper"; const fakeEnv: Record = {}; mock.module("cloudflare:workers", () => ({ env: fakeEnv, waitUntil: () => undefined })); mock.module("./directory", () => ({ forgetSiteDirectory: async () => undefined })); mock.module("../db", () => ({ all: async () => [{ id: "r1" }] })); const scoped = scopedTestState(); scoped.install(); scoped.site({ id: "s1", repo_id: "r1", owner_id: "acct", label: "app--alice", custom_domain: "Shop.Example" }); scoped .repo("r1") .run( "INSERT INTO site_pr_aliases (site_id, label, pr_number, kind, deployment_id, created_at) VALUES ('s1', 'pr-3--app--alice', 3, 'pr', 'd', 0)", ); const { accountSitesHosts, purgeAccountHostingCache } = await import("./cache-purge"); const calls: { url: string; hosts: string[] }[] = []; const realFetch = globalThis.fetch; beforeEach(() => { calls.length = 0; for (const key of Object.keys(fakeEnv)) delete fakeEnv[key]; fakeEnv.PUBLIC_URL = "https://forge.test"; fakeEnv.SITES_DOMAIN = "sites-static.test"; globalThis.fetch = (async (url: string, init: RequestInit) => { calls.push({ url, hosts: JSON.parse(String(init.body)).hosts }); return new Response("{}"); }) as typeof fetch; }); describe("hosting cache purge", () => { test("lists Sites hosts", async () => { expect(await accountSitesHosts("acct")).toEqual({ labels: ["app--alice.sites-static.test", "pr-3--app--alice.sites-static.test"], custom: ["shop.example"], }); }); test("does nothing without Cloudflare credentials", async () => { fakeEnv.CUSTOM_DOMAINS_ZONE_ID = "zone"; expect(await purgeAccountHostingCache("acct")).toBe(0); expect(calls).toHaveLength(0); }); test("purges custom domains in the SaaS zone and site labels in the sites zone", async () => { fakeEnv.CUSTOM_DOMAINS_ZONE_ID = "pz"; fakeEnv.SITES_ZONE_ID = "sz"; fakeEnv.CF_API_TOKEN = "token"; expect(await purgeAccountHostingCache("acct")).toBe(3); expect(calls.map((call) => [call.url.split("/zones/")[1], call.hosts.length])).toEqual([ ["pz/purge_cache", 1], ["sz/purge_cache", 2], ]); expect(calls[0]?.hosts).toContain("shop.example"); globalThis.fetch = realFetch; }); });