iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / container / takeover.mjsmain at aacbc74

// takeover.mjs — "ERASE AND REPLACE": what is on a person's domain and under a stack's names in
// their account, and how each thing is removed. No imports: the Worker and the run both read it.
//
//   the Worker   (worker/index.js, GET /api/erase) reads the list for the warning a person agrees to
//   the run      (erase.mjs, from run.sh) reads it again, erases it, and reads until nothing is left
//
// `cf(method, path, body)` is one call of Cloudflare's API with the person's token. It answers
// `{ status, success, result, errors, result_info }` and does not throw for a refusal.
//
// NEVER REMOVED: the zone itself, its plan, its nameservers, DNSSEC and its registration; another
// zone; Email Routing's destination addresses; a tunnel, a Pages project or an R2 bucket that only
// has a name on this zone; a Worker that is not this stack's (only its routes and domains here);
// the account's members, tokens and billing.
//
// An item: { kind, id, name, group, text, act, calls }
//   act "erase"   the run removes it with `calls`
//   act "with"    it goes when its keeper goes (a record that Email Routing keeps)
//   act "refuse"  the run cannot remove it: the person does, and nothing is erased before
//   group         "sites" | "mail" | "rules" | "dns" | "iterate": where the warning shows it
//   soft          a refusal to remove it does not stop the erase: the run says that it is left
//
// A BUCKET THAT R2 CALLS "NOT EMPTY" WITH NO FILE IN IT. A log pipeline's sink writes each file as
// an upload in parts and ends it once a minute. A pipeline that is deleted in the middle of one
// leaves the upload unfinished. The list of the bucket's files does not show it, R2 refuses to
// delete the bucket (10008), and only R2's S3 API can end such an upload: that takes the keys of
// an API token, which a sign-in at Cloudflare does not have. So the erase does two things:
//   1. it waits for the sinks to end their files (SINKS_END_MS) after it has erased what writes
//      to the pipelines (the stack's Workers and log destinations) and before it erases a pipeline
//   2. a bucket that R2 still refuses, with no file in its list, is LEFT: the run sets a rule on
//      it that removes unfinished uploads after a day, says so, and goes on. The next erase takes it.
//
// A FILE WHOSE KEY IS `.` OR `..`. A file is deleted at `…/objects/<key>`, and no address names
// such a key (`unnameable`): the request would go to the folder or to the bucket. So the erase
// sends none for it, removes every other file, LEAVES the bucket, says which files stay, and goes
// on. It sets no rule: the only rule that removes a file removes every file of the bucket after a
// day, and a new deployment can be using the bucket by then.
//
// THE TABLES OF A DATA CATALOG OUTLIVE ITS BUCKET. R2 keeps a catalog that was turned off, with
// its tables, also when its bucket is deleted, and gives them back to a new bucket of the same
// name. A log pipeline's sink refuses a table that exists ("writing to existing Catalog tables is
// not yet supported"), so the next deployment with telemetry on the domain would get no
// telemetry. So the erase drops the stack's three tables and their namespace before it turns the
// catalog off. Only the catalog's Iceberg address (CATALOG) drops a table. Each is `soft`.

/** Every name a stack's resources have had (core/alchemy/src/config.ts `resourceNamesOf`): a
 *  stack from before 11 November 2026 has `-ingress` and `-project` where a later one has
 *  `-boundary` and `-mind`. Exact names: a prefix would also match the stack of a longer domain
 *  name. */
export function namesOf(name) {
  const prefix = `iterate-${name}`;
  const store = `${prefix}-state`;
  return {
    prefix,
    workers: [
      `iterate-${name}-project`,
      ...["ingress", "boundary", "secrets", "auth", "mind", "telemetry"].map(
        (part) => `${prefix}-${part}`,
      ),
    ],
    store,
    d1: [`${prefix}-auth-db`],
    kv: [`${prefix}-auth-kv`, `iterate-${name}-project-kv`, `${prefix}-mind-kv`],
    r2: [`${prefix}-files`, `${prefix}-telemetry`],
    artifacts: `${prefix}-repos`,
    // the telemetry part (core/alchemy/src/stack.ts `telemetryPart`), beside its Worker and bucket
    telemetry: {
      worker: `${prefix}-telemetry`,
      bucket: `${prefix}-telemetry`,
      tables: ["events", "logs", "spans"].map(
        (table) => `${prefix.replaceAll("-", "_")}_telemetry_${table}`,
      ),
      destinations: ["logs", "traces"].map((dataset) => `${prefix}-telemetry-${dataset}`),
      tokens: ["catalog", "analytics"].map((use) => `${prefix}-telemetry-${use}`),
    },
    // the mind's own API token (core/alchemy/src/stack.ts `cloudflareTokenPart`): this name, then
    // the edition of its list from the third on (`isMindToken`)
    cloudflareToken: `${prefix}-cloudflare`,
    secrets: ["AlchemyStateStoreToken", "AlchemyStateStoreEncryptionKey"].map(
      (base) => `${base}_${store.replace(/[^A-Za-z0-9_]/g, "_")}`,
    ),
  };
}

/** Whether `name` is the mind's own API token of this stack: its name, with or without the edition
 *  of its list at the end (core/alchemy/src/cloudflare-token.ts `cloudflareTokenNameOf`). */
export const isMindToken = (names, name) =>
  name === names.cloudflareToken ||
  (name.startsWith(`${names.cloudflareToken}-`) &&
    /^\d+$/.test(name.slice(names.cloudflareToken.length + 1)));

/** The name of the Worker that the wizard made until 10 November 2026, for every domain. The
 *  erase takes its routes on the zone and never the Worker: another site may be on it. */
const OLDER_WORKER = "iterate";

/** Whether a Worker is somebody else's: not one of the stack's (`names`: namesOf) and not the
 *  wizard's older Worker. A DOMAIN THAT SERVES SUCH A WORKER IS NEVER ERASED: a route or a custom
 *  domain of one stops the erase (Jonas, 11 November 2026), and the person removes it first. */

export const outsideOf = (names, worker) =>
  !!worker && worker !== OLDER_WORKER && !names.workers.includes(worker);
/** The stop for such a route or custom domain, in plain words. */
const servesAnother = (address, worker) =>
  `${address} is served by the Worker ${worker}, which is not iterate's. iterate never erases a domain that serves another Worker: remove it from that Worker in Cloudflare first, or choose another domain.`;

/** The path of Cloudflare's API for the sites on Pages. */
const PAGES = "pages/projects";

/** Domains that serve more than a deployment: no erase goes near them. */
const NEVER = ["iterate.com", "iterate.app", "garple.com", "templestein.family"];
/** Why a domain is never erased, or null. `host`: where the page that asks is served. */
export function keptOf(zone, host = "") {
  if (NEVER.includes(zone))
    return `${zone} is on the list of domains that iterate never erases: it serves more than a deployment.`;
  if (host === zone || host.endsWith(`.${zone}`))
    return `This page is served from ${zone}, so ${zone} is never erased from here.`;
  return null;
}

/** The order of the erase: what holds a hostname first, then rules, mail, the records, and the
 *  stack's own resources last, its state store at the very end. */
const ORDER = [
  "workers_custom_domain",
  "workers_route",
  "custom_hostname",
  "fallback_origin",
  "pages_custom_domain",
  "r2_custom_domain",
  "access_app",
  "load_balancer",
  "waiting_room",
  "spectrum_app",
  "zone_ruleset",
  "page_rule",
  "snippet",
  "bot_fight_mode",
  "email_routing_rule",
  "email_routing_catch_all",
  "email_routing",
  "email_sending_subdomain",
  "dns_record",
  "container_application",
  "worker",
  // the telemetry part, as its destroy goes: what a Worker names after the Workers, a pipeline
  // before its sink and its stream, the catalog before its bucket
  "observability_destination",
  "pipeline",
  "pipeline_sink",
  "pipeline_stream",
  "d1_database",
  "kv_namespace",
  "r2_catalog_table",
  "r2_catalog_namespace",
  "r2_catalog",
  "r2_bucket",
  "artifacts_namespace",
  "state_store",
  "state_secret",
  "api_token",
];

/** The Iceberg address of an account's data catalogs. A call's path that starts with it goes to
 *  it and not to Cloudflare's API (erase.mjs `cf`). */
export const CATALOG = "https://catalog.cloudflarestorage.com";
/** The tables a stack's log pipelines write (core/alchemy/src/stack.ts `telemetryPart`). */
const LOG_TABLES = { namespace: "telemetry", names: ["events", "logs", "spans"] };

/** What the unread list calls the account's API tokens. */
const API_TOKENS = "the account's API tokens";
/** What the unread list calls the list of a data catalog's tables. */
const CATALOG_TABLES = "the tables in the telemetry bucket's data catalog";

const PHASES = {
  http_request_dynamic_redirect: "Redirect rules",
  http_request_redirect: "Bulk redirect rules",
  http_request_origin: "Origin rules",
  http_request_cache_settings: "Cache rules",
  http_config_settings: "Configuration rules",
  http_request_transform: "URL rewrite rules",
  http_request_late_transform: "Request header rules",
  http_response_headers_transform: "Response header rules",
  http_request_firewall_custom: "Firewall rules",
  http_ratelimit: "Rate limiting rules",
  http_custom_errors: "Custom error rules",
  http_response_compression: "Compression rules",
};

const listOf = (result) => (result == null ? [] : Array.isArray(result) ? result : [result]);
/** What Cloudflare said to a refused call, in one line. */
const saidOf = (answer) =>
  (answer.errors || [])
    .map((e) => `${e.code}: ${e.message}`)
    .concat((answer.messages || []).map((m) => m.message).filter(Boolean))
    .join("; ") || `HTTP ${answer.status}`;
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
/** Names in quotation marks: `"a"`, `"a" and "b"`, `"a", "b" and "c"`. */
const quoted = (names) => {
  const each = names.map((name) => JSON.stringify(name));
  return each.length < 2 ? each.join("") : `${each.slice(0, -1).join(", ")} and ${each.at(-1)}`;
};
const short = (text, most = 70) => {
  const s = String(text ?? "");
  return s.length > most ? `${s.slice(0, most - 1)}…` : s;
};

/** A list that Cloudflare gives in one answer. */
async function whole(cf, path) {
  const answer = await cf("GET", path);
  return answer.success ? { list: listOf(answer.result) } : { refused: answer };
}
/** A list that Cloudflare gives in pages.
 *  @returns {Promise<{ list: any[], refused?: undefined } | { refused: Record<string, any>, list?: undefined }>} */
async function paged(cf, path, per = 100) {
  const list = [];
  let last = "";
  for (let page = 1; page <= 100; page++) {
    const answer = await cf(
      "GET",
      `${path}${path.includes("?") ? "&" : "?"}page=${page}&per_page=${per}`,
    );
    if (!answer.success) return { refused: answer };
    const got = listOf(answer.result);
    // an endpoint that ignores `page` gives the same page again: it has no more
    const seen = JSON.stringify(got);
    if (seen === last) break;
    last = seen;
    list.push(...got);
    const info = answer.result_info || {};
    if (got.length < per) break;
    if (info.total_pages && page >= info.total_pages) break;
    if (info.total_count != null && list.length >= info.total_count) break;
  }
  return { list };
}

/**
 * Everything on the zone, and everything in the account with the stack's names.
 * Answers { items, unread, digest }:
 *   unread   lists Cloudflare did not let us read: { what, said, must }. With `must`, the list is
 *            one the erase cannot go without, and the erase refuses.
 *   digest   names the list: the run erases only the list the person saw.
 */
export async function inventoryOf({ cf, accountId, zoneId, zone, name }) {
  const z = `/zones/${zoneId}`;
  const a = `/accounts/${accountId}`;
  const names = namesOf(name);
  const items = [];
  const unread = [];
  const under = (host) => {
    const h = String(host || "")
      .toLowerCase()
      .replace(/^\*\./, "");
    return h === zone || h.endsWith(`.${zone}`);
  };
  const hostOf = (address) =>
    String(address || "")
      .replace(/^[a-z]+:\/\//, "")
      .split("/")[0];
  /** A list, or nothing and a line in `unread` when Cloudflare refuses it. */
  const read = async (what, must, asked) => {
    const got = await asked;
    if (got.list) return got.list;
    unread.push({ what, said: saidOf(got.refused), must });
    return [];
  };
  const add = (item) => items.push({ act: "erase", calls: [], ...item });

  const records = async () => {
    for (const r of await read("the DNS records", true, paged(cf, `${z}/dns_records`, 500))) {
      const meta = r.meta || {};
      const text = `${r.type} ${r.name} → ${short(r.content)}`;
      if (meta.r2_bucket) {
        add({
          kind: "r2_custom_domain",
          id: r.id,
          name: r.name,
          group: "sites",
          text: `${r.name} → R2 bucket ${meta.r2_bucket}`,
          calls: [
            [
              "DELETE",
              `${a}/r2/buckets/${encodeURIComponent(meta.r2_bucket)}/domains/custom/${encodeURIComponent(r.name)}`,
            ],
          ],
        });
        continue;
      }
      // Cloudflare's own records of the zone: nobody deletes them, and they are in no deploy's way
      const apex = String(r.name).toLowerCase() === zone;
      if (r.type === "SOA" || (r.type === "NS" && apex)) continue;
      const kept = meta.email_routing || meta.origin_worker_id;
      const fixed = meta.read_only || r.read_only;
      add({
        kind: "dns_record",
        id: r.id,
        name: `${r.type} ${r.name}`,
        group: "dns",
        text:
          fixed && !kept
            ? `${text}: another Cloudflare product keeps this record. Remove what uses ${r.name} in the Cloudflare dashboard.`
            : text,
        act: kept ? "with" : fixed ? "refuse" : "erase",
        calls: [["DELETE", `${z}/dns_records/${r.id}`]],
      });
    }
  };

  const routes = async () => {
    for (const r of await read("the Workers routes", true, whole(cf, `${z}/workers/routes`)))
      add({
        kind: "workers_route",
        id: r.id,
        name: r.pattern,
        script: r.script,
        group: names.workers.includes(r.script) ? "iterate" : "sites",
        text: outsideOf(names, r.script)
          ? servesAnother(r.pattern, r.script)
          : r.script
            ? `${r.pattern} → Worker ${r.script}`
            : `${r.pattern} → no Worker`,
        act: outsideOf(names, r.script) ? "refuse" : "erase",
        calls: [["DELETE", `${z}/workers/routes/${r.id}`]],
      });
    for (const d of await read(
      "the Workers custom domains",
      true,
      whole(cf, `${a}/workers/domains?zone_id=${zoneId}`),
    ))
      add({
        kind: "workers_custom_domain",
        id: d.id,
        name: d.hostname,
        group: "sites",
        text: outsideOf(names, d.service)
          ? servesAnother(d.hostname, d.service)
          : `${d.hostname} → Worker ${d.service}`,
        act: outsideOf(names, d.service) ? "refuse" : "erase",
        calls: [["DELETE", `${a}/workers/domains/${d.id}`]],
      });
  };

  const hostnames = async () => {
    for (const h of await read(
      "the custom hostnames",
      false,
      paged(cf, `${z}/custom_hostnames`, 50),
    ))
      add({
        kind: "custom_hostname",
        id: h.id,
        name: h.hostname,
        group: "sites",
        text: `${h.hostname}: a custom hostname that this domain serves`,
        calls: [["DELETE", `${z}/custom_hostnames/${h.id}`]],
      });
    const fallback = await cf("GET", `${z}/custom_hostnames/fallback_origin`);
    if (fallback.success && fallback.result?.origin)
      add({
        kind: "fallback_origin",
        id: "fallback_origin",
        name: fallback.result.origin,
        group: "sites",
        text: `${fallback.result.origin}: the fallback origin of the custom hostnames`,
        calls: [["DELETE", `${z}/custom_hostnames/fallback_origin`]],
      });
    else if (
      !fallback.success &&
      fallback.status !== 404 &&
      !(fallback.errors || []).some((e) => e.code === 1551)
    )
      unread.push({ what: "the fallback origin", said: saidOf(fallback), must: false });
    for (const lb of await read("the load balancers", false, whole(cf, `${z}/load_balancers`)))
      add({
        kind: "load_balancer",
        id: lb.id,
        name: lb.name,
        group: "sites",
        text: `${lb.name}: a load balancer`,
        calls: [["DELETE", `${z}/load_balancers/${lb.id}`]],
      });
    for (const w of await read("the waiting rooms", false, paged(cf, `${z}/waiting_rooms`, 50)))
      add({
        kind: "waiting_room",
        id: w.id,
        name: `${w.host}${w.path || ""}`,
        group: "sites",
        text: `${w.host}${w.path || ""}: a waiting room`,
        calls: [["DELETE", `${z}/waiting_rooms/${w.id}`]],
      });
    for (const s of await read("the Spectrum apps", false, whole(cf, `${z}/spectrum/apps`)))
      add({
        kind: "spectrum_app",
        id: s.id,
        name: s.dns?.name || s.id,
        group: "sites",
        text: `${s.dns?.name || s.id}: a Spectrum app. Remove it in the Cloudflare dashboard.`,
        act: "refuse",
      });
  };

  const mail = async () => {
    const routing = await cf("GET", `${z}/email/routing`);
    if (!routing.success) unread.push({ what: "Email Routing", said: saidOf(routing), must: true });
    else if (routing.result?.enabled || routing.result?.status === "ready")
      add({
        kind: "email_routing",
        id: "email_routing",
        name: zone,
        group: "mail",
        text: `Email Routing for ${zone}: mail to @${zone} stops until iterate is deployed`,
        calls: [
          ["POST", `${z}/email/routing/disable`, {}],
          ["DELETE", `${z}/email/routing/dns`],
        ],
      });
    for (const rule of await read(
      "the Email Routing rules",
      true,
      paged(cf, `${z}/email/routing/rules`, 50),
    )) {
      const all = rule.matchers?.[0]?.type === "all";
      const actions = (rule.actions || [])
        .map((x) => `${x.type}${x.value?.length ? ` ${x.value.join(", ")}` : ""}`)
        .join("; ");
      // every zone has a catch-all: Cloudflare's own (off, drop) is nothing to erase
      if (all && !rule.enabled && (rule.actions || []).every((x) => x.type === "drop")) continue;
      const id = rule.tag || rule.id;
      add({
        kind: all ? "email_routing_catch_all" : "email_routing_rule",
        id,
        name: all ? "catch-all" : rule.matchers?.map((m) => m.value).join(", ") || id,
        group: "mail",
        text: all
          ? `Every address @${zone} → ${actions}`
          : `${rule.matchers?.map((m) => m.value).join(", ")} → ${actions}`,
        calls: all
          ? [
              [
                "PUT",
                `${z}/email/routing/rules/catch_all`,
                { enabled: false, matchers: [{ type: "all" }], actions: [{ type: "drop" }] },
              ],
            ]
          : [["DELETE", `${z}/email/routing/rules/${id}`]],
      });
    }
    for (const s of await read(
      "the Email Sending domains",
      true,
      paged(cf, `${z}/email/sending/subdomains`, 50),
    ))
      add({
        kind: "email_sending_subdomain",
        id: s.tag || s.id,
        name: s.name,
        group: "mail",
        text: `Sending mail from @${s.name}`,
        calls: [["DELETE", `${z}/email/sending/subdomains/${s.tag || s.id}`]],
      });
  };

  const rules = async () => {
    for (const set of await read("the rules", true, whole(cf, `${z}/rulesets`))) {
      if (set.kind !== "zone") continue;
      const full = await cf("GET", `${z}/rulesets/${set.id}`);
      if (!full.success) {
        unread.push({ what: `the rules of ${set.phase}`, said: saidOf(full), must: true });
        continue;
      }
      const made = full.result?.rules || [];
      if (made.length === 0) continue;
      add({
        kind: "zone_ruleset",
        id: set.id,
        name: set.phase,
        group: "rules",
        text: `${PHASES[set.phase] || set.phase}: ${made
          .slice(0, 3)
          .map((r) => short(r.description || r.expression, 50))
          .join("; ")}${made.length > 3 ? `; and ${made.length - 3} more` : ""}`,
        // a phase's rules are in its entry point, which stays: one update leaves it with no rule
        calls: [["PUT", `${z}/rulesets/${set.id}`, { rules: [] }]],
      });
    }
    for (const p of await read("the page rules", false, whole(cf, `${z}/pagerules`)))
      add({
        kind: "page_rule",
        id: p.id,
        name: (p.targets || []).map((t) => t.constraint?.value).join(" "),
        group: "rules",
        text: `Page rule for ${(p.targets || []).map((t) => t.constraint?.value).join(" ")}: ${(
          p.actions || []
        )
          .map((x) => x.id)
          .join(", ")}`,
        calls: [["DELETE", `${z}/pagerules/${p.id}`]],
      });
    const snippets = await read("the snippets", false, paged(cf, `${z}/snippets`, 50));
    snippets.forEach((s, i) =>
      add({
        kind: "snippet",
        id: s.snippet_name,
        name: s.snippet_name,
        group: "rules",
        text: `Snippet ${s.snippet_name}: code that runs on each request`,
        // the rules that call the snippets go first, once
        calls: [
          ...(i === 0 ? [["DELETE", `${z}/snippets/snippet_rules`]] : []),
          ["DELETE", `${z}/snippets/${encodeURIComponent(s.snippet_name)}`],
        ],
      }),
    );
    const bots = await cf("GET", `${z}/bot_management`);
    if (!bots.success) unread.push({ what: "Bot Fight Mode", said: saidOf(bots), must: false });
    else if (bots.result?.fight_mode)
      add({
        kind: "bot_fight_mode",
        id: "bot_fight_mode",
        name: "Bot Fight Mode",
        group: "rules",
        text: "Bot Fight Mode is turned off: it challenges the programs that call iterate",
        calls: [["PUT", `${z}/bot_management`, { fight_mode: false }]],
      });
  };

  const access = async () => {
    for (const app of await read(
      "the Access applications of the domain",
      false,
      whole(cf, `${z}/access/apps`),
    ))
      add({
        kind: "access_app",
        id: app.id,
        name: app.domain || app.name,
        group: "sites",
        text: `${app.domain || app.name}: a login in front of it (Access application ${app.name})`,
        calls: [["DELETE", `${z}/access/apps/${app.id}`]],
      });
    for (const app of await read(
      "the Access applications of the account",
      false,
      paged(cf, `${a}/access/apps`, 100),
    )) {
      const hosts = [
        app.domain,
        ...(app.self_hosted_domains || []),
        ...(app.destinations || []).map((d) => d.uri),
      ]
        .filter(Boolean)
        .map(hostOf);
      const here = [...new Set(hosts.filter(under))];
      const elsewhere = [...new Set(hosts.filter((h) => !under(h)))];
      if (here.length === 0) continue;
      add({
        kind: "access_app",
        id: app.id,
        name: here.join(" "),
        group: "sites",
        text:
          elsewhere.length > 0
            ? `${here.join(", ")}: a login in front of it. The Access application ${app.name} also protects ${elsewhere.join(", ")}: take ${here.join(", ")} out of it in Zero Trust.`
            : `${here.join(", ")}: a login in front of it (Access application ${app.name})`,
        act: elsewhere.length > 0 ? "refuse" : "erase",
        calls: [["DELETE", `${a}/access/apps/${app.id}`]],
      });
    }
    // Cloudflare's own word: a site on Pages is a Pages project
    for (const site of await read("the Pages projects", false, paged(cf, `${a}/${PAGES}`, 10)))
      for (const domain of site.domains || [])
        if (under(domain))
          add({
            kind: "pages_custom_domain",
            id: `${site.name}/${domain}`,
            name: domain,
            group: "sites",
            text: `${domain} → Pages project ${site.name} (the Pages project stays)`,
            calls: [
              [
                "DELETE",
                `${a}/${PAGES}/${encodeURIComponent(site.name)}/domains/${encodeURIComponent(domain)}`,
              ],
            ],
          });
  };

  /** The telemetry part of the stack, beside its Worker and its bucket. `has`: the account shows
   *  that the stack has one. Then each list is one the erase cannot go without. For a stack that
   *  shows none, a list that Cloudflare refuses says nothing. */
  const telemetry = async (has) => {
    const t = names.telemetry;
    const part = async (what, asked) => {
      const got = await asked;
      if (got.list) return got.list;
      if (has) unread.push({ what, said: saidOf(got.refused), must: true });
      return [];
    };
    for (const [kind, lists, word, suffix] of [
      ["pipeline", "pipelines", "Pipeline", ""],
      ["pipeline_sink", "sinks", "Pipeline sink", "_sink"],
      ["pipeline_stream", "streams", "Pipeline stream", "_stream"],
    ])
      for (const p of await part(
        `the ${word.toLowerCase()}s`,
        paged(cf, `${a}/pipelines/v1/${lists}`, 50),
      ))
        if (t.tables.some((table) => p.name === `${table}${suffix}`))
          add({
            kind,
            id: p.id,
            name: p.name,
            group: "iterate",
            text: `${word} ${p.name}: it carries the stack's logs and traces to their bucket`,
            calls: [["DELETE", `${a}/pipelines/v1/${lists}/${encodeURIComponent(p.id)}`]],
          });
    for (const d of await part(
      "the Workers' log destinations",
      whole(cf, `${a}/workers/observability/destinations`),
    ))
      if (t.destinations.includes(d.name))
        add({
          kind: "observability_destination",
          id: d.slug,
          name: d.name,
          group: "iterate",
          text: `Log destination ${d.name}: where the stack's Workers send their logs and traces`,
          calls: [
            ["DELETE", `${a}/workers/observability/destinations/${encodeURIComponent(d.slug)}`],
          ],
        });
    if (has) {
      // R2 keeps a catalog that was turned off as "inactive": that one is gone for the erase
      const catalog = await cf("GET", `${a}/r2-catalog/${t.bucket}`);
      if (catalog.success && catalog.result?.status === "active") {
        add({
          kind: "r2_catalog",
          id: t.bucket,
          name: t.bucket,
          group: "iterate",
          text: `Data catalog of the R2 bucket ${t.bucket}: the tables of the stack's logs and traces`,
          calls: [["POST", `${a}/r2-catalog/${t.bucket}/disable`]],
        });
        // The stack's own tables, by their exact names. The catalog's id is the first part of its
        // Iceberg paths (its `/v1/config` says so: `overrides.prefix`).
        const ns = LOG_TABLES.namespace;
        const iceberg = `${CATALOG}/${accountId}/${t.bucket}/v1/${catalog.result.id}/namespaces/${ns}`;
        const tables = await cf("GET", `${a}/r2-catalog/${t.bucket}/namespaces/${ns}/tables`);
        const inIt = listOf(tables.result?.identifiers).map((table) => table.name);
        if (tables.success && catalog.result.id) {
          for (const table of LOG_TABLES.names.filter((name) => inIt.includes(name)))
            add({
              kind: "r2_catalog_table",
              id: `${t.bucket}/${ns}.${table}`,
              name: `${ns}.${table}`,
              bucket: t.bucket,
              group: "iterate",
              text: `Table ${ns}.${table} in the data catalog of the R2 bucket ${t.bucket}`,
              soft: true,
              calls: [["DELETE", `${iceberg}/tables/${table}`]],
            });
          // the namespace goes when the stack's tables are all it has
          if (inIt.length > 0 && inIt.every((name) => LOG_TABLES.names.includes(name)))
            add({
              kind: "r2_catalog_namespace",
              id: `${t.bucket}/${ns}`,
              name: ns,
              bucket: t.bucket,
              group: "iterate",
              text: `Namespace ${ns} in the data catalog of the R2 bucket ${t.bucket}`,
              soft: true,
              calls: [["DELETE", iceberg]],
            });
        } else if (!tables.success && tables.status !== 404)
          // the tables are `soft`, and so is their list: the erase goes on and says what can be left
          unread.push({ what: CATALOG_TABLES, said: saidOf(tables), must: false });
      } else if (!catalog.success && catalog.status !== 404)
        unread.push({
          what: "the telemetry bucket's data catalog",
          said: saidOf(catalog),
          must: true,
        });
    }
    // The stack's API tokens: telemetry's two, and the mind's own. A sign-in without Cloudflare's
    // "Account API Tokens" permission can neither read nor delete them: the erase says that they
    // are left, and goes on.
    const tokens = await paged(cf, `${a}/tokens`, 50);
    if (tokens.refused) {
      if (has) unread.push({ what: API_TOKENS, said: saidOf(tokens.refused), must: false });
      return;
    }
    for (const token of tokens.list)
      if (t.tokens.includes(token.name) || isMindToken(names, token.name))
        add({
          kind: "api_token",
          id: token.id,
          name: token.name,
          group: "iterate",
          soft: true,
          text: isMindToken(names, token.name)
            ? `API token ${token.name}: the mind read this Cloudflare account with it`
            : `API token ${token.name}: the stack's telemetry wrote and read with it`,
          calls: [["DELETE", `${a}/tokens/${token.id}`]],
        });
  };

  const stack = async () => {
    const scripts = await read("the Workers", true, whole(cf, `${a}/workers/scripts`));
    const ours = scripts.map((s) => s.id).filter((id) => names.workers.includes(id));
    const store = scripts.some((s) => s.id === names.store);
    for (const id of ours)
      add({
        kind: "worker",
        id,
        name: id,
        group: "iterate",
        text: `Worker ${id}, and what it stores`,
        calls: [["DELETE", `${a}/workers/scripts/${id}?force=true`]],
      });
    if (store)
      add({
        kind: "state_store",
        id: names.store,
        name: names.store,
        group: "iterate",
        text: `Worker ${names.store}: the record of the earlier deploy`,
        calls: [["DELETE", `${a}/workers/scripts/${names.store}?force=true`]],
      });
    if (ours.length > 0) {
      const spaces = (
        await read(
          "the Durable Objects",
          true,
          paged(cf, `${a}/workers/durable_objects/namespaces`, 1000),
        )
      )
        .filter((ns) => ours.includes(ns.script))
        .map((ns) => ns.id);
      for (const app of await read(
        "the containers",
        true,
        whole(cf, `${a}/containers/applications`),
      ))
        if (spaces.includes(app.durable_objects?.namespace_id))
          add({
            kind: "container_application",
            id: app.id,
            name: app.name,
            group: "iterate",
            text: `Sandbox containers ${app.name}`,
            calls: [["DELETE", `${a}/containers/applications/${app.id}`]],
          });
    }
    for (const db of await read(
      "the D1 databases",
      true,
      paged(cf, `${a}/d1/database?name=${names.prefix}`, 100),
    ))
      if (names.d1.includes(db.name))
        add({
          kind: "d1_database",
          id: db.uuid,
          name: db.name,
          group: "iterate",
          text: `Database ${db.name}: the members, passkeys and grants`,
          calls: [["DELETE", `${a}/d1/database/${db.uuid}`]],
        });
    for (const ns of await read(
      "the KV namespaces",
      true,
      paged(cf, `${a}/storage/kv/namespaces`, 100),
    ))
      if (names.kv.includes(ns.title))
        add({
          kind: "kv_namespace",
          id: ns.id,
          name: ns.title,
          group: "iterate",
          text: `Key-value store ${ns.title}`,
          calls: [["DELETE", `${a}/storage/kv/namespaces/${ns.id}`]],
        });
    const buckets = await read(
      "the R2 buckets",
      true,
      whole(cf, `${a}/r2/buckets?name_contains=${names.prefix}&per_page=1000`),
    );
    for (const b of buckets.flatMap((x) => x.buckets || []))
      if (names.r2.includes(b.name))
        add({
          kind: "r2_bucket",
          id: b.name,
          name: b.name,
          group: "iterate",
          text: `R2 bucket ${b.name}, and every file in it`,
        });
    await telemetry(
      ours.includes(names.telemetry.worker) ||
        buckets.some((x) => (x.buckets || []).some((b) => b.name === names.telemetry.bucket)),
    );
    for (const ns of await read(
      "the Artifacts namespaces",
      true,
      paged(cf, `${a}/artifacts/namespaces`, 50),
    ))
      if (ns.namespace === names.artifacts)
        add({
          kind: "artifacts_namespace",
          id: ns.namespace,
          name: ns.namespace,
          group: "iterate",
          text: `Artifacts namespace ${ns.namespace}: the config repo and ${plural(Math.max((ns.repo_count || 1) - 1, 0), "other repo")}`,
        });
    for (const s of await read("the Secrets Store", true, whole(cf, `${a}/secrets_store/stores`)))
      for (const secret of await read(
        "the secrets of the Secrets Store",
        true,
        paged(
          cf,
          `${a}/secrets_store/stores/${s.id}/secrets?search=${names.secrets[0].split("_").slice(1).join("_")}`,
          100,
        ),
      ))
        if (names.secrets.includes(secret.name))
          add({
            kind: "state_secret",
            id: secret.id,
            name: secret.name,
            group: "iterate",
            text: `Secret ${secret.name}: the key of the earlier deploy's record`,
            calls: [["DELETE", `${a}/secrets_store/stores/${s.id}/secrets/${secret.id}`]],
          });
  };

  await Promise.all([records(), routes(), hostnames(), mail(), rules(), access(), stack()]);
  items.sort(
    (x, y) =>
      ORDER.indexOf(x.kind) - ORDER.indexOf(y.kind) ||
      String(x.name).localeCompare(String(y.name)) ||
      String(x.id).localeCompare(String(y.id)),
  );
  return { items, unread, digest: await digestOf(items) };
}

/** A short name for a list: the kinds and ids in it, and what happens to each. */
async function digestOf(items) {
  const lines = items.map((i) => `${i.kind}|${i.id}|${i.act}`).sort();
  const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(lines.join("\n")));
  return [...new Uint8Array(hash)]
    .slice(0, 12)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

/** What stops an erase before it starts, in plain words: [] when nothing does. */
export function refusalsOf({ items, unread }) {
  return [
    ...unread
      .filter((u) => u.must)
      .map((u) => `Cloudflare did not let iterate read ${u.what} (${u.said}).`),
    ...items.filter((i) => i.act === "refuse").map((i) => i.text),
  ];
}

/** How long the erase waits for a log pipeline's sinks to end the files they write: two of their
 *  intervals (core/alchemy/src/stack.ts `rollingPolicy: { intervalSeconds: 60 }`), since what a
 *  Worker sent last can reach a sink some seconds after the Worker is gone. */
export const SINKS_END_MS = 120_000;

/** The rule that the erase sets on a bucket it has to leave. */
const UPLOADS_RULE = "iterate-erase-unfinished-uploads";

/** R2's "the bucket you tried to delete is not empty". */
const notEmpty = (answer) => (answer?.errors || []).some((e) => e.code === 10008);

/** A file's key that no address can carry. A path part `.` or `..` is not a name to a URL parser,
 *  `fetch`'s too, and no spelling of it is (`%2E` is read the same): `…/objects/.` is sent as the
 *  folder `…/objects/`, and `…/objects/..` as the bucket itself. Any other key is one path part
 *  once it is encoded. */
const unnameable = (key) => key === "." || key === "..";

/** Removes every file that the list of a bucket shows and that an address can name. Answers null,
 *  "gone" when the bucket is not there, Cloudflare's refusal, or `{ unnameable }`: the keys that
 *  are left because no address names them (the head of this file says what the erase does then). */
async function emptied(cf, bucket) {
  for (let round = 0; round < 500; round++) {
    const listed = await cf("GET", `${bucket}/objects?per_page=1000`);
    if (!listed.success) return listed.status === 404 ? "gone" : listed;
    const all = listOf(listed.result).map((o) => o.key);
    const keys = all.filter((key) => !unnameable(key));
    if (keys.length === 0) return all.length > 0 ? { unnameable: all } : null;
    for (let i = 0; i < keys.length; i += 20) {
      const refused = (
        await Promise.all(
          keys
            .slice(i, i + 20)
            .map((key) => call(cf, ["DELETE", `${bucket}/objects/${encodeURIComponent(key)}`])),
        )
      ).find(Boolean);
      if (refused) return refused;
    }
  }
  return null;
}

/** Sets the rule that removes a bucket's unfinished uploads after a day, beside the rules the
 *  bucket has. Answers true when Cloudflare took it. */
async function endsUploads(cf, bucket) {
  const has = await cf("GET", `${bucket}/lifecycle`);
  if (!has.success) return false;
  const rules = listOf(has.result?.rules).filter((rule) => rule.id !== UPLOADS_RULE);
  const set = await cf("PUT", `${bucket}/lifecycle`, {
    rules: [
      ...rules,
      {
        id: UPLOADS_RULE,
        enabled: true,
        conditions: { prefix: "" },
        abortMultipartUploadsTransition: { condition: { type: "Age", maxAge: 86400 } },
      },
    ],
  });
  return Boolean(set.success);
}

/** One call of the erase: gone already (404) is as good as removed.
 *  @param {(method: string, path: string, body?: unknown) => Promise<any>} cf
 *  @param {[method: string, path: string, body?: unknown]} one */
async function call(cf, [method, path, body]) {
  const answer = await cf(method, path, body);
  return answer.success || answer.status === 404 ? null : answer;
}

/** Removes one item. Answers null, or Cloudflare's refusal. A bucket that R2 calls not empty
 *  with no file in its list answers the refusal with `held` (and `ruled`, when the rule that
 *  removes unfinished uploads is set): see the head of this file. */
async function remove(cf, accountId, item, pause) {
  const a = `/accounts/${accountId}`;
  if (item.kind === "r2_bucket") {
    const bucket = `${a}/r2/buckets/${item.id}`;
    // R2 refuses to delete a bucket that holds a file. Something that still writes can put one
    // there after the list was empty, so a refusal is followed by another look, four times.
    for (let attempt = 1; ; attempt++) {
      const refused = await emptied(cf, bucket);
      // the bucket is not asked to go while a file is known to be in it
      if (refused) return refused === "gone" ? null : refused;
      const answer = await call(cf, ["DELETE", bucket]);
      if (!answer || !notEmpty(answer)) return answer;
      if (attempt === 4) return { ...answer, held: true, ruled: await endsUploads(cf, bucket) };
      await pause(5000);
    }
  }
  if (item.kind === "artifacts_namespace") {
    const repos = await paged(cf, `${a}/artifacts/namespaces/${item.id}/repos`, 50);
    if (repos.refused) return repos.refused;
    for (const repo of repos.list) {
      const refused = await call(cf, [
        "DELETE",
        `${a}/artifacts/namespaces/${item.id}/repos/${encodeURIComponent(repo.name)}`,
      ]);
      if (refused) return refused;
    }
    return call(cf, ["DELETE", `${a}/artifacts/namespaces/${item.id}`]);
  }
  for (const one of item.calls) {
    const refused = await call(cf, one);
    if (refused) return refused;
  }
  return null;
}

/**
 * Erases the list, then reads again until nothing is left.
 *   agreed   the digest of the list the person saw: another list is not erased
 *   say      one line of the run's log
 * Answers { ok: true }, or { ok: false, why, erased } with `why` in plain words.
 */
export async function eraseAll({ cf, accountId, zoneId, zone, name, agreed, say, wait }) {
  const pause = wait || ((ms) => new Promise((done) => setTimeout(done, ms)));
  const look = () => inventoryOf({ cf, accountId, zoneId, zone, name });
  const kept = keptOf(zone);
  if (kept) return { ok: false, erased: false, why: kept };
  let found = await look();
  const refusals = refusalsOf(found);
  if (refusals.length > 0)
    return {
      ok: false,
      erased: false,
      why: `iterate cannot erase everything on ${zone}, so it erased nothing. ${refusals.join(" ")}`,
    };
  if (agreed && agreed !== found.digest)
    return {
      ok: false,
      erased: false,
      why: `${zone} changed after you saw the list of what is erased, so nothing was erased. Look at the list again.`,
    };
  for (const u of found.unread) say(`Could not look at ${u.what} (${u.said}).`);
  if (found.items.length === 0) {
    say(`Nothing is on ${zone}, and nothing of an earlier iterate is in the account.`);
    return { ok: true };
  }
  say(`Erasing ${plural(found.items.length, "thing")} on ${zone} and of the earlier iterate.`);
  const older = found.items.some((i) => i.kind === "workers_route" && i.script === OLDER_WORKER);
  const unreadTokens = found.unread.some((u) => u.what === API_TOKENS);
  // read now: the catalog is off after the erase, and a later read does not ask for its tables
  const unreadTables = found.unread.some((u) => u.what === CATALOG_TABLES);
  // what Cloudflare did not let the run remove, and the erase goes on without (`soft`)
  const left = new Map();
  const keyOf = (item) => `${item.kind}|${item.id}`;
  let erased = false;
  let waited = false;
  for (let pass = 1; pass <= 8; pass++) {
    for (const item of found.items) {
      if (item.act !== "erase" || left.has(keyOf(item))) continue;
      // the stack's Workers and log destinations are gone by now (ORDER): nothing writes
      // to its pipelines, and their sinks end the files they write
      if (item.kind === "pipeline" && !waited) {
        waited = true;
        say(
          `Waiting ${SINKS_END_MS / 1000} seconds: the log pipelines end the files they write, so that their bucket can go.`,
        );
        await pause(SINKS_END_MS);
      }
      const refused = await remove(cf, accountId, item, pause);
      if (refused?.unnameable) {
        const keys = refused.unnameable;
        left.set(keyOf(item), { ...item, unnameable: keys });
        say(
          `Left: R2 bucket ${item.name}. ${plural(keys.length, "file")} in it ${keys.length === 1 ? "has" : "have"} a name that no address can carry (${quoted(keys)}), so iterate cannot remove ${keys.length === 1 ? "it" : "them"}.`,
        );
        continue;
      }
      if (refused?.held) {
        left.set(keyOf(item), { ...item, held: true, ruled: refused.ruled });
        say(
          `Left: R2 bucket ${item.name}. No file is in it, and Cloudflare holds an unfinished upload in it (${saidOf(refused)}).`,
        );
        continue;
      }
      if (refused && item.soft) {
        left.set(keyOf(item), item);
        say(`Left: ${item.text} (${saidOf(refused)}).`);
        continue;
      }
      if (refused)
        return {
          ok: false,
          erased,
          why: `Cloudflare did not let iterate remove this: ${item.text} (${saidOf(refused)}). ${
            erased ? `Other things on ${zone} are erased already. ` : ""
          }Remove it in the Cloudflare dashboard, then press "Erase and replace" again.`,
        };
      erased = true;
      say(`Erased: ${item.text}`);
    }
    // what a product keeps goes a moment after the product
    await pause(pass === 1 ? 3000 : 6000);
    found = await look();
    const now = refusalsOf(found);
    if (now.length > 0)
      return {
        ok: false,
        erased,
        why: `Other things on ${zone} are erased already, and iterate cannot erase the rest. ${now.join(" ")}`,
      };
    const rest = found.items.filter((item) => !left.has(keyOf(item)));
    if (rest.length === 0) {
      say(`Read again: nothing is left on ${zone}.`);
      // the stack's API tokens that are still there: nothing keeps their values now
      const where =
        "The Workers that kept their values are erased. You can delete them in Cloudflare (Manage account, Account API tokens).";
      const tokens = [...left.values()].filter((item) => item.kind === "api_token");
      const tables = [...left.values()].filter((item) => item.kind.startsWith("r2_catalog_"));
      const tablesStay = `Cloudflare keeps a catalog's tables also when its bucket is gone. While they are there, a new deployment on this domain gets no telemetry: its log pipelines cannot write to a table that exists. To remove them, you need an API token with the permission "Workers R2 Data Catalog Write" and an Iceberg client (Cloudflare's documentation of R2 Data Catalog says how).`;
      if (tables.length > 0)
        say(
          `Note: Cloudflare did not let iterate remove this from the data catalog of the R2 bucket ${tables[0].bucket}: ${tables.map((item) => item.name).join(", ")}. ${tablesStay}`,
        );
      if (unreadTables) {
        const { bucket } = namesOf(name).telemetry;
        say(
          `Note: Cloudflare did not let iterate read the tables in the data catalog of the R2 bucket ${bucket}, so it removed none. The tables of this deployment's telemetry (${LOG_TABLES.names.map((table) => `${LOG_TABLES.namespace}.${table}`).join(", ")}) can be left. ${tablesStay}`,
        );
      }
      for (const bucket of [...left.values()].filter((item) => item.held))
        say(
          `Note: The R2 bucket ${bucket.name} is left in your Cloudflare account, with no file in it. A log pipeline of this deployment did not end an upload to it, and this sign-in cannot remove an unfinished upload. ${
            bucket.ruled
              ? "iterate set a rule on the bucket that removes unfinished uploads after a day. After that you can delete the bucket in Cloudflare (R2), or an erase from this page does it."
              : "Cloudflare removes an unfinished upload after some days. After that you can delete the bucket in Cloudflare (R2), or an erase from this page does it."
          } A deployment with telemetry on this domain uses the bucket again.`,
        );
      for (const bucket of [...left.values()].filter((item) => item.unnameable))
        say(
          `Note: The R2 bucket ${bucket.name} is left in your Cloudflare account, with ${plural(bucket.unnameable.length, "file")} in it: ${quoted(bucket.unnameable)}. Every other file in it is erased. A web address that ends in "." or ".." is the address of the folder above it, so no request can name such a file, and iterate sent none. What ${bucket.unnameable.length === 1 ? "that file holds" : "those files hold"} stays in your account. You can try to remove ${bucket.unnameable.length === 1 ? "it" : "them"} in Cloudflare (R2).`,
        );
      if (tokens.length > 0)
        say(
          `Note: Cloudflare did not let iterate delete ${plural(tokens.length, "API token")} of this deployment (${[...new Set(tokens.map((item) => item.name))].join(", ")}). ${where}`,
        );
      else if (unreadTokens)
        say(
          `Note: This deployment had telemetry. Its API tokens (${namesOf(name).telemetry.tokens.join(", ")}), and ${namesOf(name).cloudflareToken} if its mind had a Cloudflare connection, can be left in your Cloudflare account: this sign-in may not read or delete API tokens. ${where}`,
        );
      if (older)
        say(
          `Note: An earlier iterate served ${zone} from its Worker “${OLDER_WORKER}”. Its routes on ${zone} are erased; the Worker itself is left in your Cloudflare account. If you do not need what it kept, you can delete it in Cloudflare (Workers & Pages).`,
        );
      return { ok: true };
    }
    say(`Read again: ${plural(rest.length, "thing")} left.`);
  }
  return {
    ok: false,
    erased,
    why: `Other things on ${zone} are erased already, and these are still there: ${found.items
      .filter((item) => !left.has(keyOf(item)))
      .slice(0, 5)
      .map((i) => i.text)
      .join("; ")}. Remove them in the Cloudflare dashboard, then press "Erase and replace" again.`,
  };
}