import { env } from "cloudflare:workers";
import { all, first, run } from "../db";
import { randomId, sha256Hex } from "../crypto";
import { HttpError, badRequest } from "../errors";
import { enforceRateLimit, requestIp } from "../limits";
import { extractArtifact, storeFile } from "../pages/collect";
import { manifestKey, metaKey, publishMeta, SCRATCH_LIMITS, slotKey } from "./config";
import { assertLabelFree, loadSiteById, unpublishSite } from "./deploy";
import { claimedLabel } from "./naming";
import { onScratchClaimed } from "./metering";
import { CLAIM_PREFIX, deployUpload, ipHash, reserveScratch, scratchResult } from "./scratch-core";
import { createScratchRepo, deleteScratchRepo, transferScratchRepo } from "./scratch-git";
import type { CollectedFiles } from "../pages/collect";
import type { ScratchResult } from "./scratch-core";
import { plain } from "./static";
import type { SiteMeta, SiteRow } from "./config";
import type { Viewer } from "~/lib/types";
const HTTP_TOO_LARGE = 413;
const SWEEP_BATCH = 50;
async function readCapped(request: Request): Promise<Uint8Array<ArrayBuffer>> {
const declared = Number(request.headers.get("content-length") ?? "0");
if (declared > SCRATCH_LIMITS.maxUploadBytes) throw new HttpError(HTTP_TOO_LARGE, "Upload exceeds 10 MiB");
if (!request.body) throw badRequest("Send a .tar.gz archive as the request body");
const reader = request.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
for (;;) {
const next = await reader.read();
if (next.done) break;
size += next.value.byteLength;
if (size > SCRATCH_LIMITS.maxUploadBytes) {
await reader.cancel();
throw new HttpError(HTTP_TOO_LARGE, "Upload exceeds 10 MiB");
}
chunks.push(next.value);
}
const out = new Uint8Array(size);
let offset = 0;