@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 243 lines 8.71 KB
Raw
1 /**
2 * Extra files packed next to a Fly/Hetzner/Railway program (Docker
3 * context or unit zip).
4 *
5 * `dest: "."` means "this directory IS the image/unit root" (`COPY . /app`),
6 * not a subfolder. {@link contextRootOf} then treats that source as the
7 * context, and {@link posixRelUnder} places `main` relative to it so
8 * `isExternal` ENTRYPOINT is `node /app/serve-node.mjs` instead of
9 * bundling `index.mjs`. Hashing skips gitignore (a parent `dist` rule
10 * would empty the hash) but still excludes `node_modules` / `.git` /
11 * `.next/cache` / `.alchemy` so the glob stays bounded.
12 */
13 import * as Effect from "effect/Effect";
14 import * as FileSystem from "effect/FileSystem";
15 import * as Path from "effect/Path";
16 import { dotAlchemyDirectory } from "../AlchemyContext.ts";
17 import { hashDirectory } from "../Command/Memo.ts";
18 import { isPathWithin } from "./isPathWithin.ts";
19 import { initialCwd } from "./Node.ts";
20 import { sha256 } from "./sha256.ts";
21
22 const ioConcurrency = 16;
23
24 /** Extra-file dest that means "merge this directory into the image/unit root". */
25 export const CONTEXT_ROOT_DEST = ".";
26
27 export const isContextRootDest = (dest: string): boolean => dest === "." || dest === "";
28
29 /**
30 * Hash extra-file trees without gitignore (a parent `dist` rule would
31 * empty the hash) but skip the directories that make a recursive glob
32 * unbounded.
33 */
34 export const EXTRA_FILES_HASH_EXCLUDE = [
35 "**/node_modules/**",
36 "**/.git/**",
37 "**/.next/cache/**",
38 "**/.alchemy/**",
39 ];
40
41 /**
42 * Extra file or directory copied next to a bundled program (Docker
43 * context, unit archive, …). `dest` is relative to the image/unit root.
44 */
45 export interface ExtraFile {
46 /** Local file or directory (absolute, or relative to {@link initialCwd}). */
47 readonly source: string;
48 /**
49 * Destination relative to the image/unit root (e.g. `"dist"`, `".next"`).
50 * `"."` means merge into the root.
51 */
52 readonly dest: string;
53 }
54
55 const posix = (value: string): string => value.replaceAll("\\", "/");
56
57 /**
58 * Path of `file` relative to `root`, POSIX. Empty string if they are the
59 * same directory. Returns `undefined` when `file` is not under `root`.
60 */
61 export const posixRelUnder = (
62 root: string,
63 file: string,
64 path: {
65 readonly resolve: (...segments: string[]) => string;
66 readonly relative: (from: string, to: string) => string;
67 readonly isAbsolute: (value: string) => boolean;
68 },
69 ): string | undefined => {
70 const from = posix(path.resolve(root));
71 const to = posix(path.resolve(file));
72 const rel = posix(path.relative(from, to));
73 if (rel === "") return "";
74 if (path.isAbsolute(rel) || rel === ".." || rel.startsWith("../")) {
75 return undefined;
76 }
77 return rel;
78 };
79
80 /**
81 * Docker/zip context root for an unbundled (`isExternal`) program. If
82 * some extraFile is `dest: "."`, that source is the context; otherwise
83 * the context is `dirname(main)`.
84 */
85 export const contextRootOf = (
86 main: string,
87 extraFiles: ReadonlyArray<{ source: string; dest: string }>,
88 path: Path.Path,
89 resolveSource: (source: string) => string,
90 ): string => {
91 const root = extraFiles.find((file) => isContextRootDest(file.dest));
92 return root !== undefined ? resolveSource(root.source) : path.dirname(main);
93 };
94
95 /** Normalize a COPY destination so it cannot escape the root. `"."` is the root. */
96 export const extraFileDestination = (destination: string): string => {
97 const normalized = destination.replaceAll("\\", "/").replace(/^\/+/, "");
98 if (isContextRootDest(normalized)) return CONTEXT_ROOT_DEST;
99 const parts = normalized
100 .split("/")
101 .filter((part) => part.length > 0 && part !== "." && part !== "..");
102 return parts.length === 0 ? "dist" : parts.join("/");
103 };
104
105 export const resolveExtraSource = (
106 source: string,
107 path: {
108 readonly isAbsolute: (value: string) => boolean;
109 readonly resolve: (...segments: string[]) => string;
110 },
111 ) => (path.isAbsolute(source) ? source : path.resolve(initialCwd, source));
112
113 const skipCopySegment = (segment: string) => segment === ".git" || segment === ".alchemy";
114
115 export const hashExtraFiles = Effect.fn(function* (
116 extraFiles: ReadonlyArray<ExtraFile> | undefined,
117 ) {
118 const fs = yield* FileSystem.FileSystem;
119 const path = yield* Path.Path;
120 const runtimeBase = process.cwd();
121 const dotAlchemy = yield* dotAlchemyDirectory;
122 const entries = yield* Effect.forEach(
123 extraFiles ?? [],
124 (extra) =>
125 Effect.gen(function* () {
126 const dest = extraFileDestination(extra.dest);
127 const source = resolveExtraSource(extra.source, path);
128 const exists = yield* fs.exists(source).pipe(Effect.orElseSucceed(() => false));
129 if (!exists || isPathWithin(dotAlchemy, source, runtimeBase)) return [dest, ""] as const;
130 const stat = yield* fs.stat(source);
131 const hash =
132 stat.type === "Directory"
133 ? yield* hashDirectory({
134 cwd: source,
135 memo: {
136 exclude: EXTRA_FILES_HASH_EXCLUDE,
137 lockfile: false,
138 },
139 }).pipe(Effect.orElseSucceed(() => ""))
140 : yield* sha256(yield* fs.readFile(source));
141 return [dest, hash] as const;
142 }),
143 { concurrency: ioConcurrency },
144 );
145 return Object.fromEntries(entries) as Record<string, string>;
146 });
147
148 /**
149 * Copy a file or directory without macOS `clonefile`. Nitro/Nuxt
150 * `.output/server` trees (and their nested `node_modules`) fail
151 * `fs.copy` with `EINVAL: invalid argument, clonefile`. Nested
152 * `node_modules` are copied — nitro's node preset emits runtime
153 * deps there (`solid-js`, `seroval`, …) and the host imports them.
154 */
155 export const copyTree = Effect.fn(function* (from: string, to: string) {
156 const fs = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const runtimeBase = process.cwd();
159 const dotAlchemy = yield* dotAlchemyDirectory;
160 if (isPathWithin(dotAlchemy, from, runtimeBase)) return;
161 const stat = yield* fs.stat(from).pipe(Effect.orElseSucceed(() => undefined));
162 if (stat === undefined) return;
163 if (stat.type !== "Directory") {
164 if (stat.type !== "File") return;
165 yield* fs.makeDirectory(path.dirname(to), { recursive: true });
166 const contents = yield* fs.readFile(from);
167 yield* fs.writeFile(to, contents);
168 return;
169 }
170 yield* fs.makeDirectory(to, { recursive: true });
171 const names = yield* fs.readDirectory(from, { recursive: true });
172 yield* Effect.all(
173 names.flatMap((name) => {
174 if (
175 name.split(/[\\/]/).some(skipCopySegment) ||
176 isPathWithin(dotAlchemy, path.join(from, name), runtimeBase)
177 )
178 return [];
179 return [
180 Effect.gen(function* () {
181 const src = path.join(from, name);
182 const item = yield* fs.stat(src).pipe(Effect.orElseSucceed(() => undefined));
183 if (item === undefined || item.type !== "File") return;
184 const dst = path.join(to, name);
185 yield* fs.makeDirectory(path.dirname(dst), { recursive: true });
186 const contents = yield* fs.readFile(src);
187 yield* fs.writeFile(dst, contents);
188 }),
189 ];
190 }),
191 { concurrency: ioConcurrency },
192 );
193 });
194
195 export const copyExtraFiles = Effect.fn(function* (
196 contextDir: string,
197 extraFiles: ReadonlyArray<ExtraFile> | undefined,
198 options?: {
199 readonly onMissing?: (file: {
200 readonly source: string;
201 readonly dest: string;
202 }) => Effect.Effect<unknown, any>;
203 },
204 ) {
205 const fs = yield* FileSystem.FileSystem;
206 const path = yield* Path.Path;
207 yield* Effect.forEach(
208 extraFiles ?? [],
209 (extra) =>
210 Effect.gen(function* () {
211 const source = resolveExtraSource(extra.source, path);
212 const destName = extraFileDestination(extra.dest);
213 const exists = yield* fs.exists(source).pipe(Effect.orElseSucceed(() => false));
214 if (!exists) {
215 if (options?.onMissing !== undefined) {
216 yield* options.onMissing({ source, dest: destName });
217 }
218 return;
219 }
220 if (isContextRootDest(destName)) {
221 const stat = yield* fs.stat(source);
222 if (stat.type === "Directory") {
223 const names = yield* fs.readDirectory(source);
224 yield* Effect.forEach(
225 names,
226 (name) => copyTree(path.join(source, name), path.join(contextDir, name)),
227 { concurrency: ioConcurrency },
228 );
229 } else {
230 yield* copyTree(source, path.join(contextDir, path.basename(source)));
231 }
232 return;
233 }
234 const dest = path.join(contextDir, destName);
235 if (yield* fs.exists(dest).pipe(Effect.orElseSucceed(() => false))) {
236 yield* fs.remove(dest, { recursive: true });
237 }
238 yield* fs.makeDirectory(path.dirname(dest), { recursive: true });
239 yield* copyTree(source, dest);
240 }),
241 { concurrency: ioConcurrency },
242 );
243 });