@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 909 lines 29.3 KB
Raw
1 import crypto from "node:crypto";
2 /**
3 * Git object codec: oid hashing, loose headers, commit/tree/tag parsing,
4 * tree encoding with git's directory sort rule, and the pack varint codecs
5 * (type+size, delta-size, OFS_DELTA offset).
6 *
7 * Pure CPU module. The only platform import is `node:crypto` (sha1), used
8 * synchronously and exposed behind Effect wrappers / a tiny incremental
9 * `Sha1` interface.
10 *
11 * Wire-format references (verified against gitformat-pack / gitprotocol-pack):
12 *
13 * - Object id = sha1 over `"<type> <size>\0" + content` (uncompressed).
14 * - Pack entry header: first byte `MSB | type(3) | size low 4 bits`, then
15 * little-endian 7-bit continuation groups.
16 * - OFS_DELTA offset: big-endian 7-bit groups **with a +1 bias applied per
17 * continuation byte** (the classic decoder bug).
18 * - Tree entries sort byte-wise by name with directories compared as if
19 * suffixed `/` (`foo.txt` < `foo/`).
20 */
21 import * as Effect from "effect/Effect";
22 import * as Schema from "effect/Schema";
23
24 // ─────────────────────────────────────────────────────────────────────────────
25 // Oids
26 // ─────────────────────────────────────────────────────────────────────────────
27
28 /**
29 * A 40-hex sha1 object id. Kept as a plain string alias in the codec layer;
30 * the REST surface brands it separately.
31 */
32 export type Oid = string;
33
34 /**
35 * The all-zero oid used by the wire protocol for "no object" (ref creation
36 * old-oid, ref deletion new-oid, empty-repo advertisement).
37 */
38 export const ZERO_OID: Oid = "0".repeat(40);
39
40 /**
41 * Regular expression matching a valid 40-hex sha1 oid.
42 */
43 export const OID_REGEX = /^[0-9a-f]{40}$/;
44
45 /**
46 * Returns `true` when the string is a well-formed 40-hex sha1 oid.
47 */
48 // NOTE: deliberately NOT a type guard — `Oid` is an unbranded `string`
49 // alias, so `s is Oid` would narrow the else-branch to `never`.
50 export const isOid = (s: string): boolean => OID_REGEX.test(s);
51
52 /**
53 * Error raised by the object codec when parsing malformed object content
54 * (commits, trees, tags) or malformed varint/offset encodings.
55 */
56 export class ObjectParseError extends Schema.TaggedError<ObjectParseError>()("ObjectParseError", {
57 reason: Schema.String,
58 }) {}
59
60 // ─────────────────────────────────────────────────────────────────────────────
61 // Object types
62 // ─────────────────────────────────────────────────────────────────────────────
63
64 /**
65 * Numeric git object types as used in pack entry headers and the object
66 * store's `objects.type` column.
67 */
68 export const ObjectType = {
69 commit: 1,
70 tree: 2,
71 blob: 3,
72 tag: 4,
73 } as const;
74
75 /**
76 * The numeric type of a real (non-delta) git object.
77 */
78 export type ObjectType = (typeof ObjectType)[keyof typeof ObjectType];
79
80 /**
81 * Numeric pack entry types: the four object types plus the two delta
82 * representations (`6 = OBJ_OFS_DELTA`, `7 = OBJ_REF_DELTA`). `0` is invalid
83 * and `5` is reserved by the format.
84 */
85 export const PackEntryType = {
86 ...ObjectType,
87 ofsDelta: 6,
88 refDelta: 7,
89 } as const;
90
91 /**
92 * The numeric type of a pack entry (object or delta).
93 */
94 export type PackEntryType = (typeof PackEntryType)[keyof typeof PackEntryType];
95
96 /**
97 * The canonical text name of a git object type (as used in loose headers and
98 * commit/tag bodies).
99 */
100 export type ObjectTypeName = "commit" | "tree" | "blob" | "tag";
101
102 const TYPE_NAMES: Record<ObjectType, ObjectTypeName> = {
103 1: "commit",
104 2: "tree",
105 3: "blob",
106 4: "tag",
107 };
108
109 /**
110 * Maps a numeric object type to its canonical text name.
111 */
112 export const objectTypeName = (type: ObjectType): ObjectTypeName => TYPE_NAMES[type];
113
114 /**
115 * Maps a text object type name back to its numeric type, or `undefined` when
116 * the name is not one of `commit|tree|blob|tag`.
117 */
118 export const objectTypeOf = (name: string): ObjectType | undefined => {
119 switch (name) {
120 case "commit":
121 return 1;
122 case "tree":
123 return 2;
124 case "blob":
125 return 3;
126 case "tag":
127 return 4;
128 default:
129 return undefined;
130 }
131 };
132
133 /**
134 * Returns `true` when a pack entry type denotes a delta (OFS or REF).
135 */
136 export const isDeltaType = (type: PackEntryType): type is 6 | 7 => type === 6 || type === 7;
137
138 // ─────────────────────────────────────────────────────────────────────────────
139 // Bytes / hex helpers
140 // ─────────────────────────────────────────────────────────────────────────────
141
142 const HEX = "0123456789abcdef";
143
144 /**
145 * Lowercase hex encoding of a byte array (used for oids and pack trailers).
146 */
147 export const bytesToHex = (bytes: Uint8Array): string => {
148 let out = "";
149 for (let i = 0; i < bytes.length; i++) {
150 const b = bytes[i]!;
151 out += HEX[b >> 4]! + HEX[b & 0x0f]!;
152 }
153 return out;
154 };
155
156 /**
157 * Decodes a lowercase/uppercase hex string into bytes. Throws
158 * {@link ObjectParseError} on odd length or non-hex characters.
159 */
160 export const hexToBytes = (hex: string): Uint8Array => {
161 if (hex.length % 2 !== 0) {
162 throw ObjectParseError.make({
163 reason: `odd-length hex string: ${hex.length}`,
164 });
165 }
166 const out = new Uint8Array(hex.length / 2);
167 for (let i = 0; i < out.length; i++) {
168 const byte = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
169 if (Number.isNaN(byte)) {
170 throw ObjectParseError.make({
171 reason: `invalid hex at position ${i * 2}`,
172 });
173 }
174 out[i] = byte;
175 }
176 return out;
177 };
178
179 /**
180 * Concatenates byte chunks into one contiguous buffer.
181 */
182 export const concatBytes = (
183 chunks: ReadonlyArray<Uint8Array>,
184 totalLength?: number,
185 ): Uint8Array => {
186 const total = totalLength ?? chunks.reduce((acc, chunk) => acc + chunk.length, 0);
187 const out = new Uint8Array(total);
188 let pos = 0;
189 for (const chunk of chunks) {
190 out.set(chunk, pos);
191 pos += chunk.length;
192 }
193 return out;
194 };
195
196 const encoder = new TextEncoder();
197 const decoder = new TextDecoder("utf-8");
198
199 /**
200 * UTF-8 encodes a string (small shared helper for the codec modules).
201 */
202 export const utf8Encode = (s: string): Uint8Array => encoder.encode(s);
203
204 /**
205 * UTF-8 decodes bytes (lossy for non-UTF-8 content — the codec never
206 * re-serializes from decoded text, so round-tripping is unaffected).
207 */
208 export const utf8Decode = (bytes: Uint8Array): string => decoder.decode(bytes);
209
210 // ─────────────────────────────────────────────────────────────────────────────
211 // Hashing
212 // ─────────────────────────────────────────────────────────────────────────────
213
214 /**
215 * Minimal incremental sha1 hasher used for pack trailers and object ids.
216 * Construct via {@link makeSha1}. `digest`/`digestHex` may be called once.
217 */
218 export interface Sha1 {
219 /** Feeds bytes into the hash. */
220 readonly update: (bytes: Uint8Array) => void;
221 /** Finalizes and returns the 20-byte raw digest. */
222 readonly digest: () => Uint8Array;
223 /** Finalizes and returns the 40-hex digest. */
224 readonly digestHex: () => string;
225 }
226
227 /**
228 * Creates an incremental sha1 hasher over `node:crypto`.
229 *
230 * This is a plain (synchronous, CPU-only) factory; call sites participate in
231 * the Effect runtime by constructing it inside `Effect.sync` (see
232 * `PackWriter`), keeping `node:crypto` contained to this module.
233 */
234 export const makeSha1 = (): Sha1 => {
235 const hash = crypto.createHash("sha1");
236 let finalized: Uint8Array | undefined;
237 return {
238 update: (bytes) => {
239 hash.update(bytes);
240 },
241 digest: () => {
242 finalized ??= new Uint8Array(hash.digest());
243 return finalized;
244 },
245 digestHex: () => {
246 finalized ??= new Uint8Array(hash.digest());
247 return bytesToHex(finalized);
248 },
249 };
250 };
251
252 /**
253 * Builds the canonical loose-object header `"<type> <size>\0"` used as the
254 * hashing prefix (and git's on-disk loose format prefix).
255 */
256 export const looseHeader = (type: ObjectType, size: number): Uint8Array =>
257 utf8Encode(`${objectTypeName(type)} ${size}\0`);
258
259 /**
260 * Computes the object id: `sha1("<type> <size>\0" + content)` over the
261 * uncompressed content.
262 */
263 /** Synchronous form of {@link hashObject} for hot loops (DESIGN §22.5). */
264 export const hashObjectSync = (type: ObjectType, content: Uint8Array): Oid => {
265 const sha = makeSha1();
266 sha.update(looseHeader(type, content.length));
267 sha.update(content);
268 return sha.digestHex();
269 };
270
271 export const hashObject = (type: ObjectType, content: Uint8Array): Effect.Effect<Oid> =>
272 Effect.sync(() => {
273 const sha = makeSha1();
274 sha.update(looseHeader(type, content.length));
275 sha.update(content);
276 return sha.digestHex();
277 });
278
279 // ─────────────────────────────────────────────────────────────────────────────
280 // Commit / tag parsing
281 // ─────────────────────────────────────────────────────────────────────────────
282
283 /**
284 * A parsed author/committer/tagger identity line:
285 * `Name <email> <unix-ts> <±hhmm>`.
286 */
287 export interface Identity {
288 readonly name: string;
289 readonly email: string;
290 /** Unix timestamp in seconds. */
291 readonly when: number;
292 /** Timezone offset as written, e.g. `+0200` or `-0700`. */
293 readonly tz: string;
294 }
295
296 /**
297 * A parsed commit object. The raw bytes remain the source of truth for
298 * hashing/round-tripping; this structure feeds the commit graph and REST
299 * reads only.
300 */
301 export interface ParsedCommit {
302 /** The commit's root tree oid. */
303 readonly tree: Oid;
304 /** Parent commit oids, in order. */
305 readonly parents: ReadonlyArray<Oid>;
306 readonly author: Identity;
307 readonly committer: Identity;
308 /** The full GPG signature block, when present. */
309 readonly gpgsig: string | undefined;
310 /** Commit message (everything after the first blank line), UTF-8 decoded. */
311 readonly message: string;
312 /**
313 * All raw headers in order as `[key, value]` pairs (continuation lines
314 * joined with `\n`), including the standard ones above.
315 */
316 readonly headers: ReadonlyArray<readonly [string, string]>;
317 }
318
319 /**
320 * A parsed annotated tag object.
321 */
322 export interface ParsedTag {
323 /** The tagged object's oid. */
324 readonly object: Oid;
325 /** The tagged object's type name. */
326 readonly targetType: ObjectTypeName;
327 /** The tag name (without `refs/tags/`). */
328 readonly tag: string;
329 /** Tagger identity; optional (ancient tags may lack it). */
330 readonly tagger: Identity | undefined;
331 /** Tag message. */
332 readonly message: string;
333 /** All raw headers in order. */
334 readonly headers: ReadonlyArray<readonly [string, string]>;
335 }
336
337 const IDENTITY_REGEX = /^(.*) <(.*)> (\d+) ([+-]\d{4})$/;
338
339 /**
340 * Parses an identity value (`Name <email> ts tz`). Fails with
341 * {@link ObjectParseError} when the shape does not match.
342 */
343 export const parseIdentity = (value: string): Effect.Effect<Identity, ObjectParseError> =>
344 Effect.suspend(() => {
345 const match = IDENTITY_REGEX.exec(value);
346 if (match === null) {
347 return Effect.fail(ObjectParseError.make({ reason: `malformed identity: ${value}` }));
348 }
349 return Effect.succeed({
350 name: match[1]!,
351 email: match[2]!,
352 when: Number.parseInt(match[3]!, 10),
353 tz: match[4]!,
354 });
355 });
356
357 /**
358 * Splits an object body into its header block and message, honoring
359 * continuation lines (lines starting with a single space extend the previous
360 * header's value, joined with `\n` — this is how `gpgsig` spans lines).
361 */
362 const parseHeaderBlock = (
363 content: Uint8Array,
364 ): {
365 readonly headers: Array<readonly [string, string]>;
366 readonly message: string;
367 } => {
368 const text = utf8Decode(content);
369 const sep = text.indexOf("\n\n");
370 const headerText = sep === -1 ? text : text.slice(0, sep);
371 const message = sep === -1 ? "" : text.slice(sep + 2);
372 const headers: Array<readonly [string, string]> = [];
373 for (const line of headerText.split("\n")) {
374 if (line.startsWith(" ") && headers.length > 0) {
375 const last = headers[headers.length - 1]!;
376 headers[headers.length - 1] = [last[0], `${last[1]}\n${line.slice(1)}`];
377 } else {
378 const space = line.indexOf(" ");
379 if (space === -1) {
380 headers.push([line, ""]);
381 } else {
382 headers.push([line.slice(0, space), line.slice(space + 1)]);
383 }
384 }
385 }
386 return { headers, message };
387 };
388
389 /**
390 * Parses a commit object's content (without the loose header). Strict about
391 * the fields the engine depends on: `tree`, `author`, `committer` must be
392 * present and well-formed; unknown headers (incl. `gpgsig`) are preserved.
393 */
394 export const parseCommit = Effect.fn(function* (content: Uint8Array) {
395 const { headers, message } = parseHeaderBlock(content);
396 let tree: Oid | undefined;
397 const parents: Array<Oid> = [];
398 let authorRaw: string | undefined;
399 let committerRaw: string | undefined;
400 let gpgsig: string | undefined;
401 for (const [key, value] of headers) {
402 switch (key) {
403 case "tree":
404 if (!isOid(value)) {
405 return yield* ObjectParseError.make({
406 reason: `commit tree is not a valid oid: ${value}`,
407 });
408 }
409 tree = value;
410 break;
411 case "parent":
412 if (!isOid(value)) {
413 return yield* ObjectParseError.make({
414 reason: `commit parent is not a valid oid: ${value}`,
415 });
416 }
417 parents.push(value);
418 break;
419 case "author":
420 authorRaw = value;
421 break;
422 case "committer":
423 committerRaw = value;
424 break;
425 case "gpgsig":
426 gpgsig = value;
427 break;
428 default:
429 break;
430 }
431 }
432 if (tree === undefined) {
433 return yield* ObjectParseError.make({ reason: "commit has no tree header" });
434 }
435 if (authorRaw === undefined) {
436 return yield* ObjectParseError.make({
437 reason: "commit has no author header",
438 });
439 }
440 if (committerRaw === undefined) {
441 return yield* ObjectParseError.make({
442 reason: "commit has no committer header",
443 });
444 }
445 const author = yield* parseIdentity(authorRaw);
446 const committer = yield* parseIdentity(committerRaw);
447 const parsed: ParsedCommit = {
448 tree,
449 parents,
450 author,
451 committer,
452 gpgsig,
453 message,
454 headers,
455 };
456 return parsed;
457 });
458
459 /**
460 * Formats an identity line value: `Name <email> <unix-ts> <±hhmm>`.
461 * Round-trips {@link parseIdentity}.
462 */
463 export const formatIdentity = (id: Identity): string =>
464 `${id.name} <${id.email}> ${id.when} ${id.tz}`;
465
466 /** Input of {@link encodeCommit}. */
467 export interface CommitFields {
468 /** The commit's root tree oid. */
469 readonly tree: Oid;
470 /** Parent commit oids, in order. */
471 readonly parents: ReadonlyArray<Oid>;
472 readonly author: Identity;
473 readonly committer: Identity;
474 /** Message, verbatim — callers include the trailing `\n`. */
475 readonly message: string;
476 }
477
478 const TZ_REGEX = /^[+-]\d{4}$/;
479
480 const validateIdentity = (role: string, id: Identity): ObjectParseError | undefined => {
481 if (/[<>\n]/.test(id.name) || /[<>\n]/.test(id.email)) {
482 return ObjectParseError.make({
483 reason: `commit ${role} name/email must not contain '<', '>' or newline`,
484 });
485 }
486 if (!Number.isInteger(id.when) || id.when < 0) {
487 return ObjectParseError.make({
488 reason: `commit ${role} timestamp is not a non-negative integer: ${id.when}`,
489 });
490 }
491 if (!TZ_REGEX.test(id.tz)) {
492 return ObjectParseError.make({
493 reason: `commit ${role} timezone is not ±hhmm: ${id.tz}`,
494 });
495 }
496 return undefined;
497 };
498
499 /**
500 * Encodes commit content (without the loose header):
501 * `tree <oid>\n` + `parent <oid>\n`* + `author …\n` + `committer …\n` +
502 * `\n` + message. Byte-exact round trip through {@link parseCommit}.
503 */
504 export const encodeCommit = (fields: CommitFields): Effect.Effect<Uint8Array, ObjectParseError> =>
505 Effect.suspend(() => {
506 if (!isOid(fields.tree)) {
507 return Effect.fail(
508 ObjectParseError.make({
509 reason: `commit tree is not a valid oid: ${fields.tree}`,
510 }),
511 );
512 }
513 for (const parent of fields.parents) {
514 if (!isOid(parent)) {
515 return Effect.fail(
516 ObjectParseError.make({
517 reason: `commit parent is not a valid oid: ${parent}`,
518 }),
519 );
520 }
521 }
522 for (const [role, id] of [
523 ["author", fields.author],
524 ["committer", fields.committer],
525 ] as const) {
526 const invalid = validateIdentity(role, id);
527 if (invalid !== undefined) return Effect.fail(invalid);
528 }
529 const lines = [
530 `tree ${fields.tree}\n`,
531 ...fields.parents.map((parent) => `parent ${parent}\n`),
532 `author ${formatIdentity(fields.author)}\n`,
533 `committer ${formatIdentity(fields.committer)}\n`,
534 `\n`,
535 fields.message,
536 ];
537 return Effect.succeed(utf8Encode(lines.join("")));
538 });
539
540 /**
541 * Parses an annotated tag object's content (without the loose header).
542 * `object`, `type`, and `tag` are required; `tagger` is optional.
543 */
544 export const parseTag = Effect.fn(function* (content: Uint8Array) {
545 const { headers, message } = parseHeaderBlock(content);
546 let object: Oid | undefined;
547 let targetType: ObjectTypeName | undefined;
548 let tag: string | undefined;
549 let taggerRaw: string | undefined;
550 for (const [key, value] of headers) {
551 switch (key) {
552 case "object":
553 if (!isOid(value)) {
554 return yield* ObjectParseError.make({
555 reason: `tag object is not a valid oid: ${value}`,
556 });
557 }
558 object = value;
559 break;
560 case "type": {
561 const t = objectTypeOf(value);
562 if (t === undefined) {
563 return yield* ObjectParseError.make({
564 reason: `tag has invalid target type: ${value}`,
565 });
566 }
567 targetType = objectTypeName(t);
568 break;
569 }
570 case "tag":
571 tag = value;
572 break;
573 case "tagger":
574 taggerRaw = value;
575 break;
576 default:
577 break;
578 }
579 }
580 if (object === undefined || targetType === undefined || tag === undefined) {
581 return yield* ObjectParseError.make({
582 reason: "tag is missing object/type/tag header",
583 });
584 }
585 const tagger = taggerRaw === undefined ? undefined : yield* parseIdentity(taggerRaw);
586 const parsed: ParsedTag = {
587 object,
588 targetType,
589 tag,
590 tagger,
591 message,
592 headers,
593 };
594 return parsed;
595 });
596
597 // ─────────────────────────────────────────────────────────────────────────────
598 // Trees
599 // ─────────────────────────────────────────────────────────────────────────────
600
601 /**
602 * One entry of a tree object.
603 *
604 * `mode` is the ascii octal mode without leading zeros as stored in canonical
605 * trees: `100644` file, `100755` executable, `120000` symlink, `160000`
606 * gitlink (submodule), `40000` subtree.
607 */
608 export interface TreeEntry {
609 readonly mode: string;
610 readonly name: string;
611 readonly oid: Oid;
612 }
613
614 /** Tree mode string for a subtree entry. */
615 export const TREE_MODE = "40000";
616 /** Tree mode string for a gitlink (submodule) entry. */
617 export const GITLINK_MODE = "160000";
618
619 /**
620 * The high-level kind of a tree entry derived from its mode.
621 */
622 export type TreeEntryKind = "blob" | "tree" | "commit";
623
624 /**
625 * Classifies a tree entry mode: `40000` → `tree`, `160000` → `commit`
626 * (gitlink), anything else → `blob`.
627 */
628 export const treeEntryKind = (mode: string): TreeEntryKind =>
629 mode === TREE_MODE ? "tree" : mode === GITLINK_MODE ? "commit" : "blob";
630
631 /**
632 * Parses a tree object's content into its entries:
633 * `<mode ascii octal> SP <name> NUL <20 raw sha1 bytes>` concatenated with no
634 * separators.
635 */
636 export const parseTree = (
637 content: Uint8Array,
638 ): Effect.Effect<ReadonlyArray<TreeEntry>, ObjectParseError> =>
639 Effect.suspend(() => {
640 const entries: Array<TreeEntry> = [];
641 let pos = 0;
642 while (pos < content.length) {
643 const spaceIdx = content.indexOf(0x20, pos);
644 if (spaceIdx === -1) {
645 return Effect.fail(
646 ObjectParseError.make({
647 reason: `tree entry at ${pos}: no space after mode`,
648 }),
649 );
650 }
651 const mode = utf8Decode(content.subarray(pos, spaceIdx));
652 if (!/^[0-7]{1,6}$/.test(mode)) {
653 return Effect.fail(
654 ObjectParseError.make({
655 reason: `tree entry at ${pos}: bad mode ${mode}`,
656 }),
657 );
658 }
659 const nulIdx = content.indexOf(0x00, spaceIdx + 1);
660 if (nulIdx === -1) {
661 return Effect.fail(
662 ObjectParseError.make({
663 reason: `tree entry at ${pos}: no NUL after name`,
664 }),
665 );
666 }
667 const name = utf8Decode(content.subarray(spaceIdx + 1, nulIdx));
668 if (name.length === 0) {
669 return Effect.fail(ObjectParseError.make({ reason: `tree entry at ${pos}: empty name` }));
670 }
671 if (nulIdx + 21 > content.length) {
672 return Effect.fail(
673 ObjectParseError.make({
674 reason: `tree entry at ${pos}: truncated sha`,
675 }),
676 );
677 }
678 const oid = bytesToHex(content.subarray(nulIdx + 1, nulIdx + 21));
679 entries.push({ mode, name, oid });
680 pos = nulIdx + 21;
681 }
682 return Effect.succeed(entries);
683 });
684
685 /**
686 * Compares two tree entries with git's canonical sort rule: byte-wise on the
687 * name **with directory entries compared as if suffixed `/`** (so `foo.txt`
688 * sorts before the tree `foo`, which sorts as `foo/`). Wrong order changes
689 * the tree hash and trips `git fsck`.
690 */
691 export const treeEntryCompare = (a: TreeEntry, b: TreeEntry): number => {
692 const aBytes = utf8Encode(treeEntryKind(a.mode) === "tree" ? `${a.name}/` : a.name);
693 const bBytes = utf8Encode(treeEntryKind(b.mode) === "tree" ? `${b.name}/` : b.name);
694 const len = Math.min(aBytes.length, bBytes.length);
695 for (let i = 0; i < len; i++) {
696 const d = aBytes[i]! - bBytes[i]!;
697 if (d !== 0) return d;
698 }
699 return aBytes.length - bBytes.length;
700 };
701
702 /**
703 * Encodes tree entries into canonical tree object content. Entries are sorted
704 * with {@link treeEntryCompare} and modes are normalized (leading zeros
705 * stripped, so `040000` becomes the canonical `40000`).
706 */
707 export const encodeTree = (
708 entries: ReadonlyArray<TreeEntry>,
709 ): Effect.Effect<Uint8Array, ObjectParseError> =>
710 Effect.suspend(() => {
711 try {
712 const sorted = [...entries].sort(treeEntryCompare);
713 const parts: Array<Uint8Array> = [];
714 let total = 0;
715 for (const entry of sorted) {
716 const mode = entry.mode.replace(/^0+(?=\d)/, "");
717 if (!/^[0-7]{1,6}$/.test(mode)) {
718 throw ObjectParseError.make({
719 reason: `invalid tree entry mode: ${entry.mode}`,
720 });
721 }
722 if (!isOid(entry.oid)) {
723 throw ObjectParseError.make({
724 reason: `invalid tree entry oid: ${entry.oid}`,
725 });
726 }
727 const head = utf8Encode(`${mode} ${entry.name}\0`);
728 const sha = hexToBytes(entry.oid);
729 parts.push(head, sha);
730 total += head.length + sha.length;
731 }
732 return Effect.succeed(concatBytes(parts, total));
733 } catch (error) {
734 return Schema.is(ObjectParseError)(error)
735 ? Effect.fail(error)
736 : Effect.fail(ObjectParseError.make({ reason: String(error) }));
737 }
738 });
739
740 // ─────────────────────────────────────────────────────────────────────────────
741 // Varint codecs (pack format)
742 // ─────────────────────────────────────────────────────────────────────────────
743
744 /**
745 * Result of decoding a pack entry type+size header.
746 */
747 export interface TypeSizeHeader {
748 readonly type: PackEntryType;
749 /** Uncompressed size of the entry data (for deltas: of the delta payload). */
750 readonly size: number;
751 /** Offset of the first byte after the header. */
752 readonly next: number;
753 }
754
755 /**
756 * Decodes the pack entry header varint at `offset`:
757 * `size = (b0 & 0x0F) | (b1 & 0x7F) << 4 | (b2 & 0x7F) << 11 | ...`,
758 * `type = (b0 >> 4) & 0x07`. Throws {@link ObjectParseError} on truncation
759 * or an invalid type (0 or 5).
760 */
761 export const decodeTypeSize = (buf: Uint8Array, offset: number): TypeSizeHeader => {
762 if (offset >= buf.length) {
763 throw ObjectParseError.make({ reason: "truncated pack entry header" });
764 }
765 let b = buf[offset]!;
766 const rawType = (b >> 4) & 0x07;
767 if (rawType === 0 || rawType === 5) {
768 throw ObjectParseError.make({
769 reason: `invalid pack entry type ${rawType} at offset ${offset}`,
770 });
771 }
772 const type = rawType as PackEntryType;
773 let size = b & 0x0f;
774 let shift = 4;
775 let i = offset + 1;
776 while ((b & 0x80) !== 0) {
777 if (i >= buf.length) {
778 throw ObjectParseError.make({ reason: "truncated pack entry header" });
779 }
780 if (shift > 53) {
781 throw ObjectParseError.make({ reason: "pack entry size varint overflow" });
782 }
783 b = buf[i]!;
784 i += 1;
785 size += (b & 0x7f) * 2 ** shift;
786 shift += 7;
787 }
788 return { type, size, next: i };
789 };
790
791 /**
792 * Encodes a pack entry type+size header varint (inverse of
793 * {@link decodeTypeSize}).
794 */
795 export const encodeTypeSize = (type: PackEntryType, size: number): Uint8Array => {
796 const out: Array<number> = [];
797 let rest = Math.floor(size / 16);
798 let first = ((type & 0x07) << 4) | (size & 0x0f);
799 if (rest > 0) first |= 0x80;
800 out.push(first);
801 while (rest > 0) {
802 let b = rest & 0x7f;
803 rest = Math.floor(rest / 128);
804 if (rest > 0) b |= 0x80;
805 out.push(b);
806 }
807 return Uint8Array.from(out);
808 };
809
810 /**
811 * Result of decoding a plain little-endian 7-bit varint.
812 */
813 export interface Varint {
814 readonly value: number;
815 /** Offset of the first byte after the varint. */
816 readonly next: number;
817 }
818
819 /**
820 * Decodes a plain little-endian 7-bit varint (MSB = continue) — the encoding
821 * used by delta payload base/result size headers. Throws
822 * {@link ObjectParseError} on truncation or overflow past 2^53.
823 */
824 export const decodeSizeVarint = (buf: Uint8Array, offset: number): Varint => {
825 let value = 0;
826 let shift = 0;
827 let i = offset;
828 for (;;) {
829 if (i >= buf.length) {
830 throw ObjectParseError.make({ reason: "truncated size varint" });
831 }
832 if (shift > 53) {
833 throw ObjectParseError.make({ reason: "size varint overflow" });
834 }
835 const b = buf[i]!;
836 i += 1;
837 value += (b & 0x7f) * 2 ** shift;
838 shift += 7;
839 if ((b & 0x80) === 0) break;
840 }
841 return { value, next: i };
842 };
843
844 /**
845 * Encodes a plain little-endian 7-bit varint (inverse of
846 * {@link decodeSizeVarint}).
847 */
848 export const encodeSizeVarint = (value: number): Uint8Array => {
849 const out: Array<number> = [];
850 let v = value;
851 for (;;) {
852 let b = v & 0x7f;
853 v = Math.floor(v / 128);
854 if (v > 0) b |= 0x80;
855 out.push(b);
856 if (v === 0) break;
857 }
858 return Uint8Array.from(out);
859 };
860
861 /**
862 * Decodes an OFS_DELTA negative-offset varint at `offset`: big-endian 7-bit
863 * groups (MSB = continue) **with a +1 bias applied on every continuation**:
864 *
865 * ```
866 * n = b0 & 0x7F
867 * while (b0 & 0x80): b0 = next; n = ((n + 1) << 7) | (b0 & 0x7F)
868 * ```
869 *
870 * Naive concatenation without the `+1` is wrong for multi-byte offsets.
871 * Throws {@link ObjectParseError} on truncation.
872 */
873 export const decodeOfsDeltaOffset = (buf: Uint8Array, offset: number): Varint => {
874 if (offset >= buf.length) {
875 throw ObjectParseError.make({ reason: "truncated ofs-delta offset" });
876 }
877 let i = offset;
878 let b = buf[i]!;
879 i += 1;
880 let n = b & 0x7f;
881 while ((b & 0x80) !== 0) {
882 if (i >= buf.length) {
883 throw ObjectParseError.make({ reason: "truncated ofs-delta offset" });
884 }
885 b = buf[i]!;
886 i += 1;
887 n = (n + 1) * 128 + (b & 0x7f);
888 if (!Number.isSafeInteger(n)) {
889 throw ObjectParseError.make({ reason: "ofs-delta offset overflow" });
890 }
891 }
892 return { value: n, next: i };
893 };
894
895 /**
896 * Encodes an OFS_DELTA negative-offset varint (inverse of
897 * {@link decodeOfsDeltaOffset}, matching git's encoder: subtract the bias per
898 * continuation byte, big-endian order).
899 */
900 export const encodeOfsDeltaOffset = (value: number): Uint8Array => {
901 const out: Array<number> = [value & 0x7f];
902 let v = Math.floor(value / 128);
903 while (v > 0) {
904 v -= 1;
905 out.unshift(0x80 | (v & 0x7f));
906 v = Math.floor(v / 128);
907 }
908 return Uint8Array.from(out);
909 };