@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 566 lines 18.2 KB
Raw
1 /**
2 * Plain-fetch client of the git-service REST API (`/api/v1`).
3 *
4 * The types mirror `@alchemy.run/git`'s API schemas (`packages/git/src/Api/Schema.ts`)
5 * by hand — the SPA deliberately ships no Effect runtime; it is an example
6 * of consuming the service from any plain JS frontend.
7 */
8
9 // ── configuration ───────────────────────────────────────────────────────────
10
11 const builtinUrl: string | undefined = import.meta.env.VITE_GIT_URL;
12
13 /**
14 * Where the service lives. Same origin as the SPA in the single-origin
15 * deployment, so the Better Auth session cookie rides along with every
16 * request (`credentials: "include"`).
17 */
18 export interface Connection {
19 readonly url: string;
20 }
21
22 export const getConnection = (): Connection => ({
23 url: (builtinUrl ?? location.origin).replace(/\/+$/, ""),
24 });
25
26 // ── auth (Better Auth, mounted at /api/auth) ────────────────────────────────
27
28 export interface User {
29 readonly id: string;
30 readonly name: string;
31 readonly email: string;
32 }
33
34 const authRequest = async <T>(
35 c: Connection,
36 method: string,
37 path: string,
38 body?: unknown,
39 ): Promise<T> => {
40 const res = await fetch(`${c.url}/api/auth${path}`, {
41 method,
42 credentials: "include",
43 headers: body !== undefined ? { "Content-Type": "application/json" } : {},
44 body: body !== undefined ? JSON.stringify(body) : undefined,
45 });
46 if (!res.ok) {
47 const text = await res.text();
48 let message = text;
49 try {
50 message = (JSON.parse(text) as { message?: string }).message ?? text;
51 } catch {
52 /* not JSON */
53 }
54 throw new ApiError(res.status, "AuthError", message || res.statusText);
55 }
56 const text = await res.text();
57 return (text.length === 0 ? null : JSON.parse(text)) as T;
58 };
59
60 export const getSession = (c: Connection): Promise<User | null> =>
61 authRequest<{ user: User } | null>(c, "GET", "/get-session").then(
62 (session) => session?.user ?? null,
63 );
64
65 export const signUp = (
66 c: Connection,
67 input: { name: string; email: string; password: string },
68 ): Promise<User> =>
69 authRequest<{ user: User }>(c, "POST", "/sign-up/email", input).then((r) => r.user);
70
71 export const signIn = (c: Connection, input: { email: string; password: string }): Promise<User> =>
72 authRequest<{ user: User }>(c, "POST", "/sign-in/email", input).then((r) => r.user);
73
74 export const signOut = (c: Connection): Promise<void> =>
75 authRequest<unknown>(c, "POST", "/sign-out", {}).then(() => undefined);
76
77 /** An API key: the password a `git` remote carries. Values are shown once. */
78 export interface ApiKey {
79 readonly id: string;
80 readonly name: string | null;
81 /** The first characters of the key, for recognition. */
82 readonly start: string | null;
83 readonly createdAt: string;
84 readonly expiresAt: string | null;
85 }
86
87 export const listApiKeys = (c: Connection): Promise<ApiKey[]> =>
88 authRequest<ApiKey[]>(c, "GET", "/api-key/list");
89
90 export const createApiKey = (c: Connection, name: string): Promise<ApiKey & { key: string }> =>
91 authRequest(c, "POST", "/api-key/create", { name });
92
93 export const deleteApiKey = (c: Connection, keyId: string): Promise<void> =>
94 authRequest<unknown>(c, "POST", "/api-key/delete", { keyId }).then(() => undefined);
95
96 export type RepoStatus = "ready" | "importing" | "forking" | "deleting";
97
98 export interface ObjectStats {
99 loose: number;
100 packed: number;
101 r2: number;
102 bytes: number;
103 }
104
105 export interface PushStats {
106 objects: number;
107 bytes: number;
108 ingestMs: number;
109 stageMs: number;
110 connectivityMs: number;
111 finalizeMs: number;
112 totalMs: number;
113 }
114
115 export interface Repo {
116 owner: string;
117 name: string;
118 repoId: string;
119 defaultBranch: string;
120 description: string | null;
121 readOnly: boolean;
122 /** Readable (REST + clone) without signing in. */
123 public: boolean;
124 forkOf: string | null;
125 status: RepoStatus;
126 createdAt: number;
127 objects: ObjectStats;
128 lastPush: PushStats | null;
129 }
130
131 export interface Ref {
132 name: string;
133 oid: string;
134 peeled?: string;
135 }
136
137 export interface Signature {
138 name: string;
139 email: string;
140 /** Unix timestamp (seconds). */
141 date: number;
142 /** Timezone offset as written, e.g. `+0200`. */
143 tz: string;
144 }
145
146 export interface CommitInfo {
147 oid: string;
148 tree: string;
149 parents: string[];
150 author: Signature;
151 committer: Signature;
152 message: string;
153 }
154
155 export interface TreeEntry {
156 mode: string;
157 name: string;
158 oid: string;
159 type: "blob" | "tree" | "commit";
160 }
161
162 export type FileStatus = "added" | "removed" | "modified";
163
164 /**
165 * One changed file in a commit diff or comparison. Content is NOT
166 * included — clients fetch old/new blobs by oid (`getBlob`) and diff
167 * locally. `oldSize`/`newSize` gate binary/oversize files without a
168 * round trip. Gitlinks (mode `160000`) carry commit oids — render
169 * "Subproject commit …", never fetch them as blobs. No rename detection
170 * in v1 (a rename is `removed` + `added`); a mode-only change is
171 * `modified` with `oldOid === newOid`.
172 */
173 export interface DiffEntry {
174 path: string;
175 status: FileStatus;
176 oldOid?: string | null;
177 newOid?: string | null;
178 oldMode?: string | null;
179 newMode?: string | null;
180 oldSize?: number | null;
181 newSize?: number | null;
182 }
183
184 /** Changed files of one commit vs its FIRST parent (null for a root commit). */
185 export interface CommitDiff {
186 oid: string;
187 parent: string | null;
188 files: DiffEntry[];
189 /** `true` when the list was cut at the server cap (1000 files). */
190 truncated: boolean;
191 }
192
193 /** GitHub-style three-dot comparison of two revisions. */
194 export interface Comparison {
195 base: string;
196 head: string;
197 mergeBase: string;
198 aheadBy: number;
199 behindBy: number;
200 /** Head-side commits, committer-time descending, capped at 250. */
201 commits: CommitInfo[];
202 commitsTruncated: boolean;
203 /** File diff of mergeBase..head (three-dot). */
204 files: DiffEntry[];
205 filesTruncated: boolean;
206 }
207
208 export interface RepoCreated {
209 repo: Repo;
210 remote: string;
211 }
212
213 export interface Page<T> {
214 items: T[];
215 nextCursor: string | null;
216 hasMore: boolean;
217 }
218
219 // ── errors ──────────────────────────────────────────────────────────────────
220
221 export class ApiError extends Error {
222 constructor(
223 readonly status: number,
224 readonly tag: string,
225 override readonly message: string,
226 ) {
227 super(message);
228 }
229 }
230
231 const parseError = async (res: Response): Promise<ApiError> => {
232 let tag = `HTTP ${res.status}`;
233 let message = res.statusText;
234 try {
235 const body: unknown = await res.clone().json();
236 if (typeof body === "object" && body !== null) {
237 const record = body as Record<string, unknown>;
238 if (typeof record._tag === "string") tag = record._tag;
239 if (typeof record.message === "string") message = record.message;
240 else if (typeof record.reason === "string") message = record.reason;
241 }
242 } catch {
243 try {
244 message = (await res.text()) || message;
245 } catch {
246 /* keep statusText */
247 }
248 }
249 return new ApiError(res.status, tag, message || tag);
250 };
251
252 // ── transport ───────────────────────────────────────────────────────────────
253
254 const request = async <T>(
255 connection: Connection,
256 method: string,
257 path: string,
258 body?: unknown,
259 ): Promise<T> => {
260 const res = await fetch(`${connection.url}/api/v1${path}`, {
261 method,
262 // The Better Auth session cookie is the credential; anonymous
263 // requests carry none and the policy confines them to public reads.
264 credentials: "include",
265 headers: body !== undefined ? { "Content-Type": "application/json" } : {},
266 body: body !== undefined ? JSON.stringify(body) : undefined,
267 });
268 if (!res.ok) throw await parseError(res);
269 if (res.status === 204) return undefined as T;
270 const text = await res.text();
271 return (text.length === 0 ? undefined : JSON.parse(text)) as T;
272 };
273
274 const seg = encodeURIComponent;
275
276 // ── repos ───────────────────────────────────────────────────────────────────
277
278 export const listRepos = (
279 c: Connection,
280 query?: { owner?: string; cursor?: string; limit?: number },
281 ): Promise<Page<Repo>> => {
282 const params = new URLSearchParams();
283 if (query?.owner) params.set("owner", query.owner);
284 if (query?.cursor) params.set("cursor", query.cursor);
285 if (query?.limit) params.set("limit", String(query.limit));
286 const qs = params.size > 0 ? `?${params}` : "";
287 return request(c, "GET", `/repos${qs}`);
288 };
289
290 export const getRepo = (c: Connection, owner: string, repo: string) =>
291 request<Repo>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}`);
292
293 export const createRepo = (
294 c: Connection,
295 payload: {
296 owner: string;
297 name: string;
298 description?: string;
299 public?: boolean;
300 },
301 ) => request<RepoCreated>(c, "POST", `/repos`, payload);
302
303 export const updateRepo = (
304 c: Connection,
305 owner: string,
306 repo: string,
307 payload: {
308 description?: string | null;
309 defaultBranch?: string;
310 readOnly?: boolean;
311 public?: boolean;
312 },
313 ) => request<Repo>(c, "PATCH", `/repos/${seg(owner)}/${seg(repo)}`, payload);
314
315 export const deleteRepo = (c: Connection, owner: string, repo: string) =>
316 request<unknown>(c, "DELETE", `/repos/${seg(owner)}/${seg(repo)}`);
317
318 export const compactRepo = (c: Connection, owner: string, repo: string) =>
319 request<unknown>(c, "POST", `/repos/${seg(owner)}/${seg(repo)}/compact`);
320
321 // ── refs ────────────────────────────────────────────────────────────────────
322
323 export const listRefs = (c: Connection, owner: string, repo: string) =>
324 request<{ head: string | null; refs: Ref[] }>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/refs`);
325
326 // ── objects ─────────────────────────────────────────────────────────────────
327
328 export const getCommit = (c: Connection, owner: string, repo: string, oid: string) =>
329 request<CommitInfo>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/commits/${seg(oid)}`);
330
331 export const getLog = (
332 c: Connection,
333 owner: string,
334 repo: string,
335 query?: { ref?: string; cursor?: string; limit?: number },
336 ): Promise<Page<CommitInfo>> => {
337 const params = new URLSearchParams();
338 if (query?.ref) params.set("ref", query.ref);
339 if (query?.cursor) params.set("cursor", query.cursor);
340 if (query?.limit) params.set("limit", String(query.limit));
341 const qs = params.size > 0 ? `?${params}` : "";
342 return request(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/log${qs}`);
343 };
344
345 export const getTree = (c: Connection, owner: string, repo: string, oid: string) =>
346 request<{ oid: string; entries: TreeEntry[] }>(
347 c,
348 "GET",
349 `/repos/${seg(owner)}/${seg(repo)}/trees/${seg(oid)}`,
350 );
351
352 /** Raw file bytes at `ref` + `path` (the streaming non-JSON route). */
353 export const getFile = async (
354 c: Connection,
355 owner: string,
356 repo: string,
357 options: { ref?: string; path: string },
358 ): Promise<Uint8Array> => {
359 const params = new URLSearchParams({ path: options.path });
360 if (options.ref) params.set("ref", options.ref);
361 const res = await fetch(`${c.url}/api/v1/repos/${seg(owner)}/${seg(repo)}/file?${params}`, {
362 credentials: "include",
363 });
364 if (!res.ok) throw await parseError(res);
365 return new Uint8Array(await res.arrayBuffer());
366 };
367
368 /** Changed files of a commit vs its first parent (empty tree for a root). */
369 export const getCommitDiff = (c: Connection, owner: string, repo: string, oid: string) =>
370 request<CommitDiff>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/commits/${seg(oid)}/diff`);
371
372 /**
373 * Three-dot comparison of two revisions (short/full refname or 40-hex
374 * oid; annotated tags peeled): merge base, ahead/behind, head-side
375 * commits, and the mergeBase..head file diff.
376 */
377 export const compareCommits = (
378 c: Connection,
379 owner: string,
380 repo: string,
381 query: { base: string; head: string },
382 ) => {
383 const params = new URLSearchParams({ base: query.base, head: query.head });
384 return request<Comparison>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/compare?${params}`);
385 };
386
387 /** JSON blob endpoint serves ≤ 1 MiB only (422 beyond; use /raw). */
388 const MAX_JSON_BLOB = 1024 * 1024;
389
390 /** Raw blob bytes by oid (the streaming non-JSON route, any size). */
391 const getBlobRaw = async (
392 c: Connection,
393 owner: string,
394 repo: string,
395 oid: string,
396 ): Promise<Uint8Array> => {
397 const res = await fetch(
398 `${c.url}/api/v1/repos/${seg(owner)}/${seg(repo)}/blobs/${seg(oid)}/raw`,
399 { credentials: "include" },
400 );
401 if (!res.ok) throw await parseError(res);
402 return new Uint8Array(await res.arrayBuffer());
403 };
404
405 /**
406 * Blob bytes by oid. Uses the JSON base64 route for blobs ≤ 1 MiB and
407 * falls back to `/raw` for bigger ones — pass `size` (known from a
408 * {@link DiffEntry}) to skip the doomed JSON attempt entirely.
409 */
410 export const getBlob = async (
411 c: Connection,
412 owner: string,
413 repo: string,
414 oid: string,
415 options?: { size?: number },
416 ): Promise<Uint8Array> => {
417 if (options?.size !== undefined && options.size > MAX_JSON_BLOB) {
418 return getBlobRaw(c, owner, repo, oid);
419 }
420 try {
421 const json = await request<{
422 oid: string;
423 size: number;
424 encoding: "base64";
425 content: string;
426 }>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/blobs/${seg(oid)}`);
427 const binary = atob(json.content);
428 const bytes = new Uint8Array(binary.length);
429 for (let index = 0; index < binary.length; index++) {
430 bytes[index] = binary.charCodeAt(index);
431 }
432 return bytes;
433 } catch (cause) {
434 // ObjectTooLarge — the size hint was absent or stale; stream it raw.
435 if (cause instanceof ApiError && cause.tag === "ObjectTooLarge") {
436 return getBlobRaw(c, owner, repo, oid);
437 }
438 throw cause;
439 }
440 };
441
442 // ── pull requests ───────────────────────────────────────────────────────────
443
444 export type PullState = "open" | "closed" | "merged";
445
446 /** Why `mergeable` is what it is (see {@link PullDetail}). */
447 export type MergeableReason = "ff" | "merge-commit" | "conflict" | "up-to-date" | "unknown";
448
449 /**
450 * A pull request. PRs track **live** branches by ref name — the record
451 * stores intent + lifecycle, never a diff snapshot; diff and mergeability
452 * are recomputed from current ref tips on every read.
453 */
454 export interface Pull {
455 /** Per-repo monotonic PR number (1-based, never reused). */
456 number: number;
457 title: string;
458 body: string | null;
459 /** Full base ref name, e.g. `refs/heads/main`. */
460 baseRef: string;
461 /** Full head ref name, e.g. `refs/heads/feature`. */
462 headRef: string;
463 state: PullState;
464 /** Epoch milliseconds. */
465 createdAt: number;
466 updatedAt: number;
467 /** Epoch milliseconds; `null` unless `state` is `merged`. */
468 mergedAt: number | null;
469 /** FF: the head tip; the merge commit otherwise. Set iff merged. */
470 mergeCommit: string | null;
471 }
472
473 /**
474 * PR detail = the row + live computed compare fields. Live fields are
475 * `null` when uncomputable: a missing base/head branch, a saturated
476 * ancestor walk, or a merged PR (its record is `mergeCommit`).
477 */
478 export interface PullDetail extends Pull {
479 /** Current tip of `baseRef`; `null` if the branch is gone. */
480 baseOid: string | null;
481 /** Current tip of `headRef`; `null` if the branch is gone. */
482 headOid: string | null;
483 mergeBase: string | null;
484 /** Commits on head not on base (`null` when the walk saturates). */
485 aheadBy: number | null;
486 /** Commits on base not on head. */
487 behindBy: number | null;
488 /**
489 * `true` = FF-able or trivially merge-able; `false` = conflicting
490 * paths or up-to-date; `null` = uncomputable.
491 */
492 mergeable: boolean | null;
493 mergeableReason: MergeableReason | null;
494 }
495
496 /** Response of a successful PR merge. */
497 export interface MergeResult {
498 method: "ff" | "merge-commit";
499 /** The oid the base ref now points at. */
500 oid: string;
501 /** The PR after the merge (`state: "merged"`). */
502 pull: Pull;
503 }
504
505 /** Lists PRs, newest first. `state` defaults to `open` server-side. */
506 export const listPulls = (
507 c: Connection,
508 owner: string,
509 repo: string,
510 query?: {
511 state?: PullState | "all";
512 cursor?: string;
513 limit?: number;
514 },
515 ): Promise<Page<Pull>> => {
516 const params = new URLSearchParams();
517 if (query?.state) params.set("state", query.state);
518 if (query?.cursor) params.set("cursor", query.cursor);
519 if (query?.limit) params.set("limit", String(query.limit));
520 const qs = params.size > 0 ? `?${params}` : "";
521 return request(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/pulls${qs}`);
522 };
523
524 /** Reads one PR with live compare fields (ahead/behind/mergeable). */
525 export const getPull = (c: Connection, owner: string, repo: string, number: number) =>
526 request<PullDetail>(c, "GET", `/repos/${seg(owner)}/${seg(repo)}/pulls/${number}`);
527
528 /** Opens a PR. `base`/`head` accept short (`main`) or full branch names. */
529 export const createPull = (
530 c: Connection,
531 owner: string,
532 repo: string,
533 payload: { title: string; body?: string; base: string; head: string },
534 ) => request<Pull>(c, "POST", `/repos/${seg(owner)}/${seg(repo)}/pulls`, payload);
535
536 /** Patches title/body, or closes/reopens via `state`. */
537 export const updatePull = (
538 c: Connection,
539 owner: string,
540 repo: string,
541 number: number,
542 payload: {
543 title?: string;
544 body?: string | null;
545 state?: "open" | "closed";
546 },
547 ) => request<Pull>(c, "PATCH", `/repos/${seg(owner)}/${seg(repo)}/pulls/${number}`, payload);
548
549 /**
550 * Merges an open PR: fast-forward when possible, else a merge commit iff
551 * the three-way tree merge is trivial. `expectedHeadOid` guards against
552 * a force-push racing the merge (409 RefConflict when stale).
553 */
554 export const mergePull = (
555 c: Connection,
556 owner: string,
557 repo: string,
558 number: number,
559 payload?: { message?: string; expectedHeadOid?: string },
560 ) =>
561 request<MergeResult>(
562 c,
563 "POST",
564 `/repos/${seg(owner)}/${seg(repo)}/pulls/${number}/merge`,
565 payload ?? {},
566 );