@narumitw/pi-sync-daemon 0.0.0-stage → 0.2.0

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 (265) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +89 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +128 -0
  6. package/dist/client.d.ts +55 -0
  7. package/dist/client.js +484 -0
  8. package/dist/consent.d.ts +24 -0
  9. package/dist/consent.js +205 -0
  10. package/dist/document.d.ts +10 -0
  11. package/dist/document.js +6 -0
  12. package/dist/endpoint.d.ts +8 -0
  13. package/dist/endpoint.js +91 -0
  14. package/dist/engine/backends/backend-factory.d.ts +6 -0
  15. package/dist/engine/backends/backend-factory.js +16 -0
  16. package/dist/engine/backends/backend-identity.d.ts +3 -0
  17. package/dist/engine/backends/backend-identity.js +38 -0
  18. package/dist/engine/backends/backend-types.d.ts +70 -0
  19. package/dist/engine/backends/backend-types.js +1 -0
  20. package/dist/engine/backends/git/git-backend.d.ts +55 -0
  21. package/dist/engine/backends/git/git-backend.js +700 -0
  22. package/dist/engine/backends/git/git-config.d.ts +5 -0
  23. package/dist/engine/backends/git/git-config.js +118 -0
  24. package/dist/engine/backends/git/git-runner.d.ts +25 -0
  25. package/dist/engine/backends/git/git-runner.js +232 -0
  26. package/dist/engine/backends/git/git-storage.d.ts +39 -0
  27. package/dist/engine/backends/git/git-storage.js +226 -0
  28. package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
  29. package/dist/engine/backends/s3/s3-backend.js +436 -0
  30. package/dist/engine/backends/s3/s3-client.d.ts +36 -0
  31. package/dist/engine/backends/s3/s3-client.js +352 -0
  32. package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
  33. package/dist/engine/backends/s3/s3-conditions.js +66 -0
  34. package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
  35. package/dist/engine/backends/snapshot-pointer.js +22 -0
  36. package/dist/engine/backends/sync-backend.d.ts +71 -0
  37. package/dist/engine/backends/sync-backend.js +23 -0
  38. package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
  39. package/dist/engine/backends/webdav/webdav-backend.js +534 -0
  40. package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
  41. package/dist/engine/backends/webdav/webdav-client.js +326 -0
  42. package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
  43. package/dist/engine/backends/webdav/webdav-config.js +73 -0
  44. package/dist/engine/commands/command-types.d.ts +31 -0
  45. package/dist/engine/commands/command-types.js +1 -0
  46. package/dist/engine/host.d.ts +70 -0
  47. package/dist/engine/host.js +16 -0
  48. package/dist/engine/paths.d.ts +9 -0
  49. package/dist/engine/paths.js +71 -0
  50. package/dist/engine/settings/config-errors.d.ts +1 -0
  51. package/dist/engine/settings/config-errors.js +4 -0
  52. package/dist/engine/settings/config-file.d.ts +33 -0
  53. package/dist/engine/settings/config-file.js +630 -0
  54. package/dist/engine/settings/config.d.ts +24 -0
  55. package/dist/engine/settings/config.js +200 -0
  56. package/dist/engine/settings/settings-management.d.ts +24 -0
  57. package/dist/engine/settings/settings-management.js +191 -0
  58. package/dist/engine/settings/settings-store.d.ts +8 -0
  59. package/dist/engine/settings/settings-store.js +41 -0
  60. package/dist/engine/settings/settings-types.d.ts +134 -0
  61. package/dist/engine/settings/settings-types.js +1 -0
  62. package/dist/engine/settings/settings-validation.d.ts +15 -0
  63. package/dist/engine/settings/settings-validation.js +356 -0
  64. package/dist/engine/snapshot/session-paths.d.ts +12 -0
  65. package/dist/engine/snapshot/session-paths.js +91 -0
  66. package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
  67. package/dist/engine/snapshot/snapshot-apply.js +262 -0
  68. package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
  69. package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
  70. package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
  71. package/dist/engine/snapshot/snapshot-codec.js +53 -0
  72. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
  73. package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
  74. package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
  75. package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
  76. package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
  77. package/dist/engine/snapshot/snapshot-paths.js +11 -0
  78. package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
  79. package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
  80. package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
  81. package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
  82. package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
  83. package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
  84. package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
  85. package/dist/engine/snapshot/snapshot-transaction.js +787 -0
  86. package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
  87. package/dist/engine/snapshot/snapshot-types.js +1 -0
  88. package/dist/engine/snapshot/snapshot.d.ts +30 -0
  89. package/dist/engine/snapshot/snapshot.js +364 -0
  90. package/dist/engine/state/json-file.d.ts +6 -0
  91. package/dist/engine/state/json-file.js +49 -0
  92. package/dist/engine/state/lock-policy.d.ts +2 -0
  93. package/dist/engine/state/lock-policy.js +2 -0
  94. package/dist/engine/state/lock.d.ts +20 -0
  95. package/dist/engine/state/lock.js +259 -0
  96. package/dist/engine/state/lockfile-fs.d.ts +13 -0
  97. package/dist/engine/state/lockfile-fs.js +13 -0
  98. package/dist/engine/state/merge-baseline-store.d.ts +11 -0
  99. package/dist/engine/state/merge-baseline-store.js +187 -0
  100. package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
  101. package/dist/engine/state/mutation-directory-sync.js +34 -0
  102. package/dist/engine/state/operation-availability.d.ts +49 -0
  103. package/dist/engine/state/operation-availability.js +40 -0
  104. package/dist/engine/state/state-directory.d.ts +14 -0
  105. package/dist/engine/state/state-directory.js +225 -0
  106. package/dist/engine/state/state-types.d.ts +27 -0
  107. package/dist/engine/state/state-types.js +1 -0
  108. package/dist/engine/state/sync-state-store.d.ts +11 -0
  109. package/dist/engine/state/sync-state-store.js +54 -0
  110. package/dist/engine/sync/agent-candidate.d.ts +44 -0
  111. package/dist/engine/sync/agent-candidate.js +207 -0
  112. package/dist/engine/sync/agent-plan.d.ts +8 -0
  113. package/dist/engine/sync/agent-plan.js +84 -0
  114. package/dist/engine/sync/agent-policy.d.ts +9 -0
  115. package/dist/engine/sync/agent-policy.js +10 -0
  116. package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
  117. package/dist/engine/sync/agent-refusal-retry.js +39 -0
  118. package/dist/engine/sync/agent-request.d.ts +14 -0
  119. package/dist/engine/sync/agent-request.js +13 -0
  120. package/dist/engine/sync/agent-runner.d.ts +6 -0
  121. package/dist/engine/sync/agent-runner.js +183 -0
  122. package/dist/engine/sync/agent-store.d.ts +7 -0
  123. package/dist/engine/sync/agent-store.js +177 -0
  124. package/dist/engine/sync/agent-sync.d.ts +4 -0
  125. package/dist/engine/sync/agent-sync.js +132 -0
  126. package/dist/engine/sync/apply-review.d.ts +8 -0
  127. package/dist/engine/sync/apply-review.js +51 -0
  128. package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
  129. package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
  130. package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
  131. package/dist/engine/sync/conflict-artifacts.js +158 -0
  132. package/dist/engine/sync/conflict-groups.d.ts +9 -0
  133. package/dist/engine/sync/conflict-groups.js +76 -0
  134. package/dist/engine/sync/conflict-preview.d.ts +4 -0
  135. package/dist/engine/sync/conflict-preview.js +53 -0
  136. package/dist/engine/sync/conflict-resolution.d.ts +13 -0
  137. package/dist/engine/sync/conflict-resolution.js +53 -0
  138. package/dist/engine/sync/conflict-retention.d.ts +5 -0
  139. package/dist/engine/sync/conflict-retention.js +61 -0
  140. package/dist/engine/sync/conflict-review.d.ts +4 -0
  141. package/dist/engine/sync/conflict-review.js +73 -0
  142. package/dist/engine/sync/content-conflicts.d.ts +10 -0
  143. package/dist/engine/sync/content-conflicts.js +70 -0
  144. package/dist/engine/sync/continuous-errors.d.ts +14 -0
  145. package/dist/engine/sync/continuous-errors.js +66 -0
  146. package/dist/engine/sync/continuous-lease.d.ts +9 -0
  147. package/dist/engine/sync/continuous-lease.js +206 -0
  148. package/dist/engine/sync/continuous-record.d.ts +31 -0
  149. package/dist/engine/sync/continuous-record.js +199 -0
  150. package/dist/engine/sync/continuous-storage.d.ts +14 -0
  151. package/dist/engine/sync/continuous-storage.js +59 -0
  152. package/dist/engine/sync/continuous-sync.d.ts +15 -0
  153. package/dist/engine/sync/continuous-sync.js +496 -0
  154. package/dist/engine/sync/continuous-watch.d.ts +3 -0
  155. package/dist/engine/sync/continuous-watch.js +65 -0
  156. package/dist/engine/sync/exclude-policy.d.ts +5 -0
  157. package/dist/engine/sync/exclude-policy.js +79 -0
  158. package/dist/engine/sync/field-migration.d.ts +5 -0
  159. package/dist/engine/sync/field-migration.js +20 -0
  160. package/dist/engine/sync/file-merge-planner.d.ts +36 -0
  161. package/dist/engine/sync/file-merge-planner.js +123 -0
  162. package/dist/engine/sync/initialization.d.ts +12 -0
  163. package/dist/engine/sync/initialization.js +75 -0
  164. package/dist/engine/sync/json-document.d.ts +29 -0
  165. package/dist/engine/sync/json-document.js +172 -0
  166. package/dist/engine/sync/local-field-policy.d.ts +2 -0
  167. package/dist/engine/sync/local-field-policy.js +26 -0
  168. package/dist/engine/sync/local-fields.d.ts +9 -0
  169. package/dist/engine/sync/local-fields.js +116 -0
  170. package/dist/engine/sync/merge-apply.d.ts +5 -0
  171. package/dist/engine/sync/merge-apply.js +386 -0
  172. package/dist/engine/sync/merge-journal.d.ts +31 -0
  173. package/dist/engine/sync/merge-journal.js +179 -0
  174. package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
  175. package/dist/engine/sync/merge-transfer-error.js +64 -0
  176. package/dist/engine/sync/merged-sync.d.ts +6 -0
  177. package/dist/engine/sync/merged-sync.js +618 -0
  178. package/dist/engine/sync/mutation-owner.d.ts +2 -0
  179. package/dist/engine/sync/mutation-owner.js +18 -0
  180. package/dist/engine/sync/package-merge.d.ts +3 -0
  181. package/dist/engine/sync/package-merge.js +82 -0
  182. package/dist/engine/sync/partial-progress.d.ts +15 -0
  183. package/dist/engine/sync/partial-progress.js +39 -0
  184. package/dist/engine/sync/remote-snapshot.d.ts +28 -0
  185. package/dist/engine/sync/remote-snapshot.js +62 -0
  186. package/dist/engine/sync/resolver-stream.d.ts +4 -0
  187. package/dist/engine/sync/resolver-stream.js +34 -0
  188. package/dist/engine/sync/session-merge.d.ts +3 -0
  189. package/dist/engine/sync/session-merge.js +178 -0
  190. package/dist/engine/sync/session-push.d.ts +5 -0
  191. package/dist/engine/sync/session-push.js +32 -0
  192. package/dist/engine/sync/settings-conflicts.d.ts +8 -0
  193. package/dist/engine/sync/settings-conflicts.js +56 -0
  194. package/dist/engine/sync/settings-merge.d.ts +13 -0
  195. package/dist/engine/sync/settings-merge.js +93 -0
  196. package/dist/engine/sync/signals.d.ts +2 -0
  197. package/dist/engine/sync/signals.js +8 -0
  198. package/dist/engine/sync/startup-timings.d.ts +11 -0
  199. package/dist/engine/sync/startup-timings.js +44 -0
  200. package/dist/engine/sync/sync-decision.d.ts +35 -0
  201. package/dist/engine/sync/sync-decision.js +66 -0
  202. package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
  203. package/dist/engine/sync/sync-error-guidance.js +55 -0
  204. package/dist/engine/sync/sync-errors.d.ts +9 -0
  205. package/dist/engine/sync/sync-errors.js +18 -0
  206. package/dist/engine/sync/sync-inspection.d.ts +26 -0
  207. package/dist/engine/sync/sync-inspection.js +40 -0
  208. package/dist/engine/sync/sync-loaders.d.ts +7 -0
  209. package/dist/engine/sync/sync-loaders.js +8 -0
  210. package/dist/engine/sync/sync-local.d.ts +5 -0
  211. package/dist/engine/sync/sync-local.js +40 -0
  212. package/dist/engine/sync/sync-mutations.d.ts +30 -0
  213. package/dist/engine/sync/sync-mutations.js +589 -0
  214. package/dist/engine/sync/sync-operations.d.ts +2 -0
  215. package/dist/engine/sync/sync-operations.js +3 -0
  216. package/dist/engine/sync/sync-policy.d.ts +85 -0
  217. package/dist/engine/sync/sync-policy.js +356 -0
  218. package/dist/engine/sync/sync-queries.d.ts +7 -0
  219. package/dist/engine/sync/sync-queries.js +195 -0
  220. package/dist/engine/sync/sync-state.d.ts +31 -0
  221. package/dist/engine/sync/sync-state.js +92 -0
  222. package/dist/engine/sync/text-merge.d.ts +19 -0
  223. package/dist/engine/sync/text-merge.js +124 -0
  224. package/dist/engine/types.d.ts +5 -0
  225. package/dist/engine/types.js +2 -0
  226. package/dist/engine/ui/merge-review.d.ts +2 -0
  227. package/dist/engine/ui/merge-review.js +7 -0
  228. package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
  229. package/dist/engine/ui/merged-sync-summary.js +86 -0
  230. package/dist/engine/ui/sync-format.d.ts +13 -0
  231. package/dist/engine/ui/sync-format.js +150 -0
  232. package/dist/engine/ui/sync-status.d.ts +9 -0
  233. package/dist/engine/ui/sync-status.js +30 -0
  234. package/dist/engine/ui/terminal-text.d.ts +3 -0
  235. package/dist/engine/ui/terminal-text.js +9 -0
  236. package/dist/engine/ui/transfer-changes.d.ts +12 -0
  237. package/dist/engine/ui/transfer-changes.js +24 -0
  238. package/dist/engine/ui/transfer-review.d.ts +3 -0
  239. package/dist/engine/ui/transfer-review.js +19 -0
  240. package/dist/engine-service.d.ts +11 -0
  241. package/dist/engine-service.js +315 -0
  242. package/dist/identity.d.ts +20 -0
  243. package/dist/identity.js +133 -0
  244. package/dist/index.d.ts +8 -0
  245. package/dist/index.js +4 -0
  246. package/dist/lifecycle-log.d.ts +7 -0
  247. package/dist/lifecycle-log.js +53 -0
  248. package/dist/lifecycle.d.ts +2 -0
  249. package/dist/lifecycle.js +21 -0
  250. package/dist/model-signature.d.ts +2 -0
  251. package/dist/model-signature.js +7 -0
  252. package/dist/monitor.d.ts +11 -0
  253. package/dist/monitor.js +245 -0
  254. package/dist/participant-admission.d.ts +5 -0
  255. package/dist/participant-admission.js +30 -0
  256. package/dist/protocol.d.ts +97 -0
  257. package/dist/protocol.js +90 -0
  258. package/dist/resolver-host.d.ts +11 -0
  259. package/dist/resolver-host.js +78 -0
  260. package/dist/server.d.ts +18 -0
  261. package/dist/server.js +724 -0
  262. package/dist/service-host.d.ts +7 -0
  263. package/dist/service-host.js +174 -0
  264. package/docs/architecture.md +133 -0
  265. package/package.json +54 -4
@@ -0,0 +1,700 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { posixJoin } from "../../paths.js";
5
+ import { stateDir } from "../../state/state-directory.js";
6
+ import { throwIfAborted } from "../../sync/signals.js";
7
+ import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
8
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
9
+ import { normalizeGitBranch, normalizeGitDirectory, normalizeGitRemote, normalizeGitRemoteIdentity, validateGitNamespace, } from "./git-config.js";
10
+ import { GitCommandError, readGitBlobs, runGit } from "./git-runner.js";
11
+ import { GIT_MANIFEST_VERSION, MAX_GIT_MANIFEST_BYTES, MAX_GIT_TREE_OUTPUT_BYTES, parseGitTree, prepareGitSnapshot, requireGitManifest, validateGitPublicationTree, validateGitSnapshot, } from "./git-storage.js";
12
+ const COMMAND_TIMEOUT_MS = 30_000;
13
+ const POST_COMMIT_TIMEOUT_MS = 45_000;
14
+ const gitCacheMutationQueues = new Map();
15
+ export class GitSyncBackend {
16
+ config;
17
+ identity;
18
+ destination;
19
+ capability = "lease-protected";
20
+ cacheRoot;
21
+ cacheDir;
22
+ allowLocalRemotes;
23
+ commandTimeoutMs;
24
+ postCommitTimeoutMs;
25
+ afterPushForTest;
26
+ afterLsRemoteForTest;
27
+ afterPayloadWriteForTest;
28
+ cacheReady;
29
+ constructor(config, options = {}) {
30
+ this.config = config;
31
+ assertGitDestination(config);
32
+ this.allowLocalRemotes = options.allowLocalRemotes === true;
33
+ if (!this.allowLocalRemotes)
34
+ assertProductionRemote(config.profile.remote);
35
+ this.identity = gitBackendIdentity(config);
36
+ this.destination = gitDestination(config);
37
+ this.cacheRoot = path.resolve(options.cacheRoot ?? path.join(stateDir(), "git"));
38
+ this.cacheDir = path.join(this.cacheRoot, this.identity.slice("git:".length), "repository.git");
39
+ this.commandTimeoutMs = options.commandTimeoutMs ?? COMMAND_TIMEOUT_MS;
40
+ this.postCommitTimeoutMs = options.postCommitTimeoutMs ?? POST_COMMIT_TIMEOUT_MS;
41
+ this.afterPushForTest = options.afterPushForTest;
42
+ this.afterLsRemoteForTest = options.afterLsRemoteForTest;
43
+ this.afterPayloadWriteForTest = options.afterPayloadWriteForTest;
44
+ }
45
+ sameRevision(left, right) {
46
+ return decodeRevision(left, this.identity) === decodeRevision(right, this.identity);
47
+ }
48
+ async readHead(signal) {
49
+ const sha = await this.fetchRemoteHead(signal);
50
+ if (!sha)
51
+ return undefined;
52
+ const { manifest } = await this.readPublication(sha, signal);
53
+ return remoteHead(sha, manifest, this.identity);
54
+ }
55
+ async readSnapshot(reference, signal) {
56
+ const head = await this.fetchRemoteHead(signal);
57
+ if (!head)
58
+ throw new Error(`Git snapshot publication was not found: ${reference}`);
59
+ const commit = await this.resolveSnapshotReference(reference, head, signal);
60
+ try {
61
+ await this.git(["cat-file", "-e", `${commit}^{commit}`], { signal });
62
+ await this.git(["merge-base", "--is-ancestor", commit, head], { signal });
63
+ }
64
+ catch (error) {
65
+ throw new Error(`Git snapshot publication was not found: ${reference}`, { cause: error });
66
+ }
67
+ const { manifest, payloadEntries } = await this.readPublication(commit, signal);
68
+ let blobs;
69
+ try {
70
+ blobs = await readGitBlobs(payloadEntries.map((entry) => entry.object), {
71
+ gitDir: this.cacheDir,
72
+ signal,
73
+ timeoutMs: this.commandTimeoutMs,
74
+ allowFileProtocol: this.allowLocalRemotes,
75
+ maxOutputBytes: manifest.files.reduce((total, file) => total + file.size, 0),
76
+ });
77
+ }
78
+ catch (error) {
79
+ if (error instanceof Error && /exceeds/u.test(error.message)) {
80
+ throw new Error("Git snapshot file content exceeds its manifest size.", { cause: error });
81
+ }
82
+ throw this.redactedError(error);
83
+ }
84
+ throwIfAborted(signal);
85
+ const files = manifest.files.map((file, index) => {
86
+ const content = blobs[index];
87
+ if (!content || content.byteLength !== file.size || sha256(content) !== file.sha256) {
88
+ throw new Error(`Git snapshot file checksum or size mismatch: ${file.path}`);
89
+ }
90
+ return { path: file.path, contentBase64: content.toString("base64"), sha256: file.sha256 };
91
+ });
92
+ const snapshot = {
93
+ version: manifest.snapshotVersion,
94
+ id: manifest.snapshotId,
95
+ createdAt: manifest.createdAt,
96
+ machine: manifest.machine,
97
+ profile: manifest.profile,
98
+ ...(manifest.snapshotSyncSessions === undefined ? {} : { syncSessions: manifest.snapshotSyncSessions }),
99
+ ...(manifest.selection === undefined ? {} : { selection: manifest.selection }),
100
+ ...(manifest.localFields === undefined ? {} : { localFields: manifest.localFields }),
101
+ files,
102
+ };
103
+ validateGitSnapshot(snapshot, manifest, this.config.destination.namespace);
104
+ return snapshot;
105
+ }
106
+ async publishSnapshot(snapshot, expected, options = {}) {
107
+ throwIfAborted(options.signal);
108
+ const files = prepareGitSnapshot(snapshot, this.config.destination.namespace);
109
+ const observed = await this.fetchRemoteHead(options.signal);
110
+ if (!matchesExpected(observed, expected, this.identity)) {
111
+ throw new SyncBackendConflictError("Git remote changed while preparing publication. Run /sync status and retry.", { currentHead: observed ? await this.headForSha(observed, options.signal) : undefined });
112
+ }
113
+ throwIfAborted(options.signal);
114
+ const manifest = {
115
+ version: GIT_MANIFEST_VERSION,
116
+ snapshotVersion: snapshot.version,
117
+ snapshotId: snapshot.id,
118
+ createdAt: snapshot.createdAt,
119
+ machine: snapshot.machine,
120
+ profile: snapshot.profile,
121
+ syncSessions: snapshot.syncSessions === true || snapshot.files.some((file) => file.path.startsWith("sessions/")),
122
+ ...(snapshot.syncSessions === undefined ? {} : { snapshotSyncSessions: snapshot.syncSessions }),
123
+ ...(snapshot.selection === undefined ? {} : { selection: snapshot.selection }),
124
+ ...(snapshot.localFields === undefined ? {} : { localFields: snapshot.localFields }),
125
+ files: files.map(({ path: filePath, sha256: fileSha, size }) => ({
126
+ path: filePath,
127
+ sha256: fileSha,
128
+ size,
129
+ })),
130
+ };
131
+ let candidate;
132
+ try {
133
+ candidate = await this.createCommit(snapshot, files, manifest, observed, options.signal);
134
+ }
135
+ catch (error) {
136
+ throw this.redactedError(error);
137
+ }
138
+ throwIfAborted(options.signal);
139
+ options.onCommit?.();
140
+ const ref = this.remoteRef();
141
+ const lease = `--force-with-lease=${ref}:${observed ?? ""}`;
142
+ let pushError;
143
+ try {
144
+ await this.git(["push", "--porcelain", "--no-verify", lease, this.config.profile.remote, `${candidate}:${ref}`], {
145
+ timeoutMs: this.postCommitTimeoutMs,
146
+ });
147
+ await this.afterPushForTest?.();
148
+ }
149
+ catch (error) {
150
+ pushError = error;
151
+ }
152
+ let current;
153
+ try {
154
+ current = await this.fetchRemoteHead(AbortSignal.timeout(this.postCommitTimeoutMs));
155
+ }
156
+ catch (error) {
157
+ throw new SyncBackendPublicationOutcomeUnknownError(`Git publication outcome is unknown: ${this.safeError(pushError ?? error)}`, { cause: pushError ?? error });
158
+ }
159
+ if (current !== candidate) {
160
+ if (pushError && current === observed) {
161
+ throw new Error(`Git publication failed without updating the owned branch: ${this.safeError(pushError)}`, {
162
+ cause: pushError,
163
+ });
164
+ }
165
+ throw new SyncBackendConflictError(pushError
166
+ ? `Git publication lease was rejected: ${this.safeError(pushError)}`
167
+ : "Git remote changed immediately after publication.", {
168
+ phase: "after-commit",
169
+ currentHead: current ? await this.headForSha(current) : undefined,
170
+ candidateMayHaveBeenActive: true,
171
+ cause: pushError instanceof Error ? pushError : undefined,
172
+ });
173
+ }
174
+ const head = await this.headForSha(candidate);
175
+ return { head, warnings: [] };
176
+ }
177
+ async listHistory(signal) {
178
+ const sha = await this.fetchRemoteHead(signal);
179
+ if (!sha)
180
+ return [];
181
+ const result = await this.git(["rev-list", "--first-parent", "--reverse", "--max-count=100", sha], { signal });
182
+ const commits = result.stdout.toString("utf8").trim().split("\n").filter(Boolean);
183
+ const entries = [];
184
+ for (const commit of commits) {
185
+ const { manifest } = await this.readPublication(commit, signal);
186
+ entries.push({
187
+ snapshotRef: commit,
188
+ snapshotId: manifest.snapshotId,
189
+ createdAt: manifest.createdAt,
190
+ machine: manifest.machine,
191
+ syncSessions: manifest.syncSessions,
192
+ });
193
+ }
194
+ return entries;
195
+ }
196
+ async diagnose(signal) {
197
+ const diagnostics = [
198
+ {
199
+ key: "git-scope",
200
+ level: "info",
201
+ message: "git check scope: read remote snapshots and inspect the local cache. Write access is not tested.",
202
+ },
203
+ ];
204
+ try {
205
+ const version = await runGit(["--version"], {
206
+ signal,
207
+ timeoutMs: this.commandTimeoutMs,
208
+ });
209
+ const versionText = version.stdout.toString("utf8").trim();
210
+ const supported = isSupportedGitVersion(versionText);
211
+ diagnostics.push({
212
+ key: "git-version",
213
+ level: supported ? "info" : "error",
214
+ message: supported
215
+ ? versionText
216
+ : `${versionText || "unknown Git version"}; pi-sync requires Git 2.30 or newer`,
217
+ });
218
+ }
219
+ catch (error) {
220
+ return [
221
+ {
222
+ key: "git-version",
223
+ level: "error",
224
+ message: syncErrorGuidance(new Error(this.safeError(error))),
225
+ },
226
+ ];
227
+ }
228
+ try {
229
+ const head = await this.readHead(signal);
230
+ if (head)
231
+ await this.readSnapshot(head.snapshotRef, signal);
232
+ diagnostics.push({
233
+ key: "git-remote",
234
+ level: "info",
235
+ message: head
236
+ ? `git remote: reachable; owned branch ${this.config.destination.branch} is valid`
237
+ : `git remote: reachable; owned branch ${this.config.destination.branch} is not created yet`,
238
+ });
239
+ diagnostics.push({
240
+ key: "git-cache",
241
+ level: "info",
242
+ message: "git cache: private bare repository is healthy",
243
+ });
244
+ }
245
+ catch (error) {
246
+ diagnostics.push({
247
+ key: "git-remote",
248
+ level: "error",
249
+ message: `git remote: ${syncErrorGuidance(new Error(this.safeError(error)))}`,
250
+ });
251
+ }
252
+ return diagnostics;
253
+ }
254
+ async resolveSnapshotReference(reference, head, signal) {
255
+ if (isCommitSha(reference) || /^[0-9a-f]{64}$/u.test(reference)) {
256
+ requireCommitSha(reference);
257
+ return reference;
258
+ }
259
+ if (!reference || reference.length > 512 || !/^[A-Za-z0-9._-]+$/u.test(reference)) {
260
+ throw new Error("Invalid Git publication reference.");
261
+ }
262
+ const result = await this.git(["rev-list", "--first-parent", "--max-count=100", head], {
263
+ signal,
264
+ });
265
+ const commits = result.stdout.toString("utf8").trim().split("\n").filter(Boolean);
266
+ const matches = [];
267
+ for (const commit of commits) {
268
+ const { manifest } = await this.readPublication(commit, signal);
269
+ if (manifest.snapshotId === reference)
270
+ matches.push(commit);
271
+ }
272
+ if (matches.length === 0) {
273
+ throw new Error(`Git snapshot publication was not found: ${reference}`);
274
+ }
275
+ if (matches.length > 1) {
276
+ throw new Error(`Git snapshot id is ambiguous; use a commit reference from /sync history: ${reference}`);
277
+ }
278
+ return matches[0];
279
+ }
280
+ async headForSha(sha, signal) {
281
+ const { manifest } = await this.readPublication(sha, signal);
282
+ return remoteHead(sha, manifest, this.identity);
283
+ }
284
+ async fetchRemoteHead(signal) {
285
+ await this.ensureCache(signal);
286
+ const result = await this.git(["ls-remote", "--refs", this.config.profile.remote, this.remoteRef()], { signal });
287
+ const line = result.stdout.toString("utf8").trim();
288
+ if (!line)
289
+ return undefined;
290
+ const [sha, ref, ...extra] = line.split(/\s+/u);
291
+ if (extra.length > 0 || ref !== this.remoteRef() || !sha) {
292
+ throw new Error("Git remote returned a malformed owned-ref response.");
293
+ }
294
+ requireCommitSha(sha);
295
+ await this.afterLsRemoteForTest?.();
296
+ return withGitCacheMutation(this.cacheDir, async () => {
297
+ const localRef = `refs/pisync/fetch/${process.pid}-${randomUUID()}`;
298
+ try {
299
+ await this.git(["fetch", "--no-tags", "--force", this.config.profile.remote, `${this.remoteRef()}:${localRef}`], { signal });
300
+ const fetched = (await this.git(["rev-parse", "--verify", localRef], { signal })).stdout
301
+ .toString("utf8")
302
+ .trim();
303
+ requireCommitSha(fetched);
304
+ return fetched;
305
+ }
306
+ finally {
307
+ await this.git(["update-ref", "-d", localRef], { timeoutMs: 5_000 }).catch(() => undefined);
308
+ }
309
+ }, signal);
310
+ }
311
+ async readManifest(commit, signal) {
312
+ requireCommitSha(commit);
313
+ const bytes = await this.showFile(commit, this.manifestPath(), signal, MAX_GIT_MANIFEST_BYTES);
314
+ let parsed;
315
+ try {
316
+ parsed = JSON.parse(bytes.toString("utf8"));
317
+ }
318
+ catch (error) {
319
+ throw new Error("Git publication manifest is malformed.", { cause: error });
320
+ }
321
+ return requireGitManifest(parsed);
322
+ }
323
+ showFile(commit, filePath, signal, maxOutputBytes) {
324
+ return this.git(["show", `${commit}:${filePath}`], { signal, maxOutputBytes }).then((result) => result.stdout);
325
+ }
326
+ async createCommit(snapshot, files, manifest, parent, signal) {
327
+ const manifestBytes = Buffer.from(`${JSON.stringify(manifest)}\n`, "utf8");
328
+ if (manifestBytes.byteLength > MAX_GIT_MANIFEST_BYTES) {
329
+ throw new Error(`Git publication manifest exceeds the ${MAX_GIT_MANIFEST_BYTES}-byte limit.`);
330
+ }
331
+ await this.ensureCache(signal);
332
+ const temporaryDirectory = await fs.mkdtemp(path.join(path.dirname(this.cacheDir), ".index-"));
333
+ const indexPath = path.join(temporaryDirectory, "index");
334
+ const payloadDirectory = path.join(temporaryDirectory, "payloads");
335
+ const env = { GIT_INDEX_FILE: indexPath };
336
+ try {
337
+ await fs.mkdir(payloadDirectory, { mode: 0o700 });
338
+ const uniqueFiles = [...new Map(files.map((file) => [file.sha256, file])).values()].sort((left, right) => left.sha256.localeCompare(right.sha256));
339
+ for (const file of uniqueFiles) {
340
+ throwIfAborted(signal);
341
+ await fs.writeFile(path.join(payloadDirectory, file.sha256), file.content, {
342
+ flag: "wx",
343
+ mode: 0o600,
344
+ });
345
+ }
346
+ await this.afterPayloadWriteForTest?.();
347
+ throwIfAborted(signal);
348
+ const hashed = await this.git(["hash-object", "-w", "--no-filters", "--stdin-paths"], {
349
+ cwd: payloadDirectory,
350
+ input: uniqueFiles.map((file) => file.sha256).join("\n") + (uniqueFiles.length ? "\n" : ""),
351
+ signal,
352
+ maxOutputBytes: Math.max(1024, uniqueFiles.length * 64),
353
+ });
354
+ const objectIds = hashed.stdout.toString("utf8").trim().split("\n").filter(Boolean);
355
+ if (objectIds.length !== uniqueFiles.length || objectIds.some((id) => !isCommitSha(id))) {
356
+ throw new Error("Git hash-object returned a malformed payload response.");
357
+ }
358
+ const objectsBySha256 = new Map(uniqueFiles.map((file, index) => [file.sha256, objectIds[index]]));
359
+ const manifestBlob = (await this.git(["hash-object", "-w", "--stdin"], { input: manifestBytes, signal })).stdout
360
+ .toString("utf8")
361
+ .trim();
362
+ if (!isCommitSha(manifestBlob))
363
+ throw new Error("Git returned an invalid manifest blob id.");
364
+ await this.git(["read-tree", "--empty"], { env, signal });
365
+ const indexLines = [
366
+ `100644 ${manifestBlob}\t${this.manifestPath()}`,
367
+ ...files.map((file) => {
368
+ const object = objectsBySha256.get(file.sha256);
369
+ if (!object)
370
+ throw new Error("Git payload object is missing after hashing.");
371
+ return `100644 ${object}\t${this.filePath(file.path)}`;
372
+ }),
373
+ ];
374
+ await this.git(["update-index", "-z", "--index-info"], {
375
+ env,
376
+ signal,
377
+ input: Buffer.from(`${indexLines.join("\0")}\0`, "utf8"),
378
+ });
379
+ const tree = (await this.git(["write-tree"], { env, signal })).stdout.toString("utf8").trim();
380
+ const date = Number.isNaN(Date.parse(snapshot.createdAt)) ? new Date().toISOString() : snapshot.createdAt;
381
+ const commit = await this.git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-F", "-"], {
382
+ signal,
383
+ input: `pi-sync snapshot ${snapshot.id}\n`,
384
+ env: {
385
+ GIT_AUTHOR_NAME: "pi-sync",
386
+ GIT_AUTHOR_EMAIL: "pi-sync@localhost",
387
+ GIT_COMMITTER_NAME: "pi-sync",
388
+ GIT_COMMITTER_EMAIL: "pi-sync@localhost",
389
+ GIT_AUTHOR_DATE: date,
390
+ GIT_COMMITTER_DATE: date,
391
+ },
392
+ });
393
+ const sha = commit.stdout.toString("utf8").trim();
394
+ requireCommitSha(sha);
395
+ return sha;
396
+ }
397
+ finally {
398
+ await fs.rm(temporaryDirectory, { recursive: true, force: true });
399
+ }
400
+ }
401
+ ensureCache(signal) {
402
+ if (!this.cacheReady) {
403
+ const operation = withGitCacheMutation(this.cacheDir, () => this.initializeCache(signal), signal);
404
+ const wrapped = operation.catch((error) => {
405
+ if (this.cacheReady === wrapped)
406
+ this.cacheReady = undefined;
407
+ throw this.redactedError(error);
408
+ });
409
+ this.cacheReady = wrapped;
410
+ }
411
+ return this.cacheReady;
412
+ }
413
+ async initializeCache(signal) {
414
+ const version = await runGit(["--version"], {
415
+ signal,
416
+ timeoutMs: this.commandTimeoutMs,
417
+ });
418
+ const versionText = version.stdout.toString("utf8").trim();
419
+ if (!isSupportedGitVersion(versionText)) {
420
+ throw new Error(`${versionText || "Unknown Git version"}; pi-sync requires Git 2.30 or newer.`);
421
+ }
422
+ const parent = path.dirname(this.cacheDir);
423
+ const cacheParent = path.dirname(this.cacheRoot);
424
+ await assertNotSymlink(cacheParent, "Git cache parent");
425
+ await assertNotSymlink(this.cacheRoot, "Git cache root");
426
+ await fs.mkdir(this.cacheRoot, { recursive: true, mode: 0o700 });
427
+ await assertNotSymlink(cacheParent, "Git cache parent");
428
+ await assertNotSymlink(this.cacheRoot, "Git cache root");
429
+ await assertNotSymlink(parent, "Git cache identity directory");
430
+ await fs.mkdir(parent, { recursive: true, mode: 0o700 });
431
+ await assertNotSymlink(parent, "Git cache identity directory");
432
+ let recreate = false;
433
+ try {
434
+ const stat = await fs.lstat(this.cacheDir);
435
+ if (stat.isSymbolicLink())
436
+ throw new Error("Refusing symlinked Git cache.");
437
+ if (!stat.isDirectory())
438
+ recreate = true;
439
+ else {
440
+ try {
441
+ recreate = !(await this.cacheUsesSha1(signal));
442
+ }
443
+ catch {
444
+ throwIfAborted(signal);
445
+ recreate = true;
446
+ }
447
+ }
448
+ }
449
+ catch (error) {
450
+ if (error.code !== "ENOENT")
451
+ throw error;
452
+ }
453
+ throwIfAborted(signal);
454
+ if (recreate)
455
+ await fs.rm(this.cacheDir, { recursive: true, force: true });
456
+ try {
457
+ await fs.access(this.cacheDir);
458
+ }
459
+ catch {
460
+ try {
461
+ await runGit(["init", "--bare", "--object-format=sha1", this.cacheDir], {
462
+ signal,
463
+ timeoutMs: this.commandTimeoutMs,
464
+ allowFileProtocol: this.allowLocalRemotes,
465
+ });
466
+ }
467
+ catch (initError) {
468
+ const concurrent = await this.cacheUsesSha1(signal).catch(() => false);
469
+ if (!concurrent)
470
+ throw initError;
471
+ }
472
+ }
473
+ if (process.platform !== "win32")
474
+ await fs.chmod(parent, 0o700);
475
+ }
476
+ async cacheUsesSha1(signal) {
477
+ const result = await this.git(["rev-parse", "--is-bare-repository", "--show-object-format"], {
478
+ signal,
479
+ });
480
+ return result.stdout.toString("utf8").trim() === "true\nsha1";
481
+ }
482
+ git(args, options = {}) {
483
+ return runGit(args, {
484
+ gitDir: this.cacheDir,
485
+ allowFileProtocol: this.allowLocalRemotes,
486
+ timeoutMs: options.timeoutMs ?? this.commandTimeoutMs,
487
+ ...options,
488
+ }).catch((error) => {
489
+ throw this.redactedError(error);
490
+ });
491
+ }
492
+ remoteRef() {
493
+ return `refs/heads/${this.config.destination.branch}`;
494
+ }
495
+ publicationPath() {
496
+ return this.config.destination.directory === "./" ? "" : this.config.destination.directory;
497
+ }
498
+ manifestPath() {
499
+ return posixJoin(this.publicationPath(), "manifest.json");
500
+ }
501
+ filePath(filePath) {
502
+ return posixJoin(this.publicationPath(), "files", filePath);
503
+ }
504
+ async readPublication(commit, signal) {
505
+ const manifest = await this.readManifest(commit, signal);
506
+ const entries = await this.readPublicationTree(commit, signal);
507
+ const payloadEntries = validateGitPublicationTree(entries, manifest, this.manifestPath(), (filePath) => this.filePath(filePath));
508
+ return { manifest, payloadEntries };
509
+ }
510
+ async readPublicationTree(commit, signal) {
511
+ const result = await this.git(["ls-tree", "-r", "-z", commit], {
512
+ signal,
513
+ maxOutputBytes: MAX_GIT_TREE_OUTPUT_BYTES,
514
+ });
515
+ return parseGitTree(result.stdout);
516
+ }
517
+ redactedError(error) {
518
+ if (error instanceof Error && error.name === "AbortError")
519
+ return error;
520
+ return new Error(this.safeError(error));
521
+ }
522
+ safeError(error) {
523
+ const raw = error instanceof GitCommandError
524
+ ? error.stderr || error.message
525
+ : error instanceof Error
526
+ ? error.message
527
+ : String(error);
528
+ return redactGitError(raw, this.config.profile.remote, this.cacheDir);
529
+ }
530
+ }
531
+ export function gitBackendIdentity(config) {
532
+ let remoteIdentity;
533
+ try {
534
+ remoteIdentity = normalizeGitRemoteIdentity(config.profile.remote);
535
+ }
536
+ catch {
537
+ remoteIdentity = config.profile.remote;
538
+ }
539
+ const canonical = JSON.stringify([remoteIdentity, config.destination.branch, config.destination.directory]);
540
+ return `git:${sha256(Buffer.from(canonical))}`;
541
+ }
542
+ function gitDestination(config) {
543
+ let host = "Git remote";
544
+ const remote = config.profile.remote;
545
+ if (remote.includes("://")) {
546
+ try {
547
+ host = new URL(remote).host;
548
+ }
549
+ catch {
550
+ host = "Git remote";
551
+ }
552
+ }
553
+ else {
554
+ const match = /^(?:[^@]+@)?(?<host>\[[^\]]+\]|[^:]+):/u.exec(remote);
555
+ if (match?.groups?.host)
556
+ host = match.groups.host;
557
+ }
558
+ return `${host} · ${config.destination.branch}:${config.destination.directory}`;
559
+ }
560
+ function remoteHead(sha, manifest, identity) {
561
+ return {
562
+ snapshotRef: sha,
563
+ snapshotId: manifest.snapshotId,
564
+ revision: `${identity}:${sha}`,
565
+ createdAt: manifest.createdAt,
566
+ machine: manifest.machine,
567
+ syncSessions: manifest.syncSessions,
568
+ ...(manifest.selection === undefined ? {} : { selection: manifest.selection }),
569
+ };
570
+ }
571
+ function matchesExpected(current, expected, identity) {
572
+ if (expected.kind === "missing")
573
+ return current === undefined;
574
+ try {
575
+ return current === decodeRevision(expected.revision, identity);
576
+ }
577
+ catch {
578
+ return false;
579
+ }
580
+ }
581
+ function decodeRevision(revision, identity) {
582
+ const prefix = `${identity}:`;
583
+ const sha = revision.startsWith(prefix) ? revision.slice(prefix.length) : "";
584
+ if (!/^[0-9a-f]{40}$/u.test(sha))
585
+ throw new Error("Invalid Git remote revision.");
586
+ return sha;
587
+ }
588
+ function isCommitSha(value) {
589
+ return /^[0-9a-f]{40}$/u.test(value);
590
+ }
591
+ function requireCommitSha(value) {
592
+ if (/^[0-9a-f]{64}$/u.test(value)) {
593
+ throw new Error("Unsupported Git SHA-256 repository; pi-sync currently requires SHA-1 refs.");
594
+ }
595
+ if (!/^[0-9a-f]{40}$/u.test(value))
596
+ throw new Error("Invalid Git publication reference.");
597
+ }
598
+ export function isSupportedGitVersion(value) {
599
+ const match = /git version (\d+)\.(\d+)/u.exec(value);
600
+ if (!match)
601
+ return false;
602
+ const major = Number(match[1]);
603
+ const minor = Number(match[2]);
604
+ return major > 2 || (major === 2 && minor >= 30);
605
+ }
606
+ function assertGitDestination(config) {
607
+ try {
608
+ if (normalizeGitBranch(config.destination.branch) !== config.destination.branch ||
609
+ normalizeGitDirectory(config.destination.directory) !== config.destination.directory) {
610
+ throw new Error("Git storage location is not normalized.");
611
+ }
612
+ validateGitNamespace(config.destination.namespace);
613
+ }
614
+ catch (error) {
615
+ throw new Error("Invalid Git storage location.", { cause: error });
616
+ }
617
+ }
618
+ function assertProductionRemote(remote) {
619
+ let normalized;
620
+ try {
621
+ normalized = normalizeGitRemote(remote);
622
+ }
623
+ catch (error) {
624
+ throw new Error(error instanceof Error ? error.message : "Invalid Git remote.", {
625
+ cause: error,
626
+ });
627
+ }
628
+ if (!normalized || normalized !== remote)
629
+ throw new Error("Invalid or non-normalized Git remote.");
630
+ }
631
+ async function withGitCacheMutation(cacheDir, run, signal) {
632
+ const previous = gitCacheMutationQueues.get(cacheDir) ?? Promise.resolve();
633
+ let started = false;
634
+ const operation = previous
635
+ .catch(() => undefined)
636
+ .then(() => {
637
+ throwIfAborted(signal);
638
+ started = true;
639
+ return run();
640
+ });
641
+ const tail = operation.then(() => undefined, () => undefined);
642
+ gitCacheMutationQueues.set(cacheDir, tail);
643
+ void tail.then(() => {
644
+ if (gitCacheMutationQueues.get(cacheDir) === tail)
645
+ gitCacheMutationQueues.delete(cacheDir);
646
+ });
647
+ if (!signal)
648
+ return operation;
649
+ throwIfAborted(signal);
650
+ let rejectAbort;
651
+ const aborted = new Promise((_resolve, reject) => {
652
+ rejectAbort = reject;
653
+ });
654
+ const onAbort = () => rejectAbort?.(abortReason(signal));
655
+ signal.addEventListener("abort", onAbort, { once: true });
656
+ if (signal.aborted)
657
+ onAbort();
658
+ try {
659
+ return await Promise.race([operation, aborted]);
660
+ }
661
+ catch (error) {
662
+ // A queued job can cancel immediately, but a running job owns a child/cache
663
+ // mutation. Drain its bounded cleanup before releasing outer sync guards.
664
+ if (started)
665
+ await tail;
666
+ throw error;
667
+ }
668
+ finally {
669
+ signal.removeEventListener("abort", onAbort);
670
+ }
671
+ }
672
+ async function assertNotSymlink(target, label) {
673
+ try {
674
+ const stat = await fs.lstat(target);
675
+ if (stat.isSymbolicLink())
676
+ throw new Error(`Refusing symlinked ${label}.`);
677
+ }
678
+ catch (error) {
679
+ if (error.code !== "ENOENT")
680
+ throw error;
681
+ }
682
+ }
683
+ function redactGitError(value, remote, cacheDir) {
684
+ return (value
685
+ .replaceAll(remote, "<git-remote>")
686
+ .replaceAll(cacheDir, "<git-cache>")
687
+ .replace(/https:\/\/[^/@\s]+@/gu, "https://<credentials>@")
688
+ .replace(/\b(password|token|authorization)=\S+/giu, "$1=<redacted>")
689
+ .replace(/\bBearer\s+\S+/giu, "Bearer <redacted>")
690
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: sanitize untrusted process output.
691
+ .replace(/[\u0000-\u001f\u007f-\u009f]/gu, " ")
692
+ .trim()
693
+ .slice(0, 4096));
694
+ }
695
+ function sha256(value) {
696
+ return createHash("sha256").update(value).digest("hex");
697
+ }
698
+ function abortReason(signal) {
699
+ return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
700
+ }