@git-stunts/git-cas 5.2.4 → 5.3.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.
- package/CHANGELOG.md +56 -1
- package/README.md +60 -13
- package/bin/actions.js +14 -1
- package/bin/config.js +203 -0
- package/bin/git-cas.js +125 -27
- package/bin/ui/passphrase-prompt.js +100 -0
- package/index.d.ts +15 -0
- package/index.js +29 -5
- package/package.json +1 -1
- package/src/domain/errors/CasError.js +3 -1
- package/src/domain/services/CasService.d.ts +20 -0
- package/src/domain/services/CasService.js +127 -25
- package/src/domain/services/VaultService.js +23 -2
- package/src/infrastructure/adapters/NodeCryptoAdapter.js +12 -2
- package/src/infrastructure/adapters/WebCryptoAdapter.js +57 -29
- package/src/infrastructure/chunkers/CdcChunker.js +5 -0
- package/src/infrastructure/chunkers/FixedChunker.js +23 -7
package/CHANGELOG.md
CHANGED
|
@@ -5,7 +5,62 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
-
## [
|
|
8
|
+
## [5.3.1] — 2026-03-15
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
- **Repeated chunk tree emission** — `createTree()` and `_createMerkleTree()` now emit one chunk blob tree entry per unique digest, preserving first-seen order at write time while leaving the manifest unchanged as the authoritative ordered index of chunk occurrences.
|
|
12
|
+
- **Invalid Git trees for repetitive content** — repetitive files no longer produce duplicate tree entry names, so emitted trees pass `git fsck --full` without `duplicateEntries` failures.
|
|
13
|
+
- **Regression coverage for tree reachability** — added unit tests for first-seen dedupe behavior and integration tests that store repetitive content, verify restore correctness, and assert clean `git fsck` results on a real Git repository.
|
|
14
|
+
|
|
15
|
+
## [5.3.0] — 2026-03-08
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
- **Vault rotate passphrase-file support** — `vault rotate` now accepts `--old-passphrase-file` and `--new-passphrase-file` flags, bringing it to parity with the store/restore passphrase-file support.
|
|
19
|
+
- **CLI store flags** — `--gzip`, `--strategy <fixed|cdc>`, `--chunk-size <n>`, `--concurrency <n>`, `--codec <json|cbor>`, `--merkle-threshold <n>`, `--target-chunk-size <n>`, `--min-chunk-size <n>`, `--max-chunk-size <n>`. All library-level chunking, compression, codec, and concurrency options are now accessible from the CLI.
|
|
20
|
+
- **CLI restore flags** — `--concurrency <n>`, `--max-restore-buffer <n>`. Parallel I/O and restore buffer limit now configurable from CLI.
|
|
21
|
+
- **`.casrc` config file** — JSON config file at the repository root provides default values for CLI flags. CLI flags always take precedence. Supports: `chunkSize`, `strategy`, `concurrency`, `codec`, `compression`, `merkleThreshold`, `maxRestoreBufferSize`, and `cdc.*` sub-keys.
|
|
22
|
+
- **CODE-EVAL.md** — Forensic architectural audit (zero-knowledge code extraction, critical assessment, roadmap reconciliation, prescriptive blueprint).
|
|
23
|
+
- **M16 Capstone** — New milestone in ROADMAP.md addressing all 9 audit flaws and 10 concerns (C1–C10). 13 task cards, ~698 LoC, ~21h estimated.
|
|
24
|
+
- **Concerns C8–C10** — Three architectural concerns from the CODE-EVAL.md audit now documented: crypto adapter LSP violation (C8), FixedChunker quadratic allocation (C9), encrypt-then-chunk dedup loss (C10).
|
|
25
|
+
- **CasError codes** — `RESTORE_TOO_LARGE` and `ENCRYPTION_BUFFER_EXCEEDED` registered in canonical error code table.
|
|
26
|
+
- **16.2 — Memory restore guard** — `CasService` accepts `maxRestoreBufferSize` (default 512 MiB). `_restoreBuffered` throws `RESTORE_TOO_LARGE` with `{ size, limit }` meta when encrypted/compressed restore would exceed the limit. Unencrypted streaming restore is unaffected.
|
|
27
|
+
- **16.3 — Web Crypto encryption buffer guard** — `WebCryptoAdapter` accepts `maxEncryptionBufferSize` (default 512 MiB). Throws `ENCRYPTION_BUFFER_EXCEEDED` when streaming encryption exceeds the limit, since Web Crypto AES-GCM is a one-shot API. NodeCryptoAdapter uses true streaming and is unaffected.
|
|
28
|
+
- **16.5 — Encrypt-then-chunk dedup warning** — `CasService.store()` now logs a warning when encryption is combined with CDC chunking, since ciphertext is pseudorandom and content-defined boundaries provide no dedup benefit.
|
|
29
|
+
- **16.10 — Orphaned blob tracking** — `STREAM_ERROR` now includes `meta.orphanedBlobs` — an array of OIDs for blobs successfully written before the stream failure. Error metric includes `orphanedBlobs` count for observability.
|
|
30
|
+
- **16.11 — Passphrase input security** — New `--vault-passphrase-file <path>` CLI option reads passphrase from file (use `-` for stdin). Interactive TTY prompt added as fallback when no other passphrase source is available. `resolvePassphrase` is now async with priority: file → flag → env → TTY → undefined. Empty passphrases rejected. File permission warning on group/world-readable files.
|
|
31
|
+
- **16.12 — KDF brute-force awareness** — `CasService` now emits `decryption_failed` metric with slug context when decryption fails with `INTEGRITY_ERROR` during encrypted restore. CLI adds a 1-second delay after `INTEGRITY_ERROR` to slow brute-force attempts. Library API imposes no delay — callers manage their own rate-limiting policy.
|
|
32
|
+
- **16.13 — GCM nonce collision docs + encryption counter** — `SECURITY.md` moved to project root with new sections: GCM nonce bound (2^32 NIST limit), key rotation frequency, KDF parameter guidance, and passphrase entropy recommendations. Vault metadata now tracks `encryptionCount`, incremented per encrypted `addToVault()`. Observability warning emitted when count exceeds 2^31. `VaultService` accepts optional `observability` port.
|
|
33
|
+
- **16.7 — Lifecycle method naming** — Added `inspectAsset()` (replaces `deleteAsset()`) and `collectReferencedChunks()` (replaces `findOrphanedChunks()`) as canonical names on both `CasService` and the facade. Old names are preserved as deprecated aliases that emit observability warnings. Type definitions updated with `@deprecated` JSDoc.
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
- **`runAction` injectable delay** — `runAction()` now accepts an optional `{ delay }` dependency, replacing the hardcoded `setTimeout` call. Tests inject a spy instead of using `vi.useFakeTimers()`, making INTEGRITY_ERROR rate-limit tests deterministic across Node, Bun, and Deno.
|
|
37
|
+
- **Test conventions** — Added `test/CONVENTIONS.md` documenting rules for deterministic, cross-runtime tests: inject time dependencies, use `chmod()` instead of `writeFile({ mode })`, avoid global state patching.
|
|
38
|
+
- **VaultService test observability wiring** — `VaultService.test.js` now passes a `mockObservability()` port to all tests instead of relying on the silent no-op default. `rotateVaultPassphrase.test.js` now passes `SilentObserver` explicitly. If observability wiring breaks, the test suite will catch it.
|
|
39
|
+
- **`NodeCryptoAdapter.encryptBuffer` JSDoc** — `@returns` annotation corrected to `Promise<...>`, matching the async implementation.
|
|
40
|
+
- **`maxRestoreBufferSize` documented** — constructor JSDoc and `#config` type in `ContentAddressableStore` now include the parameter.
|
|
41
|
+
- **ROADMAP.md heading level** — added `## Task Cards` heading between `# M16` and `### 16.1` to satisfy MD001 heading-increment rule.
|
|
42
|
+
- **16.1 — Crypto adapter behavioral normalization** — `NodeCryptoAdapter.encryptBuffer` now returns a Promise (was sync), matching Bun/Web. `decryptBuffer` validates key on all adapters. `NodeCryptoAdapter.createEncryptionStream` guards `finalize()` with `STREAM_NOT_CONSUMED`. New conformance test suite asserts identical contracts across all adapters.
|
|
43
|
+
- **16.4 — FixedChunker pre-allocated buffer** — Replaced `Buffer.concat()` loop with a pre-allocated `Buffer.allocUnsafe(chunkSize)` working buffer, eliminating O(n²) copies for many small input buffers. Matches the allocation strategy used by `CdcChunker`.
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
- **Post-decompression size guard** — `_restoreBuffered` now enforces `maxRestoreBufferSize` after decompression, not just before. Compressed payloads that inflate beyond the configured limit now throw `RESTORE_TOO_LARGE` instead of silently allocating unbounded memory.
|
|
47
|
+
- **CLI passphrase prompt deferral** — `resolveEncryptionKey` now checks vault metadata before calling `resolvePassphrase`, avoiding unnecessary TTY prompts for unencrypted vaults. Store action recipient-conflict check inspects flags/env without consuming stdin.
|
|
48
|
+
- **CRLF passphrase normalization** — `readPassphraseFile` now strips trailing `\r\n` (Windows line endings) in addition to `\n`, preventing passphrase mismatches from Windows-edited files.
|
|
49
|
+
- **Constructor validation** — `CasService.maxRestoreBufferSize` (integer >= 1024), `CasService.chunkSize` (integer >= 1024), `WebCryptoAdapter.maxEncryptionBufferSize` (finite, positive), and `FixedChunker.chunkSize` (positive integer) are now validated at construction time, preventing silent misconfiguration.
|
|
50
|
+
- **Error-path test hardening** — `orphanedBlobs`, `restoreGuard`, `kdfBruteForce`, and `conformance` tests now fail explicitly when expected errors are not thrown (previously silent pass-through).
|
|
51
|
+
- **Orphaned blob enrichment on CasError re-throw** — `_chunkAndStore` now attaches `orphanedBlobs` metadata to existing `CasError` instances before re-throwing, instead of discarding the information.
|
|
52
|
+
- **VaultService metadata mutation on retry** — `addToVault` now shallow-copies `state.metadata` before mutation, preventing `encryptionCount` from being incremented multiple times across CAS retries.
|
|
53
|
+
- **16.8 — CasError portability guard** — `Error.captureStackTrace` now guarded with a runtime check. CasError constructs correctly on runtimes where `captureStackTrace` is unavailable (e.g. Firefox, older Deno).
|
|
54
|
+
- **16.9 — Pre-commit hook + hooks directory** — `scripts/git-hooks/` renamed to `scripts/hooks/` per CLAUDE.md convention. New `pre-commit` hook runs lint gate. `install-hooks.sh` updated accordingly.
|
|
55
|
+
- **16.6 — Chunk size upper bound** — CasService, FixedChunker, and CdcChunker now reject chunk sizes exceeding 100 MiB. CasService logs a warning when chunk size exceeds 10 MiB.
|
|
56
|
+
- **ROADMAP.md M16 summary** — Corrected LoC/hours from `~430/~28h` to `~698/~21h` to match the detailed task breakdown.
|
|
57
|
+
- **VaultService constructor type** — Added missing `observability?: ObservabilityPort` parameter to `index.d.ts` declaration.
|
|
58
|
+
- **Nullish coalescing for config merging** — `strategy` and `codec` in `mergeConfig()` now use `??` instead of `||`, so empty-string CLI values don't fall through to `.casrc` defaults.
|
|
59
|
+
- **Empty passphrase rejection** — `readPassphraseFile` rejects files that yield an empty string after newline stripping. `resolvePassphrase` validates `--vault-passphrase` flag and `GIT_CAS_PASSPHRASE` env var.
|
|
60
|
+
- **KDF algorithm validation** — `vault init` and `vault rotate` now validate `--algorithm` against the supported set (`pbkdf2`, `scrypt`) before passing to the KDF.
|
|
61
|
+
- **`.casrc` config validation** — `loadConfig()` now validates all config values (types, ranges, enum membership) after JSON parsing.
|
|
62
|
+
- **Deprecated method names in docs** — Updated `deleteAsset` → `inspectAsset` and `findOrphanedChunks` → `collectReferencedChunks` in README and GUIDE.
|
|
63
|
+
- **Missing error codes in SECURITY.md** — Added `RESTORE_TOO_LARGE` and `ENCRYPTION_BUFFER_EXCEEDED` sections.
|
|
9
64
|
|
|
10
65
|
## [5.2.4] — Prism polish (2026-03-03)
|
|
11
66
|
|
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ We use the object database.
|
|
|
29
29
|
- **Manifests** a tiny explicit index of chunks + metadata (JSON/CBOR).
|
|
30
30
|
- **Tree output** generates standard Git trees so assets snap into commits cleanly.
|
|
31
31
|
- **Full round-trip** store, tree, and restore — get your bytes back, verified.
|
|
32
|
-
- **Lifecycle management** `readManifest`, `
|
|
32
|
+
- **Lifecycle management** `readManifest`, `inspectAsset`, `collectReferencedChunks` — inspect trees, plan deletions, audit storage.
|
|
33
33
|
- **Vault** GC-safe ref-based storage. One ref (`refs/cas/vault`) indexes all assets by slug. No more silent data loss from `git gc`.
|
|
34
34
|
- **Interactive dashboard** `git cas inspect` with chunk heatmap, animated progress bars, and rich manifest views.
|
|
35
35
|
- **Verify & JSON output** `git cas verify` checks integrity; `--json` on all commands for CI/scripting.
|
|
@@ -38,19 +38,35 @@ We use the object database.
|
|
|
38
38
|
|
|
39
39
|
<img src="./docs/demo.gif" alt="git-cas demo" />
|
|
40
40
|
|
|
41
|
-
## What's new in v5.
|
|
41
|
+
## What's new in v5.3.1
|
|
42
42
|
|
|
43
|
-
**
|
|
43
|
+
**Patch release — repeated chunk tree fix.**
|
|
44
44
|
|
|
45
|
-
-
|
|
46
|
-
-
|
|
47
|
-
- **
|
|
48
|
-
-
|
|
49
|
-
- **`resolveChunker` validation** — `chunkSize` now validated as a finite positive number before constructing `FixedChunker`.
|
|
50
|
-
- **File rename** — `VaultPassphraseRotator.js` → `rotateVaultPassphrase.js` (camelCase for functions, PascalCase for classes).
|
|
45
|
+
- **Unique chunk tree entries** — `createTree()` and `_createMerkleTree()` now emit one tree entry per unique chunk digest instead of repeating the same filename for repeated chunk occurrences.
|
|
46
|
+
- **Manifest remains authoritative** — chunk order and multiplicity still come entirely from the manifest; restore behavior is unchanged.
|
|
47
|
+
- **Clean `git fsck` on repetitive files** — repetitive content no longer yields duplicate tree filenames or `duplicateEntries` errors.
|
|
48
|
+
- **New regressions** — unit and integration coverage now exercises repeated-chunk files and validates real Git tree integrity with `git fsck --full`.
|
|
51
49
|
|
|
52
50
|
See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
|
|
53
51
|
|
|
52
|
+
## What's new in v5.3.0
|
|
53
|
+
|
|
54
|
+
**M16 Capstone — audit remediation, CLI configuration, and security hardening.**
|
|
55
|
+
|
|
56
|
+
- **`.casrc` config file** — JSON config at repo root sets defaults for all CLI flags (chunk size, strategy, concurrency, codec, compression, CDC params).
|
|
57
|
+
- **CLI store/restore flags** — all library-level options now accessible from the command line: `--gzip`, `--strategy`, `--chunk-size`, `--concurrency`, `--codec`, `--merkle-threshold`, and CDC-specific flags.
|
|
58
|
+
- **Passphrase-file support** — `--vault-passphrase-file <path>` on store, restore, and vault rotate (use `-` for stdin).
|
|
59
|
+
- **Memory restore guard** — `maxRestoreBufferSize` (default 512 MiB) prevents unbounded memory allocation on encrypted/compressed restore.
|
|
60
|
+
- **Web Crypto encryption buffer guard** — `maxEncryptionBufferSize` (default 512 MiB) for the one-shot AES-GCM API.
|
|
61
|
+
- **Orphaned blob tracking** — `STREAM_ERROR` now includes `meta.orphanedBlobs` for cleanup after partial store failures.
|
|
62
|
+
- **KDF brute-force awareness** — `decryption_failed` metric + CLI rate-limiting delay on `INTEGRITY_ERROR`.
|
|
63
|
+
- **Encryption counter** — vault metadata tracks `encryptionCount` with observability warning near GCM nonce bound.
|
|
64
|
+
- **Lifecycle method rename** — `inspectAsset()` / `collectReferencedChunks()` replace `deleteAsset()` / `findOrphanedChunks()` (old names preserved as deprecated aliases).
|
|
65
|
+
- **FixedChunker O(n²) fix** — pre-allocated buffer replaces `Buffer.concat()` loop.
|
|
66
|
+
- **Chunk size upper bound** — 100 MiB max enforced across all chunkers.
|
|
67
|
+
- **Constructor validation** — `chunkSize`, `maxRestoreBufferSize`, `maxEncryptionBufferSize` validated at construction time.
|
|
68
|
+
- **Cross-runtime portability** — `Error.captureStackTrace` guarded, crypto adapter contracts normalized.
|
|
69
|
+
|
|
54
70
|
## What's new in v5.2.3
|
|
55
71
|
|
|
56
72
|
**Internal refactoring — no breaking API changes.** The facade, CasService, and crypto adapters were restructured for better separation of concerns:
|
|
@@ -229,9 +245,9 @@ await cas.restoreFile({ manifest, outputPath: './restored.png' });
|
|
|
229
245
|
// Read the manifest back from a tree OID
|
|
230
246
|
const m = await cas.readManifest({ treeOid });
|
|
231
247
|
|
|
232
|
-
// Lifecycle: inspect deletion impact,
|
|
233
|
-
const { slug, chunksOrphaned } = await cas.
|
|
234
|
-
const { referenced, total } = await cas.
|
|
248
|
+
// Lifecycle: inspect deletion impact, collect referenced chunks
|
|
249
|
+
const { slug, chunksOrphaned } = await cas.inspectAsset({ treeOid });
|
|
250
|
+
const { referenced, total } = await cas.collectReferencedChunks({ treeOids: [treeOid] });
|
|
235
251
|
|
|
236
252
|
// v2.0.0: Compressed + passphrase-encrypted store
|
|
237
253
|
const manifest2 = await cas.storeFile({
|
|
@@ -295,16 +311,47 @@ git cas vault init
|
|
|
295
311
|
git cas store ./secret.bin --slug vault-entry --tree
|
|
296
312
|
git cas restore --slug vault-entry --out ./decrypted.bin
|
|
297
313
|
|
|
314
|
+
# Compression, chunking, codec, concurrency
|
|
315
|
+
git cas store ./data.bin --slug my-data --tree --gzip
|
|
316
|
+
git cas store ./data.bin --slug my-data --tree --strategy cdc
|
|
317
|
+
git cas store ./data.bin --slug my-data --tree --chunk-size 65536 --concurrency 4
|
|
318
|
+
git cas store ./data.bin --slug my-data --tree --codec cbor
|
|
319
|
+
|
|
320
|
+
# Restore with concurrency
|
|
321
|
+
git cas restore --slug my-data --out ./data.bin --concurrency 4
|
|
322
|
+
|
|
298
323
|
# JSON output on any command (for CI/scripting)
|
|
299
324
|
git cas store ./data.bin --slug my-data --tree --json
|
|
300
325
|
```
|
|
301
326
|
|
|
327
|
+
### `.casrc` — Project Config File
|
|
328
|
+
|
|
329
|
+
Place a `.casrc` JSON file at the repository root to set defaults for CLI flags.
|
|
330
|
+
CLI flags always take precedence over `.casrc` values.
|
|
331
|
+
|
|
332
|
+
```json
|
|
333
|
+
{
|
|
334
|
+
"chunkSize": 65536,
|
|
335
|
+
"strategy": "cdc",
|
|
336
|
+
"concurrency": 4,
|
|
337
|
+
"codec": "json",
|
|
338
|
+
"compression": "gzip",
|
|
339
|
+
"merkleThreshold": 500,
|
|
340
|
+
"maxRestoreBufferSize": 1073741824,
|
|
341
|
+
"cdc": {
|
|
342
|
+
"minChunkSize": 8192,
|
|
343
|
+
"targetChunkSize": 32768,
|
|
344
|
+
"maxChunkSize": 131072
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
```
|
|
348
|
+
|
|
302
349
|
## Documentation
|
|
303
350
|
|
|
304
351
|
- [Guide](./GUIDE.md) — progressive walkthrough
|
|
305
352
|
- [API Reference](./docs/API.md) — full method documentation
|
|
306
353
|
- [Architecture](./ARCHITECTURE.md) — hexagonal design overview
|
|
307
|
-
- [Security](./
|
|
354
|
+
- [Security](./SECURITY.md) — crypto design and threat model
|
|
308
355
|
|
|
309
356
|
## When to use git-cas (and when not to)
|
|
310
357
|
|
package/bin/actions.js
CHANGED
|
@@ -56,18 +56,31 @@ function getHint(code) {
|
|
|
56
56
|
return undefined;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Default delay — real setTimeout for production use.
|
|
61
|
+
* @param {number} ms
|
|
62
|
+
* @returns {Promise<void>}
|
|
63
|
+
*/
|
|
64
|
+
function defaultDelay(ms) {
|
|
65
|
+
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
66
|
+
}
|
|
67
|
+
|
|
59
68
|
/**
|
|
60
69
|
* Wrap a command action with structured error handling.
|
|
61
70
|
*
|
|
62
71
|
* @param {(...args: any[]) => Promise<void>} fn - The async action function.
|
|
63
72
|
* @param {() => boolean} getJson - Lazy getter for --json flag value.
|
|
73
|
+
* @param {{ delay?: (ms: number) => Promise<void> }} [options] - Injectable dependencies.
|
|
64
74
|
* @returns {(...args: any[]) => Promise<void>} Wrapped action.
|
|
65
75
|
*/
|
|
66
|
-
export function runAction(fn, getJson) {
|
|
76
|
+
export function runAction(fn, getJson, { delay = defaultDelay } = {}) {
|
|
67
77
|
return async (/** @type {any[]} */ ...args) => {
|
|
68
78
|
try {
|
|
69
79
|
await fn(...args);
|
|
70
80
|
} catch (/** @type {any} */ err) {
|
|
81
|
+
if (err?.code === 'INTEGRITY_ERROR') {
|
|
82
|
+
await delay(1000);
|
|
83
|
+
}
|
|
71
84
|
writeError(err, getJson());
|
|
72
85
|
process.exitCode = 1;
|
|
73
86
|
}
|
package/bin/config.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Loads `.casrc` project config from the Git working directory.
|
|
3
|
+
*
|
|
4
|
+
* `.casrc` is a JSON file placed at the repository root that provides default
|
|
5
|
+
* values for CLI flags. CLI flags always take precedence over `.casrc` values.
|
|
6
|
+
*
|
|
7
|
+
* Supported keys:
|
|
8
|
+
* chunkSize — Chunk size in bytes (integer >= 1024, default 262144)
|
|
9
|
+
* strategy — Chunking strategy: "fixed" or "cdc" (default "fixed")
|
|
10
|
+
* concurrency — Parallel chunk I/O operations (positive integer, default 1)
|
|
11
|
+
* codec — Manifest codec: "json" or "cbor" (default "json")
|
|
12
|
+
* compression — Compression algorithm: "gzip" or false (default false)
|
|
13
|
+
* merkleThreshold — Chunk count threshold for Merkle sub-manifests (default 1000)
|
|
14
|
+
* maxRestoreBufferSize — Max bytes for buffered restore (default 536870912)
|
|
15
|
+
* cdc.minChunkSize — CDC minimum chunk size
|
|
16
|
+
* cdc.targetChunkSize — CDC target chunk size
|
|
17
|
+
* cdc.maxChunkSize — CDC maximum chunk size
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { readFileSync } from 'node:fs';
|
|
21
|
+
import { resolve } from 'node:path';
|
|
22
|
+
|
|
23
|
+
const FILENAME = '.casrc';
|
|
24
|
+
const MAX_CHUNK_SIZE = 100 * 1024 * 1024;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {Object} CasConfig
|
|
28
|
+
* @property {number} [chunkSize]
|
|
29
|
+
* @property {string} [strategy]
|
|
30
|
+
* @property {number} [concurrency]
|
|
31
|
+
* @property {string} [codec]
|
|
32
|
+
* @property {string|false} [compression]
|
|
33
|
+
* @property {number} [merkleThreshold]
|
|
34
|
+
* @property {number} [maxRestoreBufferSize]
|
|
35
|
+
* @property {{ minChunkSize?: number, targetChunkSize?: number, maxChunkSize?: number }} [cdc]
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {any} value
|
|
40
|
+
* @param {string} name
|
|
41
|
+
* @param {{ min: number, max?: number }} range
|
|
42
|
+
*/
|
|
43
|
+
function assertInt(value, name, { min, max }) {
|
|
44
|
+
if (value === undefined) { return; }
|
|
45
|
+
if (!Number.isInteger(value) || value < min) {
|
|
46
|
+
throw new Error(`${FILENAME}: ${name} must be an integer >= ${min}`);
|
|
47
|
+
}
|
|
48
|
+
if (max !== undefined && value > max) {
|
|
49
|
+
throw new Error(`${FILENAME}: ${name} must not exceed ${max}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {any} value
|
|
55
|
+
* @param {string} name
|
|
56
|
+
* @param {string[]} allowed
|
|
57
|
+
*/
|
|
58
|
+
function assertEnum(value, name, allowed) {
|
|
59
|
+
if (value === undefined) { return; }
|
|
60
|
+
if (!allowed.includes(value)) {
|
|
61
|
+
throw new Error(`${FILENAME}: ${name} must be ${allowed.map((v) => `"${v}"`).join(' or ')}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param {Record<string, any>} config
|
|
67
|
+
*/
|
|
68
|
+
/**
|
|
69
|
+
* @param {{ minChunkSize?: number, targetChunkSize?: number, maxChunkSize?: number }} cdc
|
|
70
|
+
*/
|
|
71
|
+
function assertCdcOrdering(cdc) {
|
|
72
|
+
const { minChunkSize, targetChunkSize, maxChunkSize } = cdc;
|
|
73
|
+
if (minChunkSize !== undefined && maxChunkSize !== undefined && minChunkSize > maxChunkSize) {
|
|
74
|
+
throw new Error(`${FILENAME}: cdc.minChunkSize must not exceed cdc.maxChunkSize`);
|
|
75
|
+
}
|
|
76
|
+
if (targetChunkSize !== undefined && minChunkSize !== undefined && targetChunkSize < minChunkSize) {
|
|
77
|
+
throw new Error(`${FILENAME}: cdc.targetChunkSize must be >= cdc.minChunkSize`);
|
|
78
|
+
}
|
|
79
|
+
if (targetChunkSize !== undefined && maxChunkSize !== undefined && targetChunkSize > maxChunkSize) {
|
|
80
|
+
throw new Error(`${FILENAME}: cdc.targetChunkSize must be <= cdc.maxChunkSize`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {Record<string, any>} config
|
|
86
|
+
*/
|
|
87
|
+
function validateCdc(config) {
|
|
88
|
+
if (config.cdc === undefined) { return; }
|
|
89
|
+
if (typeof config.cdc !== 'object' || config.cdc === null || Array.isArray(config.cdc)) {
|
|
90
|
+
throw new Error(`${FILENAME}: cdc must be an object`);
|
|
91
|
+
}
|
|
92
|
+
for (const key of ['minChunkSize', 'targetChunkSize', 'maxChunkSize']) {
|
|
93
|
+
assertInt(config.cdc[key], `cdc.${key}`, { min: 1, max: MAX_CHUNK_SIZE });
|
|
94
|
+
}
|
|
95
|
+
assertCdcOrdering(config.cdc);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Validates `.casrc` config values after parsing.
|
|
100
|
+
*
|
|
101
|
+
* @param {Record<string, any>} config
|
|
102
|
+
*/
|
|
103
|
+
function validateConfig(config) {
|
|
104
|
+
assertInt(config.chunkSize, 'chunkSize', { min: 1024, max: MAX_CHUNK_SIZE });
|
|
105
|
+
assertEnum(config.strategy, 'strategy', ['fixed', 'cdc']);
|
|
106
|
+
assertInt(config.concurrency, 'concurrency', { min: 1 });
|
|
107
|
+
assertEnum(config.codec, 'codec', ['json', 'cbor']);
|
|
108
|
+
if (config.compression !== undefined && config.compression !== false) {
|
|
109
|
+
assertEnum(config.compression, 'compression', ['gzip']);
|
|
110
|
+
}
|
|
111
|
+
assertInt(config.merkleThreshold, 'merkleThreshold', { min: 1 });
|
|
112
|
+
assertInt(config.maxRestoreBufferSize, 'maxRestoreBufferSize', { min: 1024 });
|
|
113
|
+
validateCdc(config);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Loads `.casrc` from the given directory, returning an empty object if not found.
|
|
118
|
+
*
|
|
119
|
+
* @param {string} cwd - Directory to search for `.casrc`.
|
|
120
|
+
* @returns {CasConfig}
|
|
121
|
+
*/
|
|
122
|
+
export function loadConfig(cwd) {
|
|
123
|
+
const filePath = resolve(cwd, FILENAME);
|
|
124
|
+
try {
|
|
125
|
+
const raw = readFileSync(filePath, 'utf8');
|
|
126
|
+
const config = JSON.parse(raw);
|
|
127
|
+
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
|
128
|
+
throw new Error(`${FILENAME}: expected a JSON object`);
|
|
129
|
+
}
|
|
130
|
+
validateConfig(config);
|
|
131
|
+
return config;
|
|
132
|
+
} catch (err) {
|
|
133
|
+
if (err.code === 'ENOENT') {
|
|
134
|
+
return {};
|
|
135
|
+
}
|
|
136
|
+
if (err instanceof SyntaxError) {
|
|
137
|
+
throw new Error(`${FILENAME}: invalid JSON — ${err.message}`);
|
|
138
|
+
}
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Sets key on target if value is not undefined.
|
|
145
|
+
* @param {Record<string, any>} target
|
|
146
|
+
* @param {string} key
|
|
147
|
+
* @param {any} value
|
|
148
|
+
*/
|
|
149
|
+
function setIfDefined(target, key, value) {
|
|
150
|
+
if (value !== undefined) { target[key] = value; }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Resolves chunking config from merged CLI + config values.
|
|
155
|
+
* @param {{ strategy?: string, chunkSize?: number, cliOpts: Record<string, any>, config: CasConfig }} opts
|
|
156
|
+
* @returns {Record<string, any>|undefined}
|
|
157
|
+
*/
|
|
158
|
+
function resolveChunking({ strategy, chunkSize, cliOpts, config }) {
|
|
159
|
+
if (strategy === 'cdc') {
|
|
160
|
+
const cdcConf = config.cdc || {};
|
|
161
|
+
return {
|
|
162
|
+
strategy: 'cdc',
|
|
163
|
+
targetChunkSize: cliOpts.targetChunkSize ?? cdcConf.targetChunkSize,
|
|
164
|
+
minChunkSize: cliOpts.minChunkSize ?? cdcConf.minChunkSize,
|
|
165
|
+
maxChunkSize: cliOpts.maxChunkSize ?? cdcConf.maxChunkSize,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
if (strategy === 'fixed' && chunkSize !== undefined) {
|
|
169
|
+
return { strategy: 'fixed', chunkSize };
|
|
170
|
+
}
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Merges CLI options over `.casrc` defaults. CLI flags take precedence.
|
|
176
|
+
*
|
|
177
|
+
* @param {Record<string, any>} cliOpts - Parsed CLI options.
|
|
178
|
+
* @param {CasConfig} config - Loaded `.casrc` config.
|
|
179
|
+
* @returns {{ casConfig: Record<string, any>, storeExtras: Record<string, any> }}
|
|
180
|
+
*/
|
|
181
|
+
export function mergeConfig(cliOpts, config) {
|
|
182
|
+
const strategy = cliOpts.strategy ?? config.strategy;
|
|
183
|
+
const chunkSize = cliOpts.chunkSize ?? config.chunkSize;
|
|
184
|
+
|
|
185
|
+
/** @type {Record<string, any>} */
|
|
186
|
+
const casConfig = {};
|
|
187
|
+
setIfDefined(casConfig, 'concurrency', cliOpts.concurrency ?? config.concurrency);
|
|
188
|
+
setIfDefined(casConfig, 'chunkSize', chunkSize);
|
|
189
|
+
setIfDefined(casConfig, 'merkleThreshold', cliOpts.merkleThreshold ?? config.merkleThreshold);
|
|
190
|
+
setIfDefined(casConfig, 'maxRestoreBufferSize', cliOpts.maxRestoreBufferSize ?? config.maxRestoreBufferSize);
|
|
191
|
+
setIfDefined(casConfig, 'chunking', resolveChunking({ strategy, chunkSize, cliOpts, config }));
|
|
192
|
+
|
|
193
|
+
const codec = cliOpts.codec ?? config.codec;
|
|
194
|
+
if (codec === 'cbor') { casConfig.codec = 'cbor'; }
|
|
195
|
+
|
|
196
|
+
/** @type {Record<string, any>} */
|
|
197
|
+
const storeExtras = {};
|
|
198
|
+
if (cliOpts.gzip || config.compression === 'gzip') {
|
|
199
|
+
storeExtras.compression = { algorithm: 'gzip' };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return { casConfig, storeExtras };
|
|
203
|
+
}
|