iterate.com / cloud

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

cloud / internal-packages / installer / src / api.tsmain at aacbc74

// The page's side of the Worker's API (worker/index.js): every call, written to the activity log
// in words, and the wizard's state, kept in this tab so the OAuth round trips don't lose it.
import { useSyncExternalStore } from "react";
import { QueryClient, useQuery, type UseQueryOptions } from "@tanstack/react-query";
import { callAnswered, startAnalytics } from "./analytics.ts";
import { failedStepOf, runErrorOf, stepsOf } from "./deploy-steps.ts";

export type Domain = {
  name: string;
  available: boolean;
  price: string | null;
  renewal: string | null;
  currency: string;
  reason: string | null;
};
export type Zone = { id: string; name: string; status: string; nameServers: string[] };
export type Contact = {
  name: string;
  email: string;
  phone: string;
  street: string;
  city: string;
  postal: string;
  country: string;
};
export type CloudflareCall = {
  id?: string;
  method: string;
  path: string;
  status: number;
  success: boolean;
  expected?: boolean; // a refusal that is the call's answer, such as a check that a name is free
  errors: { code?: number | string; message: string }[];
};

export type State = {
  step: number;
  maxStep: number; // the furthest step reached: its header stays clickable
  finished: boolean;
  me: {
    connected?: boolean; // false: who they are is known, the access to Cloudflare is over
    level?: "identity" | "full";
    missing?: string[];
    telemetry?: boolean; // this access may turn a stack's telemetry on
    cloudflareToken?: boolean; // this access may give a stack's mind a Cloudflare connection

    user?: { email: string; name: string; accountName?: string | null };
    accounts: { id: string; name: string }[];
    domains?: number | null; // how many domains the access reads: the words on a long read
    created?: { id: string; name: string } | null;
  } | null;
  want: "new" | "existing";
  choosing: boolean; // back at the choice of new or existing, connected already
  name: string;
  email: string;
  account: string; // "new", or an account id
  acctName: string;
  acctKey: string | null;
  withoutTokens: boolean; // they chose the full consent without the scope that makes API tokens
  created: { id: string; name: string } | null;
  abandoned: { id: string; name: string } | null; // a new account they backed out of: it stays in Cloudflare
  needsAccess: boolean;
  readiness: {
    workersPaid: boolean | null;
    r2: boolean | null;
    paymentMethod: boolean | null;
    card: { brand: string; last4: string } | null;
    workersDev: string | false | null;
  } | null;
  path: "buy" | "have" | "elsewhere" | null;
  mode: "sandbox" | "production";
  testMode: boolean;
  words: string;
  choice: Domain | null;
  contact: Contact | null;
  zone: Zone | null;
  result: { name: string; how: "bought" | "sandbox" | "have" | "elsewhere" } | null;
  error: string | null; // "Title\nWhat to do", or one sentence
  tried: Record<string, boolean>; // the "Try iterate" items they ticked
  recovering: boolean; // "Lost your passkey?" is open: it stays open across Cloudflare's consent
  passkeyAdded: Record<string, number>; // per domain, the end of the one-use link they added a passkey with
};
/** A deploy run, as worker/deploy-run.js answers it. A line "== step <id>" starts a step. */
export type DeployState = {
  status: "idle" | "running" | "succeeded" | "failed";
  lines: string[];
  steps: { id: string; label: string }[];
  /** firstOwnerTicket: in one answer only, after a first deploy or a recovery run (worker/first-owner.js) */
  result: {
    issuer: string;
    commit: string;
    firstOwnerTicket?: string;
    firstOwnerTicketEnds?: number;
  } | null;
  startedAt?: number;
  endedAt?: number;
  /** The run erases the domain and the earlier iterate first ("Erase and replace")… */
  erase?: boolean;
  /** …and that erase is done. */
  erased?: boolean;
  /** The run's container worked, and the run failed at this step: giving up its access. */
  failedAt?: "forget";
};
/** One thing iterate Cloud keeps (GET /api/kept). */
export type Kept = { where: string; key: string; what: string };

const initial: State = {
  step: 0,
  maxStep: 0,
  finished: false,
  me: null,
  want: "new",
  choosing: false,
  name: "",
  email: "",
  account: "new",
  acctName: "", // filled with the name /api/me derives from their email
  acctKey: null,
  withoutTokens: false,
  created: null,
  abandoned: null,
  needsAccess: false,
  readiness: null,
  path: null,
  mode: "production",
  testMode: false,
  words: "",
  choice: null,
  contact: null,
  zone: null,
  result: null,
  error: null,
  tried: {},
  recovering: false,
  passkeyAdded: {},
};

const load = <T>(key: string, fallback: T): T => {
  try {
    return { ...fallback, ...JSON.parse(sessionStorage.getItem(key) || "null") } as T;
  } catch {
    return fallback;
  }
};
let state: State = load("wizard", initial);
if (new URLSearchParams(location.search).has("test")) state = { ...state, testMode: true };
const listeners = new Set<() => void>();
/** What belongs to one Cloudflare account: a domain, a zone and a deployment never move to another. */
const perAccount: Partial<State> = {
  readiness: null,
  path: null,
  words: "",
  choice: null,
  zone: null,
  result: null,
  tried: {},
  finished: false,
};
/** The browser's Back and Forward move between steps: each step is a history entry. Quiet until
 *  boot() is done, and while Back or Forward itself moves us. (History.prototype, so the router,
 *  which wraps history.pushState, doesn't take it for a navigation.) */
let quiet = true;
addEventListener("popstate", (e) => {
  quiet = true;
  setState({ step: Math.min(Number(e.state?.step) || 0, state.maxStep), error: null });
  quiet = false;
});
export function setState(patch: Partial<State> | ((s: State) => Partial<State>)) {
  const before = state;
  const change = typeof patch === "function" ? patch(state) : patch;
  state = { ...state, ...change };
  const moved =
    // oxlint-disable-next-line iterate/simple-truthiness-check -- account "" (no account chosen yet) is a change of account and must stay distinct from undefined (no change)
    change.account !== undefined &&
    change.account !== before.account &&
    !!before.account &&
    before.account !== "new";
  if (moved) state = { ...state, ...perAccount, maxStep: state.step };
  state.maxStep = Math.max(state.maxStep || 0, state.step);
  if (state.step !== before.step && !quiet)
    History.prototype.pushState.call(history, { step: state.step }, "");
  try {
    sessionStorage.setItem("wizard", JSON.stringify(state));
  } catch {}
  listeners.forEach((l) => l());
}
/** Sign out of iterate Cloud: this tab forgets what it kept, and the Worker ends the session
 *  (`/logout`), which revokes its access to Cloudflare at Cloudflare. What the Worker said of that
 *  access goes to the next page through sessionStorage (`signedOut`). */
export function signOut() {
  try {
    sessionStorage.removeItem("wizard");
    sessionStorage.removeItem("wizardLog2");
  } catch {}
  // a POST: the Worker takes a sign-out from this page alone, never from another site's link
  void fetch("/logout", { method: "POST" })
    .then((answer) => (answer.ok ? answer.text() : ""))
    .catch(() => "")
    .then((said) => {
      try {
        sessionStorage.setItem("signedOut", String(JSON.parse(said || "{}").access || "unknown"));
      } catch {}
      location.assign("/");
    });
}
/** What became of the access to Cloudflare at the sign-out that led to this page: "ended"
 *  (Cloudflare revoked it), "none" (iterate held none), "kept" or "unknown" (Cloudflare did not
 *  confirm, or the Worker did not answer). null: this page follows no sign-out. */
export let signedOut: string | null = null;
export const useWizard = () =>
  useSyncExternalStore(
    (l) => {
      listeners.add(l);
      return () => listeners.delete(l);
    },
    () => state,
  );

// ── the log ──
// What happened, newest first, in words: what the page did and what came of it. A call to Cloudflare
// is a line under the entry it belongs to; a deploy's output is one entry per step.
export type LogEntry = {
  id: string;
  at: string;
  kind: "event" | "call" | "deploy";
  text: string; // what happened, as a sentence
  ok: boolean; // false: a problem
  busy?: boolean; // still going (a deploy's current step)
  title?: string; // a call: its method and path
  cloudflare: CloudflareCall[];
  detail: string;
  count?: number;
  expected?: boolean;
};
let log: LogEntry[] = (() => {
  try {
    return JSON.parse(sessionStorage.getItem("wizardLog2") || "[]");
  } catch {
    return [];
  }
})();
const logListeners = new Set<() => void>();
/** The same thing with the same answers as the newest entry (a poll): count it, don't add a row. */
const signature = (e: Omit<LogEntry, "at" | "id">) =>
  `${e.kind}|${e.text}|${e.cloudflare.map((c) => `${c.path}:${c.status}`).join(",")}`;
/** Add an entry. With an `id`, the entry of that id is updated where it is (a deploy step's output grows). */
function addLog(entry: Omit<LogEntry, "at" | "id">, id?: string) {
  const at = new Date().toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  const i = id ? log.findIndex((e) => e.id === id) : -1;
  if (i >= 0) {
    const old = log[i];
    if (
      old.text === entry.text &&
      old.detail === entry.detail &&
      !!old.busy === !!entry.busy &&
      old.ok === entry.ok
    )
      return;
    log = log.map((e, j) => (j === i ? { ...e, ...entry } : e));
  } else if (!id && log[0] && signature(log[0]) === signature(entry))
    log = [
      { ...log[0], at, count: (log[0].count || 1) + 1, detail: entry.detail },
      ...log.slice(1),
    ];
  else log = [{ id: id || crypto.randomUUID(), at, ...entry }, ...log].slice(0, 80);
  try {
    sessionStorage.setItem("wizardLog2", JSON.stringify(log));
  } catch {}
  logListeners.forEach((l) => l());
}
export const useLog = () =>
  useSyncExternalStore(
    (l) => {
      logListeners.add(l);
      return () => logListeners.delete(l);
    },
    () => log,
  );
/** Something that happened that wasn't a call to the Worker. */
export const logEvent = (text: string, ok = true, detail = "") =>
  addLog({ kind: "event", text, ok, cloudflare: [], detail });

/** A deploy's output, as one entry per step: its lines are the detail, and the last one is busy while it runs. */
function logDeploy(zone: string, state: DeployState | undefined, enrolled?: boolean | null) {
  if (!state?.lines?.length) return;
  const run = `deploy:${zone}:${state.startedAt || 0}`;
  // the step that failed is not the last one: every run ends by giving up its access (deploy-steps.ts)
  const failedAt = failedStepOf(state);
  const labelOf = (id: string) => state.steps?.find((p) => p.id === id)?.label || id || "The run";
  const steps = stepsOf(state);
  steps.forEach((st, i) => {
    const failed = st.id === failedAt;
    const what = labelOf(st.id);
    addLog(
      {
        kind: "deploy",
        text: `Deploy on ${zone}: ${what.charAt(0).toLowerCase()}${what.slice(1)}${failed ? " failed" : ""}`,
        ok: !failed,
        busy: i === steps.length - 1 && state.status === "running",
        cloudflare: [],
        detail: st.lines.join("\n"),
      },
      `${run}:${st.id}`,
    );
  });
  // the newest entry, which the bar shows, says how the run ended: not that it gave up its access
  // oxlint-disable-next-line iterate/simple-truthiness-check -- failedStepOf gives "" for a failed run with no known step, which must still log the failure; only null means no failure
  if (failedAt !== null)
    addLog(
      {
        kind: "event",
        text: failedAt
          ? `The deploy on ${zone} failed at “${labelOf(failedAt)}”`
          : `The deploy on ${zone} did not run`,
        ok: false,
        cloudflare: [],
        detail: runErrorOf(state),
      },
      `${run}:failed`,
    );
  // as the page does: not "live" before the new address answers the Cloud, a minute at most
  const waiting = enrolled === false && Date.now() - (state.endedAt || 0) < 60_000;
  if (state.status === "succeeded" && !waiting)
    addLog(
      {
        kind: "event",
        text: `iterate is live on ${zone}`,
        ok: true,
        cloudflare: [],
        detail: "",
      },
      `${run}:live`,
    );
}

/** A registration Cloudflare took and then refused (no card, no contact…): its answer is "200", its state says no. */
const refusedRegistration = (d: any) =>
  /failed|action_required|blocked/.test(String(d.result?.state || ""));
const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
/** A call to the Worker, in words: what the page did, and what came of it. */
function describe(
  method: string,
  route: string,
  q: URLSearchParams,
  body: any,
  d: any,
  ok: boolean,
): string {
  const no = (what: string) => `${what}: ${errorOf(d)}`;
  const names = (found: string) =>
    `${found}: ${(d.domains || []).filter((x: Domain) => x.available).length} available`;
  switch (`${method} ${route}`) {
    case "GET /api/me":
      return d.user
        ? d.connected === false
          ? `You are ${d.user.email}; iterate has no access to Cloudflare now`
          : `Signed in to Cloudflare as ${d.user.email}${d.level === "full" ? `, with access to ${plural((d.accounts || []).length, "account")}` : ""}`
        : "Not signed in to Cloudflare";
    case "POST /api/account":
      return d.account
        ? `Created the Cloudflare account “${d.account.name}”`
        : no("Cloudflare didn't create the account");
    case "POST /api/account/forget":
      return "Left the new account as it is";
    case "GET /api/readiness":
      return ok
        ? `Checked the account: ${[d.paymentMethod, d.workersPaid, d.r2, d.workersDev].filter(Boolean).length} of 4 ready`
        : no("Couldn't check the account");
    case "POST /api/subdomain":
      return d.subdomain
        ? `Set the workers.dev address to ${d.subdomain}.workers.dev`
        : d.taken
          ? `${(d.tried || [body?.name]).map((n: string) => `${n}.workers.dev`).join(" and ")} ${(d.tried || []).length > 1 ? "are" : "is"} taken`
          : no("Cloudflare didn't set the workers.dev address");
    case "POST /api/deploy":
      if (body?.erase)
        return ok
          ? `Started the erase of ${body?.zone}, and the deploy after it`
          : no("The erase didn't start");
      return ok ? `Started the deploy on ${body?.zone}` : no("The deploy didn't start");
    case "GET /api/deploy":
      return no("Couldn't check the deploy");
    case "GET /api/pages":
      return ok
        ? "Looked at which pages of your deployment answer"
        : no("Couldn't look at the pages of your deployment");
    case "GET /api/kept":
      return ok
        ? `Asked what iterate Cloud keeps: ${plural((d.records || []).length, "record")}`
        : no("Couldn't ask what iterate Cloud keeps");
    case "POST /api/suggest":
      return ok
        ? names(`Looked for domain names${body?.words ? ` like “${body.words}”` : ""}`)
        : no("Cloudflare didn't answer the search");
    case "GET /api/search":
      return ok ? names(`Looked up ${q.get("q")}`) : no("Cloudflare didn't answer the search");
    case "POST /api/register":
      return refusedRegistration(d)
        ? `Cloudflare didn't register ${body?.domain}: ${d.result?.error?.message || d.result?.error?.code || d.result.state}`
        : ok
          ? `Asked Cloudflare to register ${body?.domain}`
          : no(`Cloudflare didn't register ${body?.domain}`);
    case "GET /api/registrar/contact":
      return d.onFile
        ? "Cloudflare has a registrant contact on file"
        : "Cloudflare has no registrant contact on file";
    case "GET /api/registration":
      return refusedRegistration(d)
        ? `Cloudflare didn't register ${q.get("domain")}: ${d.result?.error?.message || d.result?.error?.code || d.result.state}`
        : `Registration of ${q.get("domain")}: ${String(d.result?.state || "no answer yet").replace(/_/g, " ")}`;
    case "GET /api/zones":
      return ok
        ? `Listed the account's domains: ${(d.zones || []).length} found`
        : no("Cloudflare didn't list the domains");
    case "GET /api/zone":
      return d.zone
        ? `Found ${d.zone.name} in the account`
        : `${q.get("name")} isn't in the account yet`;
    case "POST /api/zone":
      return d.zone
        ? `Added ${d.zone.name} to Cloudflare`
        : no(`Cloudflare didn't add ${body?.name}`);
    case "PUT /api/zone/check":
      return d.zone
        ? d.zone.status === "active"
          ? `${d.zone.name} points at Cloudflare`
          : `${d.zone.name}: its nameservers haven't changed yet`
        : no("Cloudflare didn't check the nameservers");
  }
  return `${method} ${route}`;
}

export type Answer = {
  ok: boolean;
  status: number;
  error?: string;
  errors?: { code?: number; message: string }[];
  cloudflare?: CloudflareCall[];
  [k: string]: any;
};

export const OFFLINE = "Couldn't reach iterate. Check your connection, then try again.";
/** One call to the Worker. A readiness check's refusals are its answer, not a failure. */
export async function call(method: string, path: string, body?: unknown): Promise<Answer> {
  const res = await fetch(path, {
    method,
    headers: body ? { "content-type": "application/json" } : {},
    body: body ? JSON.stringify(body) : undefined,
  }).catch(() => null);
  const [route, query = ""] = path.split("?");
  if (!res) {
    addLog({
      kind: "call",
      text: "Couldn't reach iterate",
      title: `${method} ${route}`,
      ok: false,
      cloudflare: [],
      detail: `${method} ${path}\n\n→ no answer (offline?)`,
    });
    return { ok: false, status: 0, error: OFFLINE };
  }
  // a refusal has a JSON body too (what Cloudflare said): read it either way, keep the status beside it
  const said = (await res.json().catch(() => ({}))) as any;
  const data = res.ok ? said : { error: `HTTP ${res.status}`, ...said };
  const calls: CloudflareCall[] = (data.cloudflare || []).map((c: CloudflareCall) => ({
    ...c,
    id: crypto.randomUUID(),
  }));
  const q = new URLSearchParams(query);
  callAnswered({ method, route, zone: q.get("zone") || "", body, ok: res.ok, state: data.state });
  // how a deploy is going is asked every 2 seconds: the log gets its steps, not each question
  if (method === "GET" && route === "/api/deploy" && res.ok) {
    keepFirstOwner(q.get("zone") || "", data.state);
    logDeploy(q.get("zone") || "your domain", data.state, data.enrolled);
  } else
    addLog({
      kind: "call",
      text: describe(method, route, q, body, data, res.ok),
      title: `${method} ${route}`,
      ok:
        res.ok &&
        !refusedRegistration(data) &&
        (route === "/api/readiness" || !calls.some((c) => !c.success && !c.expected)),
      expected: route === "/api/readiness", // its refusals answer the checklist
      cloudflare: calls,
      detail: `${method} ${path}${body ? `\n${JSON.stringify(body, null, 2)}` : ""}\n\n→ HTTP ${res.status}\n${JSON.stringify(data, null, 2)}`,
    });
  // iterate keeps no lasting access to Cloudflare: when it is over, the person stays where they
  // are and the step asks them to connect again
  if (res.status === 401 && data.error === "not connected") {
    if (state.me?.connected !== false) logEvent("iterate's access to Cloudflare ended");
    setState(state.me ? { me: { ...state.me, connected: false } } : { step: 0 });
  }
  return { ok: res.ok, status: res.status, ...data };
}
export const errorOf = (d: Answer) =>
  d.error || (d.errors || []).map((e) => e.message).join("; ") || "Cloudflare refused it.";

let dash = "https://dash.cloudflare.com/";
/** What iterate asks Cloudflare for at the full consent, and why (worker/index.js PERMISSIONS). */
export let permissions: [string, string][] = [];
/** The rest of the account, asked at the same consent, in groups: title, what for, scopes (WIDER). */
export let wider: [string, string, string[]][] = [];
export const dashUrl = (path: string) => dash + path;
/** Set on the pretend deployment only: a pretend Cloudflare answers it, nothing is real. */
export let pretend: { home: string; site: string } | null = null;
/** The Dash of a deployment: an app of its config repo, on dash.<domain>. (`dashUrl` is
 *  Cloudflare's dashboard.) */
export const mindDashUrl = (domain: string) =>
  `${pretend ? pretend.site : "https://"}dash.${domain}/`;
/** The stack's main conversation, on its Dash: one chat with the agent at /agents/main, which
 *  greets a new owner and stays as their main thread. It needs a member's sign-in, which the passkey gives. */
export const onboardingUrl = (domain: string) => `${mindDashUrl(domain)}agents/agents/main`;
/** A page of the deployment itself, on iterate.<domain> (or its stand-in on the pretend Cloudflare). */
export const stackUrl = (domain: string, path = "") =>
  `${pretend ? pretend.site : "https://"}iterate.${domain}${path}`;
/** The first owner's ticket of a domain (worker/first-owner.js). The Worker gives it once, so it
 *  is taken out of the answer and kept here, in this page's memory alone, until it ends. */
const firstOwner = new Map<string, { ticket: string; ends: number }>();
function keepFirstOwner(domain: string, state: DeployState | undefined) {
  // a later run is an update, and an update makes the stack drop the ticket
  if (state?.status === "running") firstOwner.delete(domain);
  const { firstOwnerTicket: ticket, firstOwnerTicketEnds: ends, ...result } = state?.result || {};
  if (!state?.result || !ticket) return;
  firstOwner.set(domain, { ticket, ends: ends || 0 });
  state.result = result as DeployState["result"];
}
/** Where the first owner adds a passkey with no mailed code, and until when; null with no ticket
 *  that lives. The ticket is in the fragment: the deployment's page posts it, no address holds it. */
export function firstPasskey(domain: string, next?: string) {
  const first = firstOwner.get(domain);
  if (!first || first.ends <= Date.now()) return null;
  const path = `/keys/first${next ? `?next=${encodeURIComponent(next)}` : ""}#${first.ticket}`;
  return {
    href: stackUrl(domain, path),
    ends: first.ends,
    added: state.passkeyAdded[domain] === first.ends,
  };
}
/** The person pressed the link of `firstPasskey`, and it opened in another tab. When they come back
 *  to this tab, the wizard takes the passkey as added. The stack does not tell the Cloud: it sends
 *  the owner on only to the mind's own sites (core/auth-worker/src/key-rules.ts). The link of a
 *  recovery run ends at another time, so it is not taken as added. */
export function firstPasskeyOpened(domain: string) {
  const ends = firstOwner.get(domain)?.ends;
  if (!ends) return;
  // Browsers say "left, then came back" in different events: blur and focus, visibilitychange
  // (Safari and Firefox on a tab switch fire this alone), and pageshow after the back-forward
  // cache. One state for all of them, so the passkey is taken as added once.
  let away = false;
  const done = new AbortController();
  const leave = () => {
    away = true;
  };
  const back = () => {
    if (!away || document.visibilityState !== "visible") return;
    done.abort();
    setState((s) => ({ passkeyAdded: { ...s.passkeyAdded, [domain]: ends } }));
  };
  const on = { signal: done.signal };
  addEventListener("blur", leave, on);
  addEventListener("focus", back, on);
  document.addEventListener(
    "visibilitychange",
    () => (document.visibilityState === "hidden" ? leave() : back()),
    on,
  );
  addEventListener("pagehide", leave, on);
  addEventListener(
    "pageshow",
    (e) => {
      // a page restored from the back-forward cache was left, whatever this tab saw before
      if (e.persisted) leave();
      back();
    },
    on,
  );
}
export async function loadConfig() {
  const c: {
    dash?: string;
    permissions?: [string, string][];
    wider?: [string, string, string[]][];
    pretend?: { home: string; site: string };
    posthog?: string | null;
  } = await fetch("/api/config")
    .then((r) => (r.ok ? r.json() : {}))
    .catch(() => ({}));
  // not awaited: the page shows before posthog-js has loaded
  void startAnalytics(c.posthog);
  if (c.dash) dash = c.dash;
  if (c.pretend?.home && c.pretend.site) pretend = c.pretend;
  // oxlint-disable-next-line iterate/simple-truthiness-check -- /api/config's JSON is not validated, so a value that is not an array must stay ignored
  if (Array.isArray(c.permissions)) permissions = c.permissions;
  // oxlint-disable-next-line iterate/simple-truthiness-check -- /api/config's JSON is not validated, so a value that is not an array must stay ignored
  if (Array.isArray(c.wider)) wider = c.wider;
}

// ── the page's reads ──
/** One cache for every read from the Worker; a write refreshes the reads it changes. */
export const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false, staleTime: 5_000 } },
});
/** Where the page asks how the deploy on the chosen domain is doing: one cache entry for every
 *  part that asks. Null with no real domain (a test-mode one is not real). */
export const deployPath = (s: State) =>
  s.result && s.result.how !== "sandbox" && /^[0-9a-f]{32}$/.test(s.account)
    ? `/api/deploy?account=${s.account}&zone=${s.result.name}`
    : null;
/** A GET to the Worker, cached by its path, logged like any call. */
export function useGet(
  path: string | null,
  options: Omit<UseQueryOptions<Answer>, "queryKey" | "queryFn"> = {},
) {
  return useQuery<Answer>({
    queryKey: [path],
    queryFn: () => call("GET", path!),
    enabled: !!path,
    ...options,
  });
}

/** Before the page draws: back from Cloudflare's consent page (#connected=identity|full), a reload,
 *  or a new tab whose sign-in cookie is still good. The route's loader runs it once. */
let booted = false;
export async function boot() {
  if (booted) return; // the router asks again on Back and Forward: once is enough
  booted = true;
  try {
    await start();
  } finally {
    History.prototype.replaceState.call(history, { step: state.step }, "", "/");
    quiet = false;
  }
}
/** What a deployment's self-test page said when the owner came back from it
 *  (`#self-test=<domain>:<passed>:<failed ids>`): shown to them, never trusted. */
export let selfTestReport: { domain: string; passed: number; failed: string[] } | null = null;
async function start() {
  const s = state;
  try {
    signedOut = sessionStorage.getItem("signedOut");
    sessionStorage.removeItem("signedOut");
  } catch {}
  const hash = new URLSearchParams(location.hash.slice(1));
  history.replaceState(null, "", "/");
  const report = hash.get("self-test")?.split(":");
  if (report?.[0])
    selfTestReport = {
      domain: report[0],
      passed: Number(report[1]) || 0,
      failed: (report[2] || "").split(",").filter(Boolean),
    };
  if (hash.get("error")) {
    const cancelled = /access_denied|denied|cancel/i.test(hash.get("error")!);
    logEvent(
      cancelled
        ? "Cancelled on Cloudflare's page"
        : `Cloudflare's page sent them back: ${hash.get("error")}`,
      cancelled,
    );
    return setState({
      step: 0,
      error: cancelled
        ? "You cancelled on Cloudflare's page\nNothing changed. Try again when you're ready."
        : hash.get("error"),
    });
  }
  const back = hash.get("connected");
  if (!back && !s.me) {
    // a new tab, or the next day: ask quietly (no log row)
    const me = await fetch("/api/me")
      .then((r) => (r.ok ? (r.json() as Promise<any>) : null))
      .catch(() => null);
    if (!me?.user) return;
    const reach = (me.accounts || []) as { id: string; name: string }[];
    const patch: Partial<State> = {
      me,
      name: me.user.name || "",
      email: me.user.email || "",
      acctName: s.acctName || me.user.accountName || "",
      want: me.level === "full" ? "existing" : s.want,
    };
    // an account this page made for them earlier (another tab, a closed tab): don't offer to make a second
    if (me.created && !s.created && !s.abandoned)
      Object.assign(patch, { created: me.created, want: "new" });
    // the next day, with one account in reach: that's the one
    else if (me.level === "full" && reach.length === 1 && (!s.account || s.account === "new"))
      Object.assign(patch, { account: reach[0].id, step: Math.max(s.step, 1) });
    setState(patch);
    return;
  }
  const me = await call("GET", "/api/me");
  if (!me.ok) return setState({ step: 0, me: null });
  const reach = (me.accounts || []) as { id: string; name: string }[];
  const patch: Partial<State> = {
    me: me as unknown as State["me"],
    name: s.name || me.user?.name || "",
    email: s.email || me.user?.email || "",
    acctName: s.acctName || me.user?.accountName || "",
    error: null,
    choosing: false,
  };
  if (me.created && !s.created && !s.abandoned)
    Object.assign(patch, { created: me.created, want: "new" });
  if (back === "full") {
    const made = s.want === "new" ? s.created : null;
    if (made && !reach.some((a) => a.id === made.id))
      Object.assign(patch, {
        step: 0,
        error: `Select “${made.name}” on Cloudflare's page\nCloudflare didn't include it. Authorize again and select it.`,
      });
    else if (made && s.account !== made.id)
      Object.assign(patch, { account: made.id, step: 1, readiness: null });
    // connected again: the same account, the same place, and what we know about it stays
    else if (reach.some((a) => a.id === s.account))
      Object.assign(patch, { step: Math.max(s.step, 1) });
    else if (reach.length === 1)
      Object.assign(patch, { account: reach[0].id, step: 1, readiness: null });
    else Object.assign(patch, { account: "", step: 0 });
  }
  setState(patch);
}