git-fs-s3 0.3.9 → 0.3.11

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 CHANGED
@@ -1,12 +1,13 @@
1
1
  import {
2
2
  resolveLooseRefFast
3
- } from "./chunk-H7IGQRIA.js";
3
+ } from "./chunk-3BDDEGAP.js";
4
4
  import {
5
5
  concat,
6
6
  decodeAscii,
7
7
  decodeUtf8,
8
8
  deflate,
9
9
  encodeUtf8,
10
+ fromHex,
10
11
  isSafeFullRefName,
11
12
  sha1
12
13
  } from "./chunk-YQFNY6PG.js";
@@ -282,13 +283,6 @@ async function buildVerifiedPack(oids, objects) {
282
283
  const trailer = fromHex(await sha1(packBody));
283
284
  return concat(packBody, trailer);
284
285
  }
285
- function fromHex(hex) {
286
- const bytes = new Uint8Array(hex.length / 2);
287
- for (let i = 0; i < bytes.length; i++) {
288
- bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
289
- }
290
- return bytes;
291
- }
292
286
  var REPACK_PACK_COUNT_THRESHOLD = 4;
293
287
  async function countPacks(repo) {
294
288
  try {
@@ -393,19 +387,46 @@ async function ensureRepoInitialized(repo, defaultBranch = "main") {
393
387
  }
394
388
  }
395
389
  async function indexIncomingPack(repo, packData, hooks) {
396
- if (packData.length < 4) return;
397
- await runStep(hooks, "write + indexPack incoming pack", async () => {
398
- const fsp = rawFs(repo);
399
- const packDir = `${repo.gitdir}/objects/pack`;
400
- await fsp.mkdir(packDir, { recursive: true });
401
- const packName = `recv-${Date.now()}`;
402
- await fsp.writeFile(`${packDir}/${packName}.pack`, packData);
403
- await git4.indexPack({
404
- ...repo,
405
- dir: packDir,
406
- filepath: `${packName}.pack`
407
- });
408
- });
390
+ if (packData.length < 4) return [];
391
+ const packName = await runStep(
392
+ hooks,
393
+ "write + indexPack incoming pack",
394
+ async () => {
395
+ const fsp = rawFs(repo);
396
+ const packDir = `${repo.gitdir}/objects/pack`;
397
+ await fsp.mkdir(packDir, { recursive: true });
398
+ const packName2 = `recv-${Date.now()}`;
399
+ await fsp.writeFile(`${packDir}/${packName2}.pack`, packData);
400
+ await git4.indexPack({
401
+ ...repo,
402
+ dir: packDir,
403
+ filepath: `${packName2}.pack`
404
+ });
405
+ return packName2;
406
+ }
407
+ );
408
+ return [
409
+ `${repo.gitdir}/objects/pack/${packName}.pack`,
410
+ `${repo.gitdir}/objects/pack/${packName}.idx`
411
+ ];
412
+ }
413
+ async function checkRefCas(repo, refName, oldOid) {
414
+ if (!isSafeFullRefName(refName)) {
415
+ return { refName, ok: false, reason: "invalid ref name" };
416
+ }
417
+ const currentOid = await git4.resolveRef({ ...repo, ref: refName }).catch(() => ZERO_OID);
418
+ return currentOid === oldOid ? null : {
419
+ refName,
420
+ ok: false,
421
+ reason: "non-fast-forward, ref updated by another push"
422
+ };
423
+ }
424
+ async function validateRefUpdates(repo, refUpdates) {
425
+ return Promise.all(
426
+ refUpdates.map(
427
+ async ({ oldOid, refName }) => await checkRefCas(repo, refName, oldOid) ?? { refName, ok: true }
428
+ )
429
+ );
409
430
  }
410
431
  async function applyRefUpdates(repo, refUpdates, hooks) {
411
432
  return runStep(
@@ -413,17 +434,8 @@ async function applyRefUpdates(repo, refUpdates, hooks) {
413
434
  "apply ref updates",
414
435
  () => Promise.all(
415
436
  refUpdates.map(async ({ oldOid, newOid, refName }) => {
416
- if (!isSafeFullRefName(refName)) {
417
- return { refName, ok: false, reason: "invalid ref name" };
418
- }
419
- const currentOid = await git4.resolveRef({ ...repo, ref: refName }).catch(() => ZERO_OID);
420
- if (currentOid !== oldOid) {
421
- return {
422
- refName,
423
- ok: false,
424
- reason: "non-fast-forward, ref updated by another push"
425
- };
426
- }
437
+ const failure = await checkRefCas(repo, refName, oldOid);
438
+ if (failure) return failure;
427
439
  if (newOid === ZERO_OID) {
428
440
  await git4.deleteRef({ ...repo, ref: refName }).catch(() => {
429
441
  });
@@ -461,10 +473,41 @@ function receivePackResponse(results) {
461
473
  }
462
474
  async function applyReceivePack(repo, parsed, options, hooks) {
463
475
  await ensureRepoInitialized(repo, options?.defaultBranch ?? "main");
464
- await indexIncomingPack(repo, parsed.packData, hooks);
465
- const results = await applyRefUpdates(repo, parsed.refUpdates, hooks);
476
+ const preflight = await validateRefUpdates(repo, parsed.refUpdates);
477
+ const acceptedUpdates = parsed.refUpdates.filter(
478
+ (_, index) => preflight[index]?.ok
479
+ );
480
+ const incomingPackPaths = await indexIncomingPack(
481
+ repo,
482
+ acceptedUpdates.some((update) => update.newOid !== ZERO_OID) ? parsed.packData : new Uint8Array(),
483
+ hooks
484
+ );
485
+ const newTips = acceptedUpdates.filter((update) => update.newOid !== ZERO_OID).map((update) => update.newOid);
486
+ if (newTips.length > 0) {
487
+ const { complete } = await collectReachableOids(repo, newTips, hooks);
488
+ if (!complete) {
489
+ await Promise.all(
490
+ incomingPackPaths.map(
491
+ (filepath) => rawFs(repo).unlink(filepath).catch(() => {
492
+ })
493
+ )
494
+ );
495
+ return {
496
+ results: preflight.map(
497
+ (result) => result.ok ? { ...result, ok: false, reason: "incomplete object graph" } : result
498
+ ),
499
+ stalePackPaths: []
500
+ };
501
+ }
502
+ }
503
+ const applied = await applyRefUpdates(repo, acceptedUpdates, hooks);
504
+ const results = preflight.map(
505
+ (result, index) => result.ok ? applied.find(
506
+ (entry) => entry.refName === parsed.refUpdates[index]?.refName
507
+ ) ?? result : result
508
+ );
466
509
  const repackOptions = options?.repack;
467
- const stalePackPaths = repackOptions === false ? [] : await runStep(
510
+ const stalePackPaths = repackOptions === false || !results.some((result) => result.ok) ? [] : await runStep(
468
511
  hooks,
469
512
  "repack",
470
513
  () => repackRepository(repo, repackOptions, hooks)
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 full object graph from `startOids`, returning every reachable\n * oid. Concurrent traversal paths are deduplicated promise-per-oid; a\n * missing object is retried once, then reported through `hooks.onWarn` and\n * reflected in `complete: false`.\n */\nexport async function collectReachableOids(\n\trepo: Repo,\n\tstartOids: string[],\n\thooks?: HttpHooks,\n): Promise<ReachabilityResult> {\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\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 { 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<void> {\n\tif (packData.length < 4) return;\n\tawait runStep(hooks, \"write + indexPack incoming pack\", async () => {\n\t\tconst fsp = rawFs(repo);\n\t\tconst packDir = `${repo.gitdir}/objects/pack`;\n\t\tawait fsp.mkdir(packDir, { recursive: true });\n\n\t\tconst packName = `recv-${Date.now()}`;\n\t\tawait fsp.writeFile(`${packDir}/${packName}.pack`, packData);\n\n\t\tawait git.indexPack({\n\t\t\t...repo,\n\t\t\tdir: packDir,\n\t\t\tfilepath: `${packName}.pack`,\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\tif (!isSafeFullRefName(refName)) {\n\t\t\t\t\treturn { refName, ok: false, reason: \"invalid ref name\" };\n\t\t\t\t}\n\n\t\t\t\tconst currentOid = await git\n\t\t\t\t\t.resolveRef({ ...repo, ref: refName })\n\t\t\t\t\t.catch(() => ZERO_OID);\n\n\t\t\t\tif (currentOid !== oldOid) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trefName,\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\treason: \"non-fast-forward, ref updated by another push\",\n\t\t\t\t\t};\n\t\t\t\t}\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\tawait indexIncomingPack(repo, parsed.packData, hooks);\n\tconst results = await applyRefUpdates(repo, parsed.refUpdates, hooks);\n\tconst repackOptions = options?.repack;\n\tconst stalePackPaths =\n\t\trepackOptions === false\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, 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/** Hex string → Uint8Array. */\nfunction fromHex(hex: string): Uint8Array {\n\tconst bytes = new Uint8Array(hex.length / 2);\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\tbytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n\t}\n\treturn bytes;\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":";;;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B,iBAAiB;AAAA,QAClB;AAAA,QACA,MAAM,OAAO,QAAQ,OAAO,GAAG,iBAAiB,KAAK,CAAC;AAAA,MACvD;AAAA,IACD;AAAA,EACD;AAEA,MAAI,SAAS,YAAY;AACxB,UAAM,QAAQ,OAAO,cAAc,QAAQ,UAAU;AAAA,EACtD;AAEA,QAAM,EAAE,MAAM,SAAS,IAAI,MAAM;AAAA,IAChC;AAAA,IACA;AAAA,IACA,MAAM,qBAAqB,MAAM,OAAO,KAAK;AAAA,EAC9C;AACA,MAAI,OAAO;AAEX,MAAI,MAAM,SAAS,GAAG;AACrB,UAAM,EAAE,MAAM,SAAS,IAAI,MAAM;AAAA,MAChC;AAAA,MACA;AAAA,MACA,MAAM,qBAAqB,MAAM,OAAO,KAAK;AAAA,IAC9C;AACA,UAAM,UAAU,IAAI,IAAI,QAAQ;AAChC,WAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,QAAQ,IAAI,GAAG,CAAC;AAAA,EAC9C;AAEA,QAAM,EAAE,SAAS,IAAI,MAAM;AAAA,IAC1B;AAAA,IACA,gBAAgB,KAAK,MAAM;AAAA,IAC3B,MAAMC,KAAI,YAAY,EAAE,GAAG,MAAM,KAAK,CAAC;AAAA,EACxC;AAEA,QAAM,YACL,oBAAoB,aAAa,WAAW,IAAI,WAAW,YAAY,CAAC,CAAC;AAE1E,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","git","git","git","git","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/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 full object graph from `startOids`, returning every reachable\n * oid. Concurrent traversal paths are deduplicated promise-per-oid; a\n * missing object is retried once, then reported through `hooks.onWarn` and\n * reflected in `complete: false`.\n */\nexport async function collectReachableOids(\n\trepo: Repo,\n\tstartOids: string[],\n\thooks?: HttpHooks,\n): Promise<ReachabilityResult> {\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\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\tconst { complete } = await collectReachableOids(repo, newTips, hooks);\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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/^[0-9a-f]{40}$/i;
131
131
  function hasRecursiveFileLister(fs) {
132
132
  return typeof fs === "object" && fs !== null && "listFilesRecursively" in fs && typeof fs.listFilesRecursively === "function";
133
133
  }
134
+ function getPromisesFs(fs) {
135
+ const promises = fs.promises;
136
+ return promises ?? null;
137
+ }
138
+ function decodeFileContent(content) {
139
+ return typeof content === "string" ? content : new TextDecoder().decode(content);
140
+ }
134
141
  async function listLooseBranches(repo) {
135
142
  if (!hasRecursiveFileLister(repo.fs)) return null;
136
143
  const names = await repo.fs.listFilesRecursively(`${repo.gitdir}/refs/heads`);
@@ -138,7 +145,7 @@ async function listLooseBranches(repo) {
138
145
  }
139
146
  async function readPackedBranches(repo) {
140
147
  if (!hasRecursiveFileLister(repo.fs)) return /* @__PURE__ */ new Map();
141
- const promisesFs = repo.fs.promises;
148
+ const promisesFs = getPromisesFs(repo.fs);
142
149
  if (!promisesFs) return /* @__PURE__ */ new Map();
143
150
  try {
144
151
  const content = await promisesFs.readFile(
@@ -146,7 +153,7 @@ async function readPackedBranches(repo) {
146
153
  "utf8"
147
154
  );
148
155
  const refs = /* @__PURE__ */ new Map();
149
- for (const line of (typeof content === "string" ? content : new TextDecoder().decode(content)).split("\n")) {
156
+ for (const line of decodeFileContent(content).split("\n")) {
150
157
  const match = /^([0-9a-f]{40}) refs\/heads\/(.+)$/i.exec(line);
151
158
  if (match?.[1] && match[2] && isSafeBranchName(match[2])) {
152
159
  refs.set(match[2], match[1]);
@@ -159,11 +166,11 @@ async function readPackedBranches(repo) {
159
166
  }
160
167
  async function getCurrentLooseBranch(repo) {
161
168
  if (!hasRecursiveFileLister(repo.fs)) return null;
162
- const promisesFs = repo.fs.promises;
169
+ const promisesFs = getPromisesFs(repo.fs);
163
170
  if (!promisesFs) return null;
164
171
  try {
165
172
  const content = await promisesFs.readFile(`${repo.gitdir}/HEAD`, "utf8");
166
- const head = (typeof content === "string" ? content : new TextDecoder().decode(content)).trim();
173
+ const head = decodeFileContent(content).trim();
167
174
  const match = /^ref: refs\/heads\/(.+)$/.exec(head);
168
175
  return match?.[1] && isSafeBranchName(match[1]) ? match[1] : null;
169
176
  } catch {
@@ -171,14 +178,14 @@ async function getCurrentLooseBranch(repo) {
171
178
  }
172
179
  }
173
180
  async function resolveLooseRefFast(repo, ref) {
174
- const promisesFs = repo.fs.promises;
181
+ const promisesFs = getPromisesFs(repo.fs);
175
182
  if (promisesFs) {
176
183
  try {
177
184
  const content = await promisesFs.readFile(
178
185
  `${repo.gitdir}/${ref}`,
179
186
  "utf8"
180
187
  );
181
- const oid = (typeof content === "string" ? content : new TextDecoder().decode(content)).trim();
188
+ const oid = decodeFileContent(content).trim();
182
189
  if (FULL_SHA_RE2.test(oid)) return oid;
183
190
  } catch {
184
191
  }
@@ -669,6 +676,27 @@ function summarizeDiff(files) {
669
676
  totalFiles: files.length
670
677
  };
671
678
  }
679
+ function buildDiffFile(path, status, before, after) {
680
+ const isBinary = !!(before?.isBinary || after?.isBinary);
681
+ return {
682
+ path,
683
+ status,
684
+ additions: !isBinary && after ? countContentLines(after.text) : 0,
685
+ deletions: !isBinary && before ? countContentLines(before.text) : 0,
686
+ patch: isBinary ? "" : createUnifiedPatch({
687
+ path,
688
+ before: before?.text ?? "",
689
+ after: after?.text ?? "",
690
+ oldPath: before ? void 0 : "/dev/null",
691
+ newPath: after ? void 0 : "/dev/null"
692
+ }),
693
+ isBinary,
694
+ oldContent: before && isBinary ? toBase64(before.bytes) : void 0,
695
+ newContent: after && isBinary ? toBase64(after.bytes) : void 0,
696
+ oldSize: before?.bytes.length,
697
+ newSize: after?.bytes.length
698
+ };
699
+ }
672
700
  async function walkTreeDiff(repo, oldOid, newOid) {
673
701
  const changes = await import_isomorphic_git5.default.walk({
674
702
  ...repo,
@@ -680,41 +708,13 @@ async function walkTreeDiff(repo, oldOid, newOid) {
680
708
  const oidA2 = A ? await A.oid() : "";
681
709
  const { blob } = await import_isomorphic_git5.default.readBlob({ ...repo, oid: oidA2 });
682
710
  const before = detectBlobContent(blob);
683
- return {
684
- path: filepath,
685
- status: "deleted",
686
- additions: 0,
687
- deletions: before.isBinary ? 0 : countContentLines(before.text),
688
- patch: before.isBinary ? "" : createUnifiedPatch({
689
- path: filepath,
690
- before: before.text,
691
- after: "",
692
- newPath: "/dev/null"
693
- }),
694
- isBinary: before.isBinary,
695
- oldContent: before.isBinary ? toBase64(before.bytes) : void 0,
696
- oldSize: before.bytes.length
697
- };
711
+ return buildDiffFile(filepath, "deleted", before, null);
698
712
  }
699
713
  if (!typeA && typeB) {
700
714
  const oidB2 = B ? await B.oid() : "";
701
715
  const { blob } = await import_isomorphic_git5.default.readBlob({ ...repo, oid: oidB2 });
702
716
  const after = detectBlobContent(blob);
703
- return {
704
- path: filepath,
705
- status: "added",
706
- additions: after.isBinary ? 0 : countContentLines(after.text),
707
- deletions: 0,
708
- patch: after.isBinary ? "" : createUnifiedPatch({
709
- path: filepath,
710
- before: "",
711
- after: after.text,
712
- oldPath: "/dev/null"
713
- }),
714
- isBinary: after.isBinary,
715
- newContent: after.isBinary ? toBase64(after.bytes) : void 0,
716
- newSize: after.bytes.length
717
- };
717
+ return buildDiffFile(filepath, "added", null, after);
718
718
  }
719
719
  const [oidA, oidB] = await Promise.all([
720
720
  A ? A.oid() : Promise.resolve(""),
@@ -727,23 +727,7 @@ async function walkTreeDiff(repo, oldOid, newOid) {
727
727
  ]);
728
728
  const before = detectBlobContent(blobA);
729
729
  const after = detectBlobContent(blobB);
730
- const isBinary = before.isBinary || after.isBinary;
731
- return {
732
- path: filepath,
733
- status: "modified",
734
- additions: isBinary ? 0 : countContentLines(after.text),
735
- deletions: isBinary ? 0 : countContentLines(before.text),
736
- patch: isBinary ? "" : createUnifiedPatch({
737
- path: filepath,
738
- before: before.text,
739
- after: after.text
740
- }),
741
- isBinary,
742
- oldContent: isBinary ? toBase64(before.bytes) : void 0,
743
- newContent: isBinary ? toBase64(after.bytes) : void 0,
744
- oldSize: before.bytes.length,
745
- newSize: after.bytes.length
746
- };
730
+ return buildDiffFile(filepath, "modified", before, after);
747
731
  }
748
732
  return null;
749
733
  }
@@ -777,21 +761,7 @@ async function getCommitDiff(repo, commitSha) {
777
761
  entries.map(async ({ path, oid }) => {
778
762
  const { blob } = await import_isomorphic_git5.default.readBlob({ ...repo, oid });
779
763
  const after = detectBlobContent(blob);
780
- return {
781
- path,
782
- status: "added",
783
- additions: after.isBinary ? 0 : countContentLines(after.text),
784
- deletions: 0,
785
- patch: after.isBinary ? "" : createUnifiedPatch({
786
- path,
787
- before: "",
788
- after: after.text,
789
- oldPath: "/dev/null"
790
- }),
791
- isBinary: after.isBinary,
792
- newContent: after.isBinary ? toBase64(after.bytes) : void 0,
793
- newSize: after.bytes.length
794
- };
764
+ return buildDiffFile(path, "added", null, after);
795
765
  })
796
766
  );
797
767
  return summarizeDiff(files2);