@git-stunts/git-cas 6.0.0 → 6.0.1

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.
@@ -149,12 +149,12 @@ export default class CasService {
149
149
  }
150
150
  }
151
151
 
152
- #buildStoreStrategies({ crypto }) {
152
+ #buildStoreStrategies({ crypto, chunks = this.#chunkRepository }) {
153
153
  return Object.freeze({
154
- plain: new StorePlain(this.#chunkRepository),
155
- convergent: new StoreConvergent(this.#chunkRepository),
156
- framed: new StoreFramed({ chunks: this.#chunkRepository, framed: this.#framed }),
157
- whole: new StoreWhole({ chunks: this.#chunkRepository, crypto }),
154
+ plain: new StorePlain(chunks),
155
+ convergent: new StoreConvergent(chunks),
156
+ framed: new StoreFramed({ chunks, framed: this.#framed }),
157
+ whole: new StoreWhole({ chunks, crypto }),
158
158
  });
159
159
  }
160
160
 
@@ -243,14 +243,27 @@ export default class CasService {
243
243
  return;
244
244
  }
245
245
  if (!['fixed', 'cdc'].includes(chunking.strategy)) {
246
- throw createCasError(
247
- `Unsupported chunking strategy: ${chunking.strategy}`,
248
- ErrorCodes.INVALID_CHUNKING_STRATEGY,
249
- { strategy: chunking.strategy },
250
- );
246
+ throw createCasError(`Unsupported chunking strategy: ${chunking.strategy}`, ErrorCodes.INVALID_CHUNKING_STRATEGY, { strategy: chunking.strategy });
251
247
  }
252
248
  }
253
249
 
250
+ #validateOperationChunker(chunker) {
251
+ if (!chunker) {
252
+ return this.chunker;
253
+ }
254
+ if (typeof chunker.chunk !== 'function' || typeof chunker.strategy !== 'string') {
255
+ throw createCasError('chunker must implement ChunkingPort', ErrorCodes.INVALID_OPTIONS, { strategy: chunker.strategy });
256
+ }
257
+ return chunker;
258
+ }
259
+
260
+ #storeStrategiesFor(chunker) {
261
+ if (chunker === this.chunker) {
262
+ return this.#storeStrategies;
263
+ }
264
+ return this.#buildStoreStrategies({ crypto: this.crypto, chunks: this.#chunkRepository.withChunker(chunker) });
265
+ }
266
+
254
267
  /**
255
268
  * @param {Object} options
256
269
  * @param {AsyncIterable<Uint8Array>} options.source
@@ -263,20 +276,21 @@ export default class CasService {
263
276
  * @param {{ algorithm: 'gzip' }} [options.compression]
264
277
  * @param {Array<{label: string, key: Uint8Array}>} [options.recipients]
265
278
  * @param {number} [options.merkleThreshold]
279
+ * @param {import('../../ports/ChunkingPort.js').default} [options.chunker]
266
280
  * @returns {Promise<Manifest>}
267
281
  */
268
- async store({
269
- source,
270
- slug,
271
- filename,
272
- encryptionKey,
273
- passphrase,
274
- encryption,
275
- kdfOptions,
276
- compression,
277
- recipients,
278
- merkleThreshold,
279
- }) {
282
+ async store(options) {
283
+ const { source, slug, filename, compression, merkleThreshold } = options;
284
+ this.#validateStoreOptions(options);
285
+ const plan = await this.#buildStorePlan(options);
286
+ const manifestData = this._buildManifestData({ slug, filename, compression, chunker: plan.chunker });
287
+ const processedSource = compression ? this.#compression.compress(source) : source;
288
+
289
+ await this._dispatchStore({ processedSource, manifestData, keyInfo: plan.keyInfo, encryptionConfig: plan.encryptionConfig, chunker: plan.chunker });
290
+ return this.#finalizeStore({ manifestData, merkleThreshold, keyInfo: plan.keyInfo, slug });
291
+ }
292
+
293
+ #validateStoreOptions({ source, recipients, encryptionKey, passphrase, compression, merkleThreshold }) {
280
294
  if (!source || typeof source[Symbol.asyncIterator] !== 'function') {
281
295
  throw createCasError('source must be an async iterable', ErrorCodes.INVALID_OPTIONS, { sourceType: typeof source });
282
296
  }
@@ -286,15 +300,18 @@ export default class CasService {
286
300
  KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
287
301
  this._validateCompression(compression);
288
302
  CasService.#validateMerkleThreshold(merkleThreshold);
303
+ }
289
304
 
305
+ async #buildStorePlan({ encryptionKey, passphrase, encryption, kdfOptions, recipients, chunker }) {
306
+ const operationChunker = this.#validateOperationChunker(chunker);
290
307
  const keyInfo = recipients
291
308
  ? await this.#keyResolver.resolveRecipients(recipients)
292
309
  : await this.#keyResolver.resolveForStore(encryptionKey, passphrase, kdfOptions);
293
- const encryptionConfig = this._resolveStoreEncryptionConfig(encryption, !!keyInfo.key);
294
- const manifestData = this._buildManifestData(slug, filename, compression);
295
- const processedSource = compression ? this.#compression.compress(source) : source;
310
+ const encryptionConfig = this._resolveStoreEncryptionConfigForChunker({ encryption, hasEncryptionKey: !!keyInfo.key, chunker: operationChunker });
311
+ return { chunker: operationChunker, keyInfo, encryptionConfig };
312
+ }
296
313
 
297
- await this._dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig });
314
+ #finalizeStore({ manifestData, merkleThreshold, keyInfo, slug }) {
298
315
  const manifest = new Manifest(manifestData);
299
316
  this.#rememberMerkleThreshold(manifest, merkleThreshold);
300
317
  this.observability.metric('file', {
@@ -307,6 +324,10 @@ export default class CasService {
307
324
  return new StoreSuccess({ manifest }).manifest;
308
325
  }
309
326
 
327
+ _resolveStoreEncryptionConfigForChunker({ encryption, hasEncryptionKey, chunker }) {
328
+ return StoreEncryptionConfig.resolve({ encryption, hasEncryptionKey, chunker, observability: this.observability });
329
+ }
330
+
310
331
  /**
311
332
  * @param {Manifest} manifest
312
333
  * @param {number|undefined} merkleThreshold
@@ -317,24 +338,24 @@ export default class CasService {
317
338
  }
318
339
  }
319
340
 
320
- async _dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig }) {
341
+ async _dispatchStore({ processedSource, manifestData, keyInfo, encryptionConfig, chunker = this.chunker }) {
321
342
  const strategy = StoreStrategy.for({
322
343
  keyInfo,
323
344
  encryptionConfig,
324
- chunker: this.chunker,
345
+ chunker,
325
346
  observability: this.observability,
326
- strategies: this.#storeStrategies,
347
+ strategies: this.#storeStrategiesFor(chunker),
327
348
  });
328
349
  await strategy.execute({ processedSource, manifestData, keyInfo, encryptionConfig });
329
350
  }
330
351
 
331
- _buildManifestData(slug, filename, compression) {
352
+ _buildManifestData({ slug, filename, compression, chunker = this.chunker }) {
332
353
  const data = { slug, filename, size: 0, chunks: [] };
333
354
  if (this.formatVersion) {
334
355
  data.formatVersion = this.formatVersion;
335
356
  }
336
- if (this.chunker.strategy !== 'fixed') {
337
- data.chunking = { strategy: this.chunker.strategy, params: this.chunker.params };
357
+ if (chunker.strategy !== 'fixed') {
358
+ data.chunking = { strategy: chunker.strategy, params: chunker.params };
338
359
  }
339
360
  if (compression) {
340
361
  data.compression = { algorithm: 'gzip' };
@@ -37,6 +37,21 @@ export default class ChunkRepository {
37
37
  this.#persistence = persistence;
38
38
  }
39
39
 
40
+ /**
41
+ * @param {import('../../ports/ChunkingPort.js').default} chunker
42
+ * @returns {ChunkRepository}
43
+ */
44
+ withChunker(chunker) {
45
+ return new ChunkRepository({
46
+ chunker,
47
+ concurrency: this.#concurrency,
48
+ convergent: this.#convergent,
49
+ hashBytes: this.#hashBytes,
50
+ observability: this.#observability,
51
+ persistence: this.#persistence,
52
+ });
53
+ }
54
+
40
55
  /**
41
56
  * @param {AsyncIterable<Uint8Array>} source
42
57
  * @param {{ chunks: Array, size: number }} manifestData
@@ -64,7 +79,13 @@ export default class ChunkRepository {
64
79
  ? await this.#convergent.encryptChunk(buf, convergentKey, digest)
65
80
  : buf;
66
81
  const blob = await this.#persistence.writeBlob(blobData);
67
- this.#observability.metric('chunk', { action: 'stored', index, size: buf.length, digest, blob });
82
+ this.#observability.metric('chunk', {
83
+ action: 'stored',
84
+ index,
85
+ size: buf.length,
86
+ digest,
87
+ blob,
88
+ });
68
89
  return { index, size: buf.length, digest, blob };
69
90
  }
70
91
 
@@ -90,7 +111,7 @@ export default class ChunkRepository {
90
111
  const err = createCasError(
91
112
  `Chunk ${chunk.index} integrity check failed`,
92
113
  ErrorCodes.INTEGRITY_ERROR,
93
- { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
114
+ { chunkIndex: chunk.index, expected: chunk.digest, actual: digest }
94
115
  );
95
116
  this.#observability.metric('error', { code: err.code, message: err.message });
96
117
  throw err;
@@ -109,16 +130,16 @@ export default class ChunkRepository {
109
130
  if (maxBytes !== undefined) {
110
131
  throw createCasError(
111
132
  'Buffered restore safety requires persistence.readBlobStream() so ' +
112
- 'encrypted/compressed restore can enforce maxRestoreBufferSize with ' +
113
- 'memory-safe chunk reads. Implement readBlobStream() on the adapter ' +
114
- 'or use a GitPersistenceAdapter-backed facade. See docs/EXTENDING.md#persistence-adapter-requirements.',
133
+ 'encrypted/compressed restore can enforce maxRestoreBufferSize with ' +
134
+ 'memory-safe chunk reads. Implement readBlobStream() on the adapter ' +
135
+ 'or use a GitPersistenceAdapter-backed facade. See docs/EXTENDING.md#persistence-adapter-requirements.',
115
136
  ErrorCodes.PERSISTENCE_CAPABILITY_REQUIRED,
116
137
  {
117
138
  capability: 'readBlobStream',
118
139
  mode: 'buffered-restore',
119
140
  oid: blobOid,
120
141
  docs: 'docs/EXTENDING.md#persistence-adapter-requirements',
121
- },
142
+ }
122
143
  );
123
144
  }
124
145
  return normalizeByteChunk(await this.#persistence.readBlob(blobOid));
@@ -139,8 +160,10 @@ export default class ChunkRepository {
139
160
  * @returns {boolean}
140
161
  */
141
162
  supportsReadBlobStream() {
142
- return typeof this.#persistence.readBlobStream === 'function'
143
- && this.#persistence.readBlobStream !== GitPersistencePort.prototype.readBlobStream;
163
+ return (
164
+ typeof this.#persistence.readBlobStream === 'function' &&
165
+ this.#persistence.readBlobStream !== GitPersistencePort.prototype.readBlobStream
166
+ );
144
167
  }
145
168
 
146
169
  /**
@@ -157,7 +180,12 @@ export default class ChunkRepository {
157
180
  });
158
181
  totalRead += blob.length;
159
182
  buffers.push(blob);
160
- this.#observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
183
+ this.#observability.metric('chunk', {
184
+ action: 'restored',
185
+ index: chunk.index,
186
+ size: blob.length,
187
+ digest: chunk.digest,
188
+ });
161
189
  }
162
190
  return buffers;
163
191
  }
@@ -172,7 +200,7 @@ export default class ChunkRepository {
172
200
  throw createCasError(
173
201
  `Buffered restore read ${size} bytes from blob ${oid} (limit: ${limit})`,
174
202
  ErrorCodes.RESTORE_TOO_LARGE,
175
- { size, limit, oid, reason: 'chunk-blob-size' },
203
+ { size, limit, oid, reason: 'chunk-blob-size' }
176
204
  );
177
205
  }
178
206
 
@@ -194,7 +222,12 @@ export default class ChunkRepository {
194
222
  async *iterVerifiedChunkBlobs(manifest) {
195
223
  const fetchFn = async (chunk) => {
196
224
  const blob = await this.readAndVerifyChunk(chunk);
197
- this.#observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
225
+ this.#observability.metric('chunk', {
226
+ action: 'restored',
227
+ index: chunk.index,
228
+ size: blob.length,
229
+ digest: chunk.digest,
230
+ });
198
231
  return blob;
199
232
  };
200
233
 
@@ -215,7 +248,12 @@ export default class ChunkRepository {
215
248
  async *iterConvergentChunks(manifest, key) {
216
249
  const fetchFn = async (chunk) => {
217
250
  const plaintext = await this.readAndVerifyChunk(chunk, { convergentKey: key });
218
- this.#observability.metric('chunk', { action: 'restored', index: chunk.index, size: plaintext.length, digest: chunk.digest });
251
+ this.#observability.metric('chunk', {
252
+ action: 'restored',
253
+ index: chunk.index,
254
+ size: plaintext.length,
255
+ digest: chunk.digest,
256
+ });
219
257
  return plaintext;
220
258
  };
221
259
 
@@ -31,20 +31,25 @@ const FILE_NOT_FOUND_CODE = 'ENOENT';
31
31
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
32
32
  * @param {Array<{label: string, key: Uint8Array}>} [options.recipients] - Envelope recipients.
33
33
  * @param {number} [options.merkleThreshold] - Per-operation chunk count threshold for Merkle manifests.
34
+ * @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Per-operation chunker override.
34
35
  * @returns {Promise<Manifest>} The resulting manifest.
35
36
  */
36
- export async function storeFile(service, {
37
- filePath,
38
- slug,
39
- filename,
40
- encryptionKey,
41
- passphrase,
42
- encryption,
43
- kdfOptions,
44
- compression,
45
- recipients,
46
- merkleThreshold,
47
- }) {
37
+ export async function storeFile(
38
+ service,
39
+ {
40
+ filePath,
41
+ slug,
42
+ filename,
43
+ encryptionKey,
44
+ passphrase,
45
+ encryption,
46
+ kdfOptions,
47
+ compression,
48
+ recipients,
49
+ merkleThreshold,
50
+ chunker,
51
+ }
52
+ ) {
48
53
  const source = createReadStream(filePath);
49
54
  return await service.store({
50
55
  source,
@@ -57,6 +62,7 @@ export async function storeFile(service, {
57
62
  compression,
58
63
  recipients,
59
64
  merkleThreshold,
65
+ chunker,
60
66
  });
61
67
  }
62
68
 
@@ -73,9 +79,15 @@ export async function storeFile(service, {
73
79
  * @param {string} options.baseDirectory - The permitted base directory for restoration (e.g. repo root).
74
80
  * @returns {Promise<{ bytesWritten: number }>}
75
81
  */
76
- export async function restoreFile(service, { manifest, encryptionKey, passphrase, outputPath, baseDirectory }) {
82
+ export async function restoreFile(
83
+ service,
84
+ { manifest, encryptionKey, passphrase, outputPath, baseDirectory }
85
+ ) {
77
86
  if (!baseDirectory) {
78
- throw new CasError('baseDirectory is required for safe restoration', ErrorCodes.INVALID_OPTIONS);
87
+ throw new CasError(
88
+ 'baseDirectory is required for safe restoration',
89
+ ErrorCodes.INVALID_OPTIONS
90
+ );
79
91
  }
80
92
 
81
93
  const safeOutputPath = await resolveSafeRestorePath({ baseDirectory, outputPath });
@@ -119,7 +131,7 @@ async function resolveSafeRestorePath({ baseDirectory, outputPath }) {
119
131
  throw new CasError(
120
132
  `Restoration path "${outputPath}" escapes base directory "${baseDirectory}"`,
121
133
  ErrorCodes.SECURITY_BOUNDARY_VIOLATION,
122
- { outputPath, baseDirectory },
134
+ { outputPath, baseDirectory }
123
135
  );
124
136
  }
125
137
  return canonicalPath;
@@ -160,25 +172,18 @@ async function canonicalizeTargetPath(targetPath) {
160
172
  * @param {{ manifest: Manifest, outputPath: string, source: AsyncIterable<Uint8Array>, encryptionMeta?: EncryptionMeta }} options
161
173
  * @returns {Promise<{ bytesWritten: number }>}
162
174
  */
163
- async function restoreBufferedFile(service, {
164
- manifest,
165
- outputPath,
166
- source,
167
- encryptionMeta,
168
- }) {
175
+ async function restoreBufferedFile(service, { manifest, outputPath, source, encryptionMeta }) {
169
176
  let bytesWritten = 0;
170
177
  const outputDir = path.dirname(outputPath);
171
178
  const tempDir = await mkdtemp(path.join(outputDir, '.git-cas-restore-'));
172
179
  const tempPath = path.join(tempDir, path.basename(outputPath));
173
180
 
174
181
  try {
175
- const counter = createByteCounter((n) => { bytesWritten += n; });
182
+ const counter = createByteCounter((n) => {
183
+ bytesWritten += n;
184
+ });
176
185
 
177
- await pipeline(
178
- Readable.from(source),
179
- counter,
180
- createWriteStream(tempPath),
181
- );
186
+ await pipeline(Readable.from(source), counter, createWriteStream(tempPath));
182
187
 
183
188
  await rename(tempPath, outputPath);
184
189
  service.observability.metric('file', {
@@ -205,10 +210,7 @@ async function restoreBufferedFile(service, {
205
210
  */
206
211
  function isInsideBaseDirectory(resolvedPath, resolvedBase) {
207
212
  const relativePath = path.relative(resolvedBase, resolvedPath);
208
- return (
209
- relativePath === '' ||
210
- (!relativePath.startsWith('..') && !path.isAbsolute(relativePath))
211
- );
213
+ return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
212
214
  }
213
215
 
214
216
  /**
@@ -15,7 +15,7 @@ import CdcChunker from './CdcChunker.js';
15
15
  *
16
16
  * @param {Object} options
17
17
  * @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance (advanced).
18
- * @param {{ strategy: string, chunkSize?: number, targetChunkSize?: number, minChunkSize?: number, maxChunkSize?: number }} [options.chunking] - Declarative chunking strategy config.
18
+ * @param {{ strategy: string, chunkSize?: number, targetChunkSize?: number, minChunkSize?: number, maxChunkSize?: number, normalized?: boolean }} [options.chunking] - Declarative chunking strategy config.
19
19
  * @returns {import('../../ports/ChunkingPort.js').default|undefined}
20
20
  */
21
21
  export default function resolveChunker({ chunker, chunking } = {}) {
@@ -35,10 +35,12 @@ export default function resolveChunker({ chunker, chunking } = {}) {
35
35
  }
36
36
  // 'fixed' with valid chunkSize → FixedChunker; otherwise fall through
37
37
  // to CasService's built-in FixedChunker default.
38
- if (chunking.strategy === 'fixed'
39
- && typeof chunking.chunkSize === 'number'
40
- && Number.isFinite(chunking.chunkSize)
41
- && chunking.chunkSize > 0) {
38
+ if (
39
+ chunking.strategy === 'fixed' &&
40
+ typeof chunking.chunkSize === 'number' &&
41
+ Number.isFinite(chunking.chunkSize) &&
42
+ chunking.chunkSize > 0
43
+ ) {
42
44
  return new FixedChunker({ chunkSize: chunking.chunkSize });
43
45
  }
44
46
  }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '6.0.0';
1
+ export const PACKAGE_VERSION = '6.0.1';