// GIT OBJECTS OVER THE BLOB SEAM (docs/contributing/architecture.md#the-engine-slot): loose objects — ` // \0`, zlib-deflated, addressed by the SHA-1 of the uncompressed form — written // and read through the active BlobStore under `/objects//`, the exact layout // a bare repository keeps. Pure JS: SHA-1 through WebCrypto, loose objects stored uncompressed in zlib framing (storeZlib), // a pack deflated through the kernel's `deflate` (bytes.ts), inflate through ./inflate.ts (it reports consumed bytes, which a packfile // reader needs). Bun and workerd alike; no `git` binary anywhere. import { inflateZlib } from './inflate.ts'; import { deflate } from '../bytes.ts'; import type { BlobStore } from '../blob-store.ts'; export type GitObjectType = 'commit' | 'tree' | 'blob' | 'tag'; const ENC = new TextEncoder(); const DEC = new TextDecoder(); export async function sha1Hex(bytes: Uint8Array): Promise { const digest = new Uint8Array(await crypto.subtle.digest('SHA-1', bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer)); return [...digest].map((b) => b.toString(16).padStart(2, '0')).join(''); } export function hexToBytes(hex: string): Uint8Array { const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); return out; } export function bytesToHex(b: Uint8Array): string { return [...b].map((byte) => byte.toString(16).padStart(2, '0')).join(''); } export function concat(...parts: Uint8Array[]): Uint8Array { const n = parts.reduce((s, p) => s + p.length, 0); const out = new Uint8Array(n); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; } return out; } /** The loose-object form: header + payload (what the sha is computed over). */ export function encodeLoose(type: GitObjectType, payload: Uint8Array): Uint8Array { return concat(ENC.encode(`${type} ${payload.length}\0`), payload); } export function decodeLoose(bytes: Uint8Array): { type: GitObjectType; payload: Uint8Array } { const nul = bytes.indexOf(0); if (nul < 0) throw new Error('git object: no header'); const [type, size] = DEC.decode(bytes.subarray(0, nul)).split(' '); const payload = bytes.subarray(nul + 1); if (Number(size) !== payload.length) throw new Error(`git object: header says ${size} bytes, payload is ${payload.length}`); return { type: type as GitObjectType, payload }; } export async function hashObject(type: GitObjectType, payload: Uint8Array): Promise { return sha1Hex(encodeLoose(type, payload)); } export async function deflateZlib(bytes: Uint8Array): Promise { return deflate(bytes); } /** zlib with stored (uncompressed) deflate blocks: what git writes at `core.compression 0`, and what every * inflater reads. A loose object is written on every commit a World makes; compressing each one through the * asynchronous CompressionStream made a write's cost the stream's round trips, not the object's size. */ export function storeZlib(bytes: Uint8Array): Uint8Array { const blocks = Math.max(1, Math.ceil(bytes.length / 0xffff)); const out = new Uint8Array(2 + bytes.length + blocks * 5 + 4); out[0] = 0x78; out[1] = 0x01; let o = 2; for (let b = 0; b < blocks; b++) { const start = b * 0xffff; const len = Math.min(0xffff, bytes.length - start); out[o++] = b === blocks - 1 ? 1 : 0; out[o++] = len & 0xff; out[o++] = len >>> 8; out[o++] = ~len & 0xff; out[o++] = (~len >>> 8) & 0xff; out.set(bytes.subarray(start, start + len), o); o += len; } let a = 1; let d = 0; for (let i = 0; i < bytes.length; i++) { a = (a + bytes[i]!) % 65521; d = (d + a) % 65521; } const adler = ((d << 16) | a) >>> 0; out[o++] = adler >>> 24; out[o++] = (adler >>> 16) & 0xff; out[o++] = (adler >>> 8) & 0xff; out[o++] = adler & 0xff; return out; } /** The object store: one bare repo's objects under a key prefix in the blob seam. */ export class GitObjectStore { constructor(private readonly blobs: BlobStore, private readonly prefix: string) {} key(sha: string): string { return `${this.prefix}/objects/${sha.slice(0, 2)}/${sha.slice(2)}`; } async has(sha: string): Promise { return this.blobs.exists(this.key(sha)); } async write(type: GitObjectType, payload: Uint8Array): Promise { const loose = encodeLoose(type, payload); const sha = await sha1Hex(loose); if (!(await this.blobs.exists(this.key(sha)))) await this.blobs.put(this.key(sha), storeZlib(loose)); return sha; } async read(sha: string): Promise<{ type: GitObjectType; payload: Uint8Array } | null> { const z = await this.blobs.get(this.key(sha)); if (z === null) return null; return decodeLoose(inflateZlib(z).out); } } // ── codecs ────────────────────────────────────────────────────────────────────────────── export type TreeEntry = { mode: string; name: string; sha: string }; /** git sorts tree entries by name, with a directory's name compared as if it ended in '/'. */ export function sortTreeEntries(entries: TreeEntry[]): TreeEntry[] { const k = (e: TreeEntry) => (e.mode === '40000' || e.mode === '040000' ? `${e.name}/` : e.name); return [...entries].sort((a, b) => (k(a) < k(b) ? -1 : k(a) > k(b) ? 1 : 0)); } export function encodeTree(entries: TreeEntry[]): Uint8Array { return concat(...sortTreeEntries(entries).map((e) => concat(ENC.encode(`${e.mode.replace(/^0+(?=\d)/, '')} ${e.name}\0`), hexToBytes(e.sha)))); } export function decodeTree(payload: Uint8Array): TreeEntry[] { const out: TreeEntry[] = []; let i = 0; while (i < payload.length) { const sp = payload.indexOf(0x20, i); const nul = payload.indexOf(0, sp); out.push({ mode: DEC.decode(payload.subarray(i, sp)), name: DEC.decode(payload.subarray(sp + 1, nul)), sha: bytesToHex(payload.subarray(nul + 1, nul + 21)) }); i = nul + 21; } return out; } export type Ident = { name: string; email: string; time: number; tz: string }; export type Commit = { tree: string; parents: string[]; author: Ident; committer: Ident; message: string }; const ident = (i: Ident) => `${i.name} <${i.email}> ${i.time} ${i.tz}`; export function encodeCommit(c: Commit): Uint8Array { return ENC.encode(`tree ${c.tree}\n${c.parents.map((p) => `parent ${p}\n`).join('')}author ${ident(c.author)}\ncommitter ${ident(c.committer)}\n\n${c.message}`); } function parseIdent(s: string): Ident { const m = /^(.*) <([^>]*)> (\d+) ([+-]\d{4})$/.exec(s); if (!m) throw new Error(`git ident: ${s}`); return { name: m[1]!, email: m[2]!, time: Number(m[3]), tz: m[4]! }; } export function decodeCommit(payload: Uint8Array): Commit { const text = DEC.decode(payload); const sep = text.indexOf('\n\n'); const head = text.slice(0, sep); const message = text.slice(sep + 2); const c: Commit = { tree: '', parents: [], author: undefined as never, committer: undefined as never, message }; for (const line of head.split('\n')) { const sp = line.indexOf(' '); const k = line.slice(0, sp), v = line.slice(sp + 1); if (k === 'tree') c.tree = v; else if (k === 'parent') c.parents.push(v); else if (k === 'author') c.author = parseIdent(v); else if (k === 'committer') c.committer = parseIdent(v); } return c; } export type Tag = { object: string; type: GitObjectType; tag: string; tagger?: Ident; message: string }; export function encodeTag(t: Tag): Uint8Array { return ENC.encode(`object ${t.object}\ntype ${t.type}\ntag ${t.tag}\n${t.tagger ? `tagger ${ident(t.tagger)}\n` : ''}\n${t.message}`); } export function decodeTag(payload: Uint8Array): Tag { const text = DEC.decode(payload); const sep = text.indexOf('\n\n'); const t: Tag = { object: '', type: 'commit', tag: '', message: text.slice(sep + 2) }; for (const line of text.slice(0, sep).split('\n')) { const sp = line.indexOf(' '); const k = line.slice(0, sp), v = line.slice(sp + 1); if (k === 'object') t.object = v; else if (k === 'type') t.type = v as GitObjectType; else if (k === 'tag') t.tag = v; else if (k === 'tagger') t.tagger = parseIdent(v); } return t; }