@git-stunts/git-cas 5.3.2 → 6.0.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 (173) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +998 -214
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +296 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2224 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +208 -65
  60. package/index.js +163 -54
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
@@ -1,6 +1,9 @@
1
1
  import { Policy } from '@git-stunts/alfred';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
2
5
  import GitPersistencePort from '../../ports/GitPersistencePort.js';
3
- import CasError from '../../domain/errors/CasError.js';
6
+ import { CasError, createCasError, ErrorCodes } from '../../domain/errors/index.js';
4
7
 
5
8
  /**
6
9
  * Default resilience policy: 30 s timeout (no retry).
@@ -11,6 +14,10 @@ import CasError from '../../domain/errors/CasError.js';
11
14
  * an unref'd timer that allows Node to exit before the next attempt starts.
12
15
  */
13
16
  const DEFAULT_POLICY = Policy.timeout(30_000);
17
+ export const DEFAULT_MAX_BLOB_SIZE = 10 * 1024 * 1024;
18
+ const MIN_READ_BLOB_LIMIT = 1;
19
+ const MIN_MAX_BLOB_SIZE = 1024;
20
+ const MAX_BLOB_SIZE_LIMIT = Number.MAX_SAFE_INTEGER;
14
21
 
15
22
  /**
16
23
  * {@link GitPersistencePort} implementation backed by `@git-stunts/plumbing`.
@@ -19,6 +26,7 @@ const DEFAULT_POLICY = Policy.timeout(30_000);
19
26
  * (30 s timeout by default).
20
27
  */
21
28
  export default class GitPersistenceAdapter extends GitPersistencePort {
29
+ #maxBlobSize = DEFAULT_MAX_BLOB_SIZE;
22
30
  /**
23
31
  * @param {Object} options
24
32
  * @param {import('@git-stunts/plumbing').default} options.plumbing - GitPlumbing instance.
@@ -36,12 +44,14 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
36
44
  * @returns {Promise<string>} The Git OID of the stored blob.
37
45
  */
38
46
  async writeBlob(content) {
39
- return this.policy.execute(() =>
40
- this.plumbing.execute({
41
- args: ['hash-object', '-w', '--stdin'],
42
- input: content,
43
- }),
44
- );
47
+ return this.policy.execute(() => (
48
+ typeof globalThis.Bun !== 'undefined'
49
+ ? this.#writeBlobFromTempFile(content)
50
+ : this.plumbing.execute({
51
+ args: ['hash-object', '-w', '--stdin'],
52
+ input: content,
53
+ })
54
+ ));
45
55
  }
46
56
 
47
57
  /**
@@ -61,17 +71,54 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
61
71
  /**
62
72
  * @override
63
73
  * @param {string} oid - Git object ID.
74
+ * @param {number} [maxBytes=10485760] - Safety limit (default 10MB).
64
75
  * @returns {Promise<Buffer>} The blob content.
65
76
  */
66
- async readBlob(oid) {
67
- return this.policy.execute(async () => {
68
- const stream = await this.plumbing.executeStream({
77
+ async readBlob(oid, maxBytes) {
78
+ const limit = maxBytes === undefined
79
+ ? this.#maxBlobSize
80
+ : GitPersistenceAdapter.#validatedReadBlobLimit(maxBytes);
81
+ const chunks = [];
82
+ let bytesRead = 0;
83
+ for await (const chunk of await this.readBlobStream(oid)) {
84
+ bytesRead += chunk.length;
85
+ if (bytesRead > limit) {
86
+ throw new CasError(
87
+ `Blob ${oid} exceeds safety limit of ${limit} bytes`,
88
+ ErrorCodes.RESTORE_TOO_LARGE,
89
+ { oid, maxBytes: limit },
90
+ );
91
+ }
92
+ chunks.push(chunk);
93
+ }
94
+ return Buffer.concat(chunks);
95
+ }
96
+
97
+ /**
98
+ * Sets the adapter-level safety limit used by `readBlob()` when callers do
99
+ * not provide a per-call limit.
100
+ *
101
+ * @param {number} maxBlobSize - Metadata blob safety limit in bytes.
102
+ * @returns {void}
103
+ */
104
+ setMaxBlobSize(maxBlobSize) {
105
+ GitPersistenceAdapter.#assertMaxBlobSize(maxBlobSize);
106
+ this.#maxBlobSize = maxBlobSize;
107
+ }
108
+
109
+ /**
110
+ * @override
111
+ * @param {string} oid - Git object ID.
112
+ * @returns {Promise<AsyncIterable<Buffer>>} The blob content stream.
113
+ */
114
+ async readBlobStream(oid) {
115
+ const stream = await this.policy.execute(async () => (
116
+ await this.plumbing.executeStream({
69
117
  args: ['cat-file', 'blob', oid],
70
- });
71
- const data = await stream.collect({ asString: false });
72
- // Plumbing returns Uint8Array; ensure we return a Buffer for codec/crypto compat
73
- return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
74
- });
118
+ })
119
+ ));
120
+
121
+ return this.#bufferStream(stream);
75
122
  }
76
123
 
77
124
  /**
@@ -85,35 +132,181 @@ export default class GitPersistenceAdapter extends GitPersistencePort {
85
132
  args: ['ls-tree', '-z', treeOid],
86
133
  });
87
134
 
88
- if (!output || output.length === 0) {
89
- return [];
90
- }
135
+ return GitPersistenceAdapter.#parseTreeOutput(output);
136
+ });
137
+ }
91
138
 
92
- return output.split('\0').filter(Boolean).map((/** @type {string} */ entry) => {
93
- // Format: <mode> <type> <oid>\t<name>
94
- const tabIndex = entry.indexOf('\t');
95
- if (tabIndex === -1) {
96
- throw new CasError(
97
- `Malformed ls-tree entry: ${entry}`,
98
- 'TREE_PARSE_ERROR',
99
- { rawEntry: entry },
100
- );
101
- }
102
- const meta = entry.slice(0, tabIndex).split(' ');
103
- if (meta.length !== 3) {
104
- throw new CasError(
105
- `Malformed ls-tree entry: ${entry}`,
106
- 'TREE_PARSE_ERROR',
107
- { rawEntry: entry },
108
- );
109
- }
110
- return {
111
- mode: meta[0],
112
- type: meta[1],
113
- oid: meta[2],
114
- name: entry.slice(tabIndex + 1),
115
- };
139
+ /**
140
+ * @override
141
+ * @param {string} treeOid - Git tree OID.
142
+ * @param {string} treePath - Tree entry path/name to resolve.
143
+ * @returns {Promise<{ mode: string, type: string, oid: string, name: string }|null>}
144
+ */
145
+ async readTreeEntry(treeOid, treePath) {
146
+ return this.policy.execute(async () => {
147
+ const output = await this.plumbing.execute({
148
+ args: ['ls-tree', '-z', treeOid, '--', treePath],
116
149
  });
150
+ return GitPersistenceAdapter.#parseTreeOutput(output)[0] || null;
117
151
  });
118
152
  }
153
+
154
+ /**
155
+ * @override
156
+ * @param {string} treeOid - Git tree OID.
157
+ * @returns {AsyncIterable<{ mode: string, type: string, oid: string, name: string }>}
158
+ */
159
+ async *iterateTree(treeOid) {
160
+ const stream = await this.policy.execute(async () => (
161
+ await this.plumbing.executeStream({
162
+ args: ['ls-tree', '-z', treeOid],
163
+ })
164
+ ));
165
+ let pending = '';
166
+ for await (const chunk of stream) {
167
+ pending += GitPersistenceAdapter.#toBuffer(chunk).toString();
168
+ let nulIndex = pending.indexOf('\0');
169
+ while (nulIndex !== -1) {
170
+ const rawEntry = pending.slice(0, nulIndex);
171
+ pending = pending.slice(nulIndex + 1);
172
+ if (rawEntry) {
173
+ yield GitPersistenceAdapter.#parseTreeEntry(rawEntry);
174
+ }
175
+ nulIndex = pending.indexOf('\0');
176
+ }
177
+ }
178
+ if (pending) {
179
+ yield GitPersistenceAdapter.#parseTreeEntry(pending);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Bun can surface unhandled EPIPE writes when large buffers are fed through
185
+ * `git hash-object --stdin`. Write the blob to a temp file and hash the file
186
+ * directly instead. `--no-filters` preserves raw bytes.
187
+ *
188
+ * @param {Buffer|string} content
189
+ * @returns {Promise<string>}
190
+ */
191
+ async #writeBlobFromTempFile(content) {
192
+ const tempDir = await mkdtemp(path.join(os.tmpdir(), 'git-cas-blob-'));
193
+ const tempPath = path.join(tempDir, 'blob.bin');
194
+
195
+ try {
196
+ await writeFile(tempPath, content);
197
+ return await this.plumbing.execute({
198
+ args: ['hash-object', '-w', '--no-filters', tempPath],
199
+ });
200
+ } finally {
201
+ await rm(tempDir, { recursive: true, force: true });
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Normalizes a plumbing stdout stream into Buffer chunks.
207
+ *
208
+ * @param {AsyncIterable<Buffer|Uint8Array|string>} stream
209
+ * @returns {AsyncIterable<Buffer>}
210
+ */
211
+ async *#bufferStream(stream) {
212
+ for await (const chunk of stream) {
213
+ yield GitPersistenceAdapter.#toBuffer(chunk);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * @param {Buffer|Uint8Array|string} chunk
219
+ * @returns {Buffer}
220
+ */
221
+ static #toBuffer(chunk) {
222
+ if (Buffer.isBuffer(chunk)) {
223
+ return chunk;
224
+ }
225
+ if (chunk instanceof Uint8Array) {
226
+ return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
227
+ }
228
+ return Buffer.from(String(chunk));
229
+ }
230
+
231
+ /**
232
+ * @param {unknown} maxBytes
233
+ * @returns {number}
234
+ */
235
+ static #validatedReadBlobLimit(maxBytes) {
236
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < MIN_READ_BLOB_LIMIT || maxBytes > MAX_BLOB_SIZE_LIMIT) {
237
+ throw createCasError(
238
+ `maxBytes must be an integer in [${MIN_READ_BLOB_LIMIT}, ${MAX_BLOB_SIZE_LIMIT}]`,
239
+ ErrorCodes.INVALID_OPTIONS,
240
+ {
241
+ label: 'maxBytes',
242
+ value: maxBytes,
243
+ min: MIN_READ_BLOB_LIMIT,
244
+ max: MAX_BLOB_SIZE_LIMIT,
245
+ },
246
+ );
247
+ }
248
+ return maxBytes;
249
+ }
250
+
251
+ /**
252
+ * @param {number} maxBlobSize
253
+ * @returns {void}
254
+ */
255
+ static #assertMaxBlobSize(maxBlobSize) {
256
+ if (!Number.isInteger(maxBlobSize) || maxBlobSize < MIN_MAX_BLOB_SIZE || maxBlobSize > MAX_BLOB_SIZE_LIMIT) {
257
+ throw createCasError(
258
+ `maxBlobSize must be an integer in [${MIN_MAX_BLOB_SIZE}, ${MAX_BLOB_SIZE_LIMIT}]`,
259
+ ErrorCodes.INVALID_OPTIONS,
260
+ {
261
+ label: 'maxBlobSize',
262
+ value: maxBlobSize,
263
+ min: MIN_MAX_BLOB_SIZE,
264
+ max: MAX_BLOB_SIZE_LIMIT,
265
+ },
266
+ );
267
+ }
268
+ }
269
+
270
+ /**
271
+ * @param {string} output
272
+ * @returns {Array<{ mode: string, type: string, oid: string, name: string }>}
273
+ */
274
+ static #parseTreeOutput(output) {
275
+ if (!output || output.length === 0) {
276
+ return [];
277
+ }
278
+ return output
279
+ .split('\0')
280
+ .filter(Boolean)
281
+ .map((entry) => GitPersistenceAdapter.#parseTreeEntry(entry));
282
+ }
283
+
284
+ /**
285
+ * @param {string} entry
286
+ * @returns {{ mode: string, type: string, oid: string, name: string }}
287
+ */
288
+ static #parseTreeEntry(entry) {
289
+ const tabIndex = entry.indexOf('\t');
290
+ if (tabIndex === -1) {
291
+ throw new CasError(
292
+ `Malformed ls-tree entry: ${entry}`,
293
+ ErrorCodes.TREE_PARSE_ERROR,
294
+ { rawEntry: entry },
295
+ );
296
+ }
297
+ const meta = entry.slice(0, tabIndex).split(' ');
298
+ if (meta.length !== 3) {
299
+ throw new CasError(
300
+ `Malformed ls-tree entry: ${entry}`,
301
+ ErrorCodes.TREE_PARSE_ERROR,
302
+ { rawEntry: entry },
303
+ );
304
+ }
305
+ return {
306
+ mode: meta[0],
307
+ type: meta[1],
308
+ oid: meta[2],
309
+ name: entry.slice(tabIndex + 1),
310
+ };
311
+ }
119
312
  }
@@ -0,0 +1,62 @@
1
+ import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
2
+ import GitPlumbingInitializationError from '../../domain/errors/GitPlumbingInitializationError.js';
3
+ import GitPlumbingFactoryPort from '../../ports/GitPlumbingFactoryPort.js';
4
+
5
+ /**
6
+ * @param {{ Bun?: unknown }} runtime
7
+ * @param {{ ENV_NODE?: string }} shellRunnerFactory
8
+ * @returns {string | undefined}
9
+ */
10
+ export function resolveGitRunnerEnv(runtime = globalThis, shellRunnerFactory = ShellRunnerFactory) {
11
+ return typeof runtime.Bun !== 'undefined' ? shellRunnerFactory.ENV_NODE : undefined;
12
+ }
13
+
14
+ function optionsForCreateDefault({ cwd, env }) {
15
+ const options = { cwd };
16
+ if (env !== undefined) {
17
+ options.env = env;
18
+ }
19
+ return options;
20
+ }
21
+
22
+ export default class GitPlumbingFactoryAdapter extends GitPlumbingFactoryPort {
23
+ #GitPlumbingClass;
24
+ #runtime;
25
+ #shellRunnerFactory;
26
+
27
+ /**
28
+ * @param {Object} [options]
29
+ * @param {typeof GitPlumbing} [options.GitPlumbingClass]
30
+ * @param {typeof ShellRunnerFactory} [options.shellRunnerFactory]
31
+ * @param {{ Bun?: unknown }} [options.runtime]
32
+ */
33
+ constructor({
34
+ GitPlumbingClass = GitPlumbing,
35
+ shellRunnerFactory = ShellRunnerFactory,
36
+ runtime = globalThis,
37
+ } = {}) {
38
+ super();
39
+ this.#GitPlumbingClass = GitPlumbingClass;
40
+ this.#shellRunnerFactory = shellRunnerFactory;
41
+ this.#runtime = runtime;
42
+ }
43
+
44
+ /**
45
+ * @param {{ cwd?: string, env?: string }} [options]
46
+ * @returns {Promise<GitPlumbing>}
47
+ */
48
+ async create({ cwd = '.', env } = {}) {
49
+ const runnerEnv = env ?? resolveGitRunnerEnv(this.#runtime, this.#shellRunnerFactory);
50
+ const createOptions = optionsForCreateDefault({ cwd, env: runnerEnv });
51
+
52
+ try {
53
+ return await this.#GitPlumbingClass.createDefault(createOptions);
54
+ } catch (error) {
55
+ throw new GitPlumbingInitializationError(`Failed to initialize Git plumbing for cwd "${cwd}"`, {
56
+ cwd,
57
+ env: runnerEnv,
58
+ originalError: error,
59
+ });
60
+ }
61
+ }
62
+ }
@@ -1,5 +1,7 @@
1
1
  import { Policy } from '@git-stunts/alfred';
2
2
  import GitRefPort from '../../ports/GitRefPort.js';
3
+ import { CasError, ErrorCodes } from '../../domain/errors/index.js';
4
+ import { isGitMissingRefError } from '../../domain/helpers/gitRefErrors.js';
3
5
 
4
6
  /**
5
7
  * Default resilience policy: 30 s timeout (no retry).
@@ -10,6 +12,7 @@ import GitRefPort from '../../ports/GitRefPort.js';
10
12
  * an unref'd timer that allows Node to exit before the next attempt starts.
11
13
  */
12
14
  const DEFAULT_POLICY = Policy.timeout(30_000);
15
+ const GIT_NULL_OID = '0'.repeat(40);
13
16
 
14
17
  /**
15
18
  * {@link GitRefPort} implementation backed by `@git-stunts/plumbing`.
@@ -35,9 +38,19 @@ export default class GitRefAdapter extends GitRefPort {
35
38
  * @returns {Promise<string>} The commit OID.
36
39
  */
37
40
  async resolveRef(ref) {
38
- return this.policy.execute(() =>
39
- this.plumbing.execute({ args: ['rev-parse', ref] }),
40
- );
41
+ try {
42
+ return await this.policy.execute(() =>
43
+ this.plumbing.execute({ args: ['rev-parse', ref] }),
44
+ );
45
+ } catch (err) {
46
+ if (isGitMissingRefError(err, ref)) {
47
+ throw new CasError(`Git ref not found: ${ref}`, ErrorCodes.GIT_REF_NOT_FOUND, {
48
+ ref,
49
+ originalError: err,
50
+ });
51
+ }
52
+ throw err;
53
+ }
41
54
  }
42
55
 
43
56
  /**
@@ -74,13 +87,13 @@ export default class GitRefAdapter extends GitRefPort {
74
87
  * @param {Object} options
75
88
  * @param {string} options.ref - Git ref to update.
76
89
  * @param {string} options.newOid - New OID to set.
77
- * @param {string|null} [options.expectedOldOid] - Expected current OID for CAS.
90
+ * @param {string|null} [options.expectedOldOid] - Expected current OID for CAS; `null` means the ref must not exist.
78
91
  * @returns {Promise<void>}
79
92
  */
80
93
  async updateRef({ ref, newOid, expectedOldOid }) {
81
94
  const args = ['update-ref', ref, newOid];
82
- if (expectedOldOid) {
83
- args.push(expectedOldOid);
95
+ if (expectedOldOid !== undefined) {
96
+ args.push(expectedOldOid ?? GIT_NULL_OID);
84
97
  }
85
98
  await this.policy.execute(() =>
86
99
  this.plumbing.execute({ args }),
@@ -0,0 +1,64 @@
1
+ import { gzip, gunzip, createGzip, createGunzip } from 'node:zlib';
2
+ import { Readable } from 'node:stream';
3
+ import { promisify } from 'node:util';
4
+ import CompressionPort from '../../ports/CompressionPort.js';
5
+
6
+ const gzipAsync = promisify(gzip);
7
+ const gunzipAsync = promisify(gunzip);
8
+
9
+ /**
10
+ * Node.js compression adapter using `node:zlib` (gzip/gunzip).
11
+ *
12
+ * Provides buffer and streaming compression/decompression via Node's built-in
13
+ * zlib bindings.
14
+ */
15
+ export default class NodeCompressionAdapter extends CompressionPort {
16
+ /** @override */
17
+ async compressBuffer(buffer) {
18
+ return gzipAsync(buffer);
19
+ }
20
+
21
+ /** @override */
22
+ async decompressBuffer(buffer) {
23
+ return gunzipAsync(buffer);
24
+ }
25
+
26
+ /** @override */
27
+ async *compressStream(source) {
28
+ const gz = createGzip();
29
+ const input = Readable.from(source);
30
+ input.on('error', (error) => { gz.destroy(error); });
31
+ input.pipe(gz);
32
+ try {
33
+ for await (const chunk of gz) {
34
+ yield chunk;
35
+ }
36
+ } finally {
37
+ if (!gz.destroyed) { gz.destroy(); }
38
+ }
39
+ }
40
+
41
+ /** @override */
42
+ async *decompressStream(source) {
43
+ const gunzipStream = createGunzip();
44
+ const input = Readable.from(source);
45
+ const forwardInputError = (err) => {
46
+ const error = err instanceof Error ? err : new Error(String(err));
47
+ gunzipStream.destroy(error);
48
+ };
49
+ input.on('error', forwardInputError);
50
+ input.pipe(gunzipStream);
51
+
52
+ try {
53
+ for await (const chunk of gunzipStream) {
54
+ yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
55
+ }
56
+ } finally {
57
+ input.removeListener('error', forwardInputError);
58
+ input.destroy();
59
+ if (!gunzipStream.destroyed) {
60
+ gunzipStream.destroy();
61
+ }
62
+ }
63
+ }
64
+ }