git-fs-s3 0.3.12 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/http.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http/info-refs.ts","../src/http/pkt-line.ts","../src/http/types.ts","../src/http/reachability.ts","../src/http/receive-pack.ts","../src/http/repack.ts","../src/http/upload-pack.ts"],"sourcesContent":["import git from \"isomorphic-git\";\nimport { concat } from \"../edge-utils.js\";\nimport { resolveLooseRefFast } from \"../ops/branch.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { FLUSH, pktLine } from \"./pkt-line.js\";\nimport { type GitHttpResult, type HttpHooks, runStep } from \"./types.js\";\n\nexport type GitService = \"git-upload-pack\" | \"git-receive-pack\";\n\n/** All refs with resolved oids, plus the symref HEAD should advertise. */\nexport async function listAllRefs(repo: Repo, defaultBranch = \"main\") {\n\t// Fetch branch/tag lists and HEAD's symref target in parallel\n\tconst [branches, tags, headSymref] = await Promise.all([\n\t\tgit.listBranches(repo),\n\t\tgit.listTags(repo),\n\t\t// Wrap with Promise.resolve so a mock/stub returning undefined doesn't crash .then()\n\t\tPromise.resolve(git.currentBranch({ ...repo, fullname: true }))\n\t\t\t.then((cb) => cb ?? `refs/heads/${defaultBranch}`)\n\t\t\t.catch(() => `refs/heads/${defaultBranch}`),\n\t]);\n\n\t// Resolve all branch and tag oids in parallel\n\tconst [branchRefs, tagRefs] = await Promise.all([\n\t\tPromise.all(\n\t\t\tbranches.map(async (branch) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst oid = await resolveLooseRefFast(repo, `refs/heads/${branch}`);\n\t\t\t\t\treturn { name: `refs/heads/${branch}`, oid };\n\t\t\t\t} catch {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}),\n\t\t),\n\t\tPromise.all(\n\t\t\ttags.map(async (tag) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst oid = await resolveLooseRefFast(repo, `refs/tags/${tag}`);\n\t\t\t\t\treturn { name: `refs/tags/${tag}`, oid };\n\t\t\t\t} catch {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}),\n\t\t),\n\t]);\n\n\t// HEAD in a bare repo is almost always a symref to a branch whose oid\n\t// branchRefs already resolved above with one direct GET each — reuse it\n\t// instead of a second, separate resolveRef(\"HEAD\") call. isomorphic-git's\n\t// ref resolution runs its full multi-candidate expansion (refs/%s,\n\t// refs/tags/%s, refs/heads/%s, refs/remotes/%s, refs/remotes/%s/HEAD)\n\t// even when the symref target is already fully qualified, which used to\n\t// cost several guaranteed-404 R2 reads on every clone/fetch. Falls back\n\t// to the slow-but-correct path only when that lookup misses: detached\n\t// HEAD (points at a raw sha, not a symref) or a symref to a branch that\n\t// doesn't exist yet (freshly initialized, still-empty repo).\n\tconst headOid =\n\t\tbranchRefs.find((r) => r?.name === headSymref)?.oid ??\n\t\t(await git.resolveRef({ ...repo, ref: \"HEAD\" }).catch(() => null));\n\n\tconst refs: Array<{ name: string; oid: string }> = [];\n\tif (headOid) refs.push({ name: \"HEAD\", oid: headOid });\n\tfor (const r of branchRefs) if (r) refs.push(r);\n\tfor (const r of tagRefs) if (r) refs.push(r);\n\n\treturn { refs, headSymref };\n}\n\nexport interface InfoRefsOptions {\n\tservice: GitService;\n\tdefaultBranch?: string;\n\t/** Advertised in the agent capability. Default \"git-fs-s3\". */\n\tagent?: string;\n}\n\n/**\n * `GET …/info/refs?service=…` — the ref advertisement. Authentication and\n * authorization are the caller's job before invoking this.\n *\n * Capabilities advertised match what the sibling handlers implement:\n * side-band-64k (honored by handleUploadPack's response framing — clients\n * like isomorphic-git unconditionally expect it), tip/reachable sha1 wants,\n * delete-refs and report-status for pushes.\n */\nexport async function handleInfoRefs(\n\trepo: Repo,\n\toptions: InfoRefsOptions,\n\thooks?: HttpHooks,\n): Promise<GitHttpResult> {\n\tconst { service } = options;\n\tconst agent = options.agent ?? \"git-fs-s3\";\n\tconst { refs, headSymref } = await runStep(hooks, \"listAllRefs\", () =>\n\t\tlistAllRefs(repo, options.defaultBranch ?? \"main\"),\n\t);\n\n\tconst isUpload = service === \"git-upload-pack\";\n\tconst caps = isUpload\n\t\t? `no-progress side-band-64k symref=HEAD:${headSymref} allow-tip-sha1-in-want allow-reachable-sha1-in-want agent=${agent}`\n\t\t: `delete-refs report-status no-done agent=${agent}`;\n\n\tconst parts: Uint8Array[] = [pktLine(`# service=${service}\\n`), FLUSH];\n\n\tif (refs.length === 0) {\n\t\t// Empty repo: git needs this exact sentinel\n\t\tparts.push(\n\t\t\tpktLine(\n\t\t\t\t`0000000000000000000000000000000000000000 capabilities^{}\\0${caps}\\n`,\n\t\t\t),\n\t\t);\n\t} else {\n\t\tlet first = true;\n\t\tfor (const { name, oid } of refs) {\n\t\t\tparts.push(\n\t\t\t\tpktLine(first ? `${oid} ${name}\\0${caps}\\n` : `${oid} ${name}\\n`),\n\t\t\t);\n\t\t\tfirst = false;\n\t\t}\n\t}\n\tparts.push(FLUSH);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": `application/x-${service}-advertisement`,\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: concat(...parts),\n\t};\n}\n","/**\n * Git pkt-line framing (smart HTTP protocol wire format).\n *\n * Edge-compatible: uses Uint8Array instead of Buffer.\n */\n\nimport { concat, decodeAscii, decodeUtf8, encodeUtf8 } from \"../edge-utils.js\";\n\n/** Flush packet: exactly four zero bytes. */\nexport const FLUSH: Uint8Array<ArrayBuffer> = new Uint8Array([\n\t0x30, 0x30, 0x30, 0x30,\n]); // \"0000\"\n\n/** Frame a UTF-8 string as one pkt-line. */\nexport function pktLine(data: string): Uint8Array<ArrayBuffer> {\n\tconst body = encodeUtf8(data);\n\tconst len = (body.length + 4).toString(16).padStart(4, \"0\");\n\treturn concat(encodeUtf8(len), body);\n}\n\n/** Frame raw bytes as one pkt-line. */\nexport function pktLineBuffer(body: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst len = (body.length + 4).toString(16).padStart(4, \"0\");\n\treturn concat(encodeUtf8(len), body);\n}\n\n/** Decode pkt-lines to strings; `null` marks a flush-pkt. Stops on garbage. */\nexport function parsePktLines(buf: Uint8Array): Array<string | null> {\n\tconst lines: Array<string | null> = [];\n\tlet pos = 0;\n\twhile (pos + 4 <= buf.length) {\n\t\tconst len = Number.parseInt(decodeAscii(buf.subarray(pos, pos + 4)), 16);\n\t\tif (len === 0) {\n\t\t\tlines.push(null);\n\t\t\tpos += 4;\n\t\t} else if (len >= 4) {\n\t\t\tlines.push(decodeUtf8(buf.subarray(pos + 4, pos + len)));\n\t\t\tpos += len;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn lines;\n}\n\n/**\n * Per the git protocol, once side-band-64k has been negotiated, packfile\n * bytes in the upload-pack response must be chunked into pkt-lines each\n * prefixed with a control byte (0x01 = packfile data), terminated by a\n * flush-pkt. Without this, clients that don't special-case \"no side-band\" —\n * e.g. isomorphic-git's GitSideBand.demux, which always treats the response\n * as side-band-framed — misparse the raw packfile bytes as bogus pkt-line\n * length headers and spin forever. (Native `git` tolerates a raw unframed\n * stream when side-band isn't negotiated, so this only surfaces with\n * isomorphic-git as the HTTP client.)\n */\nconst SIDE_BAND_MAX_CHUNK = 65515;\n\nexport function sideBandPackfile(\n\tpackData: Uint8Array,\n): Uint8Array<ArrayBuffer> {\n\tconst parts: Uint8Array[] = [];\n\tfor (\n\t\tlet offset = 0;\n\t\toffset < packData.length;\n\t\toffset += SIDE_BAND_MAX_CHUNK\n\t) {\n\t\tconst chunk = packData.subarray(offset, offset + SIDE_BAND_MAX_CHUNK);\n\t\tparts.push(pktLineBuffer(concat(new Uint8Array([1]), chunk)));\n\t}\n\tparts.push(FLUSH);\n\treturn concat(...parts);\n}\n","import type { Repo } from \"../ops/types.js\";\n\n/**\n * Transport-agnostic HTTP response the handlers produce.\n *\n * `body` is pinned to `Uint8Array<ArrayBuffer>` (not the bare `Uint8Array`,\n * whose default type argument isn't consistent across TypeScript versions)\n * so it's always assignable to Fetch API `BodyInit` regardless of which\n * TypeScript/lib version a consumer compiles against — every producer here\n * (`concat`, `pktLine`, `TextEncoder.encode`) is ArrayBuffer-backed already.\n */\nexport interface GitHttpResult {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody: Uint8Array<ArrayBuffer>;\n}\n\n/** Optional instrumentation hooks shared by the /http handlers. */\nexport interface HttpHooks {\n\t/** Wrap a timed sub-step. Default: run directly. */\n\tstep?: <T>(label: string, fn: () => Promise<T>) => Promise<T>;\n\t/** Non-fatal problem sink (missing objects, failed repacks). */\n\tonWarn?: (message: string, error?: unknown) => void;\n}\n\nexport const runStep = <T>(\n\thooks: HttpHooks | undefined,\n\tlabel: string,\n\tfn: () => Promise<T>,\n): Promise<T> => (hooks?.step ? hooks.step(label, fn) : fn());\n\n/**\n * The raw promise-fs surface some /http paths need beyond isomorphic-git's\n * plumbing (writing an incoming pack file, listing/deleting pack files).\n * Both `node:fs` and this package's `GitFs` satisfy it via `.promises`.\n */\nexport interface RawFsPromises {\n\treadFile(path: string): Promise<Uint8Array | string>;\n\twriteFile(path: string, data: Uint8Array | string): Promise<void>;\n\tunlink(path: string): Promise<void>;\n\treaddir(path: string): Promise<string[]>;\n\tmkdir(path: string, options?: { recursive?: boolean }): Promise<unknown>;\n\tstat(path: string): Promise<unknown>;\n}\n\n/** Duck-type the `.promises` surface off a repo's fs. */\nexport function rawFs(repo: Repo): RawFsPromises {\n\tconst fs = repo.fs as { promises?: RawFsPromises };\n\tif (!fs?.promises) {\n\t\tthrow new TypeError(\n\t\t\t\"This operation needs a promise fs (`fs.promises`) — node:fs and createGitFs both provide one\",\n\t\t);\n\t}\n\treturn fs.promises;\n}\n","import git from \"isomorphic-git\";\nimport type { Repo } from \"../ops/types.js\";\nimport type { HttpHooks } from \"./types.js\";\n\nexport interface ReachabilityResult {\n\toids: string[];\n\t/**\n\t * False if any object in the graph couldn't be read — repack uses this\n\t * (not a raw object-count comparison) to decide whether it's safe to\n\t * delete old packs: counts alone can't distinguish \"everything read fine\"\n\t * from \"some objects silently failed\".\n\t */\n\tcomplete: boolean;\n}\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * A read landing in the gap between a repack's new consolidated pack being\n * uploaded and the stale-pack cleanup finishing can transiently miss an\n * object that is not actually lost — it exists in the new pack the whole\n * time; the reader's cached pack listing was just taken mid-transition. One\n * retry after a short delay is enough to observe the consistent listing.\n */\nconst MISSING_OBJECT_RETRY_DELAY_MS = 200;\n\n/**\n * Walk the object graph from `startOids`, returning every reachable oid.\n * Concurrent traversal paths are deduplicated promise-per-oid; a missing\n * object is retried once, then reported through `hooks.onWarn` and\n * reflected in `complete: false`.\n *\n * `haveOids` bounds the walk: any oid in this set is assumed already\n * verified (it was reachable from a ref that existed before this call) and\n * is recorded in `seen` without being read or descended into. Without a\n * boundary, every call re-walks the *entire* history from scratch — for\n * receive-pack validation (see receive-pack.ts) that means every push pays\n * for reading every object in the repo, not just the ones it introduced,\n * and one transient read failure anywhere in that whole history rejects an\n * otherwise-valid push.\n */\nexport async function collectReachableOids(\n\trepo: Repo,\n\tstartOids: string[],\n\thooks?: HttpHooks,\n\thaveOids?: ReadonlySet<string> | readonly string[],\n): Promise<ReachabilityResult> {\n\tconst have = haveOids instanceof Set ? haveOids : new Set(haveOids ?? []);\n\tconst seen = new Set<string>();\n\tlet complete = true;\n\tconst promises = new Map<string, Promise<void>>();\n\n\tasync function readAndVisitChildren(oid: string): Promise<void> {\n\t\tconst obj = await git.readObject({ ...repo, oid });\n\t\t// Add to seen only after a successful read so failed reads are excluded\n\t\t// from any pack built from this set.\n\t\tseen.add(oid);\n\t\tlet children: string[] = [];\n\t\tif (obj.type === \"commit\") {\n\t\t\tconst { commit } = await git.readCommit({ ...repo, oid });\n\t\t\tchildren = [commit.tree, ...commit.parent];\n\t\t} else if (obj.type === \"tree\") {\n\t\t\tconst { tree } = await git.readTree({ ...repo, oid });\n\t\t\tchildren = tree.map((e) => e.oid);\n\t\t} else if (obj.type === \"tag\") {\n\t\t\tconst { tag } = await git.readTag({ ...repo, oid });\n\t\t\tchildren = [tag.object];\n\t\t}\n\t\tawait Promise.all(children.map(visit));\n\t}\n\n\tfunction visit(oid: string): Promise<void> {\n\t\tconst existing = promises.get(oid);\n\t\tif (existing) return existing;\n\n\t\tif (have.has(oid)) {\n\t\t\tseen.add(oid);\n\t\t\tconst p = Promise.resolve();\n\t\t\tpromises.set(oid, p);\n\t\t\treturn p;\n\t\t}\n\n\t\tconst p = (async () => {\n\t\t\ttry {\n\t\t\t\tawait readAndVisitChildren(oid);\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tawait delay(MISSING_OBJECT_RETRY_DELAY_MS);\n\t\t\t\t\tawait readAndVisitChildren(oid);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t\thooks?.onWarn?.(`missing object ${oid}`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\n\t\tpromises.set(oid, p);\n\t\treturn p;\n\t}\n\n\tawait Promise.all(startOids.map(visit));\n\treturn { oids: Array.from(seen), complete };\n}\n","import git from \"isomorphic-git\";\nimport { concat, decodeAscii, decodeUtf8 } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { isSafeFullRefName } from \"../refs.js\";\nimport { FLUSH, pktLine } from \"./pkt-line.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type RepackOptions, repackRepository } from \"./repack.js\";\nimport { type GitHttpResult, type HttpHooks, rawFs, runStep } from \"./types.js\";\n\nconst ZERO_OID = \"0\".repeat(40);\n\nexport interface RefUpdateCommand {\n\toldOid: string;\n\tnewOid: string;\n\trefName: string;\n}\n\nexport interface RefUpdateResult {\n\trefName: string;\n\tok: boolean;\n\treason?: string;\n}\n\n/** Split a receive-pack body: pkt-line ref commands, flush, then raw PACK. */\nexport function parseReceivePackBody(body: Uint8Array): {\n\trefUpdates: RefUpdateCommand[];\n\tpackData: Uint8Array;\n} {\n\tconst refUpdates: RefUpdateCommand[] = [];\n\tlet pos = 0;\n\twhile (pos + 4 <= body.length) {\n\t\tconst len = Number.parseInt(decodeAscii(body.subarray(pos, pos + 4)), 16);\n\t\tif (len === 0) {\n\t\t\tpos += 4;\n\t\t\tbreak; // flush = end of ref update commands\n\t\t}\n\t\tif (len < 4) break;\n\t\t// Strip NUL-separated capabilities from the first command line\n\t\tconst line = decodeUtf8(body.subarray(pos + 4, pos + len))\n\t\t\t.replace(/\\n$/, \"\")\n\t\t\t.split(\"\\0\")[0];\n\t\tpos += len;\n\t\tconst parts = (line ?? \"\").split(\" \");\n\t\tconst [oldOid, newOid, refName] = parts;\n\t\tif (oldOid && newOid && refName) {\n\t\t\trefUpdates.push({ oldOid, newOid, refName });\n\t\t}\n\t}\n\treturn { refUpdates, packData: body.subarray(pos) };\n}\n\n/** Initialize the repo when its HEAD doesn't exist yet (first push). */\nexport async function ensureRepoInitialized(\n\trepo: Repo,\n\tdefaultBranch = \"main\",\n): Promise<void> {\n\tconst fsp = rawFs(repo);\n\ttry {\n\t\tawait fsp.stat(`${repo.gitdir}/HEAD`);\n\t} catch {\n\t\tawait fsp.mkdir(repo.gitdir, { recursive: true }).catch(() => {});\n\t\tawait git.init({ ...repo, dir: repo.gitdir, defaultBranch, bare: true });\n\t}\n}\n\n/** Write the incoming PACK into objects/pack/ and index it. */\nexport async function indexIncomingPack(\n\trepo: Repo,\n\tpackData: Uint8Array,\n\thooks?: HttpHooks,\n): Promise<string[]> {\n\tif (packData.length < 4) return [];\n\tconst packName = await runStep(\n\t\thooks,\n\t\t\"write + indexPack incoming pack\",\n\t\tasync () => {\n\t\t\tconst fsp = rawFs(repo);\n\t\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\t\tawait fsp.mkdir(packDir, { recursive: true });\n\n\t\t\tconst packName = `recv-${Date.now()}`;\n\t\t\tawait fsp.writeFile(`${packDir}/${packName}.pack`, packData);\n\n\t\t\tawait git.indexPack({\n\t\t\t\t...repo,\n\t\t\t\tdir: packDir,\n\t\t\t\tfilepath: `${packName}.pack`,\n\t\t\t});\n\t\t\treturn packName;\n\t\t},\n\t);\n\treturn [\n\t\t`${repo.gitdir}/objects/pack/${packName}.pack`,\n\t\t`${repo.gitdir}/objects/pack/${packName}.idx`,\n\t];\n}\n\n/**\n * Validate a ref name and compare-and-swap it against its claimed current\n * oid. Returns the failure result to report if either check fails, or\n * `null` when both pass — shared by the preflight check (`validateRefUpdates`,\n * run before the possibly-slow pack indexing/graph-walk work, purely to\n * avoid doing that work for an update already doomed to fail) and the real\n * atomicity guarantee (`applyRefUpdates`, run again right before writing,\n * since a concurrent push could have moved the ref in the time that work\n * took).\n */\nasync function checkRefCas(\n\trepo: Repo,\n\trefName: string,\n\toldOid: string,\n): Promise<RefUpdateResult | null> {\n\tif (!isSafeFullRefName(refName)) {\n\t\treturn { refName, ok: false, reason: \"invalid ref name\" };\n\t}\n\tconst currentOid = await git\n\t\t.resolveRef({ ...repo, ref: refName })\n\t\t.catch(() => ZERO_OID);\n\treturn currentOid === oldOid\n\t\t? null\n\t\t: {\n\t\t\t\trefName,\n\t\t\t\tok: false,\n\t\t\t\treason: \"non-fast-forward, ref updated by another push\",\n\t\t\t};\n}\n\nasync function validateRefUpdates(\n\trepo: Repo,\n\trefUpdates: RefUpdateCommand[],\n): Promise<RefUpdateResult[]> {\n\treturn Promise.all(\n\t\trefUpdates.map(\n\t\t\tasync ({ oldOid, refName }) =>\n\t\t\t\t(await checkRefCas(repo, refName, oldOid)) ?? { refName, ok: true },\n\t\t),\n\t);\n}\n\n/**\n * Apply ref updates, enforcing compare-and-swap against each command's\n * claimed oldOid. Every client-supplied refName is validated before any\n * filesystem call reads or writes through it.\n */\nexport async function applyRefUpdates(\n\trepo: Repo,\n\trefUpdates: RefUpdateCommand[],\n\thooks?: HttpHooks,\n): Promise<RefUpdateResult[]> {\n\treturn runStep(hooks, \"apply ref updates\", () =>\n\t\tPromise.all(\n\t\t\trefUpdates.map(async ({ oldOid, newOid, refName }) => {\n\t\t\t\tconst failure = await checkRefCas(repo, refName, oldOid);\n\t\t\t\tif (failure) return failure;\n\n\t\t\t\tif (newOid === ZERO_OID) {\n\t\t\t\t\tawait git.deleteRef({ ...repo, ref: refName }).catch(() => {});\n\t\t\t\t} else {\n\t\t\t\t\tawait git.writeRef({\n\t\t\t\t\t\t...repo,\n\t\t\t\t\t\tref: refName,\n\t\t\t\t\t\tvalue: newOid,\n\t\t\t\t\t\tforce: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { refName, ok: true };\n\t\t\t}),\n\t\t),\n\t);\n}\n\n/** The report-status response body for a set of ref-update results. */\nexport function receivePackResponse(results: RefUpdateResult[]): GitHttpResult {\n\tconst responseBody = concat(\n\t\tpktLine(\"unpack ok\\n\"),\n\t\t...results.map(({ refName, ok, reason }) =>\n\t\t\tpktLine(ok ? `ok ${refName}\\n` : `ng ${refName} ${reason}\\n`),\n\t\t),\n\t\tFLUSH,\n\t);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-git-receive-pack-result\",\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: responseBody,\n\t};\n}\n\nexport interface ApplyReceivePackOptions {\n\tdefaultBranch?: string;\n\t/**\n\t * Repack tuning, or `false` to skip repacking entirely. The returned\n\t * `stalePackPaths` are gitdir-relative pack files the repack deleted from\n\t * this repo — after syncing to any secondary storage, delete them there\n\t * too.\n\t */\n\trepack?: RepackOptions | false;\n}\n\n/**\n * The storage half of a push against `repo`: initialize if needed, index the\n * incoming pack, CAS-apply ref updates, then repack when enough packs have\n * accumulated. Serialize concurrent pushes to the same repo externally (a\n * per-repo lock); build the HTTP response afterwards with\n * {@link receivePackResponse}.\n */\nexport async function applyReceivePack(\n\trepo: Repo,\n\tparsed: { refUpdates: RefUpdateCommand[]; packData: Uint8Array },\n\toptions?: ApplyReceivePackOptions,\n\thooks?: HttpHooks,\n): Promise<{ results: RefUpdateResult[]; stalePackPaths: string[] }> {\n\tawait ensureRepoInitialized(repo, options?.defaultBranch ?? \"main\");\n\tconst preflight = await validateRefUpdates(repo, parsed.refUpdates);\n\tconst acceptedUpdates = parsed.refUpdates.filter(\n\t\t(_, index) => preflight[index]?.ok,\n\t);\n\tconst incomingPackPaths = await indexIncomingPack(\n\t\trepo,\n\t\tacceptedUpdates.some((update) => update.newOid !== ZERO_OID)\n\t\t\t? parsed.packData\n\t\t\t: new Uint8Array(),\n\t\thooks,\n\t);\n\n\tconst newTips = acceptedUpdates\n\t\t.filter((update) => update.newOid !== ZERO_OID)\n\t\t.map((update) => update.newOid);\n\tif (newTips.length > 0) {\n\t\t// Each update's pre-image (oldOid) was already reachable and readable\n\t\t// before this push — a fast-forward or new-branch push only needs its\n\t\t// *new* objects validated, not the whole pre-existing history again.\n\t\tconst haveOids = acceptedUpdates\n\t\t\t.map((update) => update.oldOid)\n\t\t\t.filter((oid) => oid !== ZERO_OID);\n\t\tconst { complete } = await collectReachableOids(\n\t\t\trepo,\n\t\t\tnewTips,\n\t\t\thooks,\n\t\t\thaveOids,\n\t\t);\n\t\tif (!complete) {\n\t\t\tawait Promise.all(\n\t\t\t\tincomingPackPaths.map((filepath) =>\n\t\t\t\t\trawFs(repo)\n\t\t\t\t\t\t.unlink(filepath)\n\t\t\t\t\t\t.catch(() => {}),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tresults: preflight.map((result) =>\n\t\t\t\t\tresult.ok\n\t\t\t\t\t\t? { ...result, ok: false, reason: \"incomplete object graph\" }\n\t\t\t\t\t\t: result,\n\t\t\t\t),\n\t\t\t\tstalePackPaths: [],\n\t\t\t};\n\t\t}\n\t}\n\n\tconst applied = await applyRefUpdates(repo, acceptedUpdates, hooks);\n\tconst results = preflight.map((result, index) =>\n\t\tresult.ok\n\t\t\t? (applied.find(\n\t\t\t\t\t(entry) => entry.refName === parsed.refUpdates[index]?.refName,\n\t\t\t\t) ?? result)\n\t\t\t: result,\n\t);\n\tconst repackOptions = options?.repack;\n\tconst stalePackPaths =\n\t\trepackOptions === false || !results.some((result) => result.ok)\n\t\t\t? []\n\t\t\t: await runStep(hooks, \"repack\", () =>\n\t\t\t\t\trepackRepository(repo, repackOptions, hooks),\n\t\t\t\t);\n\treturn { results, stalePackPaths };\n}\n","/**\n * Pack consolidation: merge all packs into one verified, non-deltified pack.\n *\n * Edge-compatible: uses Web Crypto (SHA-1), CompressionStream (deflate),\n * and Uint8Array throughout — no node:crypto, node:zlib, or Buffer.\n */\n\nimport git from \"isomorphic-git\";\nimport { concat, deflate, encodeUtf8, fromHex, sha1 } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type HttpHooks, rawFs } from \"./types.js\";\n\ntype PackObjectType = \"commit\" | \"tree\" | \"blob\" | \"tag\";\n\n// Git pack object type bits (bits 6-4 of the header's first byte) — same\n// constants real git and isomorphic-git's own (de)serializers use.\nconst PACK_OBJECT_TYPE_BITS: Record<PackObjectType, number> = {\n\tcommit: 0b0010000,\n\ttree: 0b0100000,\n\tblob: 0b0110000,\n\ttag: 0b1000000,\n};\n\n// Git's pack object header: first byte packs (continuation bit | 3-bit type |\n// low 4 bits of length); any remaining length is emitted 7 bits at a time,\n// each with its own continuation bit, little-endian.\nfunction encodePackObjectHeader(\n\ttype: PackObjectType,\n\tlength: number,\n): Uint8Array {\n\tconst bytes: number[] = [];\n\tlet more = length > 0b1111;\n\tbytes.push(\n\t\t(more ? 0b10000000 : 0) | PACK_OBJECT_TYPE_BITS[type] | (length & 0b1111),\n\t);\n\tlength >>>= 4;\n\twhile (more) {\n\t\tmore = length > 0b01111111;\n\t\tbytes.push((more ? 0b10000000 : 0) | (length & 0b01111111));\n\t\tlength >>>= 7;\n\t}\n\treturn new Uint8Array(bytes);\n}\n\n// Git's object hash: sha1(\"<type> <byte length>\\0<content>\") — matches\n// isomorphic-git's internal GitObject.wrap + shasum, computed independently\n// here rather than trusted from isomorphic-git's own read path.\nasync function hashGitObject(\n\ttype: string,\n\tcontent: Uint8Array,\n): Promise<string> {\n\tconst prefix = encodeUtf8(`${type} ${content.length}\\0`);\n\treturn sha1(concat(prefix, content));\n}\n\ntype VerifiedObject = { type: PackObjectType; content: Uint8Array };\n\n/**\n * Read every reachable object and independently re-derive its oid from the\n * bytes isomorphic-git handed back, instead of trusting the oid it was asked\n * for. isomorphic-git's *packed*-object read path never verifies the\n * resolved content's SHA-1 against the requested oid — only the\n * loose-object branch does.\n */\nasync function readAndVerifyObjects(\n\trepo: Repo,\n\toids: string[],\n): Promise<Map<string, VerifiedObject>> {\n\tconst objects = new Map<string, VerifiedObject>();\n\tconst BATCH_SIZE = 100;\n\tfor (let i = 0; i < oids.length; i += BATCH_SIZE) {\n\t\tconst batch = oids.slice(i, i + BATCH_SIZE);\n\t\tconst entries = await Promise.all(\n\t\t\tbatch.map(async (oid) => {\n\t\t\t\tconst { type, object } = await git.readObject({\n\t\t\t\t\t...repo,\n\t\t\t\t\toid,\n\t\t\t\t\tformat: \"content\",\n\t\t\t\t});\n\t\t\t\tconst content = object as unknown as Uint8Array;\n\t\t\t\tconst actualOid = await hashGitObject(type, content);\n\t\t\t\tif (actualOid !== oid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`repack: object ${oid} failed independent SHA-1 verification ` +\n\t\t\t\t\t\t\t`(recomputed ${actualOid}) — refusing to trust this read, aborting repack`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { oid, type: type as PackObjectType, content };\n\t\t\t}),\n\t\t);\n\t\tfor (const { oid, type, content } of entries) {\n\t\t\tobjects.set(oid, { type, content });\n\t\t}\n\t}\n\treturn objects;\n}\n\n/**\n * Serialize verified objects into a pack containing only full (never\n * deltified) entries, in the given oid order.\n */\nasync function buildVerifiedPack(\n\toids: string[],\n\tobjects: Map<string, VerifiedObject>,\n): Promise<Uint8Array> {\n\t// PACK header: \"PACK\" + version(2) + count, all big-endian uint32\n\tconst header = new Uint8Array(12);\n\tconst view = new DataView(header.buffer);\n\theader.set(encodeUtf8(\"PACK\"), 0);\n\tview.setUint32(4, 2, false); // version 2\n\tview.setUint32(8, oids.length, false); // object count\n\n\tconst chunks: Uint8Array[] = [header];\n\n\tconst BATCH_SIZE = 100;\n\tfor (let i = 0; i < oids.length; i += BATCH_SIZE) {\n\t\tconst batch = oids.slice(i, i + BATCH_SIZE);\n\t\tconst encoded = await Promise.all(\n\t\t\tbatch.map(async (oid) => {\n\t\t\t\tconst entry = objects.get(oid);\n\t\t\t\tif (!entry) {\n\t\t\t\t\tthrow new Error(`repack: missing verified object for ${oid}`);\n\t\t\t\t}\n\t\t\t\tconst objHeader = encodePackObjectHeader(\n\t\t\t\t\tentry.type,\n\t\t\t\t\tentry.content.length,\n\t\t\t\t);\n\t\t\t\tconst compressed = await deflate(entry.content);\n\t\t\t\treturn concat(objHeader, compressed);\n\t\t\t}),\n\t\t);\n\t\tchunks.push(...encoded);\n\t}\n\n\t// Git's pack trailer is the SHA-1 of every preceding byte (header +\n\t// every object entry) as a single digest — NOT an incremental/chained\n\t// hash. Web Crypto's subtle.digest has no streaming mode, so unlike\n\t// Node's crypto.createHash this can't be folded into the loop above;\n\t// everything is already buffered in `chunks`, so hash it in one pass.\n\tconst packBody = concat(...chunks);\n\tconst trailer = fromHex(await sha1(packBody));\n\treturn concat(packBody, trailer);\n}\n\n/**\n * Default repack threshold. Consolidating is O(total repo object count) —\n * so paying it on every push makes push latency grow with repo size forever.\n */\nexport const REPACK_PACK_COUNT_THRESHOLD = 4;\n\nasync function countPacks(repo: Repo): Promise<number> {\n\ttry {\n\t\tconst entries = await rawFs(repo).readdir(`${repo.gitdir}/objects/pack`);\n\t\treturn entries.filter((f) => f.endsWith(\".pack\")).length;\n\t} catch {\n\t\treturn 0;\n\t}\n}\n\nexport interface RepackOptions {\n\t/** Skip repacking below this many accumulated packs. Default 4. */\n\tthreshold?: number;\n}\n\n/**\n * Consolidate all pack files into one, returning the gitdir-relative paths\n * of the old .pack/.idx files it removed — after syncing the new pack to any\n * secondary storage, delete those same paths there too.\n */\nexport async function repackRepository(\n\trepo: Repo,\n\toptions?: RepackOptions,\n\thooks?: HttpHooks,\n): Promise<string[]> {\n\tconst threshold = options?.threshold ?? REPACK_PACK_COUNT_THRESHOLD;\n\tconst fsp = rawFs(repo);\n\ttry {\n\t\tif ((await countPacks(repo)) < threshold) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst [branches, tags] = await Promise.all([\n\t\t\tgit.listBranches(repo),\n\t\t\tgit.listTags(repo),\n\t\t]);\n\t\tconst refNames = [\n\t\t\t...branches.map((b) => `refs/heads/${b}`),\n\t\t\t...tags.map((t) => `refs/tags/${t}`),\n\t\t];\n\t\tconst tipOids = (\n\t\t\tawait Promise.all(\n\t\t\t\trefNames.map((ref) =>\n\t\t\t\t\tgit.resolveRef({ ...repo, ref }).catch(() => null),\n\t\t\t\t),\n\t\t\t)\n\t\t).filter((oid): oid is string => oid !== null);\n\t\tif (tipOids.length === 0) return [];\n\n\t\tconst { oids, complete } = await collectReachableOids(repo, tipOids, hooks);\n\t\tif (!complete || oids.length === 0) return [];\n\n\t\tconst objects = await readAndVerifyObjects(repo, oids);\n\t\tconst packBuffer = await buildVerifiedPack(oids, objects);\n\n\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\tawait fsp.mkdir(packDir, { recursive: true });\n\t\tconst newBase = `pack-${Date.now()}`;\n\t\tconst newPackFile = `${newBase}.pack`;\n\t\tconst newIdxFile = `${newBase}.idx`;\n\t\tawait fsp.writeFile(`${packDir}/${newPackFile}`, packBuffer);\n\n\t\tconst { oids: indexedOids } = await git.indexPack({\n\t\t\t...repo,\n\t\t\tdir: packDir,\n\t\t\tfilepath: newPackFile,\n\t\t});\n\n\t\tconst expected = new Set(oids);\n\t\tconst indexed = new Set(indexedOids);\n\t\tif (\n\t\t\tindexed.size !== expected.size ||\n\t\t\toids.some((oid) => !indexed.has(oid))\n\t\t) {\n\t\t\tawait fsp.unlink(`${packDir}/${newPackFile}`).catch(() => {});\n\t\t\tawait fsp.unlink(`${packDir}/${newIdxFile}`).catch(() => {});\n\t\t\tthrow new Error(\n\t\t\t\t\"repack: indexed pack's oid set didn't match the verified reachable set — aborting\",\n\t\t\t);\n\t\t}\n\n\t\tconst allEntries: string[] = await fsp.readdir(packDir).catch(() => []);\n\n\t\tconst staleFiles = allEntries.filter(\n\t\t\t(f) =>\n\t\t\t\tf !== newPackFile &&\n\t\t\t\tf !== newIdxFile &&\n\t\t\t\t(f.endsWith(\".pack\") || f.endsWith(\".idx\") || f.endsWith(\".keep\")),\n\t\t);\n\n\t\tawait Promise.all(\n\t\t\tstaleFiles.map((f) => fsp.unlink(`${packDir}/${f}`).catch(() => {})),\n\t\t);\n\n\t\treturn staleFiles.map((f) => `objects/pack/${f}`);\n\t} catch (err) {\n\t\thooks?.onWarn?.(\"repack failed (non-fatal)\", err);\n\t\treturn [];\n\t}\n}\n","import git from \"isomorphic-git\";\nimport { concat } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { parsePktLines, pktLine, sideBandPackfile } from \"./pkt-line.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type GitHttpResult, type HttpHooks, rawFs, runStep } from \"./types.js\";\n\nconst ZERO_OID = \"0\".repeat(40);\n\nexport interface UploadPackOptions {\n\t/**\n\t * Called once before the reachability walk — wire loose-object detection\n\t * (`GitFs.detectLooseObjects`) here so a fully packed repo's walk doesn't\n\t * pay a doomed loose-object probe per object.\n\t */\n\tbeforeWalk?: () => Promise<void>;\n}\n\n/**\n * `POST …/git-upload-pack` — serve a clone/fetch. Authorization is the\n * caller's job. Negotiation is client-driven (no multi_ack advertised):\n * \"have\" batches without \"done\" get a bare NAK; the final batch gets the\n * packfile, side-band-64k framed.\n *\n * Fast path: a fresh clone (no haves) of a repo consolidated down to a\n * single pack serves that pack's bytes directly — skipping the O(objects)\n * traversal + repack entirely.\n */\nexport async function handleUploadPack(\n\trepo: Repo,\n\tbody: Uint8Array,\n\toptions?: UploadPackOptions,\n\thooks?: HttpHooks,\n): Promise<GitHttpResult> {\n\tconst lines = parsePktLines(body);\n\n\tconst wants: string[] = [];\n\tconst haves: string[] = [];\n\tlet done = false;\n\tfor (const line of lines) {\n\t\tif (!line) continue;\n\t\tif (line.startsWith(\"want \")) {\n\t\t\twants.push(line.slice(5, 45));\n\t\t}\n\t\tif (line.startsWith(\"have \")) {\n\t\t\tconst sha = line.slice(5, 45);\n\t\t\tif (sha !== ZERO_OID) {\n\t\t\t\thaves.push(sha);\n\t\t\t}\n\t\t}\n\t\tif (line.startsWith(\"done\")) {\n\t\t\tdone = true;\n\t\t}\n\t}\n\n\tif (wants.length === 0) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { \"Content-Type\": \"application/x-git-upload-pack-result\" },\n\t\t\tbody: concat(pktLine(\"NAK\\n\")),\n\t\t};\n\t}\n\n\tif (haves.length > 0 && !done) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { \"Content-Type\": \"application/x-git-upload-pack-result\" },\n\t\t\tbody: concat(pktLine(\"NAK\\n\")),\n\t\t};\n\t}\n\n\t// Fresh clone = no haves, so all objects are needed. When the repo is down\n\t// to a single pack, serve it directly and skip the traversal + pack build.\n\tif (haves.length === 0) {\n\t\tconst packDirPath = `${repo.gitdir}/objects/pack`;\n\t\tconst entries = await runStep(hooks, \"readdir objects/pack\", () =>\n\t\t\trawFs(repo)\n\t\t\t\t.readdir(packDirPath)\n\t\t\t\t.catch(() => [] as string[]),\n\t\t);\n\t\tconst packNames = entries.filter((f) => f.endsWith(\".pack\"));\n\t\tconst packName = packNames[0];\n\t\tif (packNames.length === 1 && packName !== undefined) {\n\t\t\tconst packData = await runStep(\n\t\t\t\thooks,\n\t\t\t\t\"read consolidated pack (fast path)\",\n\t\t\t\t() => rawFs(repo).readFile(`${packDirPath}/${packName}`),\n\t\t\t);\n\t\t\tconst bytes =\n\t\t\t\tpackData instanceof Uint8Array\n\t\t\t\t\t? packData\n\t\t\t\t\t: new TextEncoder().encode(packData as string);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-git-upload-pack-result\",\n\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t},\n\t\t\t\tbody: concat(pktLine(\"NAK\\n\"), sideBandPackfile(bytes)),\n\t\t\t};\n\t\t}\n\t}\n\n\tif (options?.beforeWalk) {\n\t\tawait runStep(hooks, \"beforeWalk\", options.beforeWalk);\n\t}\n\n\tconst { oids: wantOids } = await runStep(\n\t\thooks,\n\t\t\"collectReachableOids(wants)\",\n\t\t() => collectReachableOids(repo, wants, hooks),\n\t);\n\tlet oids = wantOids;\n\n\tif (haves.length > 0) {\n\t\tconst { oids: haveOids } = await runStep(\n\t\t\thooks,\n\t\t\t\"collectReachableOids(haves)\",\n\t\t\t() => collectReachableOids(repo, haves, hooks),\n\t\t);\n\t\tconst haveSet = new Set(haveOids);\n\t\toids = oids.filter((oid) => !haveSet.has(oid));\n\t}\n\n\tconst { packfile } = await runStep(\n\t\thooks,\n\t\t`packObjects (${oids.length} oids)`,\n\t\t() => git.packObjects({ ...repo, oids }),\n\t);\n\n\tconst packBytes =\n\t\tpackfile instanceof Uint8Array ? packfile : new Uint8Array(packfile ?? []);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-git-upload-pack-result\",\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: concat(pktLine(\"NAK\\n\"), sideBandPackfile(packBytes)),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,OAAO,SAAS;;;ACST,IAAM,QAAiC,IAAI,WAAW;AAAA,EAC5D;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AACnB,CAAC;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;","names":["git","p","git","git","git","git","packName","git","ZERO_OID","git"]}
1
+ {"version":3,"sources":["../src/http/info-refs.ts","../src/http/pkt-line.ts","../src/http/types.ts","../src/http/reachability.ts","../src/http/receive-pack.ts","../src/http/repack.ts","../src/http/pack-reuse.ts","../src/http/upload-pack.ts"],"sourcesContent":["import git from \"isomorphic-git\";\nimport { concat } from \"../edge-utils.js\";\nimport {\n\tlistBranches,\n\tlistLooseRefNames,\n\tresolveLooseRefFast,\n} from \"../ops/branch.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { FLUSH, pktLine } from \"./pkt-line.js\";\nimport { type GitHttpResult, type HttpHooks, runStep } from \"./types.js\";\n\nexport type GitService = \"git-upload-pack\" | \"git-receive-pack\";\n\n/** All refs with resolved oids, plus the symref HEAD should advertise. */\nexport async function listAllRefs(repo: Repo, defaultBranch = \"main\") {\n\tconst [branches, tagNames] = await Promise.all([\n\t\tlistBranches(repo),\n\t\tlistLooseRefNames(repo, \"refs/tags\").then(\n\t\t\t(names) => names ?? git.listTags(repo),\n\t\t),\n\t]);\n\tconst tagRefs = await Promise.all(\n\t\ttagNames.map(async (tag) => {\n\t\t\tconst name = `refs/tags/${tag}`;\n\t\t\treturn resolveLooseRefFast(repo, name)\n\t\t\t\t.then((oid) => ({ name, oid }))\n\t\t\t\t.catch(() => null);\n\t\t}),\n\t);\n\tconst branchRefs = branches.map((b) => ({\n\t\tname: `refs/heads/${b.name}`,\n\t\toid: b.commit,\n\t}));\n\tconst defaultRef = branches.find((b) => b.isDefault);\n\tconst headSymref = defaultRef\n\t\t? `refs/heads/${defaultRef.name}`\n\t\t: await Promise.resolve(git.currentBranch({ ...repo, fullname: true }))\n\t\t\t\t.then((cb) => cb ?? `refs/heads/${defaultBranch}`)\n\t\t\t\t.catch(() => `refs/heads/${defaultBranch}`);\n\n\t// HEAD in a bare repo is almost always a symref to a branch whose oid\n\t// branchRefs already resolved above with one direct GET each — reuse it\n\t// instead of a second, separate resolveRef(\"HEAD\") call. isomorphic-git's\n\t// ref resolution runs its full multi-candidate expansion (refs/%s,\n\t// refs/tags/%s, refs/heads/%s, refs/remotes/%s, refs/remotes/%s/HEAD)\n\t// even when the symref target is already fully qualified, which used to\n\t// cost several guaranteed-404 R2 reads on every clone/fetch. Falls back\n\t// to the slow-but-correct path only when that lookup misses: detached\n\t// HEAD (points at a raw sha, not a symref) or a symref to a branch that\n\t// doesn't exist yet (freshly initialized, still-empty repo).\n\tconst headOid =\n\t\tbranchRefs.find((r) => r?.name === headSymref)?.oid ??\n\t\t(await git.resolveRef({ ...repo, ref: \"HEAD\" }).catch(() => null));\n\n\tconst refs: Array<{ name: string; oid: string }> = [];\n\tif (headOid) refs.push({ name: \"HEAD\", oid: headOid });\n\tfor (const r of branchRefs) if (r) refs.push(r);\n\tfor (const r of tagRefs) if (r) refs.push(r);\n\n\treturn { refs, headSymref };\n}\n\nexport interface InfoRefsOptions {\n\tservice: GitService;\n\tdefaultBranch?: string;\n\t/** Advertised in the agent capability. Default \"git-fs-s3\". */\n\tagent?: string;\n}\n\n/**\n * `GET …/info/refs?service=…` — the ref advertisement. Authentication and\n * authorization are the caller's job before invoking this.\n *\n * Capabilities advertised match what the sibling handlers implement:\n * side-band-64k (honored by handleUploadPack's response framing — clients\n * like isomorphic-git unconditionally expect it), tip/reachable sha1 wants,\n * delete-refs and report-status for pushes.\n */\nexport async function handleInfoRefs(\n\trepo: Repo,\n\toptions: InfoRefsOptions,\n\thooks?: HttpHooks,\n): Promise<GitHttpResult> {\n\tconst { service } = options;\n\tconst agent = options.agent ?? \"git-fs-s3\";\n\tconst { refs, headSymref } = await runStep(hooks, \"listAllRefs\", () =>\n\t\tlistAllRefs(repo, options.defaultBranch ?? \"main\"),\n\t);\n\n\tconst isUpload = service === \"git-upload-pack\";\n\tconst caps = isUpload\n\t\t? `no-progress side-band-64k symref=HEAD:${headSymref} allow-tip-sha1-in-want allow-reachable-sha1-in-want agent=${agent}`\n\t\t: `delete-refs report-status no-done agent=${agent}`;\n\n\tconst parts: Uint8Array[] = [pktLine(`# service=${service}\\n`), FLUSH];\n\n\tif (refs.length === 0) {\n\t\t// Empty repo: git needs this exact sentinel\n\t\tparts.push(\n\t\t\tpktLine(\n\t\t\t\t`0000000000000000000000000000000000000000 capabilities^{}\\0${caps}\\n`,\n\t\t\t),\n\t\t);\n\t} else {\n\t\tlet first = true;\n\t\tfor (const { name, oid } of refs) {\n\t\t\tparts.push(\n\t\t\t\tpktLine(first ? `${oid} ${name}\\0${caps}\\n` : `${oid} ${name}\\n`),\n\t\t\t);\n\t\t\tfirst = false;\n\t\t}\n\t}\n\tparts.push(FLUSH);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": `application/x-${service}-advertisement`,\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: concat(...parts),\n\t};\n}\n","/**\n * Git pkt-line framing (smart HTTP protocol wire format).\n *\n * Edge-compatible: uses Uint8Array instead of Buffer.\n */\n\nimport { concat, decodeAscii, decodeUtf8, encodeUtf8 } from \"../edge-utils.js\";\n\n/** Flush packet: exactly four zero bytes. */\nexport const FLUSH: Uint8Array<ArrayBuffer> = new Uint8Array([\n\t0x30, 0x30, 0x30, 0x30,\n]); // \"0000\"\n\n/** Frame a UTF-8 string as one pkt-line. */\nexport function pktLine(data: string): Uint8Array<ArrayBuffer> {\n\tconst body = encodeUtf8(data);\n\tconst len = (body.length + 4).toString(16).padStart(4, \"0\");\n\treturn concat(encodeUtf8(len), body);\n}\n\n/** Frame raw bytes as one pkt-line. */\nexport function pktLineBuffer(body: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst len = (body.length + 4).toString(16).padStart(4, \"0\");\n\treturn concat(encodeUtf8(len), body);\n}\n\n/** Decode pkt-lines to strings; `null` marks a flush-pkt. Stops on garbage. */\nexport function parsePktLines(buf: Uint8Array): Array<string | null> {\n\tconst lines: Array<string | null> = [];\n\tlet pos = 0;\n\twhile (pos + 4 <= buf.length) {\n\t\tconst len = Number.parseInt(decodeAscii(buf.subarray(pos, pos + 4)), 16);\n\t\tif (len === 0) {\n\t\t\tlines.push(null);\n\t\t\tpos += 4;\n\t\t} else if (len >= 4) {\n\t\t\tlines.push(decodeUtf8(buf.subarray(pos + 4, pos + len)));\n\t\t\tpos += len;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn lines;\n}\n\n/**\n * Per the git protocol, once side-band-64k has been negotiated, packfile\n * bytes in the upload-pack response must be chunked into pkt-lines each\n * prefixed with a control byte (0x01 = packfile data), terminated by a\n * flush-pkt. Without this, clients that don't special-case \"no side-band\" —\n * e.g. isomorphic-git's GitSideBand.demux, which always treats the response\n * as side-band-framed — misparse the raw packfile bytes as bogus pkt-line\n * length headers and spin forever. (Native `git` tolerates a raw unframed\n * stream when side-band isn't negotiated, so this only surfaces with\n * isomorphic-git as the HTTP client.)\n */\nconst SIDE_BAND_MAX_CHUNK = 65515;\n\nexport function sideBandPackfile(\n\tpackData: Uint8Array,\n): Uint8Array<ArrayBuffer> {\n\tconst parts: Uint8Array[] = [];\n\tfor (\n\t\tlet offset = 0;\n\t\toffset < packData.length;\n\t\toffset += SIDE_BAND_MAX_CHUNK\n\t) {\n\t\tconst chunk = packData.subarray(offset, offset + SIDE_BAND_MAX_CHUNK);\n\t\tparts.push(pktLineBuffer(concat(new Uint8Array([1]), chunk)));\n\t}\n\tparts.push(FLUSH);\n\treturn concat(...parts);\n}\n","import type { Repo } from \"../ops/types.js\";\n\n/**\n * Transport-agnostic HTTP response the handlers produce.\n *\n * `body` is pinned to `Uint8Array<ArrayBuffer>` (not the bare `Uint8Array`,\n * whose default type argument isn't consistent across TypeScript versions)\n * so it's always assignable to Fetch API `BodyInit` regardless of which\n * TypeScript/lib version a consumer compiles against — every producer here\n * (`concat`, `pktLine`, `TextEncoder.encode`) is ArrayBuffer-backed already.\n */\nexport interface GitHttpResult {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody: Uint8Array<ArrayBuffer>;\n}\n\n/** Optional instrumentation hooks shared by the /http handlers. */\nexport interface HttpHooks {\n\t/** Wrap a timed sub-step. Default: run directly. */\n\tstep?: <T>(label: string, fn: () => Promise<T>) => Promise<T>;\n\t/** Non-fatal problem sink (missing objects, failed repacks). */\n\tonWarn?: (message: string, error?: unknown) => void;\n}\n\nexport const runStep = <T>(\n\thooks: HttpHooks | undefined,\n\tlabel: string,\n\tfn: () => Promise<T>,\n): Promise<T> => (hooks?.step ? hooks.step(label, fn) : fn());\n\n/**\n * The raw promise-fs surface some /http paths need beyond isomorphic-git's\n * plumbing (writing an incoming pack file, listing/deleting pack files).\n * Both `node:fs` and this package's `GitFs` satisfy it via `.promises`.\n */\nexport interface RawFsPromises {\n\treadFile(path: string): Promise<Uint8Array | string>;\n\twriteFile(path: string, data: Uint8Array | string): Promise<void>;\n\tunlink(path: string): Promise<void>;\n\treaddir(path: string): Promise<string[]>;\n\tmkdir(path: string, options?: { recursive?: boolean }): Promise<unknown>;\n\tstat(path: string): Promise<unknown>;\n}\n\n/** Duck-type the `.promises` surface off a repo's fs. */\nexport function rawFs(repo: Repo): RawFsPromises {\n\tconst fs = repo.fs as { promises?: RawFsPromises };\n\tif (!fs?.promises) {\n\t\tthrow new TypeError(\n\t\t\t\"This operation needs a promise fs (`fs.promises`) — node:fs and createGitFs both provide one\",\n\t\t);\n\t}\n\treturn fs.promises;\n}\n","import git from \"isomorphic-git\";\nimport type { Repo } from \"../ops/types.js\";\nimport type { HttpHooks } from \"./types.js\";\n\nexport interface ReachabilityResult {\n\toids: string[];\n\t/**\n\t * False if any object in the graph couldn't be read — repack uses this\n\t * (not a raw object-count comparison) to decide whether it's safe to\n\t * delete old packs: counts alone can't distinguish \"everything read fine\"\n\t * from \"some objects silently failed\".\n\t */\n\tcomplete: boolean;\n}\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * A read landing in the gap between a repack's new consolidated pack being\n * uploaded and the stale-pack cleanup finishing can transiently miss an\n * object that is not actually lost — it exists in the new pack the whole\n * time; the reader's cached pack listing was just taken mid-transition. One\n * retry after a short delay is enough to observe the consistent listing.\n */\nconst MISSING_OBJECT_RETRY_DELAY_MS = 200;\n\n/**\n * Walk the object graph from `startOids`, returning every reachable oid.\n * Concurrent traversal paths are deduplicated promise-per-oid; a missing\n * object is retried once, then reported through `hooks.onWarn` and\n * reflected in `complete: false`.\n *\n * `haveOids` bounds the walk: any oid in this set is assumed already\n * verified (it was reachable from a ref that existed before this call) and\n * is recorded in `seen` without being read or descended into. Without a\n * boundary, every call re-walks the *entire* history from scratch — for\n * receive-pack validation (see receive-pack.ts) that means every push pays\n * for reading every object in the repo, not just the ones it introduced,\n * and one transient read failure anywhere in that whole history rejects an\n * otherwise-valid push.\n *\n * Commits, trees and tags are read once each (parsed). Blobs have no\n * children, so `verifyBlobs: false` records a blob from its tree entry\n * without reading (and inflating) it — for callers that read every blob\n * themselves afterwards anyway, like upload-pack's `packObjects`. Leave it\n * true wherever the walk *is* the existence check (receive-pack, repack).\n */\nexport async function collectReachableOids(\n\trepo: Repo,\n\tstartOids: string[],\n\thooks?: HttpHooks,\n\thaveOids?: ReadonlySet<string> | readonly string[],\n\toptions?: { verifyBlobs?: boolean },\n): Promise<ReachabilityResult> {\n\tconst verifyBlobs = options?.verifyBlobs ?? true;\n\tconst have = haveOids instanceof Set ? haveOids : new Set(haveOids ?? []);\n\tconst seen = new Set<string>();\n\tlet complete = true;\n\tconst promises = new Map<string, Promise<void>>();\n\n\tasync function readAndVisitChildren(oid: string): Promise<void> {\n\t\tconst obj = await git.readObject({ ...repo, oid });\n\t\tseen.add(oid);\n\t\tconst children: [string, string | undefined][] = [];\n\t\tif (obj.type === \"commit\") {\n\t\t\tconst commit = obj.object as { tree: string; parent: string[] };\n\t\t\tchildren.push([commit.tree, \"tree\"]);\n\t\t\tfor (const parent of commit.parent) children.push([parent, \"commit\"]);\n\t\t} else if (obj.type === \"tree\") {\n\t\t\tconst tree = obj.object as { oid: string; type: string }[];\n\t\t\tfor (const entry of tree) {\n\t\t\t\t// Gitlinks (submodules, mode 160000) point at commits in another\n\t\t\t\t// repository; git never stores them here, so following one would\n\t\t\t\t// report a \"missing\" object and fail every walk over that history.\n\t\t\t\tif (entry.type === \"commit\") continue;\n\t\t\t\tchildren.push([entry.oid, entry.type]);\n\t\t\t}\n\t\t} else if (obj.type === \"tag\") {\n\t\t\tchildren.push([(obj.object as { object: string }).object, undefined]);\n\t\t}\n\t\tawait Promise.all(children.map(([child, type]) => visit(child, type)));\n\t}\n\n\tfunction visit(oid: string, type?: string): Promise<void> {\n\t\tconst existing = promises.get(oid);\n\t\tif (existing) return existing;\n\n\t\tif (have.has(oid) || (type === \"blob\" && !verifyBlobs)) {\n\t\t\tseen.add(oid);\n\t\t\tconst p = Promise.resolve();\n\t\t\tpromises.set(oid, p);\n\t\t\treturn p;\n\t\t}\n\n\t\tconst p = (async () => {\n\t\t\ttry {\n\t\t\t\tawait readAndVisitChildren(oid);\n\t\t\t} catch {\n\t\t\t\ttry {\n\t\t\t\t\tawait delay(MISSING_OBJECT_RETRY_DELAY_MS);\n\t\t\t\t\tawait readAndVisitChildren(oid);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t\thooks?.onWarn?.(`missing object ${oid}`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\n\t\tpromises.set(oid, p);\n\t\treturn p;\n\t}\n\n\tawait Promise.all(startOids.map((oid) => visit(oid)));\n\treturn { oids: Array.from(seen), complete };\n}\n","import git from \"isomorphic-git\";\nimport { concat, decodeAscii, decodeUtf8 } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { isSafeFullRefName } from \"../refs.js\";\nimport { FLUSH, pktLine } from \"./pkt-line.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type RepackOptions, repackRepository } from \"./repack.js\";\nimport { type GitHttpResult, type HttpHooks, rawFs, runStep } from \"./types.js\";\n\nconst ZERO_OID = \"0\".repeat(40);\n\nexport interface RefUpdateCommand {\n\toldOid: string;\n\tnewOid: string;\n\trefName: string;\n}\n\nexport interface RefUpdateResult {\n\trefName: string;\n\tok: boolean;\n\treason?: string;\n}\n\n/** Split a receive-pack body: pkt-line ref commands, flush, then raw PACK. */\nexport function parseReceivePackBody(body: Uint8Array): {\n\trefUpdates: RefUpdateCommand[];\n\tpackData: Uint8Array;\n} {\n\tconst refUpdates: RefUpdateCommand[] = [];\n\tlet pos = 0;\n\twhile (pos + 4 <= body.length) {\n\t\tconst len = Number.parseInt(decodeAscii(body.subarray(pos, pos + 4)), 16);\n\t\tif (len === 0) {\n\t\t\tpos += 4;\n\t\t\tbreak; // flush = end of ref update commands\n\t\t}\n\t\tif (len < 4) break;\n\t\t// Strip NUL-separated capabilities from the first command line\n\t\tconst line = decodeUtf8(body.subarray(pos + 4, pos + len))\n\t\t\t.replace(/\\n$/, \"\")\n\t\t\t.split(\"\\0\")[0];\n\t\tpos += len;\n\t\tconst parts = (line ?? \"\").split(\" \");\n\t\tconst [oldOid, newOid, refName] = parts;\n\t\tif (oldOid && newOid && refName) {\n\t\t\trefUpdates.push({ oldOid, newOid, refName });\n\t\t}\n\t}\n\treturn { refUpdates, packData: body.subarray(pos) };\n}\n\n/** Initialize the repo when its HEAD doesn't exist yet (first push). */\nexport async function ensureRepoInitialized(\n\trepo: Repo,\n\tdefaultBranch = \"main\",\n): Promise<void> {\n\tconst fsp = rawFs(repo);\n\ttry {\n\t\tawait fsp.stat(`${repo.gitdir}/HEAD`);\n\t} catch {\n\t\tawait fsp.mkdir(repo.gitdir, { recursive: true }).catch(() => {});\n\t\tawait git.init({ ...repo, dir: repo.gitdir, defaultBranch, bare: true });\n\t}\n}\n\n/** Write the incoming PACK into objects/pack/ and index it. */\nexport async function indexIncomingPack(\n\trepo: Repo,\n\tpackData: Uint8Array,\n\thooks?: HttpHooks,\n): Promise<string[]> {\n\tif (packData.length < 4) return [];\n\tconst packName = await runStep(\n\t\thooks,\n\t\t\"write + indexPack incoming pack\",\n\t\tasync () => {\n\t\t\tconst fsp = rawFs(repo);\n\t\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\t\tawait fsp.mkdir(packDir, { recursive: true });\n\n\t\t\tconst packName = `recv-${Date.now()}`;\n\t\t\tawait fsp.writeFile(`${packDir}/${packName}.pack`, packData);\n\n\t\t\tawait git.indexPack({\n\t\t\t\t...repo,\n\t\t\t\tdir: packDir,\n\t\t\t\tfilepath: `${packName}.pack`,\n\t\t\t});\n\t\t\treturn packName;\n\t\t},\n\t);\n\treturn [\n\t\t`${repo.gitdir}/objects/pack/${packName}.pack`,\n\t\t`${repo.gitdir}/objects/pack/${packName}.idx`,\n\t];\n}\n\n/**\n * Validate a ref name and compare-and-swap it against its claimed current\n * oid. Returns the failure result to report if either check fails, or\n * `null` when both pass — shared by the preflight check (`validateRefUpdates`,\n * run before the possibly-slow pack indexing/graph-walk work, purely to\n * avoid doing that work for an update already doomed to fail) and the real\n * atomicity guarantee (`applyRefUpdates`, run again right before writing,\n * since a concurrent push could have moved the ref in the time that work\n * took).\n */\nasync function checkRefCas(\n\trepo: Repo,\n\trefName: string,\n\toldOid: string,\n): Promise<RefUpdateResult | null> {\n\tif (!isSafeFullRefName(refName)) {\n\t\treturn { refName, ok: false, reason: \"invalid ref name\" };\n\t}\n\tconst currentOid = await git\n\t\t.resolveRef({ ...repo, ref: refName })\n\t\t.catch(() => ZERO_OID);\n\treturn currentOid === oldOid\n\t\t? null\n\t\t: {\n\t\t\t\trefName,\n\t\t\t\tok: false,\n\t\t\t\treason: \"non-fast-forward, ref updated by another push\",\n\t\t\t};\n}\n\n/** Every branch/tag tip currently in the repo, as a validation boundary — see\n * its call site in {@link applyReceivePack}. */\nasync function collectExistingRefTips(repo: Repo): Promise<Set<string>> {\n\tconst [branches, tags] = await Promise.all([\n\t\tgit.listBranches(repo),\n\t\tgit.listTags(repo),\n\t]);\n\tconst refs = [\n\t\t...branches.map((b) => `refs/heads/${b}`),\n\t\t...tags.map((t) => `refs/tags/${t}`),\n\t];\n\tconst oids = await Promise.all(\n\t\trefs.map((ref) => git.resolveRef({ ...repo, ref }).catch(() => null)),\n\t);\n\treturn new Set(oids.filter((oid): oid is string => oid !== null));\n}\n\nasync function validateRefUpdates(\n\trepo: Repo,\n\trefUpdates: RefUpdateCommand[],\n): Promise<RefUpdateResult[]> {\n\treturn Promise.all(\n\t\trefUpdates.map(\n\t\t\tasync ({ oldOid, refName }) =>\n\t\t\t\t(await checkRefCas(repo, refName, oldOid)) ?? { refName, ok: true },\n\t\t),\n\t);\n}\n\n/**\n * Apply ref updates, enforcing compare-and-swap against each command's\n * claimed oldOid. Every client-supplied refName is validated before any\n * filesystem call reads or writes through it.\n */\nexport async function applyRefUpdates(\n\trepo: Repo,\n\trefUpdates: RefUpdateCommand[],\n\thooks?: HttpHooks,\n): Promise<RefUpdateResult[]> {\n\treturn runStep(hooks, \"apply ref updates\", () =>\n\t\tPromise.all(\n\t\t\trefUpdates.map(async ({ oldOid, newOid, refName }) => {\n\t\t\t\tconst failure = await checkRefCas(repo, refName, oldOid);\n\t\t\t\tif (failure) return failure;\n\n\t\t\t\tif (newOid === ZERO_OID) {\n\t\t\t\t\tawait git.deleteRef({ ...repo, ref: refName }).catch(() => {});\n\t\t\t\t} else {\n\t\t\t\t\tawait git.writeRef({\n\t\t\t\t\t\t...repo,\n\t\t\t\t\t\tref: refName,\n\t\t\t\t\t\tvalue: newOid,\n\t\t\t\t\t\tforce: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { refName, ok: true };\n\t\t\t}),\n\t\t),\n\t);\n}\n\n/** The report-status response body for a set of ref-update results. */\nexport function receivePackResponse(results: RefUpdateResult[]): GitHttpResult {\n\tconst responseBody = concat(\n\t\tpktLine(\"unpack ok\\n\"),\n\t\t...results.map(({ refName, ok, reason }) =>\n\t\t\tpktLine(ok ? `ok ${refName}\\n` : `ng ${refName} ${reason}\\n`),\n\t\t),\n\t\tFLUSH,\n\t);\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-git-receive-pack-result\",\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: responseBody,\n\t};\n}\n\nexport interface ApplyReceivePackOptions {\n\tdefaultBranch?: string;\n\t/**\n\t * Repack tuning, or `false` to skip repacking entirely. The returned\n\t * `stalePackPaths` are gitdir-relative pack files the repack deleted from\n\t * this repo — after syncing to any secondary storage, delete them there\n\t * too.\n\t */\n\trepack?: RepackOptions | false;\n}\n\n/**\n * The storage half of a push against `repo`: initialize if needed, index the\n * incoming pack, CAS-apply ref updates, then repack when enough packs have\n * accumulated. Serialize concurrent pushes to the same repo externally (a\n * per-repo lock); build the HTTP response afterwards with\n * {@link receivePackResponse}.\n */\nexport async function applyReceivePack(\n\trepo: Repo,\n\tparsed: { refUpdates: RefUpdateCommand[]; packData: Uint8Array },\n\toptions?: ApplyReceivePackOptions,\n\thooks?: HttpHooks,\n): Promise<{ results: RefUpdateResult[]; stalePackPaths: string[] }> {\n\tawait ensureRepoInitialized(repo, options?.defaultBranch ?? \"main\");\n\tconst preflight = await validateRefUpdates(repo, parsed.refUpdates);\n\tconst acceptedUpdates = parsed.refUpdates.filter(\n\t\t(_, index) => preflight[index]?.ok,\n\t);\n\tconst incomingPackPaths = await indexIncomingPack(\n\t\trepo,\n\t\tacceptedUpdates.some((update) => update.newOid !== ZERO_OID)\n\t\t\t? parsed.packData\n\t\t\t: new Uint8Array(),\n\t\thooks,\n\t);\n\n\tconst newTips = acceptedUpdates\n\t\t.filter((update) => update.newOid !== ZERO_OID)\n\t\t.map((update) => update.newOid);\n\tif (newTips.length > 0) {\n\t\t// Every oid reachable from an existing ref was already accepted by an\n\t\t// earlier push — not just the ref(s) this push happens to touch. A\n\t\t// brand-new branch (oldOid === ZERO_OID, so it has no pre-image of its\n\t\t// own) is the common case this matters for: creating a branch off an\n\t\t// existing one is still just one new commit's worth of new objects,\n\t\t// and shouldn't cost a walk of the entire repo history to validate.\n\t\tconst haveOids = await collectExistingRefTips(repo);\n\t\tfor (const update of acceptedUpdates) {\n\t\t\tif (update.oldOid !== ZERO_OID) haveOids.add(update.oldOid);\n\t\t}\n\t\tconst { complete } = await collectReachableOids(\n\t\t\trepo,\n\t\t\tnewTips,\n\t\t\thooks,\n\t\t\thaveOids,\n\t\t);\n\t\tif (!complete) {\n\t\t\tawait Promise.all(\n\t\t\t\tincomingPackPaths.map((filepath) =>\n\t\t\t\t\trawFs(repo)\n\t\t\t\t\t\t.unlink(filepath)\n\t\t\t\t\t\t.catch(() => {}),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tresults: preflight.map((result) =>\n\t\t\t\t\tresult.ok\n\t\t\t\t\t\t? { ...result, ok: false, reason: \"incomplete object graph\" }\n\t\t\t\t\t\t: result,\n\t\t\t\t),\n\t\t\t\tstalePackPaths: [],\n\t\t\t};\n\t\t}\n\t}\n\n\tconst applied = await applyRefUpdates(repo, acceptedUpdates, hooks);\n\tconst results = preflight.map((result, index) =>\n\t\tresult.ok\n\t\t\t? (applied.find(\n\t\t\t\t\t(entry) => entry.refName === parsed.refUpdates[index]?.refName,\n\t\t\t\t) ?? result)\n\t\t\t: result,\n\t);\n\tconst repackOptions = options?.repack;\n\tconst stalePackPaths =\n\t\trepackOptions === false || !results.some((result) => result.ok)\n\t\t\t? []\n\t\t\t: await runStep(hooks, \"repack\", () =>\n\t\t\t\t\trepackRepository(repo, repackOptions, hooks),\n\t\t\t\t);\n\treturn { results, stalePackPaths };\n}\n","/**\n * Pack consolidation: merge all packs into one, reusing stored (possibly\n * deltified) entries when every object is packed.\n *\n * Edge-compatible: uses Web Crypto (SHA-1), CompressionStream (deflate),\n * and Uint8Array throughout — no node:crypto, node:zlib, or Buffer.\n */\n\nimport git from \"isomorphic-git\";\nimport { concat, deflate, encodeUtf8, fromHex, sha1 } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport {\n\ttype PackFileName,\n\tpackFileName,\n\tparsePackDirectory,\n} from \"../pack-files.js\";\nimport { buildPackFromExistingPacks } from \"./pack-reuse.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type HttpHooks, rawFs } from \"./types.js\";\n\ntype PackObjectType = \"commit\" | \"tree\" | \"blob\" | \"tag\";\n\n// Git pack object type bits (bits 6-4 of the header's first byte) — same\n// constants real git and isomorphic-git's own (de)serializers use.\nconst PACK_OBJECT_TYPE_BITS: Record<PackObjectType, number> = {\n\tcommit: 0b0010000,\n\ttree: 0b0100000,\n\tblob: 0b0110000,\n\ttag: 0b1000000,\n};\n\n// Git's pack object header: first byte packs (continuation bit | 3-bit type |\n// low 4 bits of length); any remaining length is emitted 7 bits at a time,\n// each with its own continuation bit, little-endian.\nfunction encodePackObjectHeader(\n\ttype: PackObjectType,\n\tlength: number,\n): Uint8Array {\n\tconst bytes: number[] = [];\n\tlet more = length > 0b1111;\n\tbytes.push(\n\t\t(more ? 0b10000000 : 0) | PACK_OBJECT_TYPE_BITS[type] | (length & 0b1111),\n\t);\n\tlength >>>= 4;\n\twhile (more) {\n\t\tmore = length > 0b01111111;\n\t\tbytes.push((more ? 0b10000000 : 0) | (length & 0b01111111));\n\t\tlength >>>= 7;\n\t}\n\treturn new Uint8Array(bytes);\n}\n\n// Git's object hash: sha1(\"<type> <byte length>\\0<content>\") — matches\n// isomorphic-git's internal GitObject.wrap + shasum, computed independently\n// here rather than trusted from isomorphic-git's own read path.\nasync function hashGitObject(\n\ttype: string,\n\tcontent: Uint8Array,\n): Promise<string> {\n\tconst prefix = encodeUtf8(`${type} ${content.length}\\0`);\n\treturn sha1(concat(prefix, content));\n}\n\ntype VerifiedObject = { type: PackObjectType; content: Uint8Array };\n\n/**\n * Read every reachable object and independently re-derive its oid from the\n * bytes isomorphic-git handed back, instead of trusting the oid it was asked\n * for. isomorphic-git's *packed*-object read path never verifies the\n * resolved content's SHA-1 against the requested oid — only the\n * loose-object branch does.\n */\nasync function readAndVerifyObjects(\n\trepo: Repo,\n\toids: string[],\n): Promise<Map<string, VerifiedObject>> {\n\tconst objects = new Map<string, VerifiedObject>();\n\tconst BATCH_SIZE = 100;\n\tfor (let i = 0; i < oids.length; i += BATCH_SIZE) {\n\t\tconst batch = oids.slice(i, i + BATCH_SIZE);\n\t\tconst entries = await Promise.all(\n\t\t\tbatch.map(async (oid) => {\n\t\t\t\tconst { type, object } = await git.readObject({\n\t\t\t\t\t...repo,\n\t\t\t\t\toid,\n\t\t\t\t\tformat: \"content\",\n\t\t\t\t});\n\t\t\t\tconst content = object as unknown as Uint8Array;\n\t\t\t\tconst actualOid = await hashGitObject(type, content);\n\t\t\t\tif (actualOid !== oid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`repack: object ${oid} failed independent SHA-1 verification ` +\n\t\t\t\t\t\t\t`(recomputed ${actualOid}) — refusing to trust this read, aborting repack`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { oid, type: type as PackObjectType, content };\n\t\t\t}),\n\t\t);\n\t\tfor (const { oid, type, content } of entries) {\n\t\t\tobjects.set(oid, { type, content });\n\t\t}\n\t}\n\treturn objects;\n}\n\n/**\n * Serialize verified objects into a pack containing only full (never\n * deltified) entries, in the given oid order.\n */\nasync function buildVerifiedPack(\n\toids: string[],\n\tobjects: Map<string, VerifiedObject>,\n): Promise<Uint8Array> {\n\t// PACK header: \"PACK\" + version(2) + count, all big-endian uint32\n\tconst header = new Uint8Array(12);\n\tconst view = new DataView(header.buffer);\n\theader.set(encodeUtf8(\"PACK\"), 0);\n\tview.setUint32(4, 2, false); // version 2\n\tview.setUint32(8, oids.length, false); // object count\n\n\tconst chunks: Uint8Array[] = [header];\n\n\tconst BATCH_SIZE = 100;\n\tfor (let i = 0; i < oids.length; i += BATCH_SIZE) {\n\t\tconst batch = oids.slice(i, i + BATCH_SIZE);\n\t\tconst encoded = await Promise.all(\n\t\t\tbatch.map(async (oid) => {\n\t\t\t\tconst entry = objects.get(oid);\n\t\t\t\tif (!entry) {\n\t\t\t\t\tthrow new Error(`repack: missing verified object for ${oid}`);\n\t\t\t\t}\n\t\t\t\tconst objHeader = encodePackObjectHeader(\n\t\t\t\t\tentry.type,\n\t\t\t\t\tentry.content.length,\n\t\t\t\t);\n\t\t\t\tconst compressed = await deflate(entry.content);\n\t\t\t\treturn concat(objHeader, compressed);\n\t\t\t}),\n\t\t);\n\t\tchunks.push(...encoded);\n\t}\n\n\t// Git's pack trailer is the SHA-1 of every preceding byte (header +\n\t// every object entry) as a single digest — NOT an incremental/chained\n\t// hash. Web Crypto's subtle.digest has no streaming mode, so unlike\n\t// Node's crypto.createHash this can't be folded into the loop above;\n\t// everything is already buffered in `chunks`, so hash it in one pass.\n\tconst packBody = concat(...chunks);\n\tconst trailer = fromHex(await sha1(packBody));\n\treturn concat(packBody, trailer);\n}\n\n/**\n * Default repack threshold. Consolidating is O(total repo object count) —\n * so paying it on every push makes push latency grow with repo size forever.\n */\nexport const REPACK_PACK_COUNT_THRESHOLD = 4;\n\nasync function readPackDirectory(repo: Repo): Promise<PackFileName[]> {\n\tconst entries = await rawFs(repo)\n\t\t.readdir(`${repo.gitdir}/objects/pack`)\n\t\t.catch(() => [] as string[]);\n\treturn parsePackDirectory(entries);\n}\n\nasync function countPacks(repo: Repo): Promise<number> {\n\tconst files = await readPackDirectory(repo);\n\treturn files.filter((file) => file.kind === \"pack\").length;\n}\n\nexport interface RepackOptions {\n\t/** Skip repacking below this many accumulated packs. Default 4. */\n\tthreshold?: number;\n}\n\n/**\n * Consolidate all pack files into one, returning the gitdir-relative paths\n * of the old .pack/.idx files it removed — after syncing the new pack to any\n * secondary storage, delete those same paths there too.\n */\nexport async function repackRepository(\n\trepo: Repo,\n\toptions?: RepackOptions,\n\thooks?: HttpHooks,\n): Promise<string[]> {\n\tconst threshold = options?.threshold ?? REPACK_PACK_COUNT_THRESHOLD;\n\tconst fsp = rawFs(repo);\n\ttry {\n\t\tif ((await countPacks(repo)) < threshold) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst [branches, tags] = await Promise.all([\n\t\t\tgit.listBranches(repo),\n\t\t\tgit.listTags(repo),\n\t\t]);\n\t\tconst refNames = [\n\t\t\t...branches.map((b) => `refs/heads/${b}`),\n\t\t\t...tags.map((t) => `refs/tags/${t}`),\n\t\t];\n\t\tconst tipOids = (\n\t\t\tawait Promise.all(\n\t\t\t\trefNames.map((ref) =>\n\t\t\t\t\tgit.resolveRef({ ...repo, ref }).catch(() => null),\n\t\t\t\t),\n\t\t\t)\n\t\t).filter((oid): oid is string => oid !== null);\n\t\tif (tipOids.length === 0) return [];\n\n\t\tconst { oids: reachable, complete } = await collectReachableOids(\n\t\t\trepo,\n\t\t\ttipOids,\n\t\t\thooks,\n\t\t);\n\t\tif (!complete || reachable.length === 0) return [];\n\n\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\t// Copy stored entries when everything is packed: keeps deltas, so\n\t\t// the consolidated pack is as compact as its sources. Loose objects\n\t\t// fall back to a verified, non-deltified rebuild.\n\t\tconst packBuffer =\n\t\t\t(await buildPackFromExistingPacks(repo, reachable)) ??\n\t\t\t(await buildVerifiedPack(\n\t\t\t\treachable,\n\t\t\t\tawait readAndVerifyObjects(repo, reachable),\n\t\t\t));\n\n\t\tawait fsp.mkdir(packDir, { recursive: true });\n\t\tconst newBase = `pack-${Date.now()}`;\n\t\tconst newPackFile = packFileName(newBase, \"pack\");\n\t\tawait fsp.writeFile(`${packDir}/${newPackFile}`, packBuffer);\n\n\t\tconst { oids: indexedOids } = await git.indexPack({\n\t\t\t...repo,\n\t\t\tdir: packDir,\n\t\t\tfilepath: newPackFile,\n\t\t});\n\n\t\t// indexPack re-hashes every object it indexes, so this also verifies\n\t\t// the content. Reused packs may carry extra delta bases: superset is fine.\n\t\tconst indexed = new Set(indexedOids);\n\t\tif (reachable.some((oid) => !indexed.has(oid))) {\n\t\t\tawait Promise.all(\n\t\t\t\t([\"pack\", \"idx\"] as const).map((kind) =>\n\t\t\t\t\tfsp\n\t\t\t\t\t\t.unlink(`${packDir}/${packFileName(newBase, kind)}`)\n\t\t\t\t\t\t.catch(() => {}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\t\"repack: indexed pack is missing reachable objects — aborting\",\n\t\t\t);\n\t\t}\n\n\t\tconst stale = (await readPackDirectory(repo)).filter(\n\t\t\t(file) => file.base !== newBase,\n\t\t);\n\t\tawait Promise.all(\n\t\t\tstale.map((file) =>\n\t\t\t\tfsp.unlink(`${packDir}/${file.name}`).catch(() => {}),\n\t\t\t),\n\t\t);\n\t\treturn stale.map((file) => `objects/pack/${file.name}`);\n\t} catch (err) {\n\t\thooks?.onWarn?.(\"repack failed (non-fatal)\", err);\n\t\treturn [];\n\t}\n}\n","/**\n * Build a packfile by copying already-compressed entries out of existing\n * packs (\"pack reuse\"), instead of inflating and re-deflating every object.\n *\n * Entries keep their stored form, deltas included, so the output is as\n * compact as the packs it came from. `OFS_DELTA` entries are rewritten as\n * `REF_DELTA` (base named by oid), since offsets don't survive the move into\n * a new pack; delta bases are always included and written before the deltas\n * that use them. Formats: gitformat-pack(5).\n *\n * Edge-compatible: Web Crypto SHA-1 and Uint8Array only.\n */\n\nimport { concat, encodeUtf8, fromHex, sha1, toHex } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { packFileName, parsePackDirectory } from \"../pack-files.js\";\nimport { rawFs } from \"./types.js\";\n\nconst OBJ_OFS_DELTA = 6;\nconst OBJ_REF_DELTA = 7;\nconst OID_BYTES = 20;\nconst PACK_TRAILER_BYTES = 20;\n\nconst IDX_V2 = {\n\tmagic: 0xff744f63,\n\tversion: 2,\n\theaderBytes: 8,\n\tfanoutEntries: 256,\n\t/** Offsets with this bit set index the 64-bit large-offset table. */\n\tlargeOffsetFlag: 0x80000000,\n} as const;\n\n/** One object's stored entry inside a pack. */\ninterface PackEntry {\n\treadonly pack: Uint8Array;\n\treadonly start: number;\n\treadonly end: number;\n}\n\n/** Every object stored in a pack, by oid, plus its offset → oid inverse. */\ninterface IndexedPack {\n\treadonly entries: Map<string, PackEntry>;\n\treadonly oidAtOffset: Map<number, string>;\n}\n\n/** An object's position in a pack, as listed by its `.idx`. */\nexport interface PackIndexEntry {\n\treadonly oid: string;\n\treadonly offset: number;\n}\n\n/** Entries of a version-2 `.idx`; `null` for any other format. */\nexport function readPackIndex(idx: Uint8Array): PackIndexEntry[] | null {\n\tconst view = new DataView(idx.buffer, idx.byteOffset, idx.byteLength);\n\tconst namesStart = IDX_V2.headerBytes + IDX_V2.fanoutEntries * 4;\n\tif (\n\t\tidx.byteLength < namesStart ||\n\t\tview.getUint32(0) !== IDX_V2.magic ||\n\t\tview.getUint32(4) !== IDX_V2.version\n\t) {\n\t\treturn null;\n\t}\n\t// The last fanout slot counts every object in the pack.\n\tconst count = view.getUint32(namesStart - 4);\n\tconst crcStart = namesStart + count * OID_BYTES;\n\tconst offsetsStart = crcStart + count * 4;\n\tif (idx.byteLength < offsetsStart + count * 4) return null;\n\n\tconst entries: PackIndexEntry[] = [];\n\tfor (let i = 0; i < count; i++) {\n\t\tconst offset = view.getUint32(offsetsStart + i * 4);\n\t\t// Packs over 2 GiB never reach this in-memory path; let the caller\n\t\t// fall back instead of half-supporting the large-offset table.\n\t\tif (offset & IDX_V2.largeOffsetFlag) return null;\n\t\tconst at = namesStart + i * OID_BYTES;\n\t\tentries.push({ oid: toHex(idx.subarray(at, at + OID_BYTES)), offset });\n\t}\n\treturn entries;\n}\n\n/** Locate every entry of `pack` using its `.idx`. */\nfunction indexPack(idx: Uint8Array, pack: Uint8Array): IndexedPack | null {\n\tconst located = readPackIndex(idx);\n\tif (!located) return null;\n\n\t// An entry runs until the next entry's offset (or the pack trailer).\n\tlocated.sort((a, b) => a.offset - b.offset);\n\tconst entries = new Map<string, PackEntry>();\n\tconst oidAtOffset = new Map<number, string>();\n\tconst packEnd = pack.byteLength - PACK_TRAILER_BYTES;\n\tfor (let i = 0; i < located.length; i++) {\n\t\tconst { oid, offset } = located[i] as PackIndexEntry;\n\t\tconst end = located[i + 1]?.offset ?? packEnd;\n\t\tentries.set(oid, { pack, start: offset, end });\n\t\toidAtOffset.set(offset, oid);\n\t}\n\treturn { entries, oidAtOffset };\n}\n\n/** The variable-length type/size header that starts every pack entry. */\ninterface EntryHeader {\n\treadonly type: number;\n\treadonly size: number;\n\t/** Bytes the header occupies. */\n\treadonly length: number;\n}\n\nfunction readEntryHeader(bytes: Uint8Array, start: number): EntryHeader {\n\tlet byte = bytes[start] as number;\n\tconst type = (byte >> 4) & 0b111;\n\tlet size = byte & 0b1111;\n\tlet shift = 4;\n\tlet at = start + 1;\n\twhile (byte & 0x80) {\n\t\tbyte = bytes[at++] as number;\n\t\tsize += (byte & 0x7f) * 2 ** shift;\n\t\tshift += 7;\n\t}\n\treturn { type, size, length: at - start };\n}\n\nfunction encodeEntryHeader(type: number, size: number): Uint8Array {\n\tconst bytes: number[] = [];\n\tlet rest = Math.floor(size / 16);\n\tbytes.push((rest > 0 ? 0x80 : 0) | (type << 4) | (size % 16));\n\twhile (rest > 0) {\n\t\tconst low = rest % 128;\n\t\trest = Math.floor(rest / 128);\n\t\tbytes.push((rest > 0 ? 0x80 : 0) | low);\n\t}\n\treturn new Uint8Array(bytes);\n}\n\n/** `OFS_DELTA`'s negative base offset: big-endian base-128 with +1 carries. */\nfunction readOfsDeltaOffset(\n\tbytes: Uint8Array,\n\tstart: number,\n): { distance: number; length: number } {\n\tlet at = start;\n\tlet byte = bytes[at++] as number;\n\tlet distance = byte & 0x7f;\n\twhile (byte & 0x80) {\n\t\tbyte = bytes[at++] as number;\n\t\tdistance = (distance + 1) * 128 + (byte & 0x7f);\n\t}\n\treturn { distance, length: at - start };\n}\n\n/** A pack entry ready to copy, with the oid of its delta base if any. */\ninterface ReusableEntry {\n\treadonly bytes: Uint8Array;\n\treadonly baseOid: string | null;\n}\n\n/** Copy one entry, rewriting `OFS_DELTA` to `REF_DELTA`. */\nfunction reusableEntry(\n\tentry: PackEntry,\n\tindexed: IndexedPack,\n): ReusableEntry | null {\n\tconst { pack, start, end } = entry;\n\tconst header = readEntryHeader(pack, start);\n\tconst bodyStart = start + header.length;\n\tif (header.type === OBJ_REF_DELTA) {\n\t\treturn {\n\t\t\tbytes: pack.subarray(start, end),\n\t\t\tbaseOid: toHex(pack.subarray(bodyStart, bodyStart + OID_BYTES)),\n\t\t};\n\t}\n\tif (header.type !== OBJ_OFS_DELTA) {\n\t\treturn { bytes: pack.subarray(start, end), baseOid: null };\n\t}\n\tconst { distance, length } = readOfsDeltaOffset(pack, bodyStart);\n\tconst baseOid = indexed.oidAtOffset.get(start - distance);\n\tif (baseOid === undefined) return null;\n\treturn {\n\t\tbytes: concat(\n\t\t\tencodeEntryHeader(OBJ_REF_DELTA, header.size),\n\t\t\tfromHex(baseOid),\n\t\t\tpack.subarray(bodyStart + length, end),\n\t\t),\n\t\tbaseOid,\n\t};\n}\n\n/**\n * A pack holding at least `oids`, built from stored entries, or `null` when\n * any of them (or a delta base they need) isn't in a readable pack — e.g. a\n * loose object — so the caller should build the pack another way.\n */\nexport async function buildPackFromExistingPacks(\n\trepo: Repo,\n\toids: readonly string[],\n): Promise<Uint8Array | null> {\n\tconst fsp = rawFs(repo);\n\tconst packDir = `${repo.gitdir}/objects/pack`;\n\tconst packs = parsePackDirectory(\n\t\tawait fsp.readdir(packDir).catch(() => [] as string[]),\n\t).filter((file) => file.kind === \"pack\");\n\n\tconst indexes: IndexedPack[] = [];\n\tfor (const { base } of packs) {\n\t\t// A pack without a readable index can't be reused.\n\t\tconst [pack, idx] = await Promise.all([\n\t\t\tfsp.readFile(`${packDir}/${packFileName(base, \"pack\")}`),\n\t\t\tfsp.readFile(`${packDir}/${packFileName(base, \"idx\")}`),\n\t\t]).catch(() => [null, null]);\n\t\tif (!(pack instanceof Uint8Array) || !(idx instanceof Uint8Array)) {\n\t\t\treturn null;\n\t\t}\n\t\tconst indexed = indexPack(idx, pack);\n\t\tif (!indexed) return null;\n\t\tindexes.push(indexed);\n\t}\n\n\tconst locate = (oid: string): ReusableEntry | null => {\n\t\tfor (const indexed of indexes) {\n\t\t\tconst entry = indexed.entries.get(oid);\n\t\t\tif (entry) return reusableEntry(entry, indexed);\n\t\t}\n\t\treturn null;\n\t};\n\n\t// Depth-first so every base is written before the deltas that use it.\n\tconst ordered: Uint8Array[] = [];\n\tconst done = new Set<string>();\n\tconst pending = new Set<string>();\n\tconst visit = (oid: string): boolean => {\n\t\tif (done.has(oid)) return true;\n\t\tif (pending.has(oid)) return false; // a delta cycle means corruption\n\t\tconst entry = locate(oid);\n\t\tif (!entry) return false;\n\t\tpending.add(oid);\n\t\tif (entry.baseOid !== null && !visit(entry.baseOid)) return false;\n\t\tpending.delete(oid);\n\t\tdone.add(oid);\n\t\tordered.push(entry.bytes);\n\t\treturn true;\n\t};\n\tfor (const oid of oids) {\n\t\tif (!visit(oid)) return null;\n\t}\n\n\tconst header = new Uint8Array(12);\n\theader.set(encodeUtf8(\"PACK\"), 0);\n\tconst view = new DataView(header.buffer);\n\tview.setUint32(4, 2);\n\tview.setUint32(8, ordered.length);\n\tconst body = concat(header, ...ordered);\n\treturn concat(body, fromHex(await sha1(body)));\n}\n","import git from \"isomorphic-git\";\nimport { concat } from \"../edge-utils.js\";\nimport type { Repo } from \"../ops/types.js\";\nimport { parsePackDirectory } from \"../pack-files.js\";\nimport { buildPackFromExistingPacks } from \"./pack-reuse.js\";\nimport { parsePktLines, pktLine, sideBandPackfile } from \"./pkt-line.js\";\nimport { collectReachableOids } from \"./reachability.js\";\nimport { type GitHttpResult, type HttpHooks, rawFs, runStep } from \"./types.js\";\n\nconst ZERO_OID = \"0\".repeat(40);\n\nexport interface UploadPackOptions {\n\t/**\n\t * Called once before the reachability walk — wire loose-object detection\n\t * (`GitFs.detectLooseObjects`) here so a fully packed repo's walk doesn't\n\t * pay a doomed loose-object probe per object.\n\t */\n\tbeforeWalk?: () => Promise<void>;\n}\n\n/**\n * `POST …/git-upload-pack` — serve a clone/fetch. Authorization is the\n * caller's job. Negotiation is client-driven (no multi_ack advertised):\n * \"have\" batches without \"done\" get a bare NAK; the final batch gets the\n * packfile, side-band-64k framed.\n *\n * Fast path: a fresh clone (no haves) of a repo consolidated down to a\n * single pack serves that pack's bytes directly — skipping the O(objects)\n * traversal + repack entirely.\n */\nexport async function handleUploadPack(\n\trepo: Repo,\n\tbody: Uint8Array,\n\toptions?: UploadPackOptions,\n\thooks?: HttpHooks,\n): Promise<GitHttpResult> {\n\tconst lines = parsePktLines(body);\n\n\tconst wants: string[] = [];\n\tconst haves: string[] = [];\n\tlet done = false;\n\tfor (const line of lines) {\n\t\tif (!line) continue;\n\t\tif (line.startsWith(\"want \")) {\n\t\t\twants.push(line.slice(5, 45));\n\t\t}\n\t\tif (line.startsWith(\"have \")) {\n\t\t\tconst sha = line.slice(5, 45);\n\t\t\tif (sha !== ZERO_OID) {\n\t\t\t\thaves.push(sha);\n\t\t\t}\n\t\t}\n\t\tif (line.startsWith(\"done\")) {\n\t\t\tdone = true;\n\t\t}\n\t}\n\n\tif (wants.length === 0) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { \"Content-Type\": \"application/x-git-upload-pack-result\" },\n\t\t\tbody: concat(pktLine(\"NAK\\n\")),\n\t\t};\n\t}\n\n\tif (haves.length > 0 && !done) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: { \"Content-Type\": \"application/x-git-upload-pack-result\" },\n\t\t\tbody: concat(pktLine(\"NAK\\n\")),\n\t\t};\n\t}\n\n\t// Fresh clone = no haves, so all objects are needed. When the repo is down\n\t// to a single pack, serve it directly and skip the traversal + pack build.\n\tif (haves.length === 0) {\n\t\tconst packDirPath = `${repo.gitdir}/objects/pack`;\n\t\tconst entries = await runStep(hooks, \"readdir objects/pack\", () =>\n\t\t\trawFs(repo)\n\t\t\t\t.readdir(packDirPath)\n\t\t\t\t.catch(() => [] as string[]),\n\t\t);\n\t\tconst packNames = parsePackDirectory(entries)\n\t\t\t.filter((file) => file.kind === \"pack\")\n\t\t\t.map((file) => file.name);\n\t\tconst packName = packNames[0];\n\t\tif (packNames.length === 1 && packName !== undefined) {\n\t\t\tconst packData = await runStep(\n\t\t\t\thooks,\n\t\t\t\t\"read consolidated pack (fast path)\",\n\t\t\t\t() => rawFs(repo).readFile(`${packDirPath}/${packName}`),\n\t\t\t);\n\t\t\tconst bytes =\n\t\t\t\tpackData instanceof Uint8Array\n\t\t\t\t\t? packData\n\t\t\t\t\t: new TextEncoder().encode(packData as string);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-git-upload-pack-result\",\n\t\t\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t\t\t},\n\t\t\t\tbody: concat(pktLine(\"NAK\\n\"), sideBandPackfile(bytes)),\n\t\t\t};\n\t\t}\n\t}\n\n\tif (options?.beforeWalk) {\n\t\tawait runStep(hooks, \"beforeWalk\", options.beforeWalk);\n\t}\n\n\t// Walk haves first so the wants walk can stop at anything the client\n\t// already has, instead of re-walking all shared history a second time.\n\tlet haveSet: ReadonlySet<string> | undefined;\n\tif (haves.length > 0) {\n\t\tconst { oids: haveOids } = await runStep(\n\t\t\thooks,\n\t\t\t\"collectReachableOids(haves)\",\n\t\t\t() =>\n\t\t\t\tcollectReachableOids(repo, haves, hooks, undefined, {\n\t\t\t\t\tverifyBlobs: false,\n\t\t\t\t}),\n\t\t);\n\t\thaveSet = new Set(haveOids);\n\t}\n\n\tconst { oids: wantOids } = await runStep(\n\t\thooks,\n\t\t\"collectReachableOids(wants)\",\n\t\t() =>\n\t\t\tcollectReachableOids(repo, wants, hooks, haveSet, {\n\t\t\t\tverifyBlobs: false,\n\t\t\t}),\n\t);\n\t// Boundary oids are recorded as seen by the walk; drop them from the pack.\n\tconst oids = haveSet ? wantOids.filter((oid) => !haveSet.has(oid)) : wantOids;\n\n\t// Copy stored (already compressed, possibly deltified) entries when every\n\t// object is packed; build from scratch only when some aren't.\n\tconst reused = await runStep(\n\t\thooks,\n\t\t`reuse pack entries (${oids.length} oids)`,\n\t\t() => buildPackFromExistingPacks(repo, oids),\n\t);\n\tconst packBytes =\n\t\treused ??\n\t\t(await runStep(hooks, `packObjects (${oids.length} oids)`, async () => {\n\t\t\tconst { packfile } = await git.packObjects({ ...repo, oids });\n\t\t\treturn packfile instanceof Uint8Array\n\t\t\t\t? packfile\n\t\t\t\t: new Uint8Array(packfile ?? []);\n\t\t}));\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-git-upload-pack-result\",\n\t\t\t\"Cache-Control\": \"no-cache\",\n\t\t},\n\t\tbody: concat(pktLine(\"NAK\\n\"), sideBandPackfile(packBytes)),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,SAAS;;;ACST,IAAM,QAAiC,IAAI,WAAW;AAAA,EAC5D;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AACnB,CAAC;AAGM,SAAS,QAAQ,MAAuC;AAC9D,QAAM,OAAO,WAAW,IAAI;AAC5B,QAAM,OAAO,KAAK,SAAS,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAC1D,SAAO,OAAO,WAAW,GAAG,GAAG,IAAI;AACpC;AAGO,SAAS,cAAc,MAA2C;AACxE,QAAM,OAAO,KAAK,SAAS,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAC1D,SAAO,OAAO,WAAW,GAAG,GAAG,IAAI;AACpC;AAGO,SAAS,cAAc,KAAuC;AACpE,QAAM,QAA8B,CAAC;AACrC,MAAI,MAAM;AACV,SAAO,MAAM,KAAK,IAAI,QAAQ;AAC7B,UAAM,MAAM,OAAO,SAAS,YAAY,IAAI,SAAS,KAAK,MAAM,CAAC,CAAC,GAAG,EAAE;AACvE,QAAI,QAAQ,GAAG;AACd,YAAM,KAAK,IAAI;AACf,aAAO;AAAA,IACR,WAAW,OAAO,GAAG;A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A,EACjC,CAAC;AAEF,SAAO;AAAA,IACN,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IAClB;AAAA,IACA,MAAM,OAAO,QAAQ,OAAO,GAAG,iBAAiB,SAAS,CAAC;AAAA,EAC3D;AACD;","names":["git","p","git","git","git","git","packName","git","ZERO_OID","git"]}
package/dist/index.cjs CHANGED
@@ -34,6 +34,9 @@ __export(src_exports, {
34
34
  GitRefNotFoundError: () => GitRefNotFoundError,
35
35
  GitRepositoryNotFoundError: () => GitRepositoryNotFoundError,
36
36
  MemoryObjectStore: () => MemoryObjectStore,
37
+ PACK_FILE_KINDS: () => PACK_FILE_KINDS,
38
+ READABLE_PACK_FILE_KINDS: () => READABLE_PACK_FILE_KINDS,
39
+ classifyGitdirPath: () => classifyGitdirPath,
37
40
  concat: () => concat,
38
41
  createCachedStore: () => createCachedStore,
39
42
  createGitFs: () => createGitFs,
@@ -46,10 +49,15 @@ __export(src_exports, {
46
49
  fromHex: () => fromHex,
47
50
  hasNullByte: () => hasNullByte,
48
51
  isFullSha: () => isFullSha,
52
+ isMutableGitdirEntry: () => isMutableGitdirEntry,
49
53
  isSafeBranchName: () => isSafeBranchName,
50
54
  isSafeFullRefName: () => isSafeFullRefName,
51
55
  isSafeRefName: () => isSafeRefName,
52
56
  isSafeRepoPath: () => isSafeRepoPath,
57
+ packFileName: () => packFileName,
58
+ parseLooseObjectPath: () => parseLooseObjectPath,
59
+ parsePackDirectory: () => parsePackDirectory,
60
+ parsePackFileName: () => parsePackFileName,
53
61
  qualifyBranchRef: () => qualifyBranchRef,
54
62
  readBlobContent: () => readBlobContent,
55
63
  sha1: () => sha1,
@@ -81,6 +89,8 @@ function createCachedStore(store, options = {}) {
81
89
  const cacheMisses = options.cacheMisses ?? false;
82
90
  const cacheLists = options.cacheLists ?? false;
83
91
  const coalesce = options.coalesce ?? true;
92
+ const copy = options.copy ?? true;
93
+ const clone = (data) => copy ? data.slice() : data;
84
94
  const onHit = options.onHit;
85
95
  const onMiss = options.onMiss;
86
96
  const cache = new import_lru_cache.LRUCache({
@@ -98,7 +108,7 @@ function createCachedStore(store, options = {}) {
98
108
  const pendingLists = /* @__PURE__ */ new Map();
99
109
  const admit = (key, data) => {
100
110
  if (data.byteLength <= maxEntryBytes) {
101
- cache.set(key, data.slice(), { ttl: ttlForKey?.(key) });
111
+ cache.set(key, clone(data), { ttl: ttlForKey?.(key) });
102
112
  }
103
113
  };
104
114
  function clearStaleListEntries(key) {
@@ -121,7 +131,7 @@ function createCachedStore(store, options = {}) {
121
131
  const cached = cache.get(key);
122
132
  if (cached !== void 0) {
123
133
  onHit?.(key);
124
- return cached === MISS ? null : cached.slice();
134
+ return cached === MISS ? null : clone(cached);
125
135
  }
126
136
  const data = await coalesced(pendingGets, key, async () => {
127
137
  onMiss?.(key);
@@ -133,7 +143,7 @@ function createCachedStore(store, options = {}) {
133
143
  }
134
144
  return fetched;
135
145
  });
136
- return data === null ? null : data.slice();
146
+ return data === null ? null : clone(data);
137
147
  },
138
148
  async put(key, data) {
139
149
  await store.put(key, data);
@@ -394,6 +404,85 @@ function formatErrorResponse(error) {
394
404
  // src/git-fs.ts
395
405
  var import_lru_cache2 = require("lru-cache");
396
406
 
407
+ // src/pack-files.ts
408
+ var PACK_FILE_KINDS = [
409
+ "pack",
410
+ "idx",
411
+ "keep",
412
+ "bitmap",
413
+ "rev"
414
+ ];
415
+ var READABLE_PACK_FILE_KINDS = /* @__PURE__ */ new Set([
416
+ "pack",
417
+ "idx"
418
+ ]);
419
+ var KNOWN_KINDS = new Set(PACK_FILE_KINDS);
420
+ function isPackFileKind(value) {
421
+ return KNOWN_KINDS.has(value);
422
+ }
423
+ function parsePackFileName(name) {
424
+ const dot = name.lastIndexOf(".");
425
+ if (dot <= 0) return null;
426
+ const kind = name.slice(dot + 1);
427
+ if (!isPackFileKind(kind)) return null;
428
+ return { base: name.slice(0, dot), kind, name };
429
+ }
430
+ function packFileName(base, kind) {
431
+ return `${base}.${kind}`;
432
+ }
433
+ function parsePackDirectory(entries) {
434
+ return entries.map(parsePackFileName).filter((file) => file !== null);
435
+ }
436
+
437
+ // src/git-layout.ts
438
+ var HEX = new Set("0123456789abcdef");
439
+ function isHex(value, length) {
440
+ if (value.length !== length) return false;
441
+ for (const char of value) if (!HEX.has(char)) return false;
442
+ return true;
443
+ }
444
+ function classifyGitdirPath(path) {
445
+ const segments = path.split("/");
446
+ const [first, second, third, ...rest] = segments;
447
+ if (segments.length === 1) {
448
+ if (first === "HEAD") return { kind: "head" };
449
+ if (first === "config") return { kind: "config" };
450
+ if (first === "refs") return { kind: "refs", path };
451
+ return { kind: "other" };
452
+ }
453
+ if (first === "refs") return { kind: "refs", path };
454
+ if (first !== "objects" || second === void 0) return { kind: "other" };
455
+ if (segments.length === 2 && second === "") return { kind: "objects-dir" };
456
+ if (second === "pack" && third !== void 0 && rest.length === 0) {
457
+ if (third === "") return { kind: "pack-dir" };
458
+ const file = parsePackFileName(third);
459
+ return file ? { kind: "pack-file", file } : { kind: "other" };
460
+ }
461
+ if (third !== void 0 && rest.length === 0 && isHex(second, 2) && isHex(third, 38)) {
462
+ return { kind: "loose-object", oid: second + third };
463
+ }
464
+ return { kind: "other" };
465
+ }
466
+ function isMutableGitdirEntry(entry) {
467
+ switch (entry.kind) {
468
+ case "head":
469
+ case "refs":
470
+ case "objects-dir":
471
+ case "pack-dir":
472
+ return true;
473
+ default:
474
+ return false;
475
+ }
476
+ }
477
+ function parseLooseObjectPath(path) {
478
+ const segments = path.split("/");
479
+ if (segments.length < 3) return null;
480
+ const gitdirSegments = segments.slice(0, -3);
481
+ const entry = classifyGitdirPath(segments.slice(-3).join("/"));
482
+ if (entry.kind !== "loose-object") return null;
483
+ return { gitdir: gitdirSegments.join("/"), oid: entry.oid };
484
+ }
485
+
397
486
  // src/path.ts
398
487
  function normalizePath(filepath) {
399
488
  const segments = filepath.split("/");
@@ -418,7 +507,6 @@ function toKey(prefix, filepath) {
418
507
  // src/git-fs.ts
419
508
  var FILE_MODE = 33188;
420
509
  var DIR_MODE = 16384;
421
- var LOOSE_OBJECT_RE = /(^|\/)objects\/[0-9a-f]{2}\/[0-9a-f]{38}$/;
422
510
  var textEncoder2 = new TextEncoder();
423
511
  var textDecoder2 = new TextDecoder();
424
512
  function makeStat(type, size) {
@@ -454,16 +542,35 @@ function createGitFs(store, options = {}) {
454
542
  max: 1024,
455
543
  ttl: options.hintTtlMs ?? 36e5
456
544
  });
545
+ const registeredGitdirs = new import_lru_cache2.LRUCache({
546
+ max: 4096
547
+ });
548
+ function registeredAbsent(path) {
549
+ const slash = path.lastIndexOf("/");
550
+ if (slash < 0) return false;
551
+ const absent = registeredGitdirs.get(path.slice(0, slash));
552
+ return absent?.has(path.slice(slash + 1)) ?? false;
553
+ }
457
554
  function looseScope(path) {
458
- const match = LOOSE_OBJECT_RE.exec(path);
459
- if (match === null) return null;
460
- return path.slice(0, match.index);
555
+ return parseLooseObjectPath(path)?.gitdir ?? null;
461
556
  }
462
- function knownAbsent(path) {
463
- if (structurallyAbsent?.(path)) return true;
557
+ const pendingDetections = /* @__PURE__ */ new Map();
558
+ async function knownAbsent(path) {
559
+ if (structurallyAbsent?.(path) || registeredAbsent(path)) return true;
464
560
  if (!useLooseHints) return false;
465
561
  const scope = looseScope(path);
466
- return scope !== null && looseHints.get(scope) === "none";
562
+ if (scope === null) return false;
563
+ if (!looseHints.has(scope)) {
564
+ let pending = pendingDetections.get(scope);
565
+ if (!pending) {
566
+ pending = detectLooseObjects(scope).finally(
567
+ () => pendingDetections.delete(scope)
568
+ );
569
+ pendingDetections.set(scope, pending);
570
+ }
571
+ await pending;
572
+ }
573
+ return looseHints.get(scope) === "none";
467
574
  }
468
575
  async function isDirectory(dirKey) {
469
576
  const { objects, prefixes } = await store.list(`${dirKey}/`, {
@@ -473,9 +580,11 @@ function createGitFs(store, options = {}) {
473
580
  }
474
581
  async function stat(filepath, syscall) {
475
582
  const path = normalizePath(filepath);
476
- if (knownAbsent(path)) throw enoent(syscall, filepath);
583
+ if (await knownAbsent(path)) throw enoent(syscall, filepath);
477
584
  const k = toKey2(path);
478
- if (k === prefix || k === "") return makeStat("dir", 0);
585
+ if (k === prefix || k === "" || registeredGitdirs.has(path)) {
586
+ return makeStat("dir", 0);
587
+ }
479
588
  const fileStat = await store.head(k);
480
589
  if (fileStat) return makeStat("file", fileStat.size);
481
590
  if (useLooseHints && looseScope(path) !== null) {
@@ -487,7 +596,7 @@ function createGitFs(store, options = {}) {
487
596
  const promises = {
488
597
  async readFile(filepath, opts) {
489
598
  const path = normalizePath(filepath);
490
- if (knownAbsent(path)) throw enoent("open", filepath);
599
+ if (await knownAbsent(path)) throw enoent("open", filepath);
491
600
  const data = await store.get(toKey2(path));
492
601
  if (data === null) throw enoent("open", filepath);
493
602
  return resolveEncoding(opts) === "utf8" ? textDecoder2.decode(data) : data;
@@ -554,7 +663,7 @@ function createGitFs(store, options = {}) {
554
663
  limit: 1
555
664
  });
556
665
  const first = objects[0]?.key;
557
- const hint = first !== void 0 && LOOSE_OBJECT_RE.test(first) ? "present" : "none";
666
+ const hint = first !== void 0 && parseLooseObjectPath(first) !== null ? "present" : "none";
558
667
  looseHints.set(scope, hint);
559
668
  onNote?.(`loose objects ${hint} under ${scope}`);
560
669
  } catch {
@@ -563,7 +672,9 @@ function createGitFs(store, options = {}) {
563
672
  async function prefetchPacks(gitdir, prefetchOptions) {
564
673
  const maxPacks = prefetchOptions?.maxPacks ?? 30;
565
674
  const packDir = `${normalizePath(gitdir)}/objects/pack`;
566
- const entries = await promises.readdir(packDir).catch(() => []);
675
+ const entries = parsePackDirectory(
676
+ await promises.readdir(packDir).catch(() => [])
677
+ ).filter((file) => READABLE_PACK_FILE_KINDS.has(file.kind)).map((file) => file.name);
567
678
  if (entries.length > maxPacks * 2) {
568
679
  await detectLooseObjects(gitdir);
569
680
  return;
@@ -581,8 +692,17 @@ function createGitFs(store, options = {}) {
581
692
  const { objects } = await store.list(listPrefix);
582
693
  return objects.map((object) => object.key.slice(listPrefix.length)).filter((path) => path.length > 0).sort();
583
694
  }
695
+ function registerGitdir(gitdir, facts) {
696
+ registeredGitdirs.set(
697
+ normalizePath(gitdir),
698
+ new Set(facts?.absentFiles ?? [])
699
+ );
700
+ }
584
701
  function invalidate(pathPrefix) {
585
702
  const normalized = normalizePath(pathPrefix);
703
+ for (const dir of registeredGitdirs.keys()) {
704
+ if (dir.startsWith(normalized)) registeredGitdirs.delete(dir);
705
+ }
586
706
  for (const scope of looseHints.keys()) {
587
707
  if (scope.startsWith(normalized)) looseHints.delete(scope);
588
708
  }
@@ -594,7 +714,8 @@ function createGitFs(store, options = {}) {
594
714
  listFilesRecursively,
595
715
  detectLooseObjects,
596
716
  prefetchPacks,
597
- invalidate
717
+ invalidate,
718
+ registerGitdir
598
719
  };
599
720
  }
600
721
 
@@ -790,6 +911,9 @@ var MemoryObjectStore = class {
790
911
  GitRefNotFoundError,
791
912
  GitRepositoryNotFoundError,
792
913
  MemoryObjectStore,
914
+ PACK_FILE_KINDS,
915
+ READABLE_PACK_FILE_KINDS,
916
+ classifyGitdirPath,
793
917
  concat,
794
918
  createCachedStore,
795
919
  createGitFs,
@@ -802,10 +926,15 @@ var MemoryObjectStore = class {
802
926
  fromHex,
803
927
  hasNullByte,
804
928
  isFullSha,
929
+ isMutableGitdirEntry,
805
930
  isSafeBranchName,
806
931
  isSafeFullRefName,
807
932
  isSafeRefName,
808
933
  isSafeRepoPath,
934
+ packFileName,
935
+ parseLooseObjectPath,
936
+ parsePackDirectory,
937
+ parsePackFileName,
809
938
  qualifyBranchRef,
810
939
  readBlobContent,
811
940
  sha1,