@catamorphic/git 0.0.0-stage → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/dist/checkout-remote-backend.d.ts +12 -0
  4. package/dist/checkout-remote-backend.d.ts.map +1 -0
  5. package/dist/file-reads.d.ts +15 -0
  6. package/dist/file-reads.d.ts.map +1 -0
  7. package/dist/fs-backend.d.ts +30 -0
  8. package/dist/fs-backend.d.ts.map +1 -0
  9. package/dist/fs-remote-backend.d.ts +47 -0
  10. package/dist/fs-remote-backend.d.ts.map +1 -0
  11. package/dist/git-object-codec.d.ts +31 -0
  12. package/dist/git-object-codec.d.ts.map +1 -0
  13. package/dist/git-sync.d.ts +61 -0
  14. package/dist/git-sync.d.ts.map +1 -0
  15. package/dist/in-memory-object-store.d.ts +23 -0
  16. package/dist/in-memory-object-store.d.ts.map +1 -0
  17. package/dist/index.d.ts +24 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4746 -0
  20. package/dist/index.js.map +32 -0
  21. package/dist/migrate-workflow.d.ts +12 -0
  22. package/dist/migrate-workflow.d.ts.map +1 -0
  23. package/dist/native-git.d.ts +25 -0
  24. package/dist/native-git.d.ts.map +1 -0
  25. package/dist/native-project-repo.d.ts +57 -0
  26. package/dist/native-project-repo.d.ts.map +1 -0
  27. package/dist/network-sync.d.ts +58 -0
  28. package/dist/network-sync.d.ts.map +1 -0
  29. package/dist/network.d.ts +81 -0
  30. package/dist/network.d.ts.map +1 -0
  31. package/dist/object-remote-backend.d.ts +95 -0
  32. package/dist/object-remote-backend.d.ts.map +1 -0
  33. package/dist/object-store.d.ts +42 -0
  34. package/dist/object-store.d.ts.map +1 -0
  35. package/dist/origin-draft.d.ts +264 -0
  36. package/dist/origin-draft.d.ts.map +1 -0
  37. package/dist/origin-objects.d.ts +201 -0
  38. package/dist/origin-objects.d.ts.map +1 -0
  39. package/dist/personal-files.d.ts +6 -0
  40. package/dist/personal-files.d.ts.map +1 -0
  41. package/dist/project-manager.d.ts +214 -0
  42. package/dist/project-manager.d.ts.map +1 -0
  43. package/dist/project-repo.d.ts +79 -0
  44. package/dist/project-repo.d.ts.map +1 -0
  45. package/dist/ref-moved-error.d.ts +13 -0
  46. package/dist/ref-moved-error.d.ts.map +1 -0
  47. package/dist/ref-names.d.ts +18 -0
  48. package/dist/ref-names.d.ts.map +1 -0
  49. package/dist/types.d.ts +276 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/workspace-mirror.d.ts +110 -0
  52. package/dist/workspace-mirror.d.ts.map +1 -0
  53. package/package.json +53 -4
  54. package/src/checkout-remote-backend.ts +154 -0
  55. package/src/diff3.d.ts +16 -0
  56. package/src/file-reads.ts +53 -0
  57. package/src/fs-backend.ts +206 -0
  58. package/src/fs-remote-backend.ts +252 -0
  59. package/src/git-object-codec.ts +87 -0
  60. package/src/git-sync.ts +539 -0
  61. package/src/in-memory-object-store.ts +60 -0
  62. package/src/index.ts +110 -0
  63. package/src/migrate-workflow.ts +30 -0
  64. package/src/native-git.ts +177 -0
  65. package/src/native-project-repo.ts +515 -0
  66. package/src/network-sync.ts +239 -0
  67. package/src/network.ts +269 -0
  68. package/src/object-remote-backend.ts +366 -0
  69. package/src/object-store.ts +41 -0
  70. package/src/origin-draft.ts +1033 -0
  71. package/src/origin-objects.ts +906 -0
  72. package/src/personal-files.ts +57 -0
  73. package/src/project-manager.ts +743 -0
  74. package/src/project-repo.ts +800 -0
  75. package/src/ref-moved-error.ts +18 -0
  76. package/src/ref-names.ts +47 -0
  77. package/src/types.ts +289 -0
  78. package/src/workspace-mirror.ts +400 -0
  79. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,4746 @@
1
+ var __esm = (fn, res, err) => () => {
2
+ if (fn)
3
+ try {
4
+ res = fn(fn = 0);
5
+ } catch (e) {
6
+ err = [e];
7
+ }
8
+ if (err)
9
+ throw err[0];
10
+ return res;
11
+ };
12
+
13
+ // src/native-git.ts
14
+ import { execFile } from "node:child_process";
15
+ import fs from "node:fs/promises";
16
+ import path from "node:path";
17
+ import { promisify } from "node:util";
18
+ async function nativeGit(cwd, args, auth) {
19
+ const networkOperation = ["fetch", "push", "clone", "ls-remote"].includes(args[0] ?? "");
20
+ return (await execute("git", ["-C", cwd, ...args], {
21
+ env: {
22
+ ...process.env,
23
+ GIT_OPTIONAL_LOCKS: "0",
24
+ GIT_TERMINAL_PROMPT: "0",
25
+ ...auth ? {
26
+ GIT_CONFIG_COUNT: "1",
27
+ GIT_CONFIG_KEY_0: `http.${auth.url}.extraHeader`,
28
+ GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}`
29
+ } : {}
30
+ },
31
+ timeout: networkOperation ? 15 * 60000 : 60000,
32
+ maxBuffer: 32 * 1024 * 1024
33
+ })).stdout;
34
+ }
35
+ async function nativeGitBytes(cwd, args, input) {
36
+ const command = execute("git", ["-C", cwd, ...args], {
37
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
38
+ timeout: 60000,
39
+ maxBuffer: 64 * 1024 * 1024,
40
+ encoding: "buffer"
41
+ });
42
+ if (input)
43
+ command.child.stdin?.end(input);
44
+ return new Uint8Array((await command).stdout);
45
+ }
46
+ async function hasLocalGit({
47
+ path: root
48
+ }) {
49
+ return fs.lstat(path.join(root, ".git")).then(() => true, (error) => {
50
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
51
+ return false;
52
+ throw error;
53
+ });
54
+ }
55
+ async function discoverLocalFolder(input) {
56
+ const requested = await fs.realpath(input.path);
57
+ if (!(await fs.stat(requested)).isDirectory())
58
+ throw new Error("Choose a folder to open as a project");
59
+ let ancestor = requested;
60
+ while (!await hasLocalGit({ path: ancestor })) {
61
+ if (await fs.stat(path.join(ancestor, "HEAD")).then(() => true, () => false)) {
62
+ if ((await nativeGit(ancestor, [
63
+ "rev-parse",
64
+ "--is-bare-repository"
65
+ ]).catch(() => "")).trim() === "true")
66
+ throw new Error("Choose a working folder, not a bare Git repository");
67
+ }
68
+ const parent = path.dirname(ancestor);
69
+ if (parent === ancestor)
70
+ return {
71
+ path: requested,
72
+ commonDirectory: null,
73
+ branch: null,
74
+ defaultBranch: null,
75
+ remoteUrl: null,
76
+ remoteBranch: null
77
+ };
78
+ ancestor = parent;
79
+ }
80
+ const root = await fs.realpath((await nativeGit(requested, ["rev-parse", "--show-toplevel"])).trim());
81
+ const common = (await nativeGit(root, ["rev-parse", "--git-common-dir"])).trim();
82
+ const branch = (await nativeGit(root, ["branch", "--show-current"])).trim() || null;
83
+ const remoteName = branch ? (await nativeGit(root, [
84
+ "config",
85
+ "--get",
86
+ `branch.${branch}.remote`
87
+ ]).catch(() => "")).trim() || "origin" : "origin";
88
+ const remoteUrl = remoteName === "." ? null : (await nativeGit(root, ["remote", "get-url", remoteName]).catch(() => "")).trim() || null;
89
+ const remoteBranch = branch ? (await nativeGit(root, [
90
+ "config",
91
+ "--get",
92
+ `branch.${branch}.merge`
93
+ ]).catch(() => "")).trim().replace(/^refs\/heads\//, "") || null : null;
94
+ const defaultBranch = (await nativeGit(root, [
95
+ "symbolic-ref",
96
+ "--short",
97
+ `refs/remotes/${remoteName}/HEAD`
98
+ ]).catch(() => "")).trim().replace(`${remoteName}/`, "") || null;
99
+ return {
100
+ path: root,
101
+ commonDirectory: await fs.realpath(path.resolve(root, common)),
102
+ branch,
103
+ defaultBranch,
104
+ remoteUrl,
105
+ remoteBranch
106
+ };
107
+ }
108
+ var execute;
109
+ var init_native_git = __esm(() => {
110
+ execute = promisify(execFile);
111
+ });
112
+
113
+ // src/file-reads.ts
114
+ async function readFileSnapshot({
115
+ paths,
116
+ read,
117
+ options = {}
118
+ }) {
119
+ const selected = paths.filter((path) => options.filter?.(path) ?? true);
120
+ const files = {};
121
+ const maxFileBytes = options.maxFileBytes ?? MAX_SNAPSHOT_FILE_BYTES;
122
+ const maxTotalBytes = options.maxTotalBytes ?? MAX_SNAPSHOT_BYTES;
123
+ for (const limit of [maxFileBytes, maxTotalBytes]) {
124
+ if (!Number.isSafeInteger(limit) || limit < 1)
125
+ throw new Error("Snapshot byte limits must be positive integers");
126
+ }
127
+ let total = 0;
128
+ for (let offset = 0;offset < selected.length; offset += 8) {
129
+ const batch = await Promise.allSettled(selected.slice(offset, offset + 8).map(async (path) => {
130
+ const content = await read(path, maxFileBytes);
131
+ if (content === null)
132
+ return;
133
+ const bytes = Buffer.byteLength(content);
134
+ if (bytes > maxFileBytes)
135
+ throw new Error(`Project file '${path}' exceeds the ${maxFileBytes}-byte snapshot limit`);
136
+ total += bytes;
137
+ if (total > maxTotalBytes)
138
+ throw new Error(`Project snapshot exceeds the ${maxTotalBytes}-byte limit; narrow the source selection or exclude generated files`);
139
+ files[path] = content;
140
+ }));
141
+ for (const result of batch)
142
+ if (result.status === "rejected")
143
+ throw result.reason;
144
+ }
145
+ return files;
146
+ }
147
+ var MAX_SNAPSHOT_FILE_BYTES, MAX_SNAPSHOT_BYTES;
148
+ var init_file_reads = __esm(() => {
149
+ MAX_SNAPSHOT_FILE_BYTES = 8 * 1024 * 1024;
150
+ MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
151
+ });
152
+
153
+ // src/personal-files.ts
154
+ import fs2 from "node:fs/promises";
155
+ import path2 from "node:path";
156
+ import {
157
+ isProjectPathWithin,
158
+ PROJECT_PERSONAL_DIR
159
+ } from "@catamorphic/workflow/project-layout";
160
+ function isPersonalFile(filePath) {
161
+ const normalized = path2.posix.normalize(filePath.replaceAll("\\", "/"));
162
+ return isProjectPathWithin(normalized, PROJECT_PERSONAL_DIR);
163
+ }
164
+ async function ensurePersonalFilesExcluded({
165
+ repoPath
166
+ }) {
167
+ const dotGit = path2.join(repoPath, ".git");
168
+ const entry = await fs2.stat(dotGit).catch((error) => {
169
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
170
+ return null;
171
+ throw error;
172
+ });
173
+ if (!entry)
174
+ return;
175
+ const gitDir = entry.isDirectory() ? dotGit : path2.resolve(repoPath, (await fs2.readFile(dotGit, "utf8")).trim().replace(/^gitdir:\s*/, ""));
176
+ const common = await fs2.readFile(path2.join(gitDir, "commondir"), "utf8").catch((error) => {
177
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
178
+ return "";
179
+ throw error;
180
+ });
181
+ const commonDir = common.trim() ? path2.resolve(gitDir, common.trim()) : gitDir;
182
+ const excludePath = path2.join(commonDir, "info", "exclude");
183
+ const current = await fs2.readFile(excludePath, "utf8").catch((error) => {
184
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
185
+ return "";
186
+ throw error;
187
+ });
188
+ const rule = `/${PROJECT_PERSONAL_DIR}/`;
189
+ if (current.split(/\r?\n/).includes(rule))
190
+ return;
191
+ await fs2.mkdir(path2.dirname(excludePath), { recursive: true });
192
+ await fs2.appendFile(excludePath, `${current && !current.endsWith(`
193
+ `) ? `
194
+ ` : ""}${rule}
195
+ `);
196
+ }
197
+ var init_personal_files = () => {};
198
+
199
+ // src/ref-names.ts
200
+ function isValidRefName(ref) {
201
+ if (!ref || ref === "@" || ref.endsWith("/") || ref.endsWith("."))
202
+ return false;
203
+ if (ref.includes("..") || ref.includes("//") || ref.includes("@{"))
204
+ return false;
205
+ for (const char of ref) {
206
+ const code = char.charCodeAt(0);
207
+ if (code <= 32 || code === 127 || "~^:?*[\\".includes(char))
208
+ return false;
209
+ }
210
+ return ref.split("/").every((segment) => segment.length > 0 && !segment.startsWith(".") && !segment.endsWith(".lock"));
211
+ }
212
+ function assertValidRefName(ref) {
213
+ if (!isValidRefName(ref))
214
+ throw new InvalidRefNameError(ref);
215
+ }
216
+ function assertResolvableRef(ref) {
217
+ if (ref === "HEAD" || /^[0-9a-f]{40}$/.test(ref))
218
+ return;
219
+ assertValidRefName(ref);
220
+ }
221
+ var InvalidRefNameError;
222
+ var init_ref_names = __esm(() => {
223
+ InvalidRefNameError = class InvalidRefNameError extends Error {
224
+ constructor(ref) {
225
+ super(`Invalid ref name: ${JSON.stringify(ref)}`);
226
+ this.name = "InvalidRefNameError";
227
+ }
228
+ };
229
+ });
230
+
231
+ // src/project-repo.ts
232
+ import nodeFs from "node:fs";
233
+ import fs3 from "node:fs/promises";
234
+ import path3 from "node:path";
235
+ import {
236
+ PROJECT_WORKSPACE_ROOT,
237
+ publishedRef
238
+ } from "@catamorphic/workflow/project-layout";
239
+ import ignore from "ignore";
240
+ import git from "isomorphic-git";
241
+ function assertSafePath(filePath) {
242
+ const normalized = path3.normalize(filePath);
243
+ if (path3.isAbsolute(normalized)) {
244
+ throw new Error("Absolute paths not allowed");
245
+ }
246
+ if (normalized.startsWith("..")) {
247
+ throw new Error("Path traversal detected");
248
+ }
249
+ if (isPersonalFile(normalized)) {
250
+ throw new Error("Personal files are local-only and cannot be accessed through project APIs");
251
+ }
252
+ if (normalized.split(/[\\/]/).some((segment) => segment.toLowerCase() === ".git")) {
253
+ throw new Error("Cannot access .git directory");
254
+ }
255
+ }
256
+ async function assertNoSymlinks(root, filePath) {
257
+ let current = root;
258
+ for (const segment of path3.normalize(filePath).split(path3.sep)) {
259
+ if (!segment || segment === ".")
260
+ continue;
261
+ current = path3.join(current, segment);
262
+ const stat = await fs3.lstat(current).catch(() => {
263
+ return;
264
+ });
265
+ if (!stat)
266
+ return;
267
+ if (stat.isSymbolicLink())
268
+ throw new Error("Symbolic links cannot be read or written here");
269
+ }
270
+ }
271
+ async function walkDirectory(dir, base, options) {
272
+ if (options?.excludeNestedRepositories && dir !== base && await fs3.stat(path3.join(dir, ".git")).then(() => true, () => false))
273
+ return [];
274
+ const rules = options ? [...options.rules] : [];
275
+ if (options) {
276
+ const content = await fs3.readFile(path3.join(dir, ".gitignore"), "utf8").catch(() => "");
277
+ if (content)
278
+ rules.push({ base: dir, matcher: ignore().add(content) });
279
+ }
280
+ const entries = await fs3.readdir(dir, { withFileTypes: true });
281
+ const results = [];
282
+ for (const entry of entries) {
283
+ if (IGNORED_DIRS.has(entry.name))
284
+ continue;
285
+ if (!options?.includeHidden && entry.name.startsWith(".") && !ALLOWED_DOT_DIRS.has(entry.name) && !ALLOWED_DOT_FILES.has(entry.name))
286
+ continue;
287
+ const fullPath = path3.join(dir, entry.name);
288
+ const relativePath = path3.relative(base, fullPath);
289
+ if (isPersonalFile(relativePath))
290
+ continue;
291
+ if (options) {
292
+ let ignored = false;
293
+ for (const rule of rules) {
294
+ const result = rule.matcher.test(path3.relative(rule.base, fullPath) + (entry.isDirectory() ? "/" : ""));
295
+ if (result.ignored)
296
+ ignored = true;
297
+ if (result.unignored)
298
+ ignored = false;
299
+ }
300
+ if (ignored && !options.tracked.has(relativePath) && !options.trackedDirectories.has(relativePath))
301
+ continue;
302
+ }
303
+ if (entry.isDirectory()) {
304
+ const nested = await walkDirectory(fullPath, base, options ? { ...options, rules } : undefined);
305
+ results.push(...nested);
306
+ } else {
307
+ results.push(relativePath);
308
+ }
309
+ }
310
+ return results;
311
+ }
312
+
313
+ class ProjectRepoImpl {
314
+ projectId;
315
+ repoPath;
316
+ releaseFn;
317
+ followsSymlinks = false;
318
+ constructor(projectId, repoPath, releaseFn) {
319
+ this.projectId = projectId;
320
+ this.repoPath = repoPath;
321
+ this.releaseFn = releaseFn;
322
+ }
323
+ async readFile(filePath) {
324
+ assertSafePath(filePath);
325
+ if (!this.followsSymlinks)
326
+ await assertNoSymlinks(this.repoPath, filePath);
327
+ return fs3.readFile(path3.join(this.repoPath, filePath), "utf-8");
328
+ }
329
+ async writeFile(filePath, content) {
330
+ assertSafePath(filePath);
331
+ if (!this.followsSymlinks)
332
+ await assertNoSymlinks(this.repoPath, filePath);
333
+ const fullPath = path3.join(this.repoPath, filePath);
334
+ await fs3.mkdir(path3.dirname(fullPath), { recursive: true });
335
+ await fs3.writeFile(fullPath, content);
336
+ }
337
+ async deleteFile(filePath) {
338
+ assertSafePath(filePath);
339
+ if (!this.followsSymlinks)
340
+ await assertNoSymlinks(this.repoPath, filePath);
341
+ await fs3.unlink(path3.join(this.repoPath, filePath));
342
+ }
343
+ async listFiles(opts) {
344
+ if (!opts?.prefix)
345
+ return walkDirectory(this.repoPath, this.repoPath);
346
+ assertSafePath(opts.prefix);
347
+ try {
348
+ return await walkDirectory(path3.join(this.repoPath, opts.prefix), this.repoPath);
349
+ } catch (error) {
350
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
351
+ return [];
352
+ throw error;
353
+ }
354
+ }
355
+ async readAllFiles(options = {}) {
356
+ const tracked = new Set(await git.listFiles({ fs: nodeFs, dir: this.repoPath }));
357
+ const trackedDirectories = new Set;
358
+ for (const file of tracked) {
359
+ let directory = path3.dirname(file);
360
+ while (directory !== ".") {
361
+ trackedDirectories.add(directory);
362
+ directory = path3.dirname(directory);
363
+ }
364
+ }
365
+ const excludes = await fs3.readFile(path3.join(this.repoPath, ".git/info/exclude"), "utf8").catch(() => "");
366
+ const paths = await walkDirectory(this.repoPath, this.repoPath, {
367
+ excludeNestedRepositories: options.excludeNestedRepositories,
368
+ tracked,
369
+ trackedDirectories,
370
+ rules: excludes ? [{ base: this.repoPath, matcher: ignore().add(excludes) }] : []
371
+ });
372
+ return readFileSnapshot({
373
+ paths,
374
+ options,
375
+ read: async (file, maxBytes) => new TextDecoder().decode(await this.readSnapshotBytes(file, maxBytes))
376
+ });
377
+ }
378
+ async readSnapshotBytes(file, maxBytes) {
379
+ assertSafePath(file);
380
+ const handle = await fs3.open(path3.join(this.repoPath, file), "r");
381
+ try {
382
+ const size = (await handle.stat()).size;
383
+ if (size > maxBytes)
384
+ throw new Error(`Project file '${file}' exceeds the ${maxBytes}-byte snapshot limit`);
385
+ const buffer = Buffer.alloc(size + 1);
386
+ let bytesRead = 0;
387
+ while (bytesRead < buffer.length) {
388
+ const chunk = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead);
389
+ if (chunk.bytesRead === 0)
390
+ break;
391
+ bytesRead += chunk.bytesRead;
392
+ }
393
+ if (bytesRead > size)
394
+ throw new Error(`Project file '${file}' changed during snapshot; retry the read`);
395
+ return buffer.subarray(0, bytesRead);
396
+ } finally {
397
+ await handle.close();
398
+ }
399
+ }
400
+ async readAllFilesAtRef(ref, options) {
401
+ return this.walkFilesAtRef(ref, undefined, options);
402
+ }
403
+ async readFilesAtRef(ref, opts) {
404
+ return this.walkFilesAtRef(ref, opts.prefix);
405
+ }
406
+ async readBlobAtRef(ref, filePath, options) {
407
+ assertSafePath(filePath);
408
+ assertResolvableRef(ref);
409
+ let blob;
410
+ try {
411
+ const oid = await git.resolveRef({ fs: nodeFs, dir: this.repoPath, ref });
412
+ blob = (await git.readBlob({
413
+ fs: nodeFs,
414
+ dir: this.repoPath,
415
+ oid,
416
+ filepath: filePath
417
+ })).blob;
418
+ } catch {
419
+ return null;
420
+ }
421
+ if (options?.maxBytes !== undefined && blob.byteLength > options.maxBytes)
422
+ throw new Error(`Project file '${filePath}' exceeds the ${options.maxBytes}-byte snapshot limit`);
423
+ return blob;
424
+ }
425
+ async readFileBytes(filePath) {
426
+ assertSafePath(filePath);
427
+ if (!this.followsSymlinks)
428
+ await assertNoSymlinks(this.repoPath, filePath);
429
+ try {
430
+ return new Uint8Array(await fs3.readFile(path3.join(this.repoPath, filePath)));
431
+ } catch {
432
+ return null;
433
+ }
434
+ }
435
+ async listFilesAtRef(ref, opts) {
436
+ return (await this.listBlobsAtRef(ref, opts)).map((entry) => entry.path);
437
+ }
438
+ async listBlobsAtRef(ref, opts) {
439
+ assertResolvableRef(ref);
440
+ const oid = await git.resolveRef({ fs: nodeFs, dir: this.repoPath, ref });
441
+ const prefix = opts?.prefix;
442
+ const blobs = [];
443
+ await git.walk({
444
+ fs: nodeFs,
445
+ dir: this.repoPath,
446
+ trees: [git.TREE({ ref: oid })],
447
+ map: async (filepath, [entry]) => {
448
+ if (filepath === "." || !entry)
449
+ return;
450
+ if (isPersonalFile(filepath))
451
+ return null;
452
+ if (prefix !== undefined) {
453
+ const inside = filepath.startsWith(prefix);
454
+ const onTheWay = prefix.startsWith(`${filepath}/`);
455
+ if (!inside && !onTheWay)
456
+ return null;
457
+ if (!inside)
458
+ return;
459
+ }
460
+ if (await entry.type() === "blob") {
461
+ blobs.push({ path: filepath, oid: await entry.oid() ?? "" });
462
+ }
463
+ }
464
+ });
465
+ return blobs.sort((a, b) => a.path.localeCompare(b.path));
466
+ }
467
+ async walkFilesAtRef(ref, prefix, options) {
468
+ const blobs = await this.listBlobsAtRef(ref, prefix ? { prefix } : undefined);
469
+ return readFileSnapshot({
470
+ paths: blobs.map((blob) => blob.path),
471
+ options,
472
+ read: async (file, maxBytes) => {
473
+ const content = await this.readBlobAtRef(ref, file, { maxBytes });
474
+ if (!content)
475
+ throw new Error(`Project file '${file}' disappeared from '${ref}'`);
476
+ return new TextDecoder().decode(content);
477
+ }
478
+ });
479
+ }
480
+ async commit(message, author, opts) {
481
+ for (const file of opts?.paths ?? [])
482
+ assertSafePath(file);
483
+ const cache = {};
484
+ const indexedFiles = await git.listFiles({
485
+ fs: nodeFs,
486
+ dir: this.repoPath,
487
+ cache
488
+ });
489
+ if (indexedFiles.some(isPersonalFile)) {
490
+ throw new Error("Personal files are tracked. Remove them from the git index before checkpointing or sharing this project.");
491
+ }
492
+ const only = opts?.paths ? new Set(opts.paths) : null;
493
+ const files = (await this.listFiles()).filter((file) => !only || only.has(file));
494
+ for (let offset = 0;offset < files.length; offset += STAGING_BATCH_SIZE) {
495
+ await git.add({
496
+ fs: nodeFs,
497
+ dir: this.repoPath,
498
+ filepath: files.slice(offset, offset + STAGING_BATCH_SIZE),
499
+ parallel: false,
500
+ cache
501
+ });
502
+ }
503
+ const status = await git.statusMatrix({
504
+ fs: nodeFs,
505
+ dir: this.repoPath,
506
+ cache
507
+ });
508
+ for (const [filepath, head, workdir, stage] of status) {
509
+ if (only && !only.has(filepath))
510
+ continue;
511
+ if (head === 1 && workdir === 0 && stage === 1) {
512
+ await git.remove({ fs: nodeFs, dir: this.repoPath, filepath, cache });
513
+ }
514
+ }
515
+ return git.commit({
516
+ fs: nodeFs,
517
+ dir: this.repoPath,
518
+ message,
519
+ author,
520
+ cache
521
+ });
522
+ }
523
+ async log(options) {
524
+ if (options?.ref)
525
+ assertResolvableRef(options.ref);
526
+ try {
527
+ const commits = await git.log({
528
+ fs: nodeFs,
529
+ dir: this.repoPath,
530
+ depth: options?.maxCount,
531
+ ref: options?.ref
532
+ });
533
+ return commits.map((c) => ({
534
+ sha: c.oid,
535
+ message: c.commit.message,
536
+ author: {
537
+ name: c.commit.author.name,
538
+ email: c.commit.author.email
539
+ },
540
+ timestamp: c.commit.author.timestamp
541
+ }));
542
+ } catch {
543
+ return [];
544
+ }
545
+ }
546
+ async resolveRef(ref = "HEAD") {
547
+ assertResolvableRef(ref);
548
+ return git.resolveRef({
549
+ fs: nodeFs,
550
+ dir: this.repoPath,
551
+ ref
552
+ });
553
+ }
554
+ async checkout(ref) {
555
+ await git.checkout({
556
+ fs: nodeFs,
557
+ dir: this.repoPath,
558
+ ref: ref ?? "main",
559
+ force: true
560
+ });
561
+ }
562
+ async status() {
563
+ const branch = await this.currentBranch();
564
+ const matrix = await git.statusMatrix({
565
+ fs: nodeFs,
566
+ dir: this.repoPath
567
+ });
568
+ const modifiedFiles = matrix.filter(([, head, workdir]) => head !== workdir).map(([filepath]) => filepath);
569
+ const baseCommit = await this.resolveRef("HEAD").catch(() => null);
570
+ const remoteRef = publishedRef();
571
+ const remoteHead = await git.resolveRef({ fs: nodeFs, dir: this.repoPath, ref: remoteRef }).catch(() => null);
572
+ const { ahead, behind } = await computeAheadBehind({
573
+ dir: this.repoPath,
574
+ local: baseCommit,
575
+ remote: remoteHead
576
+ });
577
+ return {
578
+ branch,
579
+ dirty: modifiedFiles.length > 0,
580
+ modifiedFiles,
581
+ ahead,
582
+ behind,
583
+ baseCommit,
584
+ remoteHead
585
+ };
586
+ }
587
+ async currentBranch() {
588
+ const name = await git.currentBranch({
589
+ fs: nodeFs,
590
+ dir: this.repoPath,
591
+ fullname: false
592
+ });
593
+ return name ?? "main";
594
+ }
595
+ async listBranches() {
596
+ const current = await this.currentBranch();
597
+ const names = await git.listBranches({
598
+ fs: nodeFs,
599
+ dir: this.repoPath
600
+ });
601
+ const entries = await Promise.all(names.map(async (name) => {
602
+ const sha = await git.resolveRef({
603
+ fs: nodeFs,
604
+ dir: this.repoPath,
605
+ ref: `refs/heads/${name}`
606
+ }).catch(() => "");
607
+ const createdAt = await tipTimestamp(this.repoPath, sha);
608
+ return {
609
+ name,
610
+ commit: sha,
611
+ isCurrent: name === current,
612
+ createdAt
613
+ };
614
+ }));
615
+ return entries.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
616
+ }
617
+ async createBranch(name, fromRef) {
618
+ await git.branch({
619
+ fs: nodeFs,
620
+ dir: this.repoPath,
621
+ ref: name,
622
+ object: fromRef,
623
+ checkout: true
624
+ });
625
+ }
626
+ async deleteBranch(name) {
627
+ await git.deleteBranch({
628
+ fs: nodeFs,
629
+ dir: this.repoPath,
630
+ ref: name
631
+ });
632
+ }
633
+ async hasBranch(name) {
634
+ try {
635
+ await git.resolveRef({
636
+ fs: nodeFs,
637
+ dir: this.repoPath,
638
+ ref: `refs/heads/${name}`
639
+ });
640
+ return true;
641
+ } catch {
642
+ return false;
643
+ }
644
+ }
645
+ async workdirDiff() {
646
+ const matrix = await git.statusMatrix({
647
+ fs: nodeFs,
648
+ dir: this.repoPath
649
+ });
650
+ const decoder = new TextDecoder("utf-8");
651
+ const entries = [];
652
+ for (const [filepath, head, workdir] of matrix) {
653
+ if (head === workdir)
654
+ continue;
655
+ const headContent = head === 1 ? await readBlobAtHead(this.repoPath, filepath) : null;
656
+ const workdirContent = workdir === 0 ? null : await readWorkdirFile(this.repoPath, filepath, decoder);
657
+ if (head === 0 && workdir !== 0) {
658
+ entries.push({
659
+ path: filepath,
660
+ kind: "added",
661
+ before: null,
662
+ after: workdirContent
663
+ });
664
+ } else if (head !== 0 && workdir === 0) {
665
+ entries.push({
666
+ path: filepath,
667
+ kind: "deleted",
668
+ before: headContent,
669
+ after: null
670
+ });
671
+ } else {
672
+ entries.push({
673
+ path: filepath,
674
+ kind: "modified",
675
+ before: headContent,
676
+ after: workdirContent
677
+ });
678
+ }
679
+ }
680
+ return entries;
681
+ }
682
+ async diff(opts) {
683
+ const baseFiles = new Map((await this.listBlobsAtRef(opts.base)).map((entry) => [
684
+ entry.path,
685
+ entry.oid
686
+ ]));
687
+ const headFiles = new Map((await this.listBlobsAtRef(opts.head)).map((entry) => [
688
+ entry.path,
689
+ entry.oid
690
+ ]));
691
+ const changed = [
692
+ ...new Set([...baseFiles.keys(), ...headFiles.keys()])
693
+ ].filter((file) => baseFiles.get(file) !== headFiles.get(file));
694
+ const snapshots = await readFileSnapshot({
695
+ paths: changed.flatMap((file) => [`before/${file}`, `after/${file}`]),
696
+ read: async (key, maxBytes) => {
697
+ const before = key.startsWith("before/");
698
+ const file = key.slice(before ? 7 : 6);
699
+ if (!(before ? baseFiles : headFiles).has(file))
700
+ return "";
701
+ const blob = await this.readBlobAtRef(before ? opts.base : opts.head, file, { maxBytes });
702
+ return blob ? new TextDecoder().decode(blob) : "";
703
+ }
704
+ });
705
+ const entries = [];
706
+ for (const filepath of changed) {
707
+ const before = baseFiles.has(filepath) ? snapshots[`before/${filepath}`] ?? "" : null;
708
+ const after = headFiles.has(filepath) ? snapshots[`after/${filepath}`] ?? "" : null;
709
+ if (before === after)
710
+ continue;
711
+ if (before == null && after != null) {
712
+ entries.push({
713
+ path: filepath,
714
+ kind: "added",
715
+ before: null,
716
+ after
717
+ });
718
+ } else if (before != null && after == null) {
719
+ entries.push({
720
+ path: filepath,
721
+ kind: "deleted",
722
+ before,
723
+ after: null
724
+ });
725
+ } else {
726
+ entries.push({
727
+ path: filepath,
728
+ kind: "modified",
729
+ before,
730
+ after
731
+ });
732
+ }
733
+ }
734
+ return entries;
735
+ }
736
+ async moveBranch(name, sha) {
737
+ await git.writeRef({
738
+ fs: nodeFs,
739
+ dir: this.repoPath,
740
+ ref: `refs/heads/${name}`,
741
+ value: sha,
742
+ force: true
743
+ });
744
+ }
745
+ async resetWorkingTree() {
746
+ const matrix = await git.statusMatrix({
747
+ fs: nodeFs,
748
+ dir: this.repoPath
749
+ });
750
+ for (const [filepath, head, workdir] of matrix) {
751
+ if (head === workdir)
752
+ continue;
753
+ if (head === 0) {
754
+ await fs3.unlink(path3.join(this.repoPath, filepath)).catch(() => {});
755
+ } else {
756
+ await git.checkout({
757
+ fs: nodeFs,
758
+ dir: this.repoPath,
759
+ filepaths: [filepath],
760
+ force: true
761
+ });
762
+ }
763
+ }
764
+ }
765
+ async dispose() {
766
+ await this.releaseFn();
767
+ }
768
+ }
769
+ async function readBlobAtHead(dir, filepath) {
770
+ try {
771
+ const headOid = await git.resolveRef({ fs: nodeFs, dir, ref: "HEAD" });
772
+ const { blob } = await git.readBlob({
773
+ fs: nodeFs,
774
+ dir,
775
+ oid: headOid,
776
+ filepath
777
+ });
778
+ return new TextDecoder("utf-8").decode(blob);
779
+ } catch {
780
+ return null;
781
+ }
782
+ }
783
+ async function readWorkdirFile(dir, filepath, decoder) {
784
+ try {
785
+ const buf = await fs3.readFile(path3.join(dir, filepath));
786
+ return decoder.decode(buf);
787
+ } catch {
788
+ return null;
789
+ }
790
+ }
791
+ async function tipTimestamp(dir, sha) {
792
+ if (!sha)
793
+ return null;
794
+ try {
795
+ const [commit] = await git.log({
796
+ fs: nodeFs,
797
+ dir,
798
+ ref: sha,
799
+ depth: 1
800
+ });
801
+ return commit?.commit.author.timestamp ?? null;
802
+ } catch {
803
+ return null;
804
+ }
805
+ }
806
+ async function computeAheadBehind(opts) {
807
+ if (!opts.local || !opts.remote)
808
+ return { ahead: 0, behind: 0 };
809
+ if (opts.local === opts.remote)
810
+ return { ahead: 0, behind: 0 };
811
+ const localAncestry = await commitSet(opts.dir, opts.local);
812
+ const remoteAncestry = await commitSet(opts.dir, opts.remote);
813
+ let ahead = 0;
814
+ for (const sha of localAncestry) {
815
+ if (!remoteAncestry.has(sha))
816
+ ahead += 1;
817
+ }
818
+ let behind = 0;
819
+ for (const sha of remoteAncestry) {
820
+ if (!localAncestry.has(sha))
821
+ behind += 1;
822
+ }
823
+ return { ahead, behind };
824
+ }
825
+ async function commitSet(dir, ref) {
826
+ try {
827
+ const commits = await git.log({ fs: nodeFs, dir, ref, depth: 500 });
828
+ return new Set(commits.map((c) => c.oid));
829
+ } catch {
830
+ return new Set;
831
+ }
832
+ }
833
+ var IGNORED_DIRS, STAGING_BATCH_SIZE = 128, ALLOWED_DOT_DIRS, ALLOWED_DOT_FILES;
834
+ var init_project_repo = __esm(() => {
835
+ init_file_reads();
836
+ init_personal_files();
837
+ init_ref_names();
838
+ IGNORED_DIRS = new Set(["node_modules", ".git", "dist", ".turbo"]);
839
+ ALLOWED_DOT_DIRS = new Set([".agents", PROJECT_WORKSPACE_ROOT]);
840
+ ALLOWED_DOT_FILES = new Set([".gitignore"]);
841
+ });
842
+
843
+ // src/native-project-repo.ts
844
+ import fs4 from "node:fs/promises";
845
+ import path4 from "node:path";
846
+ import {
847
+ PROJECT_APP_DATA_DIR,
848
+ PROJECT_PERSONAL_DIR as PROJECT_PERSONAL_DIR2,
849
+ publishedRef as publishedRef2
850
+ } from "@catamorphic/workflow/project-layout";
851
+ var NativeProjectRepo;
852
+ var init_native_project_repo = __esm(() => {
853
+ init_file_reads();
854
+ init_native_git();
855
+ init_personal_files();
856
+ init_project_repo();
857
+ NativeProjectRepo = class NativeProjectRepo extends ProjectRepoImpl {
858
+ followsSymlinks = true;
859
+ async readFileBytes(filePath) {
860
+ assertSafePath(filePath);
861
+ const target = path4.join(this.repoPath, filePath);
862
+ const stat = await fs4.lstat(target).catch((error) => {
863
+ if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
864
+ return null;
865
+ throw error;
866
+ });
867
+ if (!stat)
868
+ return null;
869
+ if (stat.isSymbolicLink())
870
+ return new TextEncoder().encode(await fs4.readlink(target));
871
+ if (!stat.isFile())
872
+ return null;
873
+ if (stat.size > 64 * 1024 * 1024)
874
+ throw new Error("This file exceeds the 64 MB document limit. Open it from its folder.");
875
+ return this.readSnapshotBytes(filePath, 64 * 1024 * 1024);
876
+ }
877
+ async readAllFiles(options = {}) {
878
+ return readFileSnapshot({
879
+ paths: await this.listFiles(),
880
+ options: { maxFileBytes: 2 * 1024 * 1024, ...options },
881
+ read: async (file, maxBytes) => {
882
+ const stat = await fs4.lstat(path4.join(this.repoPath, file));
883
+ if (!stat.isFile() || stat.size > maxBytes)
884
+ return null;
885
+ const bytes = await this.readSnapshotBytes(file, maxBytes);
886
+ if (bytes.includes(0))
887
+ return null;
888
+ try {
889
+ return new TextDecoder("utf8", { fatal: true }).decode(bytes);
890
+ } catch {
891
+ return null;
892
+ }
893
+ }
894
+ });
895
+ }
896
+ async listFiles(opts) {
897
+ if (!await hasLocalGit({ path: this.repoPath })) {
898
+ if (opts?.prefix)
899
+ assertSafePath(opts.prefix);
900
+ const files = await walkDirectory(this.repoPath, this.repoPath, {
901
+ includeHidden: true,
902
+ excludeNestedRepositories: true,
903
+ tracked: new Set,
904
+ trackedDirectories: new Set,
905
+ rules: []
906
+ });
907
+ return files.filter((file) => !opts?.prefix || file.startsWith(opts.prefix)).sort();
908
+ }
909
+ const pathspec = opts?.prefix ? ["--", opts.prefix] : [];
910
+ const [output, removed] = await Promise.all([
911
+ nativeGit(this.repoPath, [
912
+ "ls-files",
913
+ "--stage",
914
+ "--others",
915
+ "--exclude-standard",
916
+ "-z",
917
+ ...pathspec
918
+ ]),
919
+ nativeGit(this.repoPath, ["ls-files", "--deleted", "-z", ...pathspec])
920
+ ]);
921
+ const deleted = new Set(removed.split("\x00"));
922
+ const files = new Set;
923
+ for (const record of output.split("\x00").filter(Boolean)) {
924
+ const tracked = /^(\d{6}) [a-f0-9]+ [0-3]\t(.*)$/s.exec(record);
925
+ if (tracked?.[1] === "160000")
926
+ continue;
927
+ const file = tracked?.[2] ?? record;
928
+ if (!isPersonalFile(file) && !deleted.has(file))
929
+ files.add(file);
930
+ }
931
+ return [...files].sort();
932
+ }
933
+ async findFilesContaining(input) {
934
+ if (!input.ref && !await hasLocalGit({ path: this.repoPath })) {
935
+ const matches = (file, glob) => path4.matchesGlob(file, glob) || !glob.includes("/") && path4.matchesGlob(path4.basename(file), glob);
936
+ const includes = input.globs.filter((glob) => !glob.startsWith(":!"));
937
+ const excludes = input.globs.filter((glob) => glob.startsWith(":!")).map((glob) => glob.slice(2));
938
+ const files = await this.readAllFiles({
939
+ filter: (file) => includes.some((glob) => matches(file, glob)) && !excludes.some((glob) => matches(file, glob))
940
+ });
941
+ return Object.entries(files).filter(([, content]) => content.includes(input.text)).map(([file]) => file);
942
+ }
943
+ const ref = input.ref ? await this.resolveRef(input.ref) : undefined;
944
+ try {
945
+ const output = await nativeGit(this.repoPath, [
946
+ "grep",
947
+ "-l",
948
+ "-I",
949
+ "-z",
950
+ "-F",
951
+ ...ref ? [] : ["--untracked", "--exclude-standard"],
952
+ "-e",
953
+ input.text,
954
+ ...ref ? [ref] : [],
955
+ "--",
956
+ ...input.globs
957
+ ]);
958
+ return output.split("\x00").filter(Boolean).map((file) => ref ? file.slice(ref.length + 1) : file).filter((file) => !isPersonalFile(file));
959
+ } catch (error) {
960
+ if (error instanceof Error && "code" in error && error.code === 1)
961
+ return [];
962
+ throw error;
963
+ }
964
+ }
965
+ async resolveRef(ref = "HEAD") {
966
+ return (await nativeGit(this.repoPath, [
967
+ "rev-parse",
968
+ "--verify",
969
+ "--end-of-options",
970
+ ref
971
+ ])).trim();
972
+ }
973
+ async currentBranch() {
974
+ if (!await hasLocalGit({ path: this.repoPath }))
975
+ return "main";
976
+ return (await nativeGit(this.repoPath, ["branch", "--show-current"])).trim() || "HEAD";
977
+ }
978
+ async status() {
979
+ if (!await hasLocalGit({ path: this.repoPath })) {
980
+ const modifiedFiles = await this.listFiles();
981
+ return {
982
+ branch: "main",
983
+ dirty: modifiedFiles.length > 0,
984
+ modifiedFiles,
985
+ baseCommit: null,
986
+ remoteHead: null,
987
+ ahead: 0,
988
+ behind: 0
989
+ };
990
+ }
991
+ const output = await nativeGit(this.repoPath, [
992
+ "status",
993
+ "--porcelain=v1",
994
+ "-z",
995
+ "--untracked-files=all"
996
+ ]);
997
+ const records = output.split("\x00");
998
+ const modifiedFiles = [];
999
+ for (let i = 0;i < records.length; i++) {
1000
+ const record = records[i];
1001
+ if (!record)
1002
+ continue;
1003
+ modifiedFiles.push(record.slice(3));
1004
+ if (/[RC]/.test(record.slice(0, 2))) {
1005
+ const previous = records[++i];
1006
+ if (record.slice(0, 2).includes("R") && previous)
1007
+ modifiedFiles.push(previous);
1008
+ }
1009
+ }
1010
+ const baseCommit = await this.resolveRef().catch(() => null);
1011
+ const remoteHead = await this.resolveRef(publishedRef2()).catch(() => null);
1012
+ const counts = baseCommit && remoteHead ? (await nativeGit(this.repoPath, [
1013
+ "rev-list",
1014
+ "--left-right",
1015
+ "--count",
1016
+ `${baseCommit}...${remoteHead}`
1017
+ ])).trim().split(/\s+/).map(Number) : [0, 0];
1018
+ return {
1019
+ branch: await this.currentBranch(),
1020
+ dirty: modifiedFiles.length > 0,
1021
+ modifiedFiles,
1022
+ baseCommit,
1023
+ remoteHead,
1024
+ ahead: counts[0] ?? 0,
1025
+ behind: counts[1] ?? 0
1026
+ };
1027
+ }
1028
+ async commit(message, author, opts) {
1029
+ const paths = opts?.paths;
1030
+ for (const file of paths ?? [])
1031
+ assertSafePath(file);
1032
+ if (paths?.length === 0)
1033
+ return this.resolveRef();
1034
+ if (!await hasLocalGit({ path: this.repoPath }))
1035
+ await nativeGit(this.repoPath, ["init", "--initial-branch=main"]);
1036
+ const allIndexed = (await nativeGit(this.repoPath, ["ls-files", "-z"])).split("\x00");
1037
+ if (allIndexed.some(isPersonalFile))
1038
+ throw new Error("Personal files are tracked. Remove them from the git index before checkpointing or sharing this project.");
1039
+ await ensurePersonalFilesExcluded({ repoPath: this.repoPath });
1040
+ if (!paths)
1041
+ await nativeGit(this.repoPath, ["add", "-A"]);
1042
+ else {
1043
+ const indexed = new Set((await nativeGit(this.repoPath, [
1044
+ "--literal-pathspecs",
1045
+ "ls-files",
1046
+ "-z",
1047
+ "--",
1048
+ ...paths
1049
+ ])).split("\x00"));
1050
+ const untracked = [];
1051
+ for (const file of paths) {
1052
+ if (!indexed.has(file) && await fs4.lstat(path4.join(this.repoPath, file)).then(() => true, () => false))
1053
+ untracked.push(file);
1054
+ }
1055
+ if (untracked.length)
1056
+ await nativeGit(this.repoPath, [
1057
+ "--literal-pathspecs",
1058
+ "add",
1059
+ "--intent-to-add",
1060
+ "--",
1061
+ ...untracked
1062
+ ]);
1063
+ }
1064
+ await nativeGit(this.repoPath, [
1065
+ "--literal-pathspecs",
1066
+ "-c",
1067
+ `user.name=${author.name}`,
1068
+ "-c",
1069
+ `user.email=${author.email}`,
1070
+ "commit",
1071
+ "-m",
1072
+ message,
1073
+ ...opts?.allowEmpty ? ["--allow-empty"] : [],
1074
+ ...paths ? ["--only", "--", ...paths] : []
1075
+ ]);
1076
+ return this.resolveRef();
1077
+ }
1078
+ async workdirDiff() {
1079
+ const status = await this.status();
1080
+ const entries = [];
1081
+ let retainedBytes = 0;
1082
+ for (const file of status.modifiedFiles) {
1083
+ const beforeBytes = status.baseCommit ? await this.readBlobAtRef(status.baseCommit, file) : null;
1084
+ const afterBytes = await this.readFileBytes(file);
1085
+ const decode = (bytes) => {
1086
+ if (!bytes)
1087
+ return null;
1088
+ if (bytes.length > 1024 * 1024 || bytes.includes(0))
1089
+ return "Binary or large file. Open from its folder to inspect.";
1090
+ return new TextDecoder().decode(bytes);
1091
+ };
1092
+ const entry = {
1093
+ path: file,
1094
+ kind: !beforeBytes ? "added" : !afterBytes ? "deleted" : "modified",
1095
+ before: decode(beforeBytes),
1096
+ after: decode(afterBytes)
1097
+ };
1098
+ retainedBytes += Buffer.byteLength(JSON.stringify(entry));
1099
+ if (retainedBytes > 64 * 1024 * 1024)
1100
+ throw new Error("Working diff exceeds the 64 MiB snapshot limit");
1101
+ entries.push(entry);
1102
+ }
1103
+ return entries;
1104
+ }
1105
+ async resetWorkingTree() {
1106
+ await nativeGit(this.repoPath, [
1107
+ "restore",
1108
+ "--source=HEAD",
1109
+ "--staged",
1110
+ "--worktree",
1111
+ "--",
1112
+ ".",
1113
+ `:!${PROJECT_PERSONAL_DIR2}/`
1114
+ ]);
1115
+ await nativeGit(this.repoPath, [
1116
+ "clean",
1117
+ "-fd",
1118
+ "-e",
1119
+ `${PROJECT_APP_DATA_DIR}/`,
1120
+ "-e",
1121
+ `${PROJECT_PERSONAL_DIR2}/`,
1122
+ "--",
1123
+ "."
1124
+ ]);
1125
+ }
1126
+ async checkout(ref) {
1127
+ await nativeGit(this.repoPath, ["checkout", ref ?? "main"]);
1128
+ }
1129
+ async createBranch(name, fromRef) {
1130
+ await nativeGit(this.repoPath, [
1131
+ "checkout",
1132
+ "-b",
1133
+ name,
1134
+ ...fromRef ? [fromRef] : []
1135
+ ]);
1136
+ }
1137
+ async deleteBranch(name) {
1138
+ await nativeGit(this.repoPath, ["branch", "-D", name]);
1139
+ }
1140
+ async hasBranch(name) {
1141
+ return this.resolveRef(`refs/heads/${name}`).then(() => true, () => false);
1142
+ }
1143
+ async moveBranch(name, sha) {
1144
+ await nativeGit(this.repoPath, ["update-ref", `refs/heads/${name}`, sha]);
1145
+ }
1146
+ async listBranches() {
1147
+ if (!await hasLocalGit({ path: this.repoPath }))
1148
+ return [];
1149
+ const current = await this.currentBranch();
1150
+ return (await nativeGit(this.repoPath, [
1151
+ "for-each-ref",
1152
+ "--format=%(refname:short)%09%(objectname)%09%(committerdate:unix)",
1153
+ "refs/heads/"
1154
+ ])).trim().split(`
1155
+ `).filter(Boolean).map((line) => {
1156
+ const [name = "", commit = "", timestamp] = line.split("\t");
1157
+ return {
1158
+ name,
1159
+ commit,
1160
+ isCurrent: current === name,
1161
+ createdAt: Number(timestamp) || null
1162
+ };
1163
+ });
1164
+ }
1165
+ async log(options) {
1166
+ const output = await nativeGit(this.repoPath, [
1167
+ "log",
1168
+ `--max-count=${options?.maxCount ?? 50}`,
1169
+ "--format=%H%x00%an%x00%ae%x00%at%x00%B%x00",
1170
+ options?.ref ?? "HEAD",
1171
+ "--"
1172
+ ]).catch(() => "");
1173
+ const parts = output.split("\x00");
1174
+ const commits = [];
1175
+ for (let i = 0;i + 4 < parts.length; i += 5) {
1176
+ const [sha = "", name = "", email = "", timestamp = "0", message = ""] = parts.slice(i, i + 5);
1177
+ commits.push({
1178
+ sha: sha.trim(),
1179
+ author: { name, email },
1180
+ timestamp: Number(timestamp),
1181
+ message
1182
+ });
1183
+ }
1184
+ return commits;
1185
+ }
1186
+ async listFilesAtRef(ref, opts) {
1187
+ return (await this.listBlobsAtRef(ref, opts)).map((entry) => entry.path);
1188
+ }
1189
+ async listBlobsAtRef(ref, opts) {
1190
+ const sha = await this.resolveRef(ref);
1191
+ const output = await nativeGit(this.repoPath, [
1192
+ "ls-tree",
1193
+ "-r",
1194
+ "-z",
1195
+ sha,
1196
+ ...opts?.prefix ? ["--", opts.prefix] : []
1197
+ ]);
1198
+ return output.split("\x00").filter(Boolean).flatMap((entry) => {
1199
+ const tab = entry.indexOf("\t");
1200
+ const [, type, oid] = entry.slice(0, tab).split(" ");
1201
+ return type === "blob" && oid && !isPersonalFile(entry.slice(tab + 1)) ? [{ path: entry.slice(tab + 1), oid }] : [];
1202
+ });
1203
+ }
1204
+ async readBlobAtRef(ref, filePath, options) {
1205
+ assertSafePath(filePath);
1206
+ const sha = await this.resolveRef(ref);
1207
+ const size = await nativeGit(this.repoPath, [
1208
+ "cat-file",
1209
+ "-s",
1210
+ `${sha}:${filePath}`
1211
+ ]).then((value) => Number(value.trim()), () => null);
1212
+ if (size === null)
1213
+ return null;
1214
+ if (options?.maxBytes !== undefined && size > options.maxBytes)
1215
+ throw new Error(`Project file '${filePath}' exceeds the ${options.maxBytes}-byte snapshot limit`);
1216
+ if (size > 64 * 1024 * 1024)
1217
+ throw new Error("This file exceeds the 64 MB document limit. Open it from its folder.");
1218
+ return nativeGitBytes(this.repoPath, ["show", `${sha}:${filePath}`]);
1219
+ }
1220
+ async readAllFilesAtRef(ref, options) {
1221
+ return this.readTextSnapshotAtRef(ref, { prefix: "" }, options);
1222
+ }
1223
+ async readFilesAtRef(ref, opts) {
1224
+ return this.readTextSnapshotAtRef(ref, opts);
1225
+ }
1226
+ async readTextSnapshotAtRef(ref, opts, options) {
1227
+ const sha = await this.resolveRef(ref);
1228
+ const blobs = await this.listBlobsAtRef(sha, opts);
1229
+ const byPath = new Map(blobs.map((entry) => [entry.path, entry.oid]));
1230
+ return readFileSnapshot({
1231
+ paths: blobs.map((entry) => entry.path),
1232
+ options: { maxFileBytes: 2 * 1024 * 1024, ...options },
1233
+ read: async (file, maxBytes) => {
1234
+ const oid = byPath.get(file);
1235
+ if (!oid)
1236
+ return null;
1237
+ const size = Number((await nativeGit(this.repoPath, ["cat-file", "-s", oid])).trim());
1238
+ if (size > maxBytes)
1239
+ return null;
1240
+ const bytes = await this.readBlobAtRef(sha, file, { maxBytes });
1241
+ if (!bytes || bytes.includes(0))
1242
+ return null;
1243
+ try {
1244
+ return new TextDecoder("utf8", { fatal: true }).decode(bytes);
1245
+ } catch {
1246
+ return null;
1247
+ }
1248
+ }
1249
+ });
1250
+ }
1251
+ };
1252
+ });
1253
+
1254
+ // src/git-object-codec.ts
1255
+ import { createHash } from "node:crypto";
1256
+ function wrapObject(opts) {
1257
+ const header = new TextEncoder().encode(`${opts.type} ${opts.data.byteLength}\x00`);
1258
+ const wrapped = new Uint8Array(header.byteLength + opts.data.byteLength);
1259
+ wrapped.set(header, 0);
1260
+ wrapped.set(opts.data, header.byteLength);
1261
+ const sha = createHash("sha1").update(wrapped).digest("hex");
1262
+ return { wrapped, sha };
1263
+ }
1264
+ function unwrapObject(wrapped) {
1265
+ const nullIdx = wrapped.indexOf(0);
1266
+ if (nullIdx === -1) {
1267
+ throw new Error("Malformed git object: missing header terminator");
1268
+ }
1269
+ const header = new TextDecoder().decode(wrapped.slice(0, nullIdx));
1270
+ const spaceIdx = header.indexOf(" ");
1271
+ const type = header.slice(0, spaceIdx);
1272
+ if (!OBJECT_TYPES.includes(type)) {
1273
+ throw new Error(`Malformed git object: unknown type '${type}'`);
1274
+ }
1275
+ return {
1276
+ type,
1277
+ data: wrapped.slice(nullIdx + 1)
1278
+ };
1279
+ }
1280
+ function parseCommit(data) {
1281
+ const text = new TextDecoder().decode(data);
1282
+ const headerEnd = text.indexOf(`
1283
+
1284
+ `);
1285
+ const header = headerEnd === -1 ? text : text.slice(0, headerEnd);
1286
+ const message = headerEnd === -1 ? "" : text.slice(headerEnd + 2);
1287
+ const parents = [];
1288
+ const treeLine = header.split(`
1289
+ `).find((line) => line.startsWith("tree "));
1290
+ const authorLine = header.split(`
1291
+ `).find((line) => line.startsWith("author "));
1292
+ for (const line of header.split(`
1293
+ `)) {
1294
+ if (line.startsWith("parent "))
1295
+ parents.push(line.slice(7).trim());
1296
+ }
1297
+ const authorMatch = authorLine?.match(/^author (.*) <(.*)> (\d+) [+-]\d{4}$/);
1298
+ return {
1299
+ tree: treeLine?.slice(5).trim() ?? "",
1300
+ parents,
1301
+ author: {
1302
+ name: authorMatch?.[1] ?? "",
1303
+ email: authorMatch?.[2] ?? "",
1304
+ timestamp: authorMatch ? Number(authorMatch[3]) : 0
1305
+ },
1306
+ message
1307
+ };
1308
+ }
1309
+ var OBJECT_TYPES;
1310
+ var init_git_object_codec = __esm(() => {
1311
+ OBJECT_TYPES = [
1312
+ "blob",
1313
+ "tree",
1314
+ "commit",
1315
+ "tag"
1316
+ ];
1317
+ });
1318
+
1319
+ // src/origin-objects.ts
1320
+ import diff3Merge from "diff3";
1321
+ import ignore2 from "ignore";
1322
+ function isTreeMode(mode) {
1323
+ return mode === "40000" || mode === "040000";
1324
+ }
1325
+
1326
+ class GitObjectCache {
1327
+ maxBytes;
1328
+ entries = new Map;
1329
+ bytes = 0;
1330
+ constructor(maxBytes = 64 * 1024 * 1024) {
1331
+ this.maxBytes = maxBytes;
1332
+ }
1333
+ get(key) {
1334
+ const entry = this.entries.get(key);
1335
+ if (!entry)
1336
+ return;
1337
+ this.entries.delete(key);
1338
+ this.entries.set(key, entry);
1339
+ return entry;
1340
+ }
1341
+ set(key, value) {
1342
+ if (this.entries.has(key) || value.data.byteLength > this.maxBytes / 16)
1343
+ return;
1344
+ this.entries.set(key, value);
1345
+ this.bytes += value.data.byteLength;
1346
+ for (const [oldest, entry] of this.entries) {
1347
+ if (this.bytes <= this.maxBytes)
1348
+ break;
1349
+ this.entries.delete(oldest);
1350
+ this.bytes -= entry.data.byteLength;
1351
+ }
1352
+ }
1353
+ }
1354
+ async function mapLimit(items, limit, fn) {
1355
+ const results = new Array(items.length);
1356
+ let next = 0;
1357
+ const worker = async () => {
1358
+ while (next < items.length) {
1359
+ const index = next++;
1360
+ const item = items[index];
1361
+ if (item !== undefined)
1362
+ results[index] = await fn(item);
1363
+ }
1364
+ };
1365
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
1366
+ return results;
1367
+ }
1368
+ function parseTree(data) {
1369
+ const entries = [];
1370
+ const decoder = new TextDecoder("utf-8");
1371
+ let i = 0;
1372
+ while (i < data.length) {
1373
+ let space = i;
1374
+ while (space < data.length && data[space] !== 32)
1375
+ space++;
1376
+ let nul = space + 1;
1377
+ while (nul < data.length && data[nul] !== 0)
1378
+ nul++;
1379
+ const oid = Array.from(data.slice(nul + 1, nul + 21)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
1380
+ const nameBytes = data.slice(space + 1, nul);
1381
+ entries.push({
1382
+ mode: decoder.decode(data.slice(i, space)),
1383
+ name: decoder.decode(nameBytes),
1384
+ nameBytes,
1385
+ oid
1386
+ });
1387
+ i = nul + 21;
1388
+ }
1389
+ return entries;
1390
+ }
1391
+ function nameKey(bytes) {
1392
+ return Buffer.from(bytes).toString("hex");
1393
+ }
1394
+ function entryNamed(name, mode, oid) {
1395
+ return { name, nameBytes: new TextEncoder().encode(name), mode, oid };
1396
+ }
1397
+ function treeSortKey(entry) {
1398
+ if (!isTreeMode(entry.mode))
1399
+ return entry.nameBytes;
1400
+ const key = new Uint8Array(entry.nameBytes.length + 1);
1401
+ key.set(entry.nameBytes);
1402
+ key[entry.nameBytes.length] = 47;
1403
+ return key;
1404
+ }
1405
+ function compareBytes(a, b) {
1406
+ const length = Math.min(a.length, b.length);
1407
+ for (let i = 0;i < length; i++) {
1408
+ const delta = (a[i] ?? 0) - (b[i] ?? 0);
1409
+ if (delta !== 0)
1410
+ return delta;
1411
+ }
1412
+ return a.length - b.length;
1413
+ }
1414
+ function serializeTree(entries) {
1415
+ const sorted = [...entries].sort((a, b) => compareBytes(treeSortKey(a), treeSortKey(b)));
1416
+ const parts = [];
1417
+ for (const entry of sorted) {
1418
+ const mode = isTreeMode(entry.mode) ? "40000" : entry.mode;
1419
+ parts.push(new TextEncoder().encode(`${mode} `));
1420
+ parts.push(entry.nameBytes);
1421
+ const oid = new Uint8Array(21);
1422
+ for (let i = 0;i < 20; i++)
1423
+ oid[i + 1] = Number.parseInt(entry.oid.slice(i * 2, i * 2 + 2), 16);
1424
+ parts.push(oid);
1425
+ }
1426
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
1427
+ const out = new Uint8Array(total);
1428
+ let offset = 0;
1429
+ for (const part of parts) {
1430
+ out.set(part, offset);
1431
+ offset += part.length;
1432
+ }
1433
+ return out;
1434
+ }
1435
+ function signature(author) {
1436
+ const clean = (value) => value.replace(/[<>\n]/g, "").trim();
1437
+ return `${clean(author.name)} <${clean(author.email)}> ${Math.floor(Date.now() / 1000)} +0000`;
1438
+ }
1439
+ function serializeCommit(input) {
1440
+ const lines = [
1441
+ `tree ${input.tree}`,
1442
+ ...input.parents.map((parent) => `parent ${parent}`),
1443
+ `author ${signature(input.author)}`,
1444
+ `committer ${signature(input.author)}`
1445
+ ];
1446
+ const message = input.message.endsWith(`
1447
+ `) ? input.message : `${input.message}
1448
+ `;
1449
+ return new TextEncoder().encode(`${lines.join(`
1450
+ `)}
1451
+
1452
+ ${message}`);
1453
+ }
1454
+
1455
+ class OriginObjects {
1456
+ origin;
1457
+ cache;
1458
+ constructor(origin, cache) {
1459
+ this.origin = origin;
1460
+ this.cache = cache;
1461
+ }
1462
+ async read(oid) {
1463
+ const key = `${this.origin.gitdir}\x00${oid}`;
1464
+ const cached = this.cache.get(key);
1465
+ if (cached)
1466
+ return cached;
1467
+ const object = await this.origin.readObject(oid);
1468
+ this.cache.set(key, object);
1469
+ return object;
1470
+ }
1471
+ async write(input) {
1472
+ const oid = await this.origin.writeObject(input);
1473
+ this.cache.set(`${this.origin.gitdir}\x00${oid}`, input);
1474
+ return oid;
1475
+ }
1476
+ writeBlobs(contents) {
1477
+ return mapLimit(contents, WRITE_CONCURRENCY, (data) => this.write({ type: "blob", data }));
1478
+ }
1479
+ async commit(oid) {
1480
+ const object = await this.read(oid);
1481
+ if (object.type !== "commit")
1482
+ throw new Error(`${oid} is not a commit`);
1483
+ return parseCommit(object.data);
1484
+ }
1485
+ async tree(oid) {
1486
+ if (oid === EMPTY_TREE_ID)
1487
+ return [];
1488
+ const object = await this.read(oid);
1489
+ if (object.type !== "tree")
1490
+ throw new Error(`${oid} is not a tree`);
1491
+ return parseTree(object.data);
1492
+ }
1493
+ async blob(oid) {
1494
+ const object = await this.read(oid);
1495
+ if (object.type !== "blob")
1496
+ throw new Error(`${oid} is not a file`);
1497
+ return object.data;
1498
+ }
1499
+ async files(treeOid, prefix) {
1500
+ const files = new Map;
1501
+ const walk = async (oid, base) => {
1502
+ const entries = await this.tree(oid);
1503
+ await Promise.all(entries.map(async (entry) => {
1504
+ const filePath = `${base}${entry.name}`;
1505
+ if (isPersonalFile(filePath) || entry.mode === SUBMODULE_MODE)
1506
+ return;
1507
+ if (prefix !== undefined) {
1508
+ const inside = filePath.startsWith(prefix);
1509
+ const onTheWay = prefix.startsWith(`${filePath}/`);
1510
+ if (!inside && !onTheWay)
1511
+ return;
1512
+ }
1513
+ if (isTreeMode(entry.mode))
1514
+ await walk(entry.oid, `${filePath}/`);
1515
+ else if (prefix === undefined || filePath.startsWith(prefix))
1516
+ files.set(filePath, { oid: entry.oid, mode: entry.mode });
1517
+ }));
1518
+ };
1519
+ await walk(treeOid, "");
1520
+ return files;
1521
+ }
1522
+ async entry(treeOid, filePath) {
1523
+ const segments = filePath.split("/").filter(Boolean);
1524
+ let current = treeOid;
1525
+ for (const [index, segment] of segments.entries()) {
1526
+ const found = (await this.tree(current)).find((entry) => entry.name === segment);
1527
+ if (!found)
1528
+ return null;
1529
+ if (index === segments.length - 1)
1530
+ return found;
1531
+ if (found.mode === SYMLINK_MODE)
1532
+ throw new DraftPathError({ code: "ELOOP", path: filePath });
1533
+ if (!isTreeMode(found.mode))
1534
+ return null;
1535
+ current = found.oid;
1536
+ }
1537
+ return null;
1538
+ }
1539
+ async isIgnored(treeOid, filePath, rules = new Map) {
1540
+ const segments = filePath.split("/");
1541
+ if (segments.slice(0, -1).some((segment) => ALWAYS_IGNORED.has(segment)))
1542
+ return true;
1543
+ if (!treeOid)
1544
+ return false;
1545
+ if (await this.entry(treeOid, filePath))
1546
+ return false;
1547
+ let ignored = false;
1548
+ for (let depth = 0;depth < segments.length; depth++) {
1549
+ const directory = segments.slice(0, depth).join("/");
1550
+ const base = directory ? `${directory}/` : "";
1551
+ let matcher = rules.get(directory);
1552
+ if (matcher === undefined) {
1553
+ const entry = await this.entry(treeOid, `${base}.gitignore`).catch(() => null);
1554
+ matcher = entry && !isTreeMode(entry.mode) ? ignore2().add(new TextDecoder().decode(await this.blob(entry.oid))) : null;
1555
+ rules.set(directory, matcher);
1556
+ }
1557
+ if (!matcher)
1558
+ continue;
1559
+ const result = matcher.test(filePath.slice(base.length));
1560
+ if (result.ignored)
1561
+ ignored = true;
1562
+ if (result.unignored)
1563
+ ignored = false;
1564
+ }
1565
+ return ignored;
1566
+ }
1567
+ async writeTree(treeOid, changes, options) {
1568
+ return await this.rewrite(treeOid, changes, "", options?.skipMissingDeletes) ?? this.write({ type: "tree", data: new Uint8Array });
1569
+ }
1570
+ async rewrite(treeOid, changes, base, skipMissingDeletes = false) {
1571
+ const entries = new Map((treeOid ? await this.tree(treeOid) : []).map((entry) => [
1572
+ nameKey(entry.nameBytes),
1573
+ entry
1574
+ ]));
1575
+ const keyed = (name) => nameKey(new TextEncoder().encode(name));
1576
+ const nested = new Map;
1577
+ for (const [filePath, change] of changes) {
1578
+ const slash = filePath.indexOf("/");
1579
+ if (slash >= 0) {
1580
+ const directory = filePath.slice(0, slash);
1581
+ const inner = nested.get(directory) ?? new Map;
1582
+ inner.set(filePath.slice(slash + 1), change);
1583
+ nested.set(directory, inner);
1584
+ continue;
1585
+ }
1586
+ const existing = entries.get(keyed(filePath));
1587
+ const fullPath = `${base}${filePath}`;
1588
+ if (existing && isTreeMode(existing.mode))
1589
+ throw new DraftPathError({ code: "EISDIR", path: fullPath });
1590
+ if (existing?.mode === SYMLINK_MODE)
1591
+ throw new DraftPathError({ code: "ELOOP", path: fullPath });
1592
+ if (change === null) {
1593
+ if (!existing) {
1594
+ if (skipMissingDeletes)
1595
+ continue;
1596
+ throw new DraftPathError({ code: "ENOENT", path: fullPath });
1597
+ }
1598
+ entries.delete(keyed(filePath));
1599
+ continue;
1600
+ }
1601
+ entries.set(keyed(filePath), existing ? { ...existing, oid: change.oid, mode: change.mode ?? existing.mode } : entryNamed(filePath, change.mode ?? FILE_MODE, change.oid));
1602
+ }
1603
+ const children = await Promise.all([...nested].map(async ([directory, inner]) => {
1604
+ const existing = entries.get(keyed(directory));
1605
+ const fullPath = `${base}${directory}`;
1606
+ if (existing?.mode === SYMLINK_MODE)
1607
+ throw new DraftPathError({ code: "ELOOP", path: fullPath });
1608
+ if (existing && !isTreeMode(existing.mode)) {
1609
+ const deleting = [...inner.values()].every((change) => change === null);
1610
+ if (deleting && skipMissingDeletes)
1611
+ return { directory, oid: existing.oid, keep: true };
1612
+ throw new DraftPathError({
1613
+ code: deleting ? "ENOENT" : "ENOTDIR",
1614
+ path: `${fullPath}/${[...inner.keys()][0] ?? ""}`
1615
+ });
1616
+ }
1617
+ const oid = await this.rewrite(existing?.oid ?? null, inner, `${fullPath}/`, skipMissingDeletes);
1618
+ return { directory, oid, keep: false };
1619
+ }));
1620
+ for (const child of children) {
1621
+ if (child.keep)
1622
+ continue;
1623
+ const existing = entries.get(keyed(child.directory));
1624
+ if (child.oid === null)
1625
+ entries.delete(keyed(child.directory));
1626
+ else
1627
+ entries.set(keyed(child.directory), existing ? { ...existing, mode: "40000", oid: child.oid } : entryNamed(child.directory, "40000", child.oid));
1628
+ }
1629
+ if (entries.size === 0)
1630
+ return null;
1631
+ return this.write({
1632
+ type: "tree",
1633
+ data: serializeTree([...entries.values()])
1634
+ });
1635
+ }
1636
+ async writeCommit(input) {
1637
+ return this.write({ type: "commit", data: serializeCommit(input) });
1638
+ }
1639
+ async diffTrees(before, after) {
1640
+ const changes = [];
1641
+ const fileOf = (entry) => entry && !isTreeMode(entry.mode) && entry.mode !== SUBMODULE_MODE ? { oid: entry.oid, mode: entry.mode } : null;
1642
+ const walk = async (a, b, base) => {
1643
+ if (a === b)
1644
+ return;
1645
+ const left = new Map((a ? await this.tree(a) : []).map((entry) => [entry.name, entry]));
1646
+ const right = new Map((b ? await this.tree(b) : []).map((entry) => [entry.name, entry]));
1647
+ const names = [...new Set([...left.keys(), ...right.keys()])];
1648
+ await Promise.all(names.map(async (name) => {
1649
+ const filePath = `${base}${name}`;
1650
+ if (isPersonalFile(filePath))
1651
+ return;
1652
+ const l = left.get(name);
1653
+ const r = right.get(name);
1654
+ if (l?.oid === r?.oid && l?.mode === r?.mode)
1655
+ return;
1656
+ const lTree = l && isTreeMode(l.mode) ? l.oid : null;
1657
+ const rTree = r && isTreeMode(r.mode) ? r.oid : null;
1658
+ if (lTree || rTree)
1659
+ await walk(lTree, rTree, `${filePath}/`);
1660
+ const lFile = fileOf(l);
1661
+ const rFile = fileOf(r);
1662
+ if (lFile?.oid !== rFile?.oid || lFile?.mode !== rFile?.mode)
1663
+ changes.push({ path: filePath, before: lFile, after: rFile });
1664
+ }));
1665
+ };
1666
+ await walk(before, after, "");
1667
+ return changes.sort((x, y) => x.path.localeCompare(y.path));
1668
+ }
1669
+ async compare(left, right) {
1670
+ if (left === right)
1671
+ return { base: left, ahead: 0, behind: 0 };
1672
+ const LEFT = 1;
1673
+ const RIGHT = 2;
1674
+ const BOTH = 3;
1675
+ const flags = new Map;
1676
+ const times = new Map;
1677
+ const parents = new Map;
1678
+ const queue = [];
1679
+ const push = async (oid, flag) => {
1680
+ const current = flags.get(oid) ?? 0;
1681
+ const next = current | flag;
1682
+ if (next === current)
1683
+ return;
1684
+ flags.set(oid, next);
1685
+ if (!times.has(oid)) {
1686
+ const commit = await this.commit(oid);
1687
+ times.set(oid, commit.author.timestamp);
1688
+ parents.set(oid, commit.parents);
1689
+ }
1690
+ queue.push(oid);
1691
+ };
1692
+ await push(left, LEFT);
1693
+ await push(right, RIGHT);
1694
+ let steps = 0;
1695
+ while (queue.some((oid) => flags.get(oid) !== BOTH)) {
1696
+ if (++steps > 1e5)
1697
+ throw new Error("Histories too far apart to compare");
1698
+ queue.sort((a, b) => (times.get(a) ?? 0) - (times.get(b) ?? 0));
1699
+ const oid = queue.pop();
1700
+ if (!oid)
1701
+ break;
1702
+ const flag = flags.get(oid) ?? 0;
1703
+ for (const parent of parents.get(oid) ?? [])
1704
+ await push(parent, flag);
1705
+ }
1706
+ let ahead = 0;
1707
+ let behind = 0;
1708
+ const common = [];
1709
+ for (const [oid, flag] of flags) {
1710
+ if (flag === LEFT)
1711
+ ahead++;
1712
+ else if (flag === RIGHT)
1713
+ behind++;
1714
+ else if (flag === BOTH)
1715
+ common.push(oid);
1716
+ }
1717
+ const beneath = new Set;
1718
+ for (const oid of common) {
1719
+ const stack = [...parents.get(oid) ?? []];
1720
+ while (stack.length > 0) {
1721
+ const ancestor = stack.pop();
1722
+ if (!ancestor || beneath.has(ancestor) || !flags.has(ancestor))
1723
+ continue;
1724
+ beneath.add(ancestor);
1725
+ stack.push(...parents.get(ancestor) ?? []);
1726
+ }
1727
+ }
1728
+ const best = common.filter((oid) => !beneath.has(oid)).sort((a, b) => (times.get(b) ?? 0) - (times.get(a) ?? 0) || (a < b ? -1 : 1));
1729
+ return { base: best[0] ?? null, ahead, behind };
1730
+ }
1731
+ async isReachable(input) {
1732
+ const object = await this.read(input.sha).catch(() => null);
1733
+ if (object?.type !== "commit")
1734
+ return false;
1735
+ const floor = parseCommit(object.data).author.timestamp - 86400;
1736
+ const limit = input.limit ?? 20000;
1737
+ const seen = new Set;
1738
+ const queue = [];
1739
+ const enqueue = async (sha) => {
1740
+ if (seen.has(sha))
1741
+ return;
1742
+ seen.add(sha);
1743
+ const commit = await this.commit(sha).catch(() => null);
1744
+ if (commit)
1745
+ queue.push({ sha, time: commit.author.timestamp });
1746
+ };
1747
+ for (const tip of input.tips)
1748
+ await enqueue(tip);
1749
+ while (queue.length > 0 && seen.size <= limit) {
1750
+ queue.sort((a, b) => a.time - b.time);
1751
+ const next = queue.pop();
1752
+ if (!next)
1753
+ break;
1754
+ if (next.sha === input.sha)
1755
+ return true;
1756
+ if (next.time < floor)
1757
+ continue;
1758
+ for (const parent of (await this.commit(next.sha)).parents)
1759
+ await enqueue(parent);
1760
+ }
1761
+ return false;
1762
+ }
1763
+ async log(tip, maxCount) {
1764
+ const seen = new Set;
1765
+ const queue = [];
1766
+ const out = [];
1767
+ const enqueue = async (sha) => {
1768
+ if (seen.has(sha))
1769
+ return;
1770
+ seen.add(sha);
1771
+ queue.push({ sha, commit: await this.commit(sha) });
1772
+ };
1773
+ await enqueue(tip);
1774
+ while (queue.length > 0 && out.length < maxCount) {
1775
+ queue.sort((a, b) => a.commit.author.timestamp - b.commit.author.timestamp);
1776
+ const next = queue.pop();
1777
+ if (!next)
1778
+ break;
1779
+ out.push({
1780
+ sha: next.sha,
1781
+ message: next.commit.message,
1782
+ author: {
1783
+ name: next.commit.author.name,
1784
+ email: next.commit.author.email
1785
+ },
1786
+ timestamp: next.commit.author.timestamp
1787
+ });
1788
+ for (const parent of next.commit.parents)
1789
+ await enqueue(parent);
1790
+ }
1791
+ return out;
1792
+ }
1793
+ }
1794
+ async function mergeTrees(input) {
1795
+ const { objects } = input;
1796
+ const [oursChanges, theirsChanges] = await Promise.all([
1797
+ objects.diffTrees(input.base, input.ours),
1798
+ objects.diffTrees(input.base, input.theirs)
1799
+ ]);
1800
+ const theirsByPath = new Map(theirsChanges.map((change) => [change.path, change]));
1801
+ const blobOf = async (file) => file ? objects.blob(file.oid) : null;
1802
+ const changes = new Map;
1803
+ const conflicts = [];
1804
+ const modes = new Map;
1805
+ const conflict = async (entry) => {
1806
+ const [base, ours, theirs] = await Promise.all([
1807
+ blobOf(entry.base),
1808
+ blobOf(entry.ours),
1809
+ blobOf(entry.theirs)
1810
+ ]);
1811
+ const mode = entry.ours?.mode ?? entry.theirs?.mode ?? entry.base?.mode;
1812
+ if (mode)
1813
+ modes.set(entry.path, mode);
1814
+ const binary = [base, ours, theirs].some((bytes) => bytes?.includes(0));
1815
+ const text = (bytes) => bytes && !binary ? new TextDecoder().decode(bytes) : null;
1816
+ conflicts.push({
1817
+ path: entry.path,
1818
+ base: text(base),
1819
+ ours: text(ours),
1820
+ theirs: text(theirs),
1821
+ ...binary ? { binary: true } : {}
1822
+ });
1823
+ };
1824
+ for (const ours of oursChanges) {
1825
+ const theirs = theirsByPath.get(ours.path);
1826
+ if (!theirs) {
1827
+ if (ours.after && await clashesWithTree(objects, input.theirs, ours.path)) {
1828
+ await conflict({
1829
+ path: ours.path,
1830
+ base: ours.before,
1831
+ ours: ours.after,
1832
+ theirs: null
1833
+ });
1834
+ continue;
1835
+ }
1836
+ changes.set(ours.path, ours.after ? { oid: ours.after.oid, mode: ours.after.mode } : null);
1837
+ continue;
1838
+ }
1839
+ if (ours.after?.oid === theirs.after?.oid && ours.after?.mode === theirs.after?.mode)
1840
+ continue;
1841
+ const merged = await mergeText({
1842
+ objects,
1843
+ base: ours.before,
1844
+ ours: ours.after,
1845
+ theirs: theirs.after
1846
+ });
1847
+ if (merged !== null && ours.after) {
1848
+ const [oid] = await objects.writeBlobs([merged]);
1849
+ if (oid)
1850
+ changes.set(ours.path, { oid, mode: ours.after.mode });
1851
+ continue;
1852
+ }
1853
+ await conflict({
1854
+ path: ours.path,
1855
+ base: ours.before,
1856
+ ours: ours.after,
1857
+ theirs: theirs.after
1858
+ });
1859
+ }
1860
+ const resolved = Object.entries(input.resolutions ?? {});
1861
+ if (resolved.length > 0) {
1862
+ const binary = resolved.map(([file]) => file).filter((file) => conflicts.some((entry) => entry.path === file && entry.binary));
1863
+ if (binary.length > 0)
1864
+ throw new DraftBinaryResolutionError(binary);
1865
+ const rules = new Map;
1866
+ const ignored = [];
1867
+ for (const [file] of resolved)
1868
+ if (!modes.has(file) && await objects.isIgnored(input.theirs, file, rules))
1869
+ ignored.push(file);
1870
+ if (ignored.length > 0)
1871
+ throw new DraftIgnoredPathError(ignored);
1872
+ const oids = await objects.writeBlobs(resolved.map(([, content]) => new TextEncoder().encode(content)));
1873
+ resolved.forEach(([file], index) => {
1874
+ const oid = oids[index];
1875
+ const mode = modes.get(file);
1876
+ if (oid)
1877
+ changes.set(file, mode ? { oid, mode } : { oid });
1878
+ });
1879
+ }
1880
+ const unresolved = conflicts.filter((conflict) => input.resolutions?.[conflict.path] === undefined);
1881
+ if (unresolved.length > 0)
1882
+ return { status: "conflict", conflicts: unresolved };
1883
+ return {
1884
+ status: "merged",
1885
+ tree: await objects.writeTree(input.theirs, changes, {
1886
+ skipMissingDeletes: true
1887
+ })
1888
+ };
1889
+ }
1890
+ async function clashesWithTree(objects, treeOid, filePath) {
1891
+ const at = await objects.entry(treeOid, filePath).catch(() => null);
1892
+ if (at && isTreeMode(at.mode))
1893
+ return true;
1894
+ const segments = filePath.split("/");
1895
+ for (let depth = 1;depth < segments.length; depth++) {
1896
+ const parent = await objects.entry(treeOid, segments.slice(0, depth).join("/")).catch(() => null);
1897
+ if (!parent)
1898
+ return false;
1899
+ if (!isTreeMode(parent.mode))
1900
+ return true;
1901
+ }
1902
+ return false;
1903
+ }
1904
+ async function mergeText(input) {
1905
+ if (!input.base || !input.ours || !input.theirs)
1906
+ return null;
1907
+ if (input.ours.mode !== input.theirs.mode)
1908
+ return null;
1909
+ const [base, ours, theirs] = await Promise.all([input.base, input.ours, input.theirs].map((file) => input.objects.blob(file.oid)));
1910
+ if (!base || !ours || !theirs)
1911
+ return null;
1912
+ if ([base, ours, theirs].some((bytes) => bytes.includes(0)))
1913
+ return null;
1914
+ const lines = (bytes) => new TextDecoder().decode(bytes).match(/[^\n]*\n|[^\n]+$/g) ?? [];
1915
+ const blocks = diff3Merge(lines(ours), lines(base), lines(theirs));
1916
+ const merged = [];
1917
+ for (const block of blocks) {
1918
+ if (!("ok" in block))
1919
+ return null;
1920
+ merged.push(...block.ok);
1921
+ }
1922
+ return new TextEncoder().encode(merged.join(""));
1923
+ }
1924
+ var EMPTY_TREE_ID = "4b825dc642cb6eb9a060e54bf8d69288fbee4904", FILE_MODE = "100644", SYMLINK_MODE = "120000", SUBMODULE_MODE = "160000", ALWAYS_IGNORED, WRITE_CONCURRENCY = 16, DraftPathError, DraftIgnoredPathError, DraftBinaryResolutionError;
1925
+ var init_origin_objects = __esm(() => {
1926
+ init_git_object_codec();
1927
+ init_personal_files();
1928
+ ALWAYS_IGNORED = new Set(["node_modules", ".git", "dist", ".turbo"]);
1929
+ DraftPathError = class DraftPathError extends Error {
1930
+ code;
1931
+ constructor(input) {
1932
+ super(input.code === "ENOENT" ? `No such file: ${input.path}` : input.code === "EISDIR" ? `${input.path} is a folder` : input.code === "ENOTDIR" ? `A parent of ${input.path} is a file` : "Symbolic links cannot be read or written here");
1933
+ this.name = "DraftPathError";
1934
+ this.code = input.code;
1935
+ }
1936
+ };
1937
+ DraftIgnoredPathError = class DraftIgnoredPathError extends Error {
1938
+ paths;
1939
+ constructor(paths) {
1940
+ super(`${paths.join(", ")} ${paths.length === 1 ? "is" : "are"} ignored by the project's .gitignore and never become part of the program.`);
1941
+ this.name = "DraftIgnoredPathError";
1942
+ this.paths = paths;
1943
+ }
1944
+ };
1945
+ DraftBinaryResolutionError = class DraftBinaryResolutionError extends Error {
1946
+ paths;
1947
+ constructor(paths) {
1948
+ super(`${paths.join(", ")} ${paths.length === 1 ? "is not a text file" : "are not text files"}, so text cannot resolve ${paths.length === 1 ? "it" : "them"}. Discard your draft's change or publish it again after taking the published version.`);
1949
+ this.name = "DraftBinaryResolutionError";
1950
+ this.paths = paths;
1951
+ }
1952
+ };
1953
+ });
1954
+
1955
+ // src/git-sync.ts
1956
+ import nodeFs4 from "node:fs";
1957
+ import { publishedRef as publishedRef3 } from "@catamorphic/workflow/project-layout";
1958
+ import git4 from "isomorphic-git";
1959
+ async function push(opts) {
1960
+ const branch = opts.remoteBranch ?? "main";
1961
+ const localSha = opts.localSha ?? await opts.dev.resolveRef("HEAD");
1962
+ return opts.remote.withOrigin(opts.tenantId, opts.projectId, async (origin) => {
1963
+ const ref = `refs/heads/${branch}`;
1964
+ const currentRemote = await origin.resolveRef(ref);
1965
+ if (currentRemote === localSha) {
1966
+ return { sha: localSha };
1967
+ }
1968
+ if (currentRemote && !opts.force) {
1969
+ const fastForward = await isAncestor({
1970
+ dev: opts.dev,
1971
+ ancestor: currentRemote,
1972
+ descendant: localSha
1973
+ });
1974
+ if (!fastForward) {
1975
+ throw new PushNotFastForwardError({
1976
+ localSha,
1977
+ remoteSha: currentRemote
1978
+ });
1979
+ }
1980
+ }
1981
+ await transferCommits({
1982
+ source: devSource(opts.dev),
1983
+ sink: originSink(origin),
1984
+ sha: localSha
1985
+ });
1986
+ await origin.updateRef({
1987
+ ref,
1988
+ sha: localSha,
1989
+ expected: currentRemote
1990
+ });
1991
+ await syncRemoteTrackingRef({
1992
+ dev: opts.dev,
1993
+ branch,
1994
+ sha: localSha
1995
+ });
1996
+ return { sha: localSha };
1997
+ });
1998
+ }
1999
+ async function fetchRemote(opts) {
2000
+ const branch = opts.remoteBranch ?? "main";
2001
+ return opts.remote.withOrigin(opts.tenantId, opts.projectId, async (origin) => {
2002
+ const ref = `refs/heads/${branch}`;
2003
+ const remoteSha = await origin.resolveRef(ref);
2004
+ if (!remoteSha)
2005
+ return { sha: null, alreadyUpToDate: true };
2006
+ const alreadyUpToDate = await devHasCommit({
2007
+ dev: opts.dev,
2008
+ sha: remoteSha
2009
+ });
2010
+ if (!alreadyUpToDate) {
2011
+ await transferCommits({
2012
+ source: originSource(origin),
2013
+ sink: devSink(opts.dev),
2014
+ sha: remoteSha
2015
+ });
2016
+ }
2017
+ await syncRemoteTrackingRef({
2018
+ dev: opts.dev,
2019
+ branch,
2020
+ sha: remoteSha
2021
+ });
2022
+ return { sha: remoteSha, alreadyUpToDate };
2023
+ });
2024
+ }
2025
+ async function pull(opts) {
2026
+ const branch = opts.remoteBranch ?? "main";
2027
+ const author = opts.author ?? SYSTEM_AUTHOR;
2028
+ const fetched = await fetchRemote(opts);
2029
+ if (!fetched.sha) {
2030
+ return {
2031
+ status: "up-to-date",
2032
+ mergeCommit: null,
2033
+ conflicts: []
2034
+ };
2035
+ }
2036
+ const localSha = await opts.dev.resolveRef("HEAD");
2037
+ if (localSha === fetched.sha) {
2038
+ return {
2039
+ status: "up-to-date",
2040
+ mergeCommit: null,
2041
+ conflicts: []
2042
+ };
2043
+ }
2044
+ const localIsAhead = await isAncestor({
2045
+ dev: opts.dev,
2046
+ ancestor: fetched.sha,
2047
+ descendant: localSha
2048
+ });
2049
+ if (localIsAhead) {
2050
+ return {
2051
+ status: "up-to-date",
2052
+ mergeCommit: null,
2053
+ conflicts: []
2054
+ };
2055
+ }
2056
+ const currentBranch = await opts.dev.currentBranch();
2057
+ try {
2058
+ const result = await git4.merge({
2059
+ fs: nodeFs4,
2060
+ dir: opts.dev.repoPath,
2061
+ ours: currentBranch,
2062
+ theirs: fetched.sha,
2063
+ author,
2064
+ committer: author,
2065
+ fastForward: true,
2066
+ abortOnConflict: false,
2067
+ message: `Merge origin/${branch} into ${currentBranch}`
2068
+ });
2069
+ await git4.checkout({
2070
+ fs: nodeFs4,
2071
+ dir: opts.dev.repoPath,
2072
+ ref: currentBranch,
2073
+ force: true
2074
+ });
2075
+ return {
2076
+ status: "clean",
2077
+ mergeCommit: result.oid ?? null,
2078
+ conflicts: []
2079
+ };
2080
+ } catch (err) {
2081
+ const maybeConflict = err;
2082
+ if (maybeConflict?.code === "MergeConflictError") {
2083
+ const conflicts = await collectConflicts({
2084
+ dev: opts.dev,
2085
+ oursSha: localSha,
2086
+ theirsSha: fetched.sha,
2087
+ raw: maybeConflict.data
2088
+ });
2089
+ return {
2090
+ status: "conflict",
2091
+ mergeCommit: null,
2092
+ conflicts
2093
+ };
2094
+ }
2095
+ throw err;
2096
+ }
2097
+ }
2098
+ function devSource(dev) {
2099
+ const cache = {};
2100
+ return {
2101
+ hasObject: (sha) => git4.readObject({ fs: nodeFs4, dir: dev.repoPath, oid: sha, cache }).then(() => true).catch(() => false),
2102
+ readObject: async (sha) => {
2103
+ const obj = await git4.readObject({
2104
+ fs: nodeFs4,
2105
+ dir: dev.repoPath,
2106
+ oid: sha,
2107
+ cache,
2108
+ format: "content"
2109
+ });
2110
+ return {
2111
+ type: obj.type,
2112
+ data: obj.object
2113
+ };
2114
+ }
2115
+ };
2116
+ }
2117
+ function devSink(dev) {
2118
+ const cache = {};
2119
+ return {
2120
+ hasObject: (sha) => git4.readObject({ fs: nodeFs4, dir: dev.repoPath, oid: sha, cache }).then(() => true).catch(() => false),
2121
+ writeObject: (opts) => git4.writeObject({
2122
+ fs: nodeFs4,
2123
+ dir: dev.repoPath,
2124
+ type: opts.type,
2125
+ object: opts.data,
2126
+ format: "content"
2127
+ })
2128
+ };
2129
+ }
2130
+ function originSource(origin) {
2131
+ return {
2132
+ hasObject: (sha) => origin.hasObject(sha),
2133
+ readObject: (sha) => origin.readObject(sha)
2134
+ };
2135
+ }
2136
+ function originSink(origin) {
2137
+ return {
2138
+ hasObject: (sha) => origin.hasObject(sha),
2139
+ writeObject: (opts) => origin.writeObject(opts)
2140
+ };
2141
+ }
2142
+ async function transferCommits(opts) {
2143
+ let frontier = [opts.sha];
2144
+ const seen = new Set;
2145
+ while (frontier.length > 0) {
2146
+ const batch = [...new Set(frontier)].filter((sha) => !seen.has(sha));
2147
+ for (const sha of batch)
2148
+ seen.add(sha);
2149
+ const next = await mapLimit(batch, TRANSFER_CONCURRENCY, async (sha) => {
2150
+ if (await opts.sink.hasObject(sha))
2151
+ return [];
2152
+ const obj = await opts.source.readObject(sha);
2153
+ await opts.sink.writeObject(obj);
2154
+ if (obj.type === "commit") {
2155
+ const commit = parseCommit2(obj.data);
2156
+ return [commit.tree, ...commit.parents];
2157
+ }
2158
+ if (obj.type === "tree")
2159
+ return parseTree2(obj.data).filter((entry) => entry.mode !== "160000").map((entry) => entry.oid);
2160
+ return [];
2161
+ });
2162
+ frontier = next.flat();
2163
+ }
2164
+ }
2165
+ function parseCommit2(data) {
2166
+ const text = new TextDecoder("utf-8").decode(data);
2167
+ const headerEnd = text.indexOf(`
2168
+
2169
+ `);
2170
+ const header = headerEnd === -1 ? text : text.slice(0, headerEnd);
2171
+ const parents = [];
2172
+ let tree = "";
2173
+ for (const line of header.split(`
2174
+ `)) {
2175
+ if (line.startsWith("tree "))
2176
+ tree = line.slice(5).trim();
2177
+ else if (line.startsWith("parent "))
2178
+ parents.push(line.slice(7).trim());
2179
+ }
2180
+ return { tree, parents };
2181
+ }
2182
+ function parseTree2(data) {
2183
+ const entries = [];
2184
+ let i = 0;
2185
+ while (i < data.length) {
2186
+ let spaceIdx = i;
2187
+ while (spaceIdx < data.length && data[spaceIdx] !== 32)
2188
+ spaceIdx++;
2189
+ const mode = new TextDecoder("utf-8").decode(data.slice(i, spaceIdx));
2190
+ let nullIdx = spaceIdx + 1;
2191
+ while (nullIdx < data.length && data[nullIdx] !== 0)
2192
+ nullIdx++;
2193
+ const name = new TextDecoder("utf-8").decode(data.slice(spaceIdx + 1, nullIdx));
2194
+ const oidBytes = data.slice(nullIdx + 1, nullIdx + 21);
2195
+ const oid = Array.from(oidBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
2196
+ entries.push({ mode, name, oid });
2197
+ i = nullIdx + 21;
2198
+ }
2199
+ return entries;
2200
+ }
2201
+ async function isAncestor(opts) {
2202
+ if (opts.ancestor === opts.descendant)
2203
+ return true;
2204
+ if (opts.dev instanceof NativeProjectRepo)
2205
+ return nativeGit(opts.dev.repoPath, [
2206
+ "merge-base",
2207
+ "--is-ancestor",
2208
+ opts.ancestor,
2209
+ opts.descendant
2210
+ ]).then(() => true, () => false);
2211
+ try {
2212
+ const commits = await git4.log({
2213
+ fs: nodeFs4,
2214
+ dir: opts.dev.repoPath,
2215
+ ref: opts.descendant,
2216
+ depth: -1
2217
+ });
2218
+ return commits.some((c) => c.oid === opts.ancestor);
2219
+ } catch {
2220
+ return false;
2221
+ }
2222
+ }
2223
+ async function devHasCommit(opts) {
2224
+ if (opts.dev instanceof NativeProjectRepo)
2225
+ return nativeGit(opts.dev.repoPath, ["cat-file", "-e", opts.sha]).then(() => true, () => false);
2226
+ try {
2227
+ await git4.readObject({
2228
+ fs: nodeFs4,
2229
+ dir: opts.dev.repoPath,
2230
+ oid: opts.sha
2231
+ });
2232
+ return true;
2233
+ } catch {
2234
+ return false;
2235
+ }
2236
+ }
2237
+ async function syncRemoteTrackingRef(opts) {
2238
+ if (opts.dev instanceof NativeProjectRepo) {
2239
+ await nativeGit(opts.dev.repoPath, [
2240
+ "update-ref",
2241
+ publishedRef3(opts.branch),
2242
+ opts.sha
2243
+ ]);
2244
+ return;
2245
+ }
2246
+ await git4.writeRef({
2247
+ fs: nodeFs4,
2248
+ dir: opts.dev.repoPath,
2249
+ ref: publishedRef3(opts.branch),
2250
+ value: opts.sha,
2251
+ force: true
2252
+ });
2253
+ }
2254
+ async function collectConflicts(opts) {
2255
+ const raw = opts.raw;
2256
+ const paths = raw?.filepaths ?? [];
2257
+ const result = [];
2258
+ for (const filepath of paths) {
2259
+ const ours = await readAtRef(opts.dev.repoPath, opts.oursSha, filepath);
2260
+ const theirs = await readAtRef(opts.dev.repoPath, opts.theirsSha, filepath);
2261
+ const baseSha = await git4.findMergeBase({
2262
+ fs: nodeFs4,
2263
+ dir: opts.dev.repoPath,
2264
+ oids: [opts.oursSha, opts.theirsSha]
2265
+ }).then((bases) => bases[0] ?? null).catch(() => null);
2266
+ const base = baseSha ? await readAtRef(opts.dev.repoPath, baseSha, filepath) : null;
2267
+ result.push({
2268
+ path: filepath,
2269
+ base,
2270
+ ours,
2271
+ theirs
2272
+ });
2273
+ }
2274
+ return result;
2275
+ }
2276
+ async function readAtRef(dir, oid, filepath) {
2277
+ try {
2278
+ const { blob } = await git4.readBlob({
2279
+ fs: nodeFs4,
2280
+ dir,
2281
+ oid,
2282
+ filepath
2283
+ });
2284
+ return new TextDecoder("utf-8").decode(blob);
2285
+ } catch {
2286
+ return null;
2287
+ }
2288
+ }
2289
+ var SYSTEM_AUTHOR, PushNotFastForwardError, TRANSFER_CONCURRENCY = 16;
2290
+ var init_git_sync = __esm(() => {
2291
+ init_native_git();
2292
+ init_native_project_repo();
2293
+ init_origin_objects();
2294
+ SYSTEM_AUTHOR = {
2295
+ name: "Work",
2296
+ email: "system@work.software"
2297
+ };
2298
+ PushNotFastForwardError = class PushNotFastForwardError extends Error {
2299
+ localSha;
2300
+ remoteSha;
2301
+ constructor(opts) {
2302
+ super(`Push is not a fast-forward (local ${opts.localSha.slice(0, 8)} vs remote ${opts.remoteSha.slice(0, 8)})`);
2303
+ this.name = "PushNotFastForwardError";
2304
+ this.localSha = opts.localSha;
2305
+ this.remoteSha = opts.remoteSha;
2306
+ }
2307
+ };
2308
+ });
2309
+
2310
+ // src/checkout-remote-backend.ts
2311
+ init_native_git();
2312
+ init_native_project_repo();
2313
+ import { PUBLISHED_REF_PREFIX } from "@catamorphic/workflow/project-layout";
2314
+
2315
+ class CheckoutRemoteBackend {
2316
+ roots;
2317
+ shared;
2318
+ constructor(roots, shared) {
2319
+ this.roots = roots;
2320
+ this.shared = shared;
2321
+ }
2322
+ async initRemote(tenantId, projectId) {
2323
+ if (!await this.roots(tenantId, projectId))
2324
+ await this.shared.initRemote(tenantId, projectId);
2325
+ }
2326
+ async deleteRemote(tenantId, projectId) {
2327
+ if (!await this.roots(tenantId, projectId))
2328
+ await this.shared.deleteRemote(tenantId, projectId);
2329
+ }
2330
+ async exists(tenantId, projectId) {
2331
+ return Boolean(await this.roots(tenantId, projectId)) || this.shared.exists(tenantId, projectId);
2332
+ }
2333
+ async withOrigin(tenantId, projectId, fn) {
2334
+ const root = await this.roots(tenantId, projectId);
2335
+ return root ? fn(new CheckoutOrigin(root, projectId)) : this.shared.withOrigin(tenantId, projectId, fn);
2336
+ }
2337
+ }
2338
+
2339
+ class CheckoutOrigin {
2340
+ root;
2341
+ projectId;
2342
+ gitdir;
2343
+ constructor(root, projectId) {
2344
+ this.root = root;
2345
+ this.projectId = projectId;
2346
+ this.gitdir = root;
2347
+ }
2348
+ publicationRef(ref) {
2349
+ if (!ref.startsWith("refs/heads/"))
2350
+ throw new Error(`Unsupported publication ref: ${ref}`);
2351
+ return `${PUBLISHED_REF_PREFIX}/${ref.slice("refs/heads/".length)}`;
2352
+ }
2353
+ async resolveRef(ref) {
2354
+ return nativeGit(this.root, [
2355
+ "rev-parse",
2356
+ "--verify",
2357
+ this.publicationRef(ref)
2358
+ ]).then((s) => s.trim(), () => null);
2359
+ }
2360
+ async listRefs(prefix) {
2361
+ if (!await hasLocalGit({ path: this.root }))
2362
+ return [];
2363
+ const output = await nativeGit(this.root, [
2364
+ "for-each-ref",
2365
+ "--format=%(refname)%09%(objectname)",
2366
+ `${PUBLISHED_REF_PREFIX}/`
2367
+ ]);
2368
+ return output.trim().split(`
2369
+ `).filter(Boolean).flatMap((line) => {
2370
+ const [name, sha] = line.split("\t");
2371
+ const ref = name?.replace(`${PUBLISHED_REF_PREFIX}/`, "refs/heads/");
2372
+ return ref?.startsWith(prefix) && sha ? [{ ref, sha }] : [];
2373
+ });
2374
+ }
2375
+ async updateRef(input) {
2376
+ await nativeGit(this.root, [
2377
+ "update-ref",
2378
+ this.publicationRef(input.ref),
2379
+ input.sha,
2380
+ ...input.expected !== undefined ? [input.expected ?? "0000000000000000000000000000000000000000"] : []
2381
+ ]);
2382
+ }
2383
+ async deleteRef(input) {
2384
+ await nativeGit(this.root, [
2385
+ "update-ref",
2386
+ "-d",
2387
+ this.publicationRef(input.ref),
2388
+ ...input.expected !== undefined ? [input.expected] : []
2389
+ ]);
2390
+ }
2391
+ async hasObject(sha) {
2392
+ return nativeGit(this.root, ["cat-file", "-e", sha]).then(() => true, () => false);
2393
+ }
2394
+ async readObject(sha) {
2395
+ const type = (await nativeGit(this.root, ["cat-file", "-t", sha])).trim();
2396
+ if (type !== "blob" && type !== "tree" && type !== "commit" && type !== "tag")
2397
+ throw new Error(`Unsupported Git object: ${type}`);
2398
+ return {
2399
+ type,
2400
+ data: await nativeGitBytes(this.root, ["cat-file", type, sha])
2401
+ };
2402
+ }
2403
+ async writeObject(input) {
2404
+ return new TextDecoder().decode(await nativeGitBytes(this.root, ["hash-object", "-w", "--stdin", "-t", input.type], input.data)).trim();
2405
+ }
2406
+ async log(ref, maxCount) {
2407
+ const repo = new NativeProjectRepo(this.projectId, this.root, async () => {});
2408
+ return repo.log({ ref: this.publicationRef(ref), maxCount });
2409
+ }
2410
+ }
2411
+
2412
+ // src/index.ts
2413
+ init_file_reads();
2414
+
2415
+ // src/fs-backend.ts
2416
+ init_personal_files();
2417
+ import nodeFs2 from "node:fs";
2418
+ import fs5 from "node:fs/promises";
2419
+ import path5 from "node:path";
2420
+ import git2 from "isomorphic-git";
2421
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2422
+ function assertUuid(value) {
2423
+ if (!UUID_RE.test(value)) {
2424
+ throw new Error(`Invalid UUID: ${value}`);
2425
+ }
2426
+ }
2427
+
2428
+ class FsBackend {
2429
+ basePath;
2430
+ pathResolver;
2431
+ initializedRoots = new Map;
2432
+ constructor(basePath, pathResolver) {
2433
+ this.basePath = basePath;
2434
+ this.pathResolver = pathResolver;
2435
+ }
2436
+ resolveInternalPath(tenantId, projectId, externalUserId) {
2437
+ assertUuid(tenantId);
2438
+ assertUuid(projectId);
2439
+ const base = path5.join(this.basePath, tenantId, projectId);
2440
+ const dir = externalUserId ? path5.join(base, "dev", sanitizeUserId(externalUserId)) : base;
2441
+ if (!path5.resolve(dir).startsWith(path5.resolve(this.basePath))) {
2442
+ throw new Error("Path traversal detected");
2443
+ }
2444
+ return dir;
2445
+ }
2446
+ async resolveProjectPath(tenantId, projectId, externalUserId) {
2447
+ const rootPath = await this.pathResolver?.(tenantId, projectId);
2448
+ if (rootPath)
2449
+ return rootPath;
2450
+ const initializedRoot = this.initializedRoots.get(`${tenantId}:${projectId}`);
2451
+ if (initializedRoot)
2452
+ return initializedRoot;
2453
+ return this.resolveInternalPath(tenantId, projectId, externalUserId);
2454
+ }
2455
+ async acquireProject(tenantId, projectId, externalUserId) {
2456
+ const projectPath = await this.resolveProjectPath(tenantId, projectId, externalUserId);
2457
+ try {
2458
+ await fs5.access(projectPath);
2459
+ } catch {
2460
+ throw new Error(`Project not found: ${projectId}`);
2461
+ }
2462
+ await ensurePersonalFilesExcluded({ repoPath: projectPath });
2463
+ return {
2464
+ repoPath: projectPath,
2465
+ release: async () => {}
2466
+ };
2467
+ }
2468
+ async initProject(tenantId, projectId, opts) {
2469
+ const projectPath = opts?.rootPath ?? await this.resolveProjectPath(tenantId, projectId, opts?.externalUserId);
2470
+ if (opts?.rootPath)
2471
+ this.initializedRoots.set(`${tenantId}:${projectId}`, projectPath);
2472
+ await fs5.mkdir(projectPath, { recursive: true });
2473
+ const gitDir = path5.join(projectPath, ".git");
2474
+ const hasRepo = await fs5.access(gitDir).then(() => true, () => false);
2475
+ if (!hasRepo) {
2476
+ await git2.init({ fs: nodeFs2, dir: projectPath, defaultBranch: "main" });
2477
+ }
2478
+ await ensurePersonalFilesExcluded({ repoPath: projectPath });
2479
+ return projectPath;
2480
+ }
2481
+ mirrorPath(tenantId, projectId) {
2482
+ assertUuid(tenantId);
2483
+ assertUuid(projectId);
2484
+ return path5.join(this.basePath, ".mirrors", tenantId, `${projectId}.git`);
2485
+ }
2486
+ cachePath(tenantId, projectId, name) {
2487
+ assertUuid(tenantId);
2488
+ assertUuid(projectId);
2489
+ return path5.join(this.basePath, tenantId, projectId, "cache", sanitizeUserId(name));
2490
+ }
2491
+ async deleteProject(tenantId, projectId) {
2492
+ const projectRoot = path5.join(this.basePath, tenantId, projectId);
2493
+ await fs5.rm(projectRoot, { recursive: true, force: true });
2494
+ await fs5.rm(this.mirrorPath(tenantId, projectId), {
2495
+ recursive: true,
2496
+ force: true
2497
+ });
2498
+ this.initializedRoots.delete(`${tenantId}:${projectId}`);
2499
+ }
2500
+ async deleteCopy(tenantId, projectId, externalUserId) {
2501
+ if (await this.pathResolver?.(tenantId, projectId) || this.initializedRoots.has(`${tenantId}:${projectId}`))
2502
+ return;
2503
+ await fs5.rm(this.resolveInternalPath(tenantId, projectId, externalUserId), {
2504
+ recursive: true,
2505
+ force: true
2506
+ });
2507
+ }
2508
+ async exists(tenantId, projectId, externalUserId) {
2509
+ const projectPath = await this.resolveProjectPath(tenantId, projectId, externalUserId);
2510
+ try {
2511
+ await fs5.access(projectPath);
2512
+ return true;
2513
+ } catch {
2514
+ return false;
2515
+ }
2516
+ }
2517
+ }
2518
+ function sanitizeUserId(value) {
2519
+ let encoded = "";
2520
+ for (const byte of new TextEncoder().encode(value)) {
2521
+ const char = String.fromCharCode(byte);
2522
+ encoded += /[a-z0-9._-]/.test(char) ? char : `%${byte.toString(16).padStart(2, "0")}`;
2523
+ }
2524
+ if (!encoded || encoded === "." || encoded === "..")
2525
+ throw new Error(`Invalid externalUserId: ${value}`);
2526
+ return encoded;
2527
+ }
2528
+ // src/fs-remote-backend.ts
2529
+ import nodeFs3 from "node:fs";
2530
+ import fs6 from "node:fs/promises";
2531
+ import path6 from "node:path";
2532
+ import git3 from "isomorphic-git";
2533
+
2534
+ // src/ref-moved-error.ts
2535
+ class RefMovedError extends Error {
2536
+ ref;
2537
+ constructor(input) {
2538
+ super(`Ref ${input.ref} moved (expected ${input.expected ?? "none"}, got ${input.actual ?? "none"})`);
2539
+ this.name = "RefMovedError";
2540
+ this.ref = input.ref;
2541
+ }
2542
+ }
2543
+
2544
+ // src/fs-remote-backend.ts
2545
+ init_ref_names();
2546
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2547
+ function assertUuid2(value) {
2548
+ if (!UUID_RE2.test(value)) {
2549
+ throw new Error(`Invalid UUID: ${value}`);
2550
+ }
2551
+ }
2552
+ var refLocks = new Map;
2553
+ async function withRefLock(key, fn) {
2554
+ const previous = refLocks.get(key) ?? Promise.resolve();
2555
+ const run = previous.catch(() => {}).then(fn);
2556
+ refLocks.set(key, run);
2557
+ try {
2558
+ return await run;
2559
+ } finally {
2560
+ if (refLocks.get(key) === run)
2561
+ refLocks.delete(key);
2562
+ }
2563
+ }
2564
+
2565
+ class FsRemoteBackend {
2566
+ basePath;
2567
+ constructor(basePath) {
2568
+ this.basePath = basePath;
2569
+ }
2570
+ resolveBarePath(tenantId, projectId) {
2571
+ assertUuid2(tenantId);
2572
+ assertUuid2(projectId);
2573
+ const barePath = path6.join(this.basePath, tenantId, `${projectId}.git`);
2574
+ if (!path6.resolve(barePath).startsWith(path6.resolve(this.basePath))) {
2575
+ throw new Error("Path traversal detected");
2576
+ }
2577
+ return barePath;
2578
+ }
2579
+ async initRemote(tenantId, projectId) {
2580
+ const barePath = this.resolveBarePath(tenantId, projectId);
2581
+ await fs6.mkdir(barePath, { recursive: true });
2582
+ await git3.init({
2583
+ fs: nodeFs3,
2584
+ dir: barePath,
2585
+ bare: true,
2586
+ defaultBranch: "main"
2587
+ });
2588
+ }
2589
+ async deleteRemote(tenantId, projectId) {
2590
+ const barePath = this.resolveBarePath(tenantId, projectId);
2591
+ await fs6.rm(barePath, { recursive: true, force: true });
2592
+ }
2593
+ async exists(tenantId, projectId) {
2594
+ const barePath = this.resolveBarePath(tenantId, projectId);
2595
+ try {
2596
+ await fs6.access(barePath);
2597
+ return true;
2598
+ } catch {
2599
+ return false;
2600
+ }
2601
+ }
2602
+ async withOrigin(tenantId, projectId, fn) {
2603
+ const barePath = this.resolveBarePath(tenantId, projectId);
2604
+ const origin = new FsOriginRepo(barePath);
2605
+ return fn(origin);
2606
+ }
2607
+ }
2608
+
2609
+ class FsOriginRepo {
2610
+ gitdir;
2611
+ cache = {};
2612
+ constructor(gitdir) {
2613
+ this.gitdir = gitdir;
2614
+ }
2615
+ async resolveRef(ref) {
2616
+ assertResolvableRef(ref);
2617
+ try {
2618
+ return await git3.resolveRef({ fs: nodeFs3, gitdir: this.gitdir, ref });
2619
+ } catch {
2620
+ return null;
2621
+ }
2622
+ }
2623
+ async listRefs(prefix) {
2624
+ const normalized = prefix.endsWith("/") ? prefix : `${prefix}/`;
2625
+ const stripped = normalized.replace(/\/$/, "");
2626
+ const refs = await git3.listBranches({
2627
+ fs: nodeFs3,
2628
+ gitdir: this.gitdir
2629
+ });
2630
+ const prefixMatch = stripped === "refs/heads";
2631
+ if (!prefixMatch)
2632
+ return [];
2633
+ const entries = await Promise.all(refs.map(async (name) => ({
2634
+ ref: `refs/heads/${name}`,
2635
+ sha: await git3.resolveRef({
2636
+ fs: nodeFs3,
2637
+ gitdir: this.gitdir,
2638
+ ref: `refs/heads/${name}`
2639
+ })
2640
+ })));
2641
+ return entries;
2642
+ }
2643
+ async updateRef(opts) {
2644
+ await withRefLock(`${this.gitdir}\x00${opts.ref}`, () => this.writeRefChecked(opts));
2645
+ }
2646
+ async writeRefChecked(opts) {
2647
+ assertValidRefName(opts.ref);
2648
+ if (opts.expected !== undefined) {
2649
+ const current = await this.resolveRef(opts.ref);
2650
+ if (current !== opts.expected) {
2651
+ throw new RefMovedError({
2652
+ ref: opts.ref,
2653
+ expected: opts.expected,
2654
+ actual: current
2655
+ });
2656
+ }
2657
+ }
2658
+ await git3.writeRef({
2659
+ fs: nodeFs3,
2660
+ gitdir: this.gitdir,
2661
+ ref: opts.ref,
2662
+ value: opts.sha,
2663
+ force: true
2664
+ });
2665
+ }
2666
+ async deleteRef(input) {
2667
+ await withRefLock(`${this.gitdir}\x00${input.ref}`, () => this.deleteRefChecked(input));
2668
+ }
2669
+ async deleteRefChecked(input) {
2670
+ assertValidRefName(input.ref);
2671
+ if (input.expected !== undefined) {
2672
+ const current = await this.resolveRef(input.ref);
2673
+ if (current !== input.expected)
2674
+ throw new RefMovedError({
2675
+ ref: input.ref,
2676
+ expected: input.expected,
2677
+ actual: current
2678
+ });
2679
+ }
2680
+ await git3.deleteRef({ fs: nodeFs3, gitdir: this.gitdir, ref: input.ref });
2681
+ }
2682
+ async hasObject(sha) {
2683
+ try {
2684
+ await git3.readObject({
2685
+ fs: nodeFs3,
2686
+ gitdir: this.gitdir,
2687
+ oid: sha,
2688
+ cache: this.cache
2689
+ });
2690
+ return true;
2691
+ } catch {
2692
+ return false;
2693
+ }
2694
+ }
2695
+ async readObject(sha) {
2696
+ const obj = await git3.readObject({
2697
+ fs: nodeFs3,
2698
+ gitdir: this.gitdir,
2699
+ oid: sha,
2700
+ format: "content",
2701
+ cache: this.cache
2702
+ });
2703
+ if (obj.type === "deflated" || obj.type === "wrapped") {
2704
+ throw new Error(`Unexpected object format for ${sha}: ${obj.type}`);
2705
+ }
2706
+ return {
2707
+ type: obj.type,
2708
+ data: obj.object
2709
+ };
2710
+ }
2711
+ async writeObject(opts) {
2712
+ return git3.writeObject({
2713
+ fs: nodeFs3,
2714
+ gitdir: this.gitdir,
2715
+ type: opts.type,
2716
+ object: opts.data,
2717
+ format: "content"
2718
+ });
2719
+ }
2720
+ async log(ref, maxCount = 50) {
2721
+ try {
2722
+ const commits = await git3.log({
2723
+ fs: nodeFs3,
2724
+ gitdir: this.gitdir,
2725
+ ref,
2726
+ depth: maxCount
2727
+ });
2728
+ return commits.map((c) => ({
2729
+ sha: c.oid,
2730
+ message: c.commit.message,
2731
+ author: {
2732
+ name: c.commit.author.name,
2733
+ email: c.commit.author.email
2734
+ },
2735
+ timestamp: c.commit.author.timestamp
2736
+ }));
2737
+ } catch {
2738
+ return [];
2739
+ }
2740
+ }
2741
+ }
2742
+
2743
+ // src/index.ts
2744
+ init_git_sync();
2745
+
2746
+ // src/in-memory-object-store.ts
2747
+ import { createHash as createHash2 } from "node:crypto";
2748
+
2749
+ // src/object-store.ts
2750
+ class PreconditionFailedError extends Error {
2751
+ constructor(key) {
2752
+ super(`Conditional write failed for '${key}'`);
2753
+ this.name = "PreconditionFailedError";
2754
+ }
2755
+ }
2756
+
2757
+ // src/in-memory-object-store.ts
2758
+ class InMemoryObjectStore {
2759
+ objects = new Map;
2760
+ async get(key) {
2761
+ const entry = this.objects.get(key);
2762
+ if (!entry)
2763
+ return null;
2764
+ return { data: entry.data.slice(), etag: entry.etag };
2765
+ }
2766
+ async has(key) {
2767
+ return this.objects.has(key);
2768
+ }
2769
+ async put(key, data, opts) {
2770
+ const current = this.objects.get(key);
2771
+ if (opts?.ifNoneMatch === "*" && current) {
2772
+ throw new PreconditionFailedError(key);
2773
+ }
2774
+ if (opts?.ifMatch !== undefined) {
2775
+ if (!current || current.etag !== opts.ifMatch) {
2776
+ throw new PreconditionFailedError(key);
2777
+ }
2778
+ }
2779
+ const etag = `"${createHash2("md5").update(data).digest("hex")}"`;
2780
+ this.objects.set(key, { data: data.slice(), etag });
2781
+ }
2782
+ async list(prefix) {
2783
+ return [...this.objects.keys()].filter((key) => key.startsWith(prefix));
2784
+ }
2785
+ async delete(key, opts) {
2786
+ if (opts?.ifMatch !== undefined && this.objects.get(key)?.etag !== opts.ifMatch)
2787
+ throw new PreconditionFailedError(key);
2788
+ this.objects.delete(key);
2789
+ }
2790
+ async deletePrefix(prefix) {
2791
+ for (const key of await this.list(prefix)) {
2792
+ this.objects.delete(key);
2793
+ }
2794
+ }
2795
+ }
2796
+ // src/migrate-workflow.ts
2797
+ async function migrateWorkflowToProject({
2798
+ projectManager,
2799
+ tenantId,
2800
+ projectId,
2801
+ workflowName,
2802
+ workflowCode
2803
+ }) {
2804
+ const sanitizedName = workflowName.replace(/[^a-zA-Z0-9-]/g, "-").toLowerCase();
2805
+ const repo = await projectManager.create(tenantId, projectId, {
2806
+ name: sanitizedName,
2807
+ initialFiles: {
2808
+ [`src/${sanitizedName}.ts`]: workflowCode
2809
+ }
2810
+ });
2811
+ const sha = await repo.resolveRef("HEAD");
2812
+ await repo.dispose();
2813
+ return { projectId, commitSha: sha };
2814
+ }
2815
+
2816
+ // src/index.ts
2817
+ init_native_git();
2818
+ init_native_project_repo();
2819
+
2820
+ // src/network.ts
2821
+ init_native_git();
2822
+ import nodeFs5 from "node:fs";
2823
+ import { MANAGED_BRANCH_PREFIX } from "@catamorphic/workflow/project-layout";
2824
+ import git5 from "isomorphic-git";
2825
+ import http from "isomorphic-git/http/node";
2826
+ function onAuthFor(credentials) {
2827
+ return credentials ? () => ({
2828
+ username: credentials.username,
2829
+ password: credentials.password
2830
+ }) : undefined;
2831
+ }
2832
+ async function cloneFromRemote(opts) {
2833
+ if (opts.native) {
2834
+ const auth = opts.credentials ? { ...opts.credentials, url: opts.url } : undefined;
2835
+ await nativeGit(opts.repoPath, ["remote", "add", "origin", opts.url]);
2836
+ await nativeGit(opts.repoPath, ["fetch", "--tags", "origin"], auth);
2837
+ const remoteBranch = opts.branch ?? (await nativeGit(opts.repoPath, ["ls-remote", "--symref", "origin", "HEAD"], auth)).match(/ref: refs\/heads\/(.+)\tHEAD/)?.[1];
2838
+ if (!remoteBranch)
2839
+ throw new Error("The repository has no default branch to check out");
2840
+ await nativeGit(opts.repoPath, [
2841
+ "checkout",
2842
+ "-B",
2843
+ remoteBranch,
2844
+ "--track",
2845
+ `origin/${remoteBranch}`
2846
+ ]);
2847
+ await nativeGit(opts.repoPath, [
2848
+ "symbolic-ref",
2849
+ "refs/remotes/origin/HEAD",
2850
+ `refs/remotes/origin/${remoteBranch}`
2851
+ ]);
2852
+ return {
2853
+ sha: (await nativeGit(opts.repoPath, ["rev-parse", "HEAD"])).trim(),
2854
+ remoteBranch
2855
+ };
2856
+ }
2857
+ await git5.addRemote({
2858
+ fs: nodeFs5,
2859
+ dir: opts.repoPath,
2860
+ remote: "origin",
2861
+ url: opts.url,
2862
+ force: true
2863
+ });
2864
+ const result = await git5.fetch({
2865
+ fs: nodeFs5,
2866
+ http,
2867
+ dir: opts.repoPath,
2868
+ remote: "origin",
2869
+ ...opts.branch ? { ref: opts.branch } : {},
2870
+ singleBranch: true,
2871
+ tags: false,
2872
+ onAuth: onAuthFor(opts.credentials)
2873
+ });
2874
+ const sha = result.fetchHead;
2875
+ if (!sha) {
2876
+ throw new Error(`Remote '${opts.url}' has no commits to clone`);
2877
+ }
2878
+ const remoteBranch = opts.branch ?? (result.defaultBranch ? result.defaultBranch.replace(/^refs\/heads\//, "") : "main");
2879
+ await git5.writeRef({
2880
+ fs: nodeFs5,
2881
+ dir: opts.repoPath,
2882
+ ref: "refs/heads/main",
2883
+ value: sha,
2884
+ force: true
2885
+ });
2886
+ await git5.checkout({
2887
+ fs: nodeFs5,
2888
+ dir: opts.repoPath,
2889
+ ref: "main",
2890
+ force: true
2891
+ });
2892
+ return { sha, remoteBranch };
2893
+ }
2894
+
2895
+ class RemotePushRefusedError extends Error {
2896
+ remoteBranch;
2897
+ constructor(remoteBranch, reason) {
2898
+ super(`Work will not push '${remoteBranch}': ${reason}`);
2899
+ this.remoteBranch = remoteBranch;
2900
+ this.name = "RemotePushRefusedError";
2901
+ }
2902
+ }
2903
+ function isManagedBranch(branch) {
2904
+ return branch.startsWith(MANAGED_BRANCH_PREFIX) && branch.length > MANAGED_BRANCH_PREFIX.length;
2905
+ }
2906
+ function assertPushAllowed(input) {
2907
+ if (input.ownership === "owned")
2908
+ return;
2909
+ if (!isManagedBranch(input.remoteBranch)) {
2910
+ throw new RemotePushRefusedError(input.remoteBranch, `this repository is attached, so Work only pushes branches it creates under '${MANAGED_BRANCH_PREFIX}'. Open a pull request instead.`);
2911
+ }
2912
+ if (input.force) {
2913
+ throw new RemotePushRefusedError(input.remoteBranch, "Work never rewrites history in an attached repository.");
2914
+ }
2915
+ }
2916
+ async function pushToRemote(opts) {
2917
+ const { ref, remoteBranch } = opts;
2918
+ for (const name of [ref, remoteBranch]) {
2919
+ if (!name || /[:\s+]|^-|^refs\/heads\//.test(name)) {
2920
+ throw new RemotePushRefusedError(name, "not a plain branch or ref name.");
2921
+ }
2922
+ }
2923
+ assertPushAllowed(opts);
2924
+ if (opts.native) {
2925
+ await nativeGit(opts.repoPath, [
2926
+ "push",
2927
+ ...opts.force ? ["--force-with-lease"] : [],
2928
+ opts.url,
2929
+ `${ref}:refs/heads/${remoteBranch}`
2930
+ ], opts.credentials ? { ...opts.credentials, url: opts.url } : undefined);
2931
+ return;
2932
+ }
2933
+ await git5.push({
2934
+ fs: nodeFs5,
2935
+ http,
2936
+ dir: opts.repoPath,
2937
+ url: opts.url,
2938
+ ref,
2939
+ remoteRef: `refs/heads/${remoteBranch}`,
2940
+ force: opts.force ?? false,
2941
+ onAuth: onAuthFor(opts.credentials)
2942
+ });
2943
+ }
2944
+ async function fetchFromRemote(opts) {
2945
+ const remote = "catamorphic-network";
2946
+ await git5.addRemote({
2947
+ fs: nodeFs5,
2948
+ dir: opts.repoPath,
2949
+ remote,
2950
+ url: opts.url,
2951
+ force: true
2952
+ });
2953
+ try {
2954
+ const result = await git5.fetch({
2955
+ fs: nodeFs5,
2956
+ http,
2957
+ dir: opts.repoPath,
2958
+ url: opts.url,
2959
+ remote,
2960
+ ref: opts.branch,
2961
+ remoteRef: opts.branch,
2962
+ singleBranch: true,
2963
+ tags: false,
2964
+ onAuth: onAuthFor(opts.credentials)
2965
+ });
2966
+ return { sha: result.fetchHead };
2967
+ } catch (err) {
2968
+ if (err instanceof git5.Errors.NotFoundError && err.data.what === opts.branch) {
2969
+ return { sha: null };
2970
+ }
2971
+ throw err;
2972
+ }
2973
+ }
2974
+ // src/network-sync.ts
2975
+ init_native_git();
2976
+ init_native_project_repo();
2977
+ import nodeFs6 from "node:fs";
2978
+ import { MANAGED_BRANCH_PREFIX as MANAGED_BRANCH_PREFIX2 } from "@catamorphic/workflow/project-layout";
2979
+ import git6 from "isomorphic-git";
2980
+ async function syncWithNetworkRemote(opts) {
2981
+ const { dev } = opts;
2982
+ const dir = dev.repoPath;
2983
+ const owned = opts.ownership === "owned";
2984
+ const currentBranch = await dev.currentBranch();
2985
+ if (dev instanceof NativeProjectRepo) {
2986
+ if (currentBranch === "HEAD")
2987
+ return { status: "no-op", localSha: null, remoteSha: null };
2988
+ const localSha = await dev.resolveRef();
2989
+ const auth = opts.credentials ? { ...opts.credentials, url: opts.url } : undefined;
2990
+ const target = (await nativeGit(dir, [
2991
+ "config",
2992
+ "--get",
2993
+ `branch.${currentBranch}.merge`
2994
+ ]).catch(() => "")).trim().replace(/^refs\/heads\//, "") || currentBranch;
2995
+ const remote = (await nativeGit(dir, ["ls-remote", opts.url, `refs/heads/${target}`], auth)).trim();
2996
+ const remoteSha = remote.split(/\s+/)[0] || null;
2997
+ const push = async () => {
2998
+ if (!owned)
2999
+ return { status: "ahead", localSha, remoteSha };
3000
+ await pushToRemote({
3001
+ repoPath: dir,
3002
+ native: true,
3003
+ url: opts.url,
3004
+ credentials: opts.credentials,
3005
+ ownership: opts.ownership,
3006
+ ref: currentBranch,
3007
+ remoteBranch: target
3008
+ });
3009
+ return { status: "pushed", localSha, remoteSha: localSha };
3010
+ };
3011
+ if (!remoteSha)
3012
+ return push();
3013
+ if (remoteSha === localSha)
3014
+ return { status: "up-to-date", localSha, remoteSha };
3015
+ await nativeGit(dir, ["fetch", opts.url, `refs/heads/${target}`], auth);
3016
+ if (await nativeGit(dir, [
3017
+ "merge-base",
3018
+ "--is-ancestor",
3019
+ remoteSha,
3020
+ localSha
3021
+ ]).then(() => true, () => false)) {
3022
+ return push();
3023
+ }
3024
+ if (!await nativeGit(dir, [
3025
+ "merge-base",
3026
+ "--is-ancestor",
3027
+ localSha,
3028
+ remoteSha
3029
+ ]).then(() => true, () => false)) {
3030
+ return { status: "diverged", localSha, remoteSha };
3031
+ }
3032
+ if ((await dev.status()).dirty)
3033
+ return { status: "deferred", localSha, remoteSha };
3034
+ await nativeGit(dir, ["merge", "--ff-only", remoteSha]);
3035
+ return { status: "pulled", localSha: remoteSha, remoteSha };
3036
+ }
3037
+ if (currentBranch !== "main") {
3038
+ return { status: "no-op", localSha: null, remoteSha: null };
3039
+ }
3040
+ const localSha = await dev.resolveRef("refs/heads/main");
3041
+ const { sha: remoteSha } = await fetchFromRemote({
3042
+ repoPath: dir,
3043
+ url: opts.url,
3044
+ credentials: opts.credentials,
3045
+ branch: opts.remoteBranch
3046
+ });
3047
+ const push = (remoteBranch) => pushToRemote({
3048
+ repoPath: dir,
3049
+ url: opts.url,
3050
+ credentials: opts.credentials,
3051
+ ownership: opts.ownership,
3052
+ ref: "main",
3053
+ remoteBranch
3054
+ });
3055
+ if (!remoteSha) {
3056
+ if (!owned)
3057
+ return { status: "ahead", localSha, remoteSha };
3058
+ await push(opts.remoteBranch);
3059
+ return { status: "pushed", localSha, remoteSha: localSha };
3060
+ }
3061
+ if (remoteSha === localSha) {
3062
+ return { status: "up-to-date", localSha, remoteSha };
3063
+ }
3064
+ const isDescendent = (oid, ancestor) => git6.isDescendent({ fs: nodeFs6, dir, oid, ancestor, depth: -1 }).catch(() => false);
3065
+ if (await isDescendent(localSha, remoteSha)) {
3066
+ if (!owned)
3067
+ return { status: "ahead", localSha, remoteSha };
3068
+ await push(opts.remoteBranch);
3069
+ return { status: "pushed", localSha, remoteSha: localSha };
3070
+ }
3071
+ const behind = await isDescendent(remoteSha, localSha);
3072
+ if (!behind && !owned)
3073
+ return { status: "diverged", localSha, remoteSha };
3074
+ const { dirty } = await dev.status();
3075
+ if (dirty)
3076
+ return { status: "deferred", localSha, remoteSha };
3077
+ if (behind) {
3078
+ await git6.writeRef({
3079
+ fs: nodeFs6,
3080
+ dir,
3081
+ ref: "refs/heads/main",
3082
+ value: remoteSha,
3083
+ force: true
3084
+ });
3085
+ await git6.checkout({ fs: nodeFs6, dir, ref: "main", force: true });
3086
+ return { status: "pulled", localSha: remoteSha, remoteSha };
3087
+ }
3088
+ try {
3089
+ const merge = await git6.merge({
3090
+ fs: nodeFs6,
3091
+ dir,
3092
+ ours: "main",
3093
+ theirs: remoteSha,
3094
+ author: opts.author,
3095
+ committer: opts.author,
3096
+ fastForward: true,
3097
+ abortOnConflict: true,
3098
+ message: `Merge remote ${opts.remoteBranch} into main`
3099
+ });
3100
+ await git6.checkout({ fs: nodeFs6, dir, ref: "main", force: true });
3101
+ const mergedSha = merge.oid ?? await dev.resolveRef("refs/heads/main");
3102
+ await push(opts.remoteBranch);
3103
+ return { status: "merged", localSha: mergedSha, remoteSha: mergedSha };
3104
+ } catch (err) {
3105
+ if (err?.code !== "MergeConflictError")
3106
+ throw err;
3107
+ const rescueBranch = rescueBranchName(opts.now ?? new Date);
3108
+ await push(rescueBranch);
3109
+ return { status: "diverged", localSha, remoteSha, rescueBranch };
3110
+ }
3111
+ }
3112
+ function rescueBranchName(now) {
3113
+ const pad = (n) => String(n).padStart(2, "0");
3114
+ return `${MANAGED_BRANCH_PREFIX2}diverged-${now.getUTCFullYear()}-${pad(now.getUTCMonth() + 1)}-${pad(now.getUTCDate())}_${pad(now.getUTCHours())}-${pad(now.getUTCMinutes())}`;
3115
+ }
3116
+ // src/object-remote-backend.ts
3117
+ init_git_object_codec();
3118
+ import { randomUUID } from "node:crypto";
3119
+ init_ref_names();
3120
+ var UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3121
+ function assertUuid3(value) {
3122
+ if (!UUID_RE3.test(value)) {
3123
+ throw new Error(`Invalid UUID: ${value}`);
3124
+ }
3125
+ }
3126
+ var SHA_RE = /^[0-9a-f]{40}$/;
3127
+ var REF_RE = /^refs\/[A-Za-z0-9._/-]+$/;
3128
+ function assertRefName(ref) {
3129
+ if (!REF_RE.test(ref) || !isValidRefName(ref))
3130
+ throw new InvalidRefNameError(ref);
3131
+ }
3132
+ async function probeConditionalWrites(input) {
3133
+ const { store, key } = input;
3134
+ const refused = async (write) => write().then(() => false, (error) => {
3135
+ if (error instanceof PreconditionFailedError)
3136
+ return true;
3137
+ throw error;
3138
+ });
3139
+ try {
3140
+ await store.put(key, new TextEncoder().encode(`probe ${randomUUID()}`));
3141
+ const stale = await store.get(key);
3142
+ await store.put(key, new TextEncoder().encode(`probe ${randomUUID()}`));
3143
+ const entry = await store.get(key);
3144
+ if (!stale || !entry)
3145
+ return "the store did not keep a written object";
3146
+ if (stale.etag === entry.etag)
3147
+ return "the store kept an object's ETag when its content changed";
3148
+ if (!await refused(() => store.put(key, new TextEncoder().encode("again"), {
3149
+ ifNoneMatch: "*"
3150
+ })))
3151
+ return "the store ignores If-None-Match on writes";
3152
+ if (!await refused(() => store.delete(key, { ifMatch: stale.etag })) || !await store.has(key))
3153
+ return "the store ignores If-Match on deletes, so a draft could be deleted after another replica moved it";
3154
+ await store.delete(key, { ifMatch: entry.etag });
3155
+ if (await store.has(key))
3156
+ return "the store did not delete an object whose ETag matched";
3157
+ return null;
3158
+ } finally {
3159
+ await store.delete(key).catch(() => {});
3160
+ }
3161
+ }
3162
+
3163
+ class ObjectRemoteBackend {
3164
+ store;
3165
+ keyPrefix;
3166
+ draftCheck;
3167
+ constructor(opts) {
3168
+ this.store = opts.store;
3169
+ this.keyPrefix = opts.keyPrefix ?? "";
3170
+ }
3171
+ basePath(tenantId, projectId) {
3172
+ assertUuid3(tenantId);
3173
+ assertUuid3(projectId);
3174
+ return `${this.keyPrefix}${tenantId}/${projectId}`;
3175
+ }
3176
+ markerKey(tenantId, projectId) {
3177
+ return `${this.basePath(tenantId, projectId)}/repo.json`;
3178
+ }
3179
+ async initRemote(tenantId, projectId) {
3180
+ const marker = new TextEncoder().encode(JSON.stringify({ createdAt: new Date().toISOString() }));
3181
+ try {
3182
+ await this.store.put(this.markerKey(tenantId, projectId), marker, {
3183
+ ifNoneMatch: "*"
3184
+ });
3185
+ } catch (err) {
3186
+ if (!(err instanceof PreconditionFailedError))
3187
+ throw err;
3188
+ }
3189
+ }
3190
+ async deleteRemote(tenantId, projectId) {
3191
+ await this.store.deletePrefix(`${this.basePath(tenantId, projectId)}/`);
3192
+ }
3193
+ async exists(tenantId, projectId) {
3194
+ return this.store.has(this.markerKey(tenantId, projectId));
3195
+ }
3196
+ draftSupport() {
3197
+ this.draftCheck ??= probeConditionalWrites({
3198
+ store: this.store,
3199
+ key: `${this.keyPrefix}conformance/${randomUUID()}`
3200
+ }).then((failure) => failure ? { supported: false, reason: failure } : { supported: true }, (error) => {
3201
+ this.draftCheck = undefined;
3202
+ throw error;
3203
+ });
3204
+ return this.draftCheck;
3205
+ }
3206
+ async withOrigin(tenantId, projectId, fn) {
3207
+ return fn(new ObjectOriginRepo({
3208
+ store: this.store,
3209
+ basePath: this.basePath(tenantId, projectId)
3210
+ }));
3211
+ }
3212
+ }
3213
+
3214
+ class ObjectOriginRepo {
3215
+ store;
3216
+ basePath;
3217
+ gitdir;
3218
+ constructor(opts) {
3219
+ this.store = opts.store;
3220
+ this.basePath = opts.basePath;
3221
+ this.gitdir = `objectstore://${opts.basePath}`;
3222
+ }
3223
+ refKey(ref) {
3224
+ assertRefName(ref);
3225
+ return `${this.basePath}/${ref}`;
3226
+ }
3227
+ objectKey(sha) {
3228
+ if (!SHA_RE.test(sha)) {
3229
+ throw new Error(`Invalid object sha: ${sha}`);
3230
+ }
3231
+ return `${this.basePath}/objects/${sha}`;
3232
+ }
3233
+ async resolveRef(ref) {
3234
+ const entry = await this.store.get(this.refKey(ref));
3235
+ if (!entry)
3236
+ return null;
3237
+ const sha = new TextDecoder().decode(entry.data).trim();
3238
+ return SHA_RE.test(sha) ? sha : null;
3239
+ }
3240
+ async listRefs(prefix) {
3241
+ const normalized = prefix.endsWith("/") ? prefix : `${prefix}/`;
3242
+ assertRefName(normalized.slice(0, -1));
3243
+ const keys = await this.store.list(`${this.basePath}/${normalized}`);
3244
+ const entries = await Promise.all(keys.map(async (key) => {
3245
+ const ref = key.slice(this.basePath.length + 1);
3246
+ const sha = await this.resolveRef(ref);
3247
+ return sha ? { ref, sha } : null;
3248
+ }));
3249
+ return entries.filter((entry) => entry !== null);
3250
+ }
3251
+ async updateRef(opts) {
3252
+ const key = this.refKey(opts.ref);
3253
+ const body = new TextEncoder().encode(opts.sha);
3254
+ if (opts.expected === undefined) {
3255
+ await this.store.put(key, body);
3256
+ return;
3257
+ }
3258
+ const expected = opts.expected;
3259
+ const moved = async () => {
3260
+ throw new RefMovedError({
3261
+ ref: opts.ref,
3262
+ expected,
3263
+ actual: await this.resolveRef(opts.ref)
3264
+ });
3265
+ };
3266
+ if (opts.expected === null) {
3267
+ try {
3268
+ await this.store.put(key, body, { ifNoneMatch: "*" });
3269
+ } catch (err) {
3270
+ if (err instanceof PreconditionFailedError)
3271
+ await moved();
3272
+ throw err;
3273
+ }
3274
+ return;
3275
+ }
3276
+ const currentEntry = await this.store.get(key);
3277
+ const currentSha = currentEntry ? new TextDecoder().decode(currentEntry.data).trim() : null;
3278
+ if (!currentEntry || currentSha !== opts.expected) {
3279
+ await moved();
3280
+ return;
3281
+ }
3282
+ try {
3283
+ await this.store.put(key, body, { ifMatch: currentEntry.etag });
3284
+ } catch (err) {
3285
+ if (err instanceof PreconditionFailedError)
3286
+ await moved();
3287
+ throw err;
3288
+ }
3289
+ }
3290
+ async deleteRef(input) {
3291
+ const key = this.refKey(input.ref);
3292
+ if (input.expected === undefined) {
3293
+ await this.store.delete(key);
3294
+ return;
3295
+ }
3296
+ const entry = await this.store.get(key);
3297
+ const actual = entry ? new TextDecoder().decode(entry.data).trim() : null;
3298
+ const moved = () => new RefMovedError({
3299
+ ref: input.ref,
3300
+ expected: input.expected ?? null,
3301
+ actual
3302
+ });
3303
+ if (!entry || actual !== input.expected)
3304
+ throw moved();
3305
+ try {
3306
+ await this.store.delete(key, { ifMatch: entry.etag });
3307
+ } catch (err) {
3308
+ if (err instanceof PreconditionFailedError)
3309
+ throw moved();
3310
+ throw err;
3311
+ }
3312
+ }
3313
+ async hasObject(sha) {
3314
+ return this.store.has(this.objectKey(sha));
3315
+ }
3316
+ async readObject(sha) {
3317
+ const entry = await this.store.get(this.objectKey(sha));
3318
+ if (!entry) {
3319
+ throw new Error(`Object not found: ${sha}`);
3320
+ }
3321
+ return unwrapObject(entry.data);
3322
+ }
3323
+ async writeObject(opts) {
3324
+ const { wrapped, sha } = wrapObject(opts);
3325
+ if (!await this.hasObject(sha)) {
3326
+ await this.store.put(this.objectKey(sha), wrapped);
3327
+ }
3328
+ return sha;
3329
+ }
3330
+ async log(ref, maxCount = 50) {
3331
+ const tip = await this.resolveRef(ref);
3332
+ if (!tip)
3333
+ return [];
3334
+ const commits = [];
3335
+ const seen = new Set;
3336
+ const queue = [tip];
3337
+ while (queue.length > 0 && commits.length < maxCount) {
3338
+ const sha = queue.shift();
3339
+ if (!sha || seen.has(sha))
3340
+ continue;
3341
+ seen.add(sha);
3342
+ const entry = await this.store.get(this.objectKey(sha));
3343
+ if (!entry)
3344
+ break;
3345
+ const obj = unwrapObject(entry.data);
3346
+ if (obj.type !== "commit")
3347
+ break;
3348
+ const commit = parseCommit(obj.data);
3349
+ commits.push({
3350
+ sha,
3351
+ message: commit.message,
3352
+ author: { name: commit.author.name, email: commit.author.email },
3353
+ timestamp: commit.author.timestamp
3354
+ });
3355
+ queue.push(...commit.parents);
3356
+ }
3357
+ return commits.sort((a, b) => b.timestamp - a.timestamp);
3358
+ }
3359
+ }
3360
+ // src/origin-draft.ts
3361
+ init_file_reads();
3362
+ init_git_sync();
3363
+ init_origin_objects();
3364
+ init_project_repo();
3365
+ import path7 from "node:path";
3366
+ import {
3367
+ DRAFT_REF_PREFIX,
3368
+ draftRef,
3369
+ PUBLISHED_REF_PREFIX as PUBLISHED_REF_PREFIX2,
3370
+ publishedRef as publishedRef4,
3371
+ SYSTEM_COMMIT_AUTHOR
3372
+ } from "@catamorphic/workflow/project-layout";
3373
+ init_ref_names();
3374
+ var MAIN = "refs/heads/main";
3375
+ var BRANCHES = "refs/heads/";
3376
+ var SESSION_BRANCHES = `${BRANCHES}sessions/`;
3377
+ var SHA_RE2 = /^[0-9a-f]{40}$/;
3378
+ var MAX_ATTEMPTS = 8;
3379
+
3380
+ class DraftBusyError extends Error {
3381
+ constructor() {
3382
+ super("The project changed while saving. Try again.");
3383
+ this.name = "DraftBusyError";
3384
+ }
3385
+ }
3386
+
3387
+ class DraftContentChangedError extends Error {
3388
+ constructor(path) {
3389
+ super(`${path} changed since it was read`);
3390
+ this.name = "DraftContentChangedError";
3391
+ }
3392
+ }
3393
+
3394
+ class DraftRefNotAllowedError extends Error {
3395
+ constructor(ref) {
3396
+ super(`Unknown ref: ${ref}`);
3397
+ this.name = "DraftRefNotAllowedError";
3398
+ }
3399
+ }
3400
+
3401
+ class InvalidBaseError extends Error {
3402
+ constructor(base) {
3403
+ super(`${base} is not a commit of the published program`);
3404
+ this.name = "InvalidBaseError";
3405
+ }
3406
+ }
3407
+
3408
+ class NoDraftError extends Error {
3409
+ constructor() {
3410
+ super("This view of the program has no draft to change");
3411
+ this.name = "NoDraftError";
3412
+ }
3413
+ }
3414
+
3415
+ class DraftUnresolvedError extends Error {
3416
+ conflicts;
3417
+ constructor(conflicts) {
3418
+ super(`Resolve ${conflicts.map((conflict) => conflict.path).join(", ")} too.`);
3419
+ this.name = "DraftUnresolvedError";
3420
+ this.conflicts = conflicts;
3421
+ }
3422
+ }
3423
+
3424
+ class DraftsUnsupportedError extends Error {
3425
+ constructor(reason) {
3426
+ super(`Member drafts are unavailable on this project storage: ${reason}`);
3427
+ this.name = "DraftsUnsupportedError";
3428
+ }
3429
+ }
3430
+
3431
+ class OriginDraftRepo {
3432
+ projectId;
3433
+ ref;
3434
+ tenantId;
3435
+ remote;
3436
+ cache;
3437
+ author;
3438
+ head;
3439
+ readable = new Set;
3440
+ constructor(args) {
3441
+ this.tenantId = args.tenantId;
3442
+ this.projectId = args.projectId;
3443
+ this.ref = args.externalUserId === null ? null : draftRef(args.externalUserId);
3444
+ this.remote = args.remote;
3445
+ this.cache = args.cache;
3446
+ this.author = args.author ?? SYSTEM_COMMIT_AUTHOR;
3447
+ }
3448
+ withObjects(fn) {
3449
+ return this.remote.withOrigin(this.tenantId, this.projectId, (origin) => fn(new OriginObjects(origin, this.cache)));
3450
+ }
3451
+ async attempt(fn) {
3452
+ try {
3453
+ return await this.withObjects(async (objects) => {
3454
+ try {
3455
+ return await fn(objects);
3456
+ } catch (error) {
3457
+ if (error instanceof RefMovedError)
3458
+ return null;
3459
+ throw error;
3460
+ }
3461
+ });
3462
+ } catch (error) {
3463
+ if (error instanceof RefMovedError)
3464
+ return null;
3465
+ throw error;
3466
+ }
3467
+ }
3468
+ async tips(objects) {
3469
+ const [draft, main] = await Promise.all([
3470
+ this.ref ? objects.origin.resolveRef(this.ref) : null,
3471
+ objects.origin.resolveRef(MAIN)
3472
+ ]);
3473
+ return { draft, main };
3474
+ }
3475
+ draftRefOrThrow() {
3476
+ if (!this.ref)
3477
+ throw new NoDraftError;
3478
+ return this.ref;
3479
+ }
3480
+ async mayReadCommit(objects, sha) {
3481
+ if (this.readable.has(sha))
3482
+ return true;
3483
+ const { draft, main } = await this.tips(objects);
3484
+ const own = [draft, main].filter((tip) => tip !== null);
3485
+ let reachable = await objects.isReachable({ sha, tips: own });
3486
+ if (!reachable) {
3487
+ const branches = (await objects.origin.listRefs(BRANCHES)).filter((entry) => !isPrivateRef(entry.ref) && entry.ref !== MAIN).map((entry) => entry.sha);
3488
+ reachable = branches.length > 0 && await objects.isReachable({ sha, tips: branches });
3489
+ }
3490
+ if (reachable)
3491
+ this.readable.add(sha);
3492
+ return reachable;
3493
+ }
3494
+ async resolveIn(objects, ref) {
3495
+ if (ref === "HEAD" || ref === this.ref) {
3496
+ if (!this.head) {
3497
+ const { draft, main } = await this.tips(objects);
3498
+ this.head = { sha: draft ?? main };
3499
+ }
3500
+ return this.head.sha;
3501
+ }
3502
+ if (SHA_RE2.test(ref))
3503
+ return await this.mayReadCommit(objects, ref) ? ref : null;
3504
+ assertValidRefName(ref);
3505
+ const full = ref.startsWith(`${PUBLISHED_REF_PREFIX2}/`) ? `${BRANCHES}${ref.slice(PUBLISHED_REF_PREFIX2.length + 1)}` : ref.startsWith("refs/") ? ref : `${BRANCHES}${ref}`;
3506
+ assertValidRefName(full);
3507
+ if (!full.startsWith(BRANCHES) || isPrivateRef(full))
3508
+ throw new DraftRefNotAllowedError(ref);
3509
+ return objects.origin.resolveRef(full);
3510
+ }
3511
+ async treeAt(objects, ref) {
3512
+ const sha = await this.resolveIn(objects, ref);
3513
+ if (!sha)
3514
+ throw new Error(`Unknown ref: ${ref}`);
3515
+ return (await objects.commit(sha)).tree;
3516
+ }
3517
+ async resolveRef(ref = "HEAD") {
3518
+ const sha = await this.withObjects((objects) => this.resolveIn(objects, ref));
3519
+ if (!sha)
3520
+ throw new Error(`Unknown ref: ${ref}`);
3521
+ return sha;
3522
+ }
3523
+ async readFileBytes(filePath) {
3524
+ const normalized = normalizePath(filePath);
3525
+ return this.withObjects(async (objects) => {
3526
+ const head = await this.resolveIn(objects, "HEAD");
3527
+ if (!head)
3528
+ return null;
3529
+ const entry = await objects.entry((await objects.commit(head)).tree, normalized);
3530
+ if (!entry || isTreeMode(entry.mode))
3531
+ return null;
3532
+ if (entry.mode === SYMLINK_MODE)
3533
+ throw new DraftPathError({ code: "ELOOP", path: normalized });
3534
+ return objects.blob(entry.oid);
3535
+ });
3536
+ }
3537
+ async readFile(filePath) {
3538
+ const bytes = await this.readFileBytes(filePath);
3539
+ if (!bytes)
3540
+ throw new DraftPathError({
3541
+ code: "ENOENT",
3542
+ path: normalizePath(filePath)
3543
+ });
3544
+ return new TextDecoder().decode(bytes);
3545
+ }
3546
+ async listFiles(opts) {
3547
+ const prefix = opts?.prefix ? `${normalizePath(opts.prefix).replace(/\/+$/, "")}/` : undefined;
3548
+ return this.listFilesAtRef("HEAD", prefix ? { prefix } : undefined);
3549
+ }
3550
+ async readAllFiles(options) {
3551
+ return this.readAllFilesAtRef("HEAD", options);
3552
+ }
3553
+ async listBlobsAtRef(ref, opts) {
3554
+ return this.withObjects(async (objects) => {
3555
+ const sha = await this.resolveIn(objects, ref);
3556
+ if (!sha)
3557
+ return [];
3558
+ const files = await objects.files((await objects.commit(sha)).tree, opts?.prefix);
3559
+ return [...files].map(([filePath, file]) => ({ path: filePath, oid: file.oid })).sort((a, b) => a.path.localeCompare(b.path));
3560
+ });
3561
+ }
3562
+ async listFilesAtRef(ref, opts) {
3563
+ return (await this.listBlobsAtRef(ref, opts)).map((entry) => entry.path);
3564
+ }
3565
+ async readBlobAtRef(ref, filePath, options) {
3566
+ const normalized = normalizePath(filePath);
3567
+ const blob = await this.withObjects(async (objects) => {
3568
+ const sha = await this.resolveIn(objects, ref);
3569
+ if (!sha)
3570
+ return null;
3571
+ const entry = await objects.entry((await objects.commit(sha)).tree, normalized).catch(() => null);
3572
+ if (!entry || isTreeMode(entry.mode))
3573
+ return null;
3574
+ return objects.blob(entry.oid);
3575
+ });
3576
+ if (blob && options?.maxBytes !== undefined && blob.byteLength > options.maxBytes)
3577
+ throw new Error(`Project file '${normalized}' exceeds the ${options.maxBytes}-byte snapshot limit`);
3578
+ return blob;
3579
+ }
3580
+ async readAllFilesAtRef(ref, options) {
3581
+ return this.snapshotAt(ref, undefined, options);
3582
+ }
3583
+ async readFilesAtRef(ref, opts) {
3584
+ return this.snapshotAt(ref, opts.prefix);
3585
+ }
3586
+ async snapshotAt(ref, prefix, options) {
3587
+ return this.withObjects(async (objects) => {
3588
+ const sha = await this.resolveIn(objects, ref);
3589
+ if (!sha)
3590
+ return {};
3591
+ const files = await objects.files((await objects.commit(sha)).tree, prefix);
3592
+ return readFileSnapshot({
3593
+ paths: [...files.keys()].sort(),
3594
+ options,
3595
+ read: async (file, maxBytes) => {
3596
+ const entry = files.get(file);
3597
+ if (!entry)
3598
+ return null;
3599
+ const blob = await objects.blob(entry.oid);
3600
+ if (blob.byteLength > maxBytes)
3601
+ throw new Error(`Project file '${file}' exceeds the ${maxBytes}-byte snapshot limit`);
3602
+ return new TextDecoder().decode(blob);
3603
+ }
3604
+ });
3605
+ });
3606
+ }
3607
+ async writeFile(filePath, content, opts) {
3608
+ await this.write({
3609
+ changes: [{ path: filePath, content }],
3610
+ message: opts?.message
3611
+ });
3612
+ }
3613
+ async deleteFile(filePath, opts) {
3614
+ await this.write({
3615
+ changes: [{ path: filePath, delete: true }],
3616
+ message: opts?.message
3617
+ });
3618
+ }
3619
+ async write(input) {
3620
+ const pending = new Map;
3621
+ for (const change of input.changes)
3622
+ pending.set(normalizePath(change.path), "delete" in change ? null : typeof change.content === "string" ? new TextEncoder().encode(change.content) : change.content);
3623
+ const draftRefName = this.draftRefOrThrow();
3624
+ if (pending.size === 0)
3625
+ return null;
3626
+ const message = input.message ?? `Draft: ${[...pending.keys()].slice(0, 3).join(", ")}${pending.size > 3 ? ", ..." : ""}`;
3627
+ const written = [...pending].filter((entry) => entry[1] !== null);
3628
+ const oids = await this.withObjects((objects) => objects.writeBlobs(written.map(([, content]) => content)));
3629
+ const blobs = new Map(written.map(([file], index) => [file, oids[index]]));
3630
+ for (let attempt = 0;attempt < MAX_ATTEMPTS; attempt++) {
3631
+ const outcome = await this.attempt(async (objects) => {
3632
+ const { draft, main } = await this.tips(objects);
3633
+ const parent = draft ?? main;
3634
+ const baseTree = parent ? (await objects.commit(parent)).tree : null;
3635
+ for (const [file, content] of Object.entries(input.expected ?? {})) {
3636
+ const entry = baseTree ? await objects.entry(baseTree, normalizePath(file)) : null;
3637
+ const current = entry && !isTreeMode(entry.mode) ? new TextDecoder().decode(await objects.blob(entry.oid)) : null;
3638
+ if (current !== content)
3639
+ throw new DraftContentChangedError(file);
3640
+ }
3641
+ const rules = new Map;
3642
+ const ignored = [];
3643
+ const changes = new Map;
3644
+ for (const [file] of pending) {
3645
+ if (await objects.isIgnored(baseTree, file, rules)) {
3646
+ ignored.push(file);
3647
+ continue;
3648
+ }
3649
+ const oid = blobs.get(file);
3650
+ changes.set(file, oid ? { oid } : null);
3651
+ }
3652
+ if (ignored.length > 0 && !input.skipIgnored)
3653
+ throw new DraftIgnoredPathError(ignored);
3654
+ if (changes.size === 0)
3655
+ return { sha: parent };
3656
+ const tree = await objects.writeTree(baseTree, changes, {
3657
+ skipMissingDeletes: input.skipMissingDeletes
3658
+ });
3659
+ if (tree === baseTree)
3660
+ return { sha: parent };
3661
+ const sha = await objects.writeCommit({
3662
+ tree,
3663
+ parents: parent ? [parent] : [],
3664
+ author: this.author,
3665
+ message
3666
+ });
3667
+ await objects.origin.updateRef({
3668
+ ref: draftRefName,
3669
+ sha,
3670
+ expected: draft
3671
+ });
3672
+ return { sha };
3673
+ });
3674
+ if (outcome) {
3675
+ this.head = { sha: outcome.sha };
3676
+ return outcome.sha;
3677
+ }
3678
+ }
3679
+ throw new DraftBusyError;
3680
+ }
3681
+ async log(options) {
3682
+ return this.withObjects(async (objects) => {
3683
+ const tip = await this.resolveIn(objects, options?.ref ?? "HEAD");
3684
+ return tip ? objects.log(tip, options?.maxCount ?? 50) : [];
3685
+ });
3686
+ }
3687
+ async status() {
3688
+ return this.withObjects(async (objects) => {
3689
+ const { draft, main } = await this.tips(objects);
3690
+ const clean = {
3691
+ branch: "main",
3692
+ dirty: false,
3693
+ modifiedFiles: [],
3694
+ ahead: 0,
3695
+ behind: 0,
3696
+ baseCommit: main,
3697
+ remoteHead: main
3698
+ };
3699
+ if (!draft)
3700
+ return clean;
3701
+ const { base, ahead, behind } = main ? await objects.compare(draft, main) : { base: null, ahead: 0, behind: 0 };
3702
+ const changes = await objects.diffTrees(base ? (await objects.commit(base)).tree : null, (await objects.commit(draft)).tree);
3703
+ return {
3704
+ ...clean,
3705
+ dirty: changes.length > 0,
3706
+ modifiedFiles: changes.map((change) => change.path),
3707
+ ahead,
3708
+ behind,
3709
+ baseCommit: draft
3710
+ };
3711
+ });
3712
+ }
3713
+ async workdirDiff() {
3714
+ return this.withObjects(async (objects) => {
3715
+ const { draft, main } = await this.tips(objects);
3716
+ if (!draft)
3717
+ return [];
3718
+ const base = main ? (await objects.compare(draft, main)).base : null;
3719
+ return describeChanges({
3720
+ objects,
3721
+ before: base ? (await objects.commit(base)).tree : null,
3722
+ after: (await objects.commit(draft)).tree
3723
+ });
3724
+ });
3725
+ }
3726
+ async diff(opts) {
3727
+ return this.withObjects(async (objects) => describeChanges({
3728
+ objects,
3729
+ before: await this.treeAt(objects, opts.base),
3730
+ after: await this.treeAt(objects, opts.head)
3731
+ }));
3732
+ }
3733
+ async discard() {
3734
+ const ref = this.draftRefOrThrow();
3735
+ this.head = undefined;
3736
+ return this.withObjects(async (objects) => {
3737
+ if (!await objects.origin.resolveRef(ref))
3738
+ return false;
3739
+ await objects.origin.deleteRef({ ref });
3740
+ return true;
3741
+ });
3742
+ }
3743
+ async publish(input) {
3744
+ const ref = this.draftRefOrThrow();
3745
+ this.head = undefined;
3746
+ for (let attempt = 0;attempt < MAX_ATTEMPTS; attempt++) {
3747
+ const plan = await this.withObjects(async (objects) => {
3748
+ const { draft, main } = await this.tips(objects);
3749
+ const nothing = async () => {
3750
+ if (draft)
3751
+ await clearDraft(objects, ref, draft);
3752
+ return {
3753
+ kind: "done",
3754
+ done: {
3755
+ status: "nothing-to-deploy",
3756
+ commitSha: null,
3757
+ remoteSha: main,
3758
+ conflicts: []
3759
+ }
3760
+ };
3761
+ };
3762
+ if (!draft)
3763
+ return nothing();
3764
+ const draftTree = (await objects.commit(draft)).tree;
3765
+ if (!main)
3766
+ return { kind: "publish", draft, main, tree: draftTree };
3767
+ const { base } = await objects.compare(draft, main);
3768
+ const mainTree = (await objects.commit(main)).tree;
3769
+ let tree = draftTree;
3770
+ if (base !== main) {
3771
+ const merged = await mergeTrees({
3772
+ objects,
3773
+ base: base ? (await objects.commit(base)).tree : null,
3774
+ ours: draftTree,
3775
+ theirs: mainTree
3776
+ });
3777
+ if (merged.status === "conflict")
3778
+ return {
3779
+ kind: "done",
3780
+ done: {
3781
+ status: "conflict",
3782
+ commitSha: draft,
3783
+ remoteSha: main,
3784
+ conflicts: merged.conflicts
3785
+ }
3786
+ };
3787
+ tree = merged.tree;
3788
+ }
3789
+ if (tree === mainTree)
3790
+ return nothing();
3791
+ return { kind: "publish", draft, main, tree };
3792
+ });
3793
+ if (plan.kind === "done")
3794
+ return plan.done;
3795
+ const published = await this.attempt(async (objects) => {
3796
+ const mainTree = plan.main ? (await objects.commit(plan.main)).tree : null;
3797
+ input.guard?.((await objects.diffTrees(mainTree, plan.tree)).map((change) => change.path));
3798
+ const sha = await objects.writeCommit({
3799
+ tree: plan.tree,
3800
+ parents: plan.main ? [plan.main] : [],
3801
+ author: input.author,
3802
+ message: input.message
3803
+ });
3804
+ await objects.origin.updateRef({ ref: MAIN, sha, expected: plan.main });
3805
+ await clearDraft(objects, ref, plan.draft);
3806
+ return sha;
3807
+ });
3808
+ if (published)
3809
+ return {
3810
+ status: "deployed",
3811
+ commitSha: published,
3812
+ remoteSha: published,
3813
+ conflicts: []
3814
+ };
3815
+ }
3816
+ throw new DraftBusyError;
3817
+ }
3818
+ async pull() {
3819
+ return this.mergeMain({});
3820
+ }
3821
+ async resolveConflicts(input) {
3822
+ const resolutions = Object.fromEntries(Object.entries(input.resolutions).map(([file, content]) => [
3823
+ normalizePath(file),
3824
+ content
3825
+ ]));
3826
+ const result = await this.mergeMain({
3827
+ resolutions,
3828
+ message: input.message
3829
+ });
3830
+ if (result.status === "conflict")
3831
+ throw new DraftUnresolvedError(result.conflicts);
3832
+ if (!result.mergeCommit)
3833
+ throw new Error("There is no draft to resolve conflicts in");
3834
+ return result.mergeCommit;
3835
+ }
3836
+ async mergeMain(input) {
3837
+ const ref = this.draftRefOrThrow();
3838
+ this.head = undefined;
3839
+ for (let attempt = 0;attempt < MAX_ATTEMPTS; attempt++) {
3840
+ const plan = await this.withObjects(async (objects) => {
3841
+ const upToDate = (sha) => ({
3842
+ kind: "done",
3843
+ result: { status: "up-to-date", mergeCommit: sha, conflicts: [] }
3844
+ });
3845
+ const { draft, main } = await this.tips(objects);
3846
+ if (!draft || !main)
3847
+ return upToDate(draft ?? main);
3848
+ const { base } = await objects.compare(draft, main);
3849
+ const baseTree = base ? (await objects.commit(base)).tree : null;
3850
+ const draftTree = (await objects.commit(draft)).tree;
3851
+ const changed = (await objects.diffTrees(baseTree, draftTree)).length > 0;
3852
+ if (!changed && !input.resolutions) {
3853
+ await clearDraft(objects, ref, draft);
3854
+ return upToDate(main);
3855
+ }
3856
+ if (base === main && !input.resolutions)
3857
+ return upToDate(draft);
3858
+ const merged = await mergeTrees({
3859
+ objects,
3860
+ base: baseTree,
3861
+ ours: draftTree,
3862
+ theirs: (await objects.commit(main)).tree,
3863
+ resolutions: input.resolutions
3864
+ });
3865
+ if (merged.status === "conflict")
3866
+ return {
3867
+ kind: "done",
3868
+ result: {
3869
+ status: "conflict",
3870
+ mergeCommit: null,
3871
+ conflicts: merged.conflicts
3872
+ }
3873
+ };
3874
+ return { kind: "merged", draft, main, tree: merged.tree };
3875
+ });
3876
+ if (plan.kind === "done")
3877
+ return plan.result;
3878
+ const sha = await this.attempt(async (objects) => {
3879
+ const commit = await objects.writeCommit({
3880
+ tree: plan.tree,
3881
+ parents: [plan.draft, plan.main],
3882
+ author: this.author,
3883
+ message: input.message ?? "Merge published changes into draft"
3884
+ });
3885
+ await objects.origin.updateRef({
3886
+ ref,
3887
+ sha: commit,
3888
+ expected: plan.draft
3889
+ });
3890
+ return commit;
3891
+ });
3892
+ if (sha)
3893
+ return { status: "clean", mergeCommit: sha, conflicts: [] };
3894
+ }
3895
+ throw new DraftBusyError;
3896
+ }
3897
+ async dispose() {}
3898
+ }
3899
+ async function publishFilesToOrigin(input) {
3900
+ const files = Object.entries(input.files).map(([file, content]) => [normalizePath(file), new TextEncoder().encode(content)]);
3901
+ const withOrigin = (fn) => input.remote.withOrigin(input.tenantId, input.projectId, (origin) => fn(new OriginObjects(origin, input.cache)));
3902
+ const oids = await withOrigin((objects) => objects.writeBlobs(files.map(([, content]) => content)));
3903
+ const changes = new Map;
3904
+ files.forEach(([file], index) => {
3905
+ const oid = oids[index];
3906
+ if (oid)
3907
+ changes.set(file, { oid });
3908
+ });
3909
+ for (let attempt = 0;attempt < MAX_ATTEMPTS; attempt++) {
3910
+ const result = await withOrigin(async (objects) => {
3911
+ const main = await objects.origin.resolveRef(MAIN);
3912
+ const mainTree = main ? (await objects.commit(main)).tree : null;
3913
+ const rules = new Map;
3914
+ const ignored = [];
3915
+ for (const [file] of changes)
3916
+ if (await objects.isIgnored(mainTree, file, rules))
3917
+ ignored.push(file);
3918
+ if (ignored.length > 0)
3919
+ throw new DraftIgnoredPathError(ignored);
3920
+ let tree;
3921
+ if (input.base && main && input.base !== main) {
3922
+ if (!SHA_RE2.test(input.base) || !await objects.isReachable({ sha: input.base, tips: [main] }))
3923
+ throw new InvalidBaseError(input.base);
3924
+ const baseTree = (await objects.commit(input.base)).tree;
3925
+ const merged = await mergeTrees({
3926
+ objects,
3927
+ base: baseTree,
3928
+ ours: await objects.writeTree(baseTree, changes),
3929
+ theirs: mainTree ?? baseTree
3930
+ });
3931
+ if (merged.status === "conflict")
3932
+ return {
3933
+ status: "conflict",
3934
+ commitSha: input.base,
3935
+ remoteSha: main,
3936
+ conflicts: merged.conflicts
3937
+ };
3938
+ tree = merged.tree;
3939
+ } else {
3940
+ tree = await objects.writeTree(mainTree, changes);
3941
+ }
3942
+ if (tree === mainTree)
3943
+ return {
3944
+ status: "nothing-to-deploy",
3945
+ commitSha: null,
3946
+ remoteSha: main,
3947
+ conflicts: []
3948
+ };
3949
+ input.guard?.((await objects.diffTrees(mainTree, tree)).map((change) => change.path));
3950
+ const sha = await objects.writeCommit({
3951
+ tree,
3952
+ parents: main ? [main] : [],
3953
+ author: input.author,
3954
+ message: input.message
3955
+ });
3956
+ try {
3957
+ await objects.origin.updateRef({ ref: MAIN, sha, expected: main });
3958
+ } catch (error) {
3959
+ if (error instanceof RefMovedError)
3960
+ return null;
3961
+ throw error;
3962
+ }
3963
+ return {
3964
+ status: "deployed",
3965
+ commitSha: sha,
3966
+ remoteSha: sha,
3967
+ conflicts: []
3968
+ };
3969
+ }).catch((error) => {
3970
+ if (error instanceof RefMovedError)
3971
+ return null;
3972
+ throw error;
3973
+ });
3974
+ if (result)
3975
+ return result;
3976
+ }
3977
+ throw new DraftBusyError;
3978
+ }
3979
+ async function refreshPublished(input) {
3980
+ const branch = input.branch ?? "main";
3981
+ assertValidRefName(`${BRANCHES}${branch}`);
3982
+ if (input.repo instanceof OriginDraftRepo)
3983
+ return input.remote.withOrigin(input.tenantId, input.projectId, (origin) => origin.resolveRef(`${BRANCHES}${branch}`));
3984
+ const fetched = await fetchRemote({
3985
+ dev: input.repo,
3986
+ remote: input.remote,
3987
+ tenantId: input.tenantId,
3988
+ projectId: input.projectId,
3989
+ remoteBranch: branch
3990
+ });
3991
+ return fetched.sha ? input.repo.resolveRef(publishedRef4(branch)).catch(() => null) : null;
3992
+ }
3993
+ function isPrivateRef(ref) {
3994
+ const lower = ref.toLowerCase();
3995
+ return lower.startsWith(SESSION_BRANCHES) || lower.startsWith(`${DRAFT_REF_PREFIX}/`);
3996
+ }
3997
+ async function clearDraft(objects, ref, expected) {
3998
+ await objects.origin.deleteRef({ ref, expected }).catch((error) => {
3999
+ if (!(error instanceof RefMovedError))
4000
+ throw error;
4001
+ });
4002
+ }
4003
+ async function describeChanges(input) {
4004
+ const decode = async (oid) => oid ? new TextDecoder().decode(await input.objects.blob(oid)) : null;
4005
+ const changes = await input.objects.diffTrees(input.before, input.after);
4006
+ return Promise.all(changes.map(async (change) => {
4007
+ const before = await decode(change.before?.oid);
4008
+ const after = await decode(change.after?.oid);
4009
+ return {
4010
+ path: change.path,
4011
+ kind: before === null ? "added" : after === null ? "deleted" : "modified",
4012
+ before,
4013
+ after
4014
+ };
4015
+ }));
4016
+ }
4017
+ function normalizePath(filePath) {
4018
+ const slashed = filePath.replace(/\\/g, "/");
4019
+ if (slashed.startsWith("/"))
4020
+ throw new Error("Absolute paths not allowed");
4021
+ const normalized = path7.posix.normalize(slashed).replace(/^(\.\/)+/, "");
4022
+ assertSafePath(normalized);
4023
+ if (!normalized || normalized === ".")
4024
+ throw new DraftPathError({ code: "EISDIR", path: filePath });
4025
+ return normalized;
4026
+ }
4027
+
4028
+ // src/index.ts
4029
+ init_origin_objects();
4030
+ init_personal_files();
4031
+
4032
+ // src/project-manager.ts
4033
+ import fs8 from "node:fs/promises";
4034
+ import { tmpdir as tmpdir2 } from "node:os";
4035
+ import path9 from "node:path";
4036
+ import {
4037
+ PROJECT_GITIGNORE_PATH,
4038
+ PROJECT_MANIFEST_PATH
4039
+ } from "@catamorphic/workflow/project-layout";
4040
+ init_git_sync();
4041
+ init_native_git();
4042
+ init_native_project_repo();
4043
+ init_origin_objects();
4044
+ init_project_repo();
4045
+
4046
+ // src/workspace-mirror.ts
4047
+ init_native_git();
4048
+ import { execFile as execFile2 } from "node:child_process";
4049
+ import fs7 from "node:fs/promises";
4050
+ import { tmpdir } from "node:os";
4051
+ import path8 from "node:path";
4052
+ var COMMIT = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
4053
+ function parseWorkspaceRef(value) {
4054
+ const ref = value.trim();
4055
+ if (COMMIT.test(ref))
4056
+ return ref;
4057
+ if (ref.length === 0 || ref.length > 255 || ref.startsWith("-") || ref.startsWith("/") || ref.endsWith("/") || ref.endsWith(".") || ref.endsWith(".lock") || ref.includes("..") || ref.includes("//") || ref.includes("@{") || /[\s:~^?*[\\\u0000-\u001f\u007f+]/.test(ref)) {
4058
+ throw new Error(`'${value}' is not a branch, tag, commit, or full ref such as refs/pull/42/head`);
4059
+ }
4060
+ return ref;
4061
+ }
4062
+ function isCommitId(ref) {
4063
+ return COMMIT.test(ref);
4064
+ }
4065
+ var mirrorLocks = new Map;
4066
+ async function withMirrorLock(mirrorPath, work) {
4067
+ const previous = mirrorLocks.get(mirrorPath) ?? Promise.resolve();
4068
+ const next = previous.then(work, work);
4069
+ const settled = next.then(() => {
4070
+ return;
4071
+ }, () => {
4072
+ return;
4073
+ });
4074
+ mirrorLocks.set(mirrorPath, settled);
4075
+ try {
4076
+ return await next;
4077
+ } finally {
4078
+ if (mirrorLocks.get(mirrorPath) === settled)
4079
+ mirrorLocks.delete(mirrorPath);
4080
+ }
4081
+ }
4082
+ async function ensureMirror(mirrorPath) {
4083
+ const exists = await fs7.access(path8.join(mirrorPath, "HEAD")).then(() => true, () => false);
4084
+ if (exists)
4085
+ return;
4086
+ await fs7.mkdir(mirrorPath, { recursive: true });
4087
+ await nativeGit(mirrorPath, ["init", "--bare", "--quiet"]);
4088
+ await nativeGit(mirrorPath, ["config", "gc.auto", "0"]);
4089
+ }
4090
+ async function fetchIntoMirror(opts) {
4091
+ const ref = parseWorkspaceRef(opts.ref);
4092
+ assertPinRef(opts.pin);
4093
+ return withMirrorLock(opts.mirrorPath, async () => {
4094
+ await ensureMirror(opts.mirrorPath);
4095
+ const known = isCommitId(ref) && await nativeGit(opts.mirrorPath, [
4096
+ "cat-file",
4097
+ "-e",
4098
+ `${ref}^{commit}`
4099
+ ]).then(() => true, () => false);
4100
+ if (!known) {
4101
+ await nativeGit(opts.mirrorPath, [
4102
+ "fetch",
4103
+ "--quiet",
4104
+ "--no-tags",
4105
+ "--no-write-fetch-head",
4106
+ opts.url,
4107
+ `+${ref}:${opts.pin}`
4108
+ ], opts.credentials ? { ...opts.credentials, url: opts.url } : undefined).catch((error) => {
4109
+ throw new Error(`Could not fetch '${ref}' from the project's remote: ${gitErrorText(error)}`);
4110
+ });
4111
+ } else {
4112
+ await nativeGit(opts.mirrorPath, ["update-ref", opts.pin, ref]);
4113
+ }
4114
+ const commit = (await nativeGit(opts.mirrorPath, [
4115
+ "rev-parse",
4116
+ "--verify",
4117
+ `${opts.pin}^{commit}`
4118
+ ])).trim();
4119
+ return { commit };
4120
+ });
4121
+ }
4122
+ async function unpinMirrorRef(opts) {
4123
+ assertPinRef(opts.pin);
4124
+ const exists = await fs7.access(path8.join(opts.mirrorPath, "HEAD")).then(() => true, () => false);
4125
+ if (!exists)
4126
+ return;
4127
+ await withMirrorLock(opts.mirrorPath, () => nativeGit(opts.mirrorPath, ["update-ref", "-d", opts.pin]).catch(() => ""));
4128
+ }
4129
+ async function mirrorChangedFiles(opts) {
4130
+ const output = await nativeGit(opts.mirrorPath, [
4131
+ "diff",
4132
+ "--name-only",
4133
+ "--no-renames",
4134
+ "-z",
4135
+ opts.from,
4136
+ opts.to
4137
+ ]).catch(() => "");
4138
+ const all = output.split("\x00").filter(Boolean);
4139
+ return { files: all.slice(0, opts.limit ?? 50), total: all.length };
4140
+ }
4141
+ async function copyFromMirror(opts) {
4142
+ assertPinRef(opts.pin);
4143
+ assertPinRef(opts.into);
4144
+ await withMirrorLock(opts.mirrorPath, () => nativeGit(opts.repoPath, [
4145
+ "fetch",
4146
+ "--quiet",
4147
+ "--no-tags",
4148
+ "--no-write-fetch-head",
4149
+ opts.mirrorPath,
4150
+ `+${opts.pin}:${opts.into}`
4151
+ ]));
4152
+ }
4153
+ var MOVE_AUTHOR = [
4154
+ "-c",
4155
+ "user.name=Work",
4156
+ "-c",
4157
+ "user.email=system@work.software"
4158
+ ];
4159
+ async function moveCheckoutBase(opts) {
4160
+ await copyFromMirror({
4161
+ mirrorPath: opts.mirrorPath,
4162
+ pin: opts.pin,
4163
+ repoPath: opts.repoPath,
4164
+ into: "refs/work/base"
4165
+ });
4166
+ const head = async () => (await nativeGit(opts.repoPath, ["rev-parse", "HEAD"])).trim();
4167
+ if (opts.update === "reset") {
4168
+ await nativeGit(opts.repoPath, ["reset", "--quiet", "--hard", opts.to]);
4169
+ await nativeGit(opts.repoPath, ["clean", "-fdq"]);
4170
+ return { status: "moved", head: await head() };
4171
+ }
4172
+ try {
4173
+ await nativeGit(opts.repoPath, [
4174
+ ...MOVE_AUTHOR,
4175
+ "rebase",
4176
+ "--quiet",
4177
+ "--autostash",
4178
+ "--onto",
4179
+ opts.to,
4180
+ opts.from
4181
+ ]);
4182
+ return { status: "moved", head: await head() };
4183
+ } catch {
4184
+ const files = (await nativeGit(opts.repoPath, [
4185
+ "diff",
4186
+ "--name-only",
4187
+ "--diff-filter=U"
4188
+ ]).catch(() => "")).split(`
4189
+ `).filter(Boolean);
4190
+ await nativeGit(opts.repoPath, ["rebase", "--abort"]).catch(() => "");
4191
+ return { status: "conflict", head: await head(), files };
4192
+ }
4193
+ }
4194
+ async function buildSeedPack(opts) {
4195
+ const depth = await nativeGit(opts.repoPath, [
4196
+ "rev-list",
4197
+ "--count",
4198
+ `${opts.base}..${opts.head}`
4199
+ ]).then((count) => Number.parseInt(count.trim(), 10) + 1).catch(() => 1);
4200
+ const directory = await fs7.mkdtemp(path8.join(tmpdir(), "work-seed-"));
4201
+ try {
4202
+ await nativeGit(directory, ["init", "--bare", "--quiet"]);
4203
+ const pin = `refs/work/seed/${process.pid}-${Date.now()}`;
4204
+ await nativeGit(opts.repoPath, ["update-ref", pin, opts.head]);
4205
+ try {
4206
+ await nativeGit(directory, [
4207
+ "fetch",
4208
+ "--quiet",
4209
+ "--no-tags",
4210
+ `--depth=${depth}`,
4211
+ `file://${path8.resolve(opts.repoPath)}`,
4212
+ `+${pin}:refs/heads/main`
4213
+ ]);
4214
+ } finally {
4215
+ await nativeGit(opts.repoPath, ["update-ref", "-d", pin]).catch(() => "");
4216
+ }
4217
+ const shallow = await fs7.readFile(path8.join(directory, "shallow"), "utf8").then((text) => text.split(`
4218
+ `).filter(Boolean)).catch(() => []);
4219
+ const pack = await gitOutput({
4220
+ cwd: directory,
4221
+ args: ["pack-objects", "--revs", "--stdout", "--quiet"],
4222
+ input: `${opts.head}
4223
+ `
4224
+ });
4225
+ return { pack, shallow };
4226
+ } finally {
4227
+ await fs7.rm(directory, { recursive: true, force: true });
4228
+ }
4229
+ }
4230
+ function seedPackInstallScript(opts) {
4231
+ for (const commit of opts.shallow) {
4232
+ if (!COMMIT.test(commit))
4233
+ throw new Error("Invalid shallow commit");
4234
+ }
4235
+ const gitDir = `"$(git rev-parse --git-dir)"`;
4236
+ return [
4237
+ `base64 -d < ${shellQuote(opts.packFile)} | git index-pack --stdin --fix-thin >/dev/null`,
4238
+ `rm -f ${shellQuote(opts.packFile)}`,
4239
+ ...opts.shallow.length > 0 ? [
4240
+ `touch ${gitDir}/shallow`,
4241
+ `printf '%s\\n' ${opts.shallow.join(" ")} >> ${gitDir}/shallow`,
4242
+ `sort -u -o ${gitDir}/shallow ${gitDir}/shallow`
4243
+ ] : []
4244
+ ].join(" && ");
4245
+ }
4246
+ function shellQuote(value) {
4247
+ return `'${value.replaceAll("'", `'\\''`)}'`;
4248
+ }
4249
+ function assertPinRef(ref) {
4250
+ if (!/^refs\/[A-Za-z0-9._/-]+$/.test(ref) || ref.includes("..")) {
4251
+ throw new Error(`Invalid mirror ref '${ref}'`);
4252
+ }
4253
+ }
4254
+ function gitErrorText(error) {
4255
+ const stderr = error && typeof error === "object" && "stderr" in error ? String(error.stderr) : "";
4256
+ const text = (stderr || (error instanceof Error ? error.message : "")).split(`
4257
+ `).map((line) => line.trim()).filter((line) => line.length > 0 && !/authorization/i.test(line)).slice(-2).join(" ");
4258
+ return text || "the remote refused the request";
4259
+ }
4260
+ function gitOutput(opts) {
4261
+ return new Promise((resolve, reject) => {
4262
+ const child = execFile2("git", ["-C", opts.cwd, ...opts.args], {
4263
+ encoding: "buffer",
4264
+ maxBuffer: 2 * 1024 * 1024 * 1024,
4265
+ timeout: 15 * 60000,
4266
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }
4267
+ }, (error, stdout) => {
4268
+ if (error)
4269
+ reject(error);
4270
+ else
4271
+ resolve(new Uint8Array(stdout));
4272
+ });
4273
+ child.stdin?.end(opts.input ?? "");
4274
+ });
4275
+ }
4276
+
4277
+ // src/project-manager.ts
4278
+ var PROJECT_GITIGNORE = `/app-data/
4279
+ node_modules/
4280
+ dist/
4281
+ .turbo/
4282
+ .DS_Store
4283
+ `;
4284
+ var SEEDING_MARKER = ".git/work-seeding";
4285
+ var PROGRAM_READER_ID = "\x00program-reader";
4286
+ var SYSTEM_AUTHOR2 = {
4287
+ name: "Work",
4288
+ email: "system@work.software"
4289
+ };
4290
+
4291
+ class ProjectManager {
4292
+ storage;
4293
+ remote;
4294
+ localRoots;
4295
+ objects = new GitObjectCache;
4296
+ draftCheck;
4297
+ preparing = new Map;
4298
+ constructor(storage, remote, localRoots) {
4299
+ this.storage = storage;
4300
+ this.remote = remote;
4301
+ this.localRoots = localRoots;
4302
+ }
4303
+ async open(tenantId, projectId, externalUserId) {
4304
+ const { repoPath, release } = await this.storage.acquireProject(tenantId, projectId, externalUserId);
4305
+ return await this.localPath({ tenantId, projectId }) ? new NativeProjectRepo(projectId, repoPath, release) : new ProjectRepoImpl(projectId, repoPath, release);
4306
+ }
4307
+ async openDraft(input) {
4308
+ if (input.externalUserId === PROGRAM_READER_ID)
4309
+ return this.openPublished(input);
4310
+ if (await this.localPath(input))
4311
+ return this.open(input.tenantId, input.projectId, input.externalUserId);
4312
+ if (this.remote) {
4313
+ const support = await this.draftSupport();
4314
+ if (!support.supported)
4315
+ throw new DraftsUnsupportedError(support.reason);
4316
+ return new OriginDraftRepo({
4317
+ ...input,
4318
+ remote: this.remote,
4319
+ cache: this.objects
4320
+ });
4321
+ }
4322
+ return this.openCopy(input.tenantId, input.projectId, input.externalUserId);
4323
+ }
4324
+ draftSupport() {
4325
+ this.draftCheck ??= ((this.remote?.draftSupport) ? this.remote.draftSupport() : Promise.resolve({ supported: true })).catch((error) => {
4326
+ this.draftCheck = undefined;
4327
+ throw error;
4328
+ });
4329
+ return this.draftCheck;
4330
+ }
4331
+ async openPublished(input) {
4332
+ if (this.remote && !await this.localPath(input))
4333
+ return new OriginDraftRepo({
4334
+ ...input,
4335
+ externalUserId: null,
4336
+ remote: this.remote,
4337
+ cache: this.objects
4338
+ });
4339
+ return this.open(input.tenantId, input.projectId);
4340
+ }
4341
+ async draftStoreFolder(input) {
4342
+ const folder = this.storage.cachePath?.(input.tenantId, input.projectId, `store-${input.externalUserId}`);
4343
+ if (!folder)
4344
+ return null;
4345
+ await fs8.mkdir(folder, { recursive: true });
4346
+ return folder;
4347
+ }
4348
+ async publishFiles(input) {
4349
+ if (!this.remote)
4350
+ throw new Error("Publishing requires durable project storage");
4351
+ return publishFilesToOrigin({
4352
+ ...input,
4353
+ remote: this.remote,
4354
+ cache: this.objects
4355
+ });
4356
+ }
4357
+ async openCopy(tenantId, projectId, externalUserId) {
4358
+ const key = JSON.stringify([tenantId, projectId, externalUserId]);
4359
+ let pending = this.preparing.get(key);
4360
+ if (!pending) {
4361
+ pending = this.prepareCopy({
4362
+ tenantId,
4363
+ projectId,
4364
+ externalUserId
4365
+ }).finally(() => this.preparing.delete(key));
4366
+ this.preparing.set(key, pending);
4367
+ }
4368
+ await pending;
4369
+ return this.open(tenantId, projectId, externalUserId);
4370
+ }
4371
+ async prepareCopy(args) {
4372
+ const { tenantId, projectId, externalUserId } = args;
4373
+ if (await this.storage.exists(tenantId, projectId, externalUserId)) {
4374
+ const { repoPath, release } = await this.storage.acquireProject(tenantId, projectId, externalUserId);
4375
+ await release();
4376
+ const unfinished = await fs8.access(path9.join(repoPath, SEEDING_MARKER)).then(() => true, () => false);
4377
+ if (!unfinished)
4378
+ return;
4379
+ await this.storage.deleteCopy(tenantId, projectId, externalUserId);
4380
+ }
4381
+ const repoPath = await this.storage.initProject(tenantId, projectId, {
4382
+ externalUserId
4383
+ });
4384
+ if (!this.remote)
4385
+ return;
4386
+ const marker = path9.join(repoPath, SEEDING_MARKER);
4387
+ await fs8.writeFile(marker, "");
4388
+ const { release } = await this.storage.acquireProject(tenantId, projectId, externalUserId);
4389
+ const repo = new ProjectRepoImpl(projectId, repoPath, release);
4390
+ try {
4391
+ await seedFromOrigin({
4392
+ remote: this.remote,
4393
+ tenantId,
4394
+ projectId,
4395
+ dev: repo
4396
+ });
4397
+ await fs8.rm(marker, { force: true });
4398
+ } catch (error) {
4399
+ await repo.dispose();
4400
+ await this.storage.deleteCopy(tenantId, projectId, externalUserId).catch(() => {});
4401
+ throw error;
4402
+ }
4403
+ await repo.dispose();
4404
+ }
4405
+ async openEphemeral(args) {
4406
+ if (!this.remote)
4407
+ throw new Error("An ephemeral checkout requires durable project storage");
4408
+ const directory = await fs8.mkdtemp(path9.join(tmpdir2(), "catamorphic-checkout-"));
4409
+ const cleanup = () => fs8.rm(directory, { recursive: true, force: true });
4410
+ try {
4411
+ const storage = new FsBackend(directory);
4412
+ const repoPath = await storage.initProject(args.tenantId, args.projectId);
4413
+ const repo = new ProjectRepoImpl(args.projectId, repoPath, cleanup);
4414
+ await seedFromOrigin({ remote: this.remote, ...args, dev: repo });
4415
+ return repo;
4416
+ } catch (error) {
4417
+ await cleanup();
4418
+ throw error;
4419
+ }
4420
+ }
4421
+ async openSession(args) {
4422
+ const userId = `session-${args.sessionId}`;
4423
+ const existed = await this.storage.exists(args.tenantId, args.projectId, userId);
4424
+ const repo = await this.openCopy(args.tenantId, args.projectId, userId);
4425
+ try {
4426
+ if (this.remote && (!existed || args.refresh)) {
4427
+ await Promise.resolve().then(() => init_git_sync());
4428
+ const fetched = await fetchRemote({
4429
+ dev: repo,
4430
+ remote: this.remote,
4431
+ tenantId: args.tenantId,
4432
+ projectId: args.projectId,
4433
+ remoteBranch: `sessions/${args.sessionId}`
4434
+ });
4435
+ if (fetched.sha && fetched.sha !== await repo.resolveRef("HEAD")) {
4436
+ if ((await repo.status()).dirty)
4437
+ throw new Error("Session has uncheckpointed work on this machine. Recover it before moving the session.");
4438
+ await repo.moveBranch("main", fetched.sha);
4439
+ await repo.checkout("main");
4440
+ }
4441
+ }
4442
+ return repo;
4443
+ } catch (error) {
4444
+ await repo.dispose();
4445
+ throw error;
4446
+ }
4447
+ }
4448
+ async checkpointSession(args) {
4449
+ const repo = await this.openSession(args);
4450
+ try {
4451
+ const sha = (await repo.status()).dirty ? await repo.commit(args.message, args.author) : await repo.resolveRef("HEAD");
4452
+ if (this.remote)
4453
+ await push({
4454
+ dev: repo,
4455
+ remote: this.remote,
4456
+ tenantId: args.tenantId,
4457
+ projectId: args.projectId,
4458
+ remoteBranch: `sessions/${args.sessionId}`,
4459
+ localSha: sha
4460
+ });
4461
+ return sha;
4462
+ } finally {
4463
+ await repo.dispose();
4464
+ }
4465
+ }
4466
+ mirrorPath(args) {
4467
+ return this.storage.mirrorPath?.(args.tenantId, args.projectId) ?? null;
4468
+ }
4469
+ async setSessionBase(args) {
4470
+ const mirrorPath = this.mirrorPath(args);
4471
+ if (!mirrorPath)
4472
+ throw new Error("This host keeps no project mirror");
4473
+ const repo = await this.openSession({
4474
+ tenantId: args.tenantId,
4475
+ projectId: args.projectId,
4476
+ sessionId: args.sessionId,
4477
+ refresh: true
4478
+ });
4479
+ try {
4480
+ await copyFromMirror({
4481
+ mirrorPath,
4482
+ pin: args.pin,
4483
+ repoPath: repo.repoPath,
4484
+ into: "refs/work/base"
4485
+ });
4486
+ await repo.moveBranch("main", args.commit);
4487
+ await repo.checkout("main");
4488
+ await repo.resetWorkingTree();
4489
+ await this.publishSession({ ...args, repo, head: args.commit });
4490
+ } finally {
4491
+ await repo.dispose();
4492
+ }
4493
+ }
4494
+ async moveSessionBase(args) {
4495
+ const mirrorPath = this.mirrorPath(args);
4496
+ if (!mirrorPath)
4497
+ throw new Error("This host keeps no project mirror");
4498
+ const repo = await this.openSession({
4499
+ tenantId: args.tenantId,
4500
+ projectId: args.projectId,
4501
+ sessionId: args.sessionId,
4502
+ refresh: true
4503
+ });
4504
+ try {
4505
+ const outcome = await moveCheckoutBase({
4506
+ repoPath: repo.repoPath,
4507
+ mirrorPath,
4508
+ pin: args.pin,
4509
+ from: args.from,
4510
+ to: args.to,
4511
+ update: args.update
4512
+ });
4513
+ if (outcome.status === "moved")
4514
+ await this.publishSession({ ...args, repo, head: outcome.head });
4515
+ return outcome;
4516
+ } finally {
4517
+ await repo.dispose();
4518
+ }
4519
+ }
4520
+ async publishSession(args) {
4521
+ if (!this.remote)
4522
+ return;
4523
+ await push({
4524
+ dev: args.repo,
4525
+ remote: this.remote,
4526
+ tenantId: args.tenantId,
4527
+ projectId: args.projectId,
4528
+ remoteBranch: `sessions/${args.sessionId}`,
4529
+ localSha: args.head,
4530
+ force: true
4531
+ });
4532
+ }
4533
+ async resetSession(args) {
4534
+ const repo = await this.openSession({
4535
+ tenantId: args.tenantId,
4536
+ projectId: args.projectId,
4537
+ sessionId: args.sessionId,
4538
+ refresh: true
4539
+ });
4540
+ try {
4541
+ await repo.moveBranch("main", args.commit);
4542
+ await repo.checkout("main");
4543
+ await repo.resetWorkingTree();
4544
+ await this.publishSession({ ...args, repo, head: args.commit });
4545
+ } finally {
4546
+ await repo.dispose();
4547
+ }
4548
+ }
4549
+ async deleteSession(args) {
4550
+ if (this.remote && await this.remote.exists(args.tenantId, args.projectId))
4551
+ await this.remote.withOrigin(args.tenantId, args.projectId, (origin) => origin.deleteRef({ ref: `refs/heads/sessions/${args.sessionId}` }));
4552
+ await this.storage.deleteCopy(args.tenantId, args.projectId, `session-${args.sessionId}`);
4553
+ }
4554
+ async localPath(input) {
4555
+ return await this.localRoots?.(input.tenantId, input.projectId) ?? null;
4556
+ }
4557
+ async create(tenantId, projectId, opts) {
4558
+ if (opts?.importExisting) {
4559
+ if (!opts.rootPath)
4560
+ throw new Error("Opening a repository requires its folder path");
4561
+ const checkout = await discoverLocalFolder({ path: opts.rootPath });
4562
+ const local = await this.localPath({ tenantId, projectId });
4563
+ if (!local || await fs8.realpath(local) !== checkout.path)
4564
+ throw new Error("Register the checkout's canonical folder with localCheckouts before importing it");
4565
+ return new NativeProjectRepo(projectId, checkout.path, async () => {});
4566
+ }
4567
+ const repoPath = await this.storage.initProject(tenantId, projectId, {
4568
+ externalUserId: opts?.externalUserId,
4569
+ rootPath: opts?.rootPath
4570
+ });
4571
+ const projectName = opts?.name ?? "my-project";
4572
+ const local = await this.localPath({ tenantId, projectId });
4573
+ if (opts?.cloneFrom) {
4574
+ await cloneFromRemote({
4575
+ repoPath,
4576
+ native: Boolean(local),
4577
+ url: opts.cloneFrom.url,
4578
+ credentials: opts.cloneFrom.credentials,
4579
+ branch: opts.cloneFrom.branch
4580
+ });
4581
+ const repo = local ? new NativeProjectRepo(projectId, repoPath, async () => {}) : new ProjectRepoImpl(projectId, repoPath, async () => {});
4582
+ if (this.remote && !local) {
4583
+ await this.remote.initRemote(tenantId, projectId);
4584
+ await push({
4585
+ dev: repo,
4586
+ remote: this.remote,
4587
+ tenantId,
4588
+ projectId,
4589
+ remoteBranch: "main"
4590
+ });
4591
+ }
4592
+ return repo;
4593
+ }
4594
+ const manifestPath = path9.join(repoPath, PROJECT_MANIFEST_PATH);
4595
+ const manifestExists = await fs8.access(manifestPath).then(() => true, () => false);
4596
+ if (!manifestExists && !opts?.empty) {
4597
+ await fs8.mkdir(path9.dirname(manifestPath), { recursive: true });
4598
+ await fs8.writeFile(manifestPath, `${JSON.stringify({
4599
+ name: projectName,
4600
+ environments: {
4601
+ default: {
4602
+ description: "Run where this host places work",
4603
+ workloads: ["agent", "workflow"]
4604
+ }
4605
+ },
4606
+ defaultEnvironment: "default"
4607
+ }, null, 2)}
4608
+ `);
4609
+ }
4610
+ const gitignorePath = path9.join(repoPath, PROJECT_GITIGNORE_PATH);
4611
+ const gitignoreExists = await fs8.access(gitignorePath).then(() => true, () => false);
4612
+ if (!gitignoreExists && !opts?.empty) {
4613
+ await fs8.writeFile(gitignorePath, PROJECT_GITIGNORE);
4614
+ }
4615
+ if (opts?.initialFiles && !opts.empty) {
4616
+ for (const [filePath, content] of Object.entries(opts.initialFiles)) {
4617
+ const fullPath = path9.join(repoPath, filePath);
4618
+ await fs8.mkdir(path9.dirname(fullPath), { recursive: true });
4619
+ await fs8.writeFile(fullPath, content);
4620
+ }
4621
+ }
4622
+ const repo = local ? new NativeProjectRepo(projectId, repoPath, async () => {}) : new ProjectRepoImpl(projectId, repoPath, async () => {});
4623
+ const hasHead = await repo.resolveRef("HEAD").then(() => true, () => false);
4624
+ if (!hasHead) {
4625
+ await repo.commit("Initial commit", SYSTEM_AUTHOR2, { allowEmpty: true });
4626
+ }
4627
+ if (this.remote) {
4628
+ await this.remote.initRemote(tenantId, projectId);
4629
+ await push({
4630
+ dev: repo,
4631
+ remote: this.remote,
4632
+ tenantId,
4633
+ projectId,
4634
+ remoteBranch: "main"
4635
+ });
4636
+ }
4637
+ return repo;
4638
+ }
4639
+ async delete(tenantId, projectId) {
4640
+ await this.storage.deleteProject(tenantId, projectId);
4641
+ if (this.remote) {
4642
+ await this.remote.deleteRemote(tenantId, projectId).catch(() => {});
4643
+ }
4644
+ }
4645
+ async exists(tenantId, projectId, externalUserId) {
4646
+ return this.storage.exists(tenantId, projectId, externalUserId);
4647
+ }
4648
+ get remoteBackend() {
4649
+ return this.remote;
4650
+ }
4651
+ }
4652
+ async function seedFromOrigin(opts) {
4653
+ await Promise.resolve().then(() => init_git_sync());
4654
+ const fetched = await fetchRemote({
4655
+ dev: opts.dev,
4656
+ remote: opts.remote,
4657
+ tenantId: opts.tenantId,
4658
+ projectId: opts.projectId,
4659
+ remoteBranch: "main"
4660
+ });
4661
+ if (fetched.sha) {
4662
+ const nodeFs = (await import("node:fs")).default;
4663
+ const git = (await import("isomorphic-git")).default;
4664
+ await git.writeRef({
4665
+ fs: nodeFs,
4666
+ dir: opts.dev.repoPath,
4667
+ ref: "refs/heads/main",
4668
+ value: fetched.sha,
4669
+ force: true
4670
+ });
4671
+ await git.checkout({
4672
+ fs: nodeFs,
4673
+ dir: opts.dev.repoPath,
4674
+ ref: "main",
4675
+ force: true
4676
+ });
4677
+ }
4678
+ }
4679
+
4680
+ // src/index.ts
4681
+ init_project_repo();
4682
+ init_ref_names();
4683
+ export {
4684
+ CheckoutRemoteBackend,
4685
+ DraftBinaryResolutionError,
4686
+ DraftBusyError,
4687
+ DraftContentChangedError,
4688
+ DraftIgnoredPathError,
4689
+ DraftPathError,
4690
+ DraftRefNotAllowedError,
4691
+ DraftUnresolvedError,
4692
+ DraftsUnsupportedError,
4693
+ FsBackend,
4694
+ FsOriginRepo,
4695
+ FsRemoteBackend,
4696
+ GitObjectCache,
4697
+ InMemoryObjectStore,
4698
+ InvalidBaseError,
4699
+ InvalidRefNameError,
4700
+ NativeProjectRepo,
4701
+ NoDraftError,
4702
+ ObjectOriginRepo,
4703
+ ObjectRemoteBackend,
4704
+ OriginDraftRepo,
4705
+ PROGRAM_READER_ID,
4706
+ PROJECT_GITIGNORE,
4707
+ PreconditionFailedError,
4708
+ ProjectManager,
4709
+ ProjectRepoImpl,
4710
+ PushNotFastForwardError,
4711
+ RefMovedError,
4712
+ RemotePushRefusedError,
4713
+ assertPushAllowed,
4714
+ assertValidRefName,
4715
+ buildSeedPack,
4716
+ cloneFromRemote,
4717
+ copyFromMirror,
4718
+ discoverLocalFolder,
4719
+ ensurePersonalFilesExcluded,
4720
+ fetchFromRemote,
4721
+ fetchIntoMirror,
4722
+ fetchRemote,
4723
+ hasLocalGit,
4724
+ isCommitId,
4725
+ isManagedBranch,
4726
+ isPersonalFile,
4727
+ isValidRefName,
4728
+ migrateWorkflowToProject,
4729
+ mirrorChangedFiles,
4730
+ moveCheckoutBase,
4731
+ nativeGit,
4732
+ parseWorkspaceRef,
4733
+ probeConditionalWrites,
4734
+ pull,
4735
+ push,
4736
+ pushToRemote,
4737
+ readFileSnapshot,
4738
+ refreshPublished,
4739
+ seedPackInstallScript,
4740
+ shellQuote,
4741
+ syncWithNetworkRemote,
4742
+ unpinMirrorRef
4743
+ };
4744
+
4745
+ //# debugId=F09D854298D138D564756E2164756E21
4746
+ //# sourceMappingURL=index.js.map