@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, 06:00 UTC

main
ts 179 lines 5.45 KB
Raw
1 import * as zlib from "node:zlib";
2 /**
3 * Gzipped ustar of a directory. Used to upload a generated Docker
4 * context (Railway `/up`, and any other gzip-tarball consumer).
5 */
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Path from "effect/Path";
9
10 const encoder = new TextEncoder();
11
12 const pad512 = (size: number) => (512 - (size % 512)) % 512;
13
14 const byteLength = (value: string) => encoder.encode(value).byteLength;
15
16 // `encodeInto` stops before a character that does not fit, so a field is
17 // never cut in the middle of a multi-byte UTF-8 sequence.
18 const writeBytes = (buf: Uint8Array, offset: number, value: string, length: number) => {
19 encoder.encodeInto(value, buf.subarray(offset, offset + length));
20 };
21
22 const writeOctal = (buf: Uint8Array, offset: number, value: number, length: number) => {
23 writeBytes(buf, offset, `${value.toString(8).padStart(length - 1, "0")}\0`, length);
24 };
25
26 const headerBlock = (input: {
27 name: string;
28 size: number;
29 type: string;
30 mode: number;
31 prefix?: string;
32 }): Uint8Array => {
33 const buf = new Uint8Array(512);
34 writeBytes(buf, 0, input.name, 100);
35 writeOctal(buf, 100, input.mode, 8);
36 writeOctal(buf, 108, 0, 8);
37 writeOctal(buf, 116, 0, 8);
38 writeOctal(buf, 124, input.size, 12);
39 writeOctal(buf, 136, Math.floor(Date.now() / 1000), 12);
40 for (let i = 148; i < 156; i++) buf[i] = 0x20;
41 buf[156] = input.type.charCodeAt(0);
42 writeBytes(buf, 257, "ustar", 6);
43 buf[262] = 0;
44 writeBytes(buf, 263, "00", 2);
45 if (input.prefix !== undefined) {
46 writeBytes(buf, 345, input.prefix, 155);
47 }
48 let sum = 0;
49 for (const byte of buf) sum += byte;
50 writeBytes(buf, 148, `${sum.toString(8).padStart(6, "0")}\0 `, 8);
51 return buf;
52 };
53
54 // ustar field limits are in bytes, so measure the UTF-8 encoding, not
55 // `string.length` (UTF-16 code units).
56 const splitUstarName = (rel: string): { name: string; prefix?: string } | undefined => {
57 if (byteLength(rel) <= 100) return { name: rel };
58 for (let i = rel.indexOf("/"); i >= 1; i = rel.indexOf("/", i + 1)) {
59 const prefix = rel.slice(0, i);
60 const name = rel.slice(i + 1);
61 if (byteLength(prefix) > 155) return undefined;
62 if (name.length > 0 && byteLength(name) <= 100) {
63 return { prefix, name };
64 }
65 }
66 return undefined;
67 };
68
69 const gnuLongLink = (name: string): Uint8Array[] => {
70 const bytes = encoder.encode(`${name}\0`);
71 const header = headerBlock({
72 name: "././@LongLink",
73 size: bytes.length,
74 type: "L",
75 mode: 0,
76 });
77 const pad = pad512(bytes.length);
78 return pad > 0 ? [header, bytes, new Uint8Array(pad)] : [header, bytes];
79 };
80
81 const concat = (chunks: ReadonlyArray<Uint8Array>): Uint8Array => {
82 const total = chunks.reduce((n, chunk) => n + chunk.byteLength, 0);
83 const out = new Uint8Array(total);
84 let offset = 0;
85 for (const chunk of chunks) {
86 out.set(chunk, offset);
87 offset += chunk.byteLength;
88 }
89 return out;
90 };
91
92 type WalkEntry = {
93 rel: string;
94 abs: string;
95 dir: boolean;
96 mode: number;
97 };
98
99 const walkDirectory = (
100 root: string,
101 ): Effect.Effect<WalkEntry[], unknown, FileSystem.FileSystem | Path.Path> =>
102 Effect.gen(function* () {
103 const fs = yield* FileSystem.FileSystem;
104 const path = yield* Path.Path;
105 const files: WalkEntry[] = [];
106 const walk = (dir: string, rel: string): Effect.Effect<void, unknown> =>
107 Effect.gen(function* () {
108 const entries = [...(yield* fs.readDirectory(dir))].sort();
109 for (const entry of entries) {
110 const abs = path.join(dir, entry);
111 const childRel = rel.length === 0 ? entry : `${rel}/${entry}`;
112 const posixRel = childRel.replaceAll("\\", "/");
113 const stat = yield* fs.stat(abs);
114 if (stat.type === "Directory") {
115 files.push({
116 rel: posixRel,
117 abs,
118 dir: true,
119 mode: stat.mode & 0o7777,
120 });
121 yield* walk(abs, posixRel);
122 } else if (stat.type === "File") {
123 files.push({
124 rel: posixRel,
125 abs,
126 dir: false,
127 mode: stat.mode & 0o7777,
128 });
129 }
130 }
131 });
132 yield* walk(root, "");
133 return files;
134 });
135
136 const fileBlocks = (rel: string, size: number, type: "0" | "5", mode: number): Uint8Array[] => {
137 const split = splitUstarName(rel);
138 if (split === undefined) {
139 return [
140 ...gnuLongLink(rel),
141 headerBlock({
142 name: rel,
143 size,
144 type,
145 mode,
146 }),
147 ];
148 }
149 return [headerBlock({ ...split, size, type, mode })];
150 };
151
152 /**
153 * Pack `root` into a gzipped tar (ustar + GNU long-name). Paths are
154 * relative to `root` with POSIX separators.
155 */
156 export const tarGzipDirectory = Effect.fn(function* (
157 root: string,
158 options?: { preserveMode?: boolean },
159 ) {
160 const fs = yield* FileSystem.FileSystem;
161 const files = yield* walkDirectory(root);
162 const chunks: Uint8Array[] = [];
163 for (const file of files) {
164 if (file.dir) {
165 chunks.push(...fileBlocks(`${file.rel}/`, 0, "5", options?.preserveMode ? file.mode : 0o755));
166 continue;
167 }
168 const content = yield* fs.readFile(file.abs);
169 chunks.push(
170 ...fileBlocks(file.rel, content.byteLength, "0", options?.preserveMode ? file.mode : 0o644),
171 );
172 chunks.push(content);
173 const pad = pad512(content.byteLength);
174 if (pad > 0) chunks.push(new Uint8Array(pad));
175 }
176 chunks.push(new Uint8Array(1024));
177 const tar = concat(chunks);
178 return yield* Effect.sync(() => zlib.gzipSync(tar));
179 });