@git-stunts/git-cas 5.1.0 → 5.2.4

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 (45) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +144 -7
  3. package/bin/actions.js +25 -7
  4. package/bin/git-cas.js +150 -26
  5. package/bin/ui/context.js +13 -0
  6. package/bin/ui/dashboard-cmds.js +14 -6
  7. package/bin/ui/dashboard-view.js +55 -6
  8. package/bin/ui/dashboard.js +109 -7
  9. package/bin/ui/encryption-card.js +2 -2
  10. package/bin/ui/heatmap.js +20 -2
  11. package/bin/ui/history-timeline.js +8 -6
  12. package/bin/ui/manifest-view.js +37 -8
  13. package/bin/ui/progress.js +60 -38
  14. package/index.d.ts +22 -1
  15. package/index.js +80 -114
  16. package/package.json +2 -1
  17. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  18. package/src/domain/schemas/ManifestSchema.d.ts +2 -0
  19. package/src/domain/schemas/ManifestSchema.js +2 -0
  20. package/src/domain/services/CasService.d.ts +8 -1
  21. package/src/domain/services/CasService.js +123 -210
  22. package/src/domain/services/KeyResolver.js +220 -0
  23. package/src/domain/services/Semaphore.js +2 -2
  24. package/src/domain/services/VaultService.js +49 -27
  25. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  26. package/src/domain/value-objects/Manifest.d.ts +2 -0
  27. package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
  28. package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
  29. package/src/infrastructure/adapters/FileIOHelper.js +64 -0
  30. package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
  31. package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
  32. package/src/infrastructure/adapters/NodeCryptoAdapter.js +38 -7
  33. package/src/infrastructure/adapters/SilentObserver.js +15 -0
  34. package/src/infrastructure/adapters/StatsCollector.js +15 -1
  35. package/src/infrastructure/adapters/WebCryptoAdapter.js +68 -18
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/FixedChunker.js +5 -1
  38. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  39. package/src/infrastructure/codecs/CborCodec.js +11 -3
  40. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  41. package/src/ports/CodecPort.js +3 -3
  42. package/src/ports/CryptoPort.js +56 -23
  43. package/src/ports/GitPersistencePort.js +4 -4
  44. package/src/ports/GitRefPort.js +10 -10
  45. package/src/types/ambient.d.ts +37 -0
package/bin/git-cas.js CHANGED
@@ -18,35 +18,54 @@ const getJson = () => program.opts().json;
18
18
  program
19
19
  .name('git-cas')
20
20
  .description('Content Addressable Storage backed by Git')
21
- .version('5.0.0')
21
+ .version('5.2.2')
22
22
  .option('-q, --quiet', 'Suppress progress output')
23
23
  .option('--json', 'Output results as JSON');
24
24
 
25
25
  /**
26
26
  * Read a 32-byte raw encryption key from a file.
27
+ *
28
+ * @param {string} keyFilePath
29
+ * @returns {Buffer}
27
30
  */
28
31
  function readKeyFile(keyFilePath) {
29
- return readFileSync(keyFilePath);
32
+ const buf = readFileSync(keyFilePath);
33
+ if (buf.length !== 32) {
34
+ throw new Error(`Invalid key length: expected 32 bytes, got ${buf.length} (${keyFilePath})`);
35
+ }
36
+ return buf;
30
37
  }
31
38
 
32
39
  /**
33
40
  * Create a CAS instance for the given working directory with an optional observability adapter.
41
+ *
42
+ * @param {string} cwd
43
+ * @param {{ observability?: import('../index.js').ObservabilityPort }} [opts]
44
+ * @returns {ContentAddressableStore}
34
45
  */
35
- function createCas(cwd, { observability } = {}) {
46
+ function createCas(cwd, opts = {}) {
36
47
  const runner = ShellRunnerFactory.create();
37
48
  const plumbing = new GitPlumbing({ runner, cwd });
38
- return new ContentAddressableStore({ plumbing, observability });
49
+ return new ContentAddressableStore({ plumbing, observability: opts.observability });
39
50
  }
40
51
 
41
52
  /**
42
53
  * Derive the encryption key from vault metadata + passphrase.
54
+ *
55
+ * @param {ContentAddressableStore} cas
56
+ * @param {import('../index.js').VaultMetadata} metadata
57
+ * @param {string} passphrase
58
+ * @returns {Promise<Buffer>}
43
59
  */
44
60
  async function deriveVaultKey(cas, metadata, passphrase) {
61
+ if (!metadata.encryption?.kdf) {
62
+ throw new Error('Missing or malformed encryption metadata');
63
+ }
45
64
  const { kdf } = metadata.encryption;
46
65
  const { key } = await cas.deriveKey({
47
66
  passphrase,
48
67
  salt: Buffer.from(kdf.salt, 'base64'),
49
- algorithm: kdf.algorithm,
68
+ algorithm: /** @type {"pbkdf2" | "scrypt"} */ (kdf.algorithm),
50
69
  iterations: kdf.iterations,
51
70
  cost: kdf.cost,
52
71
  blockSize: kdf.blockSize,
@@ -57,6 +76,9 @@ async function deriveVaultKey(cas, metadata, passphrase) {
57
76
 
58
77
  /**
59
78
  * Resolve passphrase from --vault-passphrase flag or GIT_CAS_PASSPHRASE env var.
79
+ *
80
+ * @param {Record<string, any>} opts
81
+ * @returns {string | undefined}
60
82
  */
61
83
  function resolvePassphrase(opts) {
62
84
  return opts.vaultPassphrase ?? process.env.GIT_CAS_PASSPHRASE;
@@ -64,6 +86,10 @@ function resolvePassphrase(opts) {
64
86
 
65
87
  /**
66
88
  * Resolve encryption key from --key-file or --vault-passphrase / GIT_CAS_PASSPHRASE.
89
+ *
90
+ * @param {ContentAddressableStore} cas
91
+ * @param {Record<string, any>} opts
92
+ * @returns {Promise<Buffer | undefined>}
67
93
  */
68
94
  async function resolveEncryptionKey(cas, opts) {
69
95
  if (opts.keyFile) {
@@ -83,6 +109,8 @@ async function resolveEncryptionKey(cas, opts) {
83
109
 
84
110
  /**
85
111
  * Validate --slug / --oid flags (exactly one required).
112
+ *
113
+ * @param {Record<string, any>} opts
86
114
  */
87
115
  function validateRestoreFlags(opts) {
88
116
  if (opts.slug && opts.oid) {
@@ -96,10 +124,25 @@ function validateRestoreFlags(opts) {
96
124
  // ---------------------------------------------------------------------------
97
125
  // store
98
126
  // ---------------------------------------------------------------------------
127
+
128
+ /**
129
+ * @typedef {Object} StoreFileOpts
130
+ * @property {string} filePath - Path to the file to store.
131
+ * @property {string} slug - Asset slug identifier.
132
+ * @property {Buffer} [encryptionKey] - 32-byte AES-256-GCM key.
133
+ * @property {Array<{ label: string, key: Buffer }>} [recipients] - Envelope recipients.
134
+ */
135
+
99
136
  /**
100
137
  * Build store options, resolving encryption key or recipients.
138
+ *
139
+ * @param {ContentAddressableStore} cas
140
+ * @param {string} file
141
+ * @param {Record<string, any>} opts
142
+ * @returns {Promise<StoreFileOpts>}
101
143
  */
102
144
  async function buildStoreOpts(cas, file, opts) {
145
+ /** @type {StoreFileOpts} */
103
146
  const storeOpts = { filePath: file, slug: opts.slug };
104
147
  if (opts.recipient) {
105
148
  storeOpts.recipients = opts.recipient;
@@ -113,6 +156,10 @@ async function buildStoreOpts(cas, file, opts) {
113
156
  /**
114
157
  * Parse a --recipient flag value into { label, key }.
115
158
  * Format: label:keyfile
159
+ *
160
+ * @param {string} value
161
+ * @param {Array<{ label: string, key: Buffer }>} [previous]
162
+ * @returns {Array<{ label: string, key: Buffer }>}
116
163
  */
117
164
  function parseRecipient(value, previous) {
118
165
  const sep = value.indexOf(':');
@@ -140,7 +187,7 @@ program
140
187
  .option('--force', 'Overwrite existing vault entry')
141
188
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption (prefer GIT_CAS_PASSPHRASE env var)')
142
189
  .option('--cwd <dir>', 'Git working directory', '.')
143
- .action(runAction(async (file, opts) => {
190
+ .action(runAction(async (/** @type {string} */ file, /** @type {Record<string, any>} */ opts) => {
144
191
  if (opts.recipient && (opts.keyFile || resolvePassphrase(opts))) {
145
192
  throw new Error('Provide --key-file/--vault-passphrase or --recipient, not both');
146
193
  }
@@ -176,7 +223,7 @@ program
176
223
  .description('Create a Git tree from a manifest')
177
224
  .requiredOption('--manifest <path>', 'Path to manifest JSON file')
178
225
  .option('--cwd <dir>', 'Git working directory', '.')
179
- .action(runAction(async (opts) => {
226
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
180
227
  const cas = createCas(opts.cwd);
181
228
  const raw = readFileSync(opts.manifest, 'utf8');
182
229
  const manifest = new Manifest(JSON.parse(raw));
@@ -199,7 +246,7 @@ program
199
246
  .option('--oid <tree-oid>', 'Direct tree OID')
200
247
  .option('--heatmap', 'Show chunk heatmap visualization')
201
248
  .option('--cwd <dir>', 'Git working directory', '.')
202
- .action(runAction(async (opts) => {
249
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
203
250
  validateRestoreFlags(opts);
204
251
  const cas = createCas(opts.cwd);
205
252
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
@@ -229,7 +276,7 @@ program
229
276
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
230
277
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption (prefer GIT_CAS_PASSPHRASE env var)')
231
278
  .option('--cwd <dir>', 'Git working directory', '.')
232
- .action(runAction(async (opts) => {
279
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
233
280
  validateRestoreFlags(opts);
234
281
  const quiet = program.opts().quiet || program.opts().json;
235
282
  const observer = new EventEmitterObserver();
@@ -237,11 +284,7 @@ program
237
284
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
238
285
  const manifest = await cas.readManifest({ treeOid });
239
286
 
240
- const restoreOpts = { manifest };
241
287
  const encryptionKey = await resolveEncryptionKey(cas, opts);
242
- if (encryptionKey) {
243
- restoreOpts.encryptionKey = encryptionKey;
244
- }
245
288
 
246
289
  const progress = createRestoreProgress({
247
290
  totalChunks: manifest.chunks.length, quiet,
@@ -250,7 +293,8 @@ program
250
293
  let bytesWritten;
251
294
  try {
252
295
  ({ bytesWritten } = await cas.restoreFile({
253
- ...restoreOpts,
296
+ manifest,
297
+ ...(encryptionKey ? { encryptionKey } : {}),
254
298
  outputPath: opts.out,
255
299
  }));
256
300
  } finally {
@@ -273,7 +317,7 @@ program
273
317
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
274
318
  .option('--oid <tree-oid>', 'Direct tree OID')
275
319
  .option('--cwd <dir>', 'Git working directory', '.')
276
- .action(runAction(async (opts) => {
320
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
277
321
  validateRestoreFlags(opts);
278
322
  const cas = createCas(opts.cwd);
279
323
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
@@ -303,13 +347,14 @@ vault
303
347
  .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption (prefer GIT_CAS_PASSPHRASE env var)')
304
348
  .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)', 'pbkdf2')
305
349
  .option('--cwd <dir>', 'Git working directory', '.')
306
- .action(runAction(async (opts) => {
350
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
307
351
  const cas = createCas(opts.cwd);
352
+ /** @type {{ passphrase?: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
308
353
  const initOpts = {};
309
354
  const passphrase = resolvePassphrase(opts);
310
355
  if (passphrase) {
311
356
  initOpts.passphrase = passphrase;
312
- initOpts.kdfOptions = { algorithm: opts.algorithm };
357
+ initOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
313
358
  }
314
359
  const { commitOid } = await cas.initVault(initOpts);
315
360
  const json = program.opts().json;
@@ -328,7 +373,7 @@ vault
328
373
  .description('List vault entries')
329
374
  .option('--filter <pattern>', 'Filter entries by glob pattern')
330
375
  .option('--cwd <dir>', 'Git working directory', '.')
331
- .action(runAction(async (opts) => {
376
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
332
377
  const cas = createCas(opts.cwd);
333
378
  const all = await cas.listVault();
334
379
  const entries = filterEntries(all, opts.filter);
@@ -349,7 +394,7 @@ vault
349
394
  .command('remove <slug>')
350
395
  .description('Remove an entry from the vault')
351
396
  .option('--cwd <dir>', 'Git working directory', '.')
352
- .action(runAction(async (slug, opts) => {
397
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
353
398
  const cas = createCas(opts.cwd);
354
399
  const { commitOid, removedTreeOid } = await cas.removeFromVault({ slug });
355
400
  const json = program.opts().json;
@@ -368,11 +413,12 @@ vault
368
413
  .description('Show info for a vault entry')
369
414
  .option('--encryption', 'Show vault encryption details')
370
415
  .option('--cwd <dir>', 'Git working directory', '.')
371
- .action(runAction(async (slug, opts) => {
416
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
372
417
  const cas = createCas(opts.cwd);
373
418
  const treeOid = await cas.resolveVaultEntry({ slug });
374
419
  const json = program.opts().json;
375
420
  if (json) {
421
+ /** @type {Record<string, any>} */
376
422
  const result = { slug, treeOid };
377
423
  if (opts.encryption) {
378
424
  const metadata = await cas.getVaultMetadata();
@@ -400,7 +446,7 @@ vault
400
446
  .option('--cwd <dir>', 'Git working directory', '.')
401
447
  .option('-n, --max-count <n>', 'Limit number of commits')
402
448
  .option('--pretty', 'Render as color-coded timeline')
403
- .action(runAction(async (opts) => {
449
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
404
450
  const runner = ShellRunnerFactory.create();
405
451
  const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
406
452
  const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
@@ -417,7 +463,7 @@ vault
417
463
  const history = output
418
464
  .split('\n')
419
465
  .filter(Boolean)
420
- .map((line) => {
466
+ .map((/** @type {string} */ line) => {
421
467
  const [commitOid, ...messageParts] = line.trim().split(/\s+/);
422
468
  return { commitOid, message: messageParts.join(' ') };
423
469
  });
@@ -429,6 +475,41 @@ vault
429
475
  }
430
476
  }, getJson));
431
477
 
478
+ // ---------------------------------------------------------------------------
479
+ // vault rotate
480
+ // ---------------------------------------------------------------------------
481
+ vault
482
+ .command('rotate')
483
+ .description('Rotate vault-level encryption passphrase')
484
+ .requiredOption('--old-passphrase <pass>', 'Current vault passphrase')
485
+ .requiredOption('--new-passphrase <pass>', 'New vault passphrase')
486
+ .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)')
487
+ .option('--cwd <dir>', 'Git working directory', '.')
488
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
489
+ const cas = createCas(opts.cwd);
490
+ /** @type {{ oldPassphrase: string, newPassphrase: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
491
+ const rotateOpts = {
492
+ oldPassphrase: opts.oldPassphrase,
493
+ newPassphrase: opts.newPassphrase,
494
+ };
495
+ if (opts.algorithm) {
496
+ rotateOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
497
+ }
498
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase(rotateOpts);
499
+ const json = program.opts().json;
500
+ if (json) {
501
+ process.stdout.write(`${JSON.stringify({ commitOid, rotatedSlugs, skippedSlugs })}\n`);
502
+ } else {
503
+ process.stdout.write(`${commitOid}\n`);
504
+ if (rotatedSlugs.length) {
505
+ process.stderr.write(`rotated: ${rotatedSlugs.join(', ')}\n`);
506
+ }
507
+ if (skippedSlugs.length) {
508
+ process.stderr.write(`skipped: ${skippedSlugs.join(', ')}\n`);
509
+ }
510
+ }
511
+ }, getJson));
512
+
432
513
  // ---------------------------------------------------------------------------
433
514
  // vault dashboard
434
515
  // ---------------------------------------------------------------------------
@@ -436,12 +517,55 @@ vault
436
517
  .command('dashboard')
437
518
  .description('Interactive vault explorer')
438
519
  .option('--cwd <dir>', 'Git working directory', '.')
439
- .action(runAction(async (opts) => {
520
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
440
521
  const cas = createCas(opts.cwd);
441
522
  const { launchDashboard } = await import('./ui/dashboard.js');
442
523
  await launchDashboard(cas);
443
524
  }, getJson));
444
525
 
526
+ // ---------------------------------------------------------------------------
527
+ // rotate
528
+ // ---------------------------------------------------------------------------
529
+ program
530
+ .command('rotate')
531
+ .description('Rotate an encryption key without re-encrypting data')
532
+ .option('--slug <slug>', 'Resolve tree OID from vault slug')
533
+ .option('--oid <tree-oid>', 'Direct tree OID')
534
+ .requiredOption('--old-key-file <path>', 'Path to current 32-byte key file')
535
+ .requiredOption('--new-key-file <path>', 'Path to new 32-byte key file')
536
+ .option('--label <label>', 'Rotate only the named recipient')
537
+ .option('--cwd <dir>', 'Git working directory', '.')
538
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
539
+ validateRestoreFlags(opts);
540
+ const cas = createCas(opts.cwd);
541
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
542
+ const manifest = await cas.readManifest({ treeOid });
543
+
544
+ const oldKey = readKeyFile(opts.oldKeyFile);
545
+ const newKey = readKeyFile(opts.newKeyFile);
546
+
547
+ /** @type {{ manifest: Manifest, oldKey: Buffer, newKey: Buffer, label?: string }} */
548
+ const rotateOpts = { manifest, oldKey, newKey };
549
+ if (opts.label) { rotateOpts.label = opts.label; }
550
+
551
+ const updated = await cas.rotateKey(rotateOpts);
552
+ const json = program.opts().json;
553
+
554
+ if (opts.slug) {
555
+ const newTreeOid = await cas.createTree({ manifest: updated });
556
+ await cas.addToVault({ slug: opts.slug, treeOid: newTreeOid, force: true });
557
+ if (json) {
558
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid, keyVersion: updated.encryption?.keyVersion })}\n`);
559
+ } else {
560
+ process.stdout.write(`${newTreeOid}\n`);
561
+ }
562
+ } else if (json) {
563
+ process.stdout.write(`${JSON.stringify(updated.toJSON())}\n`);
564
+ } else {
565
+ process.stdout.write(`${JSON.stringify(updated.toJSON(), null, 2)}\n`);
566
+ }
567
+ }, getJson));
568
+
445
569
  // ---------------------------------------------------------------------------
446
570
  // recipient add / remove / list
447
571
  // ---------------------------------------------------------------------------
@@ -456,7 +580,7 @@ recipient
456
580
  .requiredOption('--key-file <path>', 'Path to 32-byte key file for the new recipient')
457
581
  .requiredOption('--existing-key-file <path>', 'Path to key file of an existing recipient')
458
582
  .option('--cwd <dir>', 'Git working directory', '.')
459
- .action(runAction(async (slug, opts) => {
583
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
460
584
  const cas = createCas(opts.cwd);
461
585
  const treeOid = await cas.resolveVaultEntry({ slug });
462
586
  const manifest = await cas.readManifest({ treeOid });
@@ -487,7 +611,7 @@ recipient
487
611
  .description('Remove a recipient from an envelope-encrypted asset')
488
612
  .requiredOption('--label <label>', 'Label of the recipient to remove')
489
613
  .option('--cwd <dir>', 'Git working directory', '.')
490
- .action(runAction(async (slug, opts) => {
614
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
491
615
  const cas = createCas(opts.cwd);
492
616
  const treeOid = await cas.resolveVaultEntry({ slug });
493
617
  const manifest = await cas.readManifest({ treeOid });
@@ -509,7 +633,7 @@ recipient
509
633
  .command('list <slug>')
510
634
  .description('List recipients of an envelope-encrypted asset')
511
635
  .option('--cwd <dir>', 'Git working directory', '.')
512
- .action(runAction(async (slug, opts) => {
636
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
513
637
  const cas = createCas(opts.cwd);
514
638
  const treeOid = await cas.resolveVaultEntry({ slug });
515
639
  const manifest = await cas.readManifest({ treeOid });
package/bin/ui/context.js CHANGED
@@ -5,11 +5,14 @@
5
5
  import { createBijou } from '@flyingrobots/bijou';
6
6
  import { nodeRuntime, chalkStyle } from '@flyingrobots/bijou-node';
7
7
 
8
+ /** @type {import('@flyingrobots/bijou').BijouContext | null} */
8
9
  let ctx = null;
9
10
 
10
11
  /**
11
12
  * Returns a bijou context that writes to stderr instead of stdout.
12
13
  * Stdout is reserved for structured output (OIDs, JSON).
14
+ *
15
+ * @returns {import('@flyingrobots/bijou').BijouContext}
13
16
  */
14
17
  export function getCliContext() {
15
18
  if (ctx) {
@@ -25,8 +28,12 @@ export function getCliContext() {
25
28
  return ctx;
26
29
  }
27
30
 
31
+ /**
32
+ * @returns {import('@flyingrobots/bijou').IOPort}
33
+ */
28
34
  function stderrIO() {
29
35
  return {
36
+ /** @param {string} data */
30
37
  write(data) {
31
38
  process.stderr.write(data);
32
39
  },
@@ -36,6 +43,7 @@ function stderrIO() {
36
43
  rawInput() {
37
44
  throw new Error('rawInput() not supported in CLI context');
38
45
  },
46
+ /** @param {(cols: number, rows: number) => void} callback */
39
47
  onResize(callback) {
40
48
  const handler = () => {
41
49
  callback(process.stderr.columns ?? 80, process.stderr.rows ?? 24);
@@ -43,12 +51,17 @@ function stderrIO() {
43
51
  process.stderr.on('resize', handler);
44
52
  return { dispose() { process.stderr.removeListener('resize', handler); } };
45
53
  },
54
+ /**
55
+ * @param {() => void} callback
56
+ * @param {number} ms
57
+ */
46
58
  setInterval(callback, ms) {
47
59
  const id = globalThis.setInterval(callback, ms);
48
60
  return { dispose() { globalThis.clearInterval(id); } };
49
61
  },
50
62
  readFile() { throw new Error('readFile() not supported'); },
51
63
  readDir() { throw new Error('readDir() not supported'); },
64
+ /** @param {string[]} segments */
52
65
  joinPath(...segments) { return segments.join('/'); },
53
66
  };
54
67
  }
@@ -2,8 +2,12 @@
2
2
  * Async command factories for the vault dashboard.
3
3
  */
4
4
 
5
+ /** @typedef {import('../../index.js').default} ContentAddressableStore */
6
+
5
7
  /**
6
8
  * Load vault entries and metadata in parallel.
9
+ *
10
+ * @param {ContentAddressableStore} cas
7
11
  */
8
12
  export function loadEntriesCmd(cas) {
9
13
  return async () => {
@@ -12,23 +16,27 @@ export function loadEntriesCmd(cas) {
12
16
  cas.listVault(),
13
17
  cas.getVaultMetadata(),
14
18
  ]);
15
- return { type: 'loaded-entries', entries, metadata };
16
- } catch (err) {
17
- return { type: 'load-error', source: 'entries', error: err.message };
19
+ return /** @type {const} */ ({ type: 'loaded-entries', entries, metadata });
20
+ } catch (/** @type {any} */ err) {
21
+ return /** @type {const} */ ({ type: 'load-error', source: 'entries', error: /** @type {Error} */ (err).message });
18
22
  }
19
23
  };
20
24
  }
21
25
 
22
26
  /**
23
27
  * Load a single manifest by slug and tree OID.
28
+ *
29
+ * @param {ContentAddressableStore} cas
30
+ * @param {string} slug
31
+ * @param {string} treeOid
24
32
  */
25
33
  export function loadManifestCmd(cas, slug, treeOid) {
26
34
  return async () => {
27
35
  try {
28
36
  const manifest = await cas.readManifest({ treeOid });
29
- return { type: 'loaded-manifest', slug, manifest };
30
- } catch (err) {
31
- return { type: 'load-error', source: 'manifest', slug, error: err.message };
37
+ return /** @type {const} */ ({ type: 'loaded-manifest', slug, manifest });
38
+ } catch (/** @type {any} */ err) {
39
+ return /** @type {const} */ ({ type: 'load-error', source: 'manifest', slug, error: /** @type {Error} */ (err).message });
32
40
  }
33
41
  };
34
42
  }
@@ -6,8 +6,18 @@ import { badge } from '@flyingrobots/bijou';
6
6
  import { flex, viewport } from '@flyingrobots/bijou-tui';
7
7
  import { renderManifestView } from './manifest-view.js';
8
8
 
9
+ /**
10
+ * @typedef {import('./dashboard.js').DashModel} DashModel
11
+ * @typedef {import('./dashboard.js').DashDeps} DashDeps
12
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
13
+ * @typedef {import('../../src/domain/value-objects/Manifest.js').default} Manifest
14
+ */
15
+
9
16
  /**
10
17
  * Format bytes as compact string.
18
+ *
19
+ * @param {number} bytes
20
+ * @returns {string}
11
21
  */
12
22
  function formatSize(bytes) {
13
23
  if (bytes < 1024) { return `${bytes}B`; }
@@ -18,6 +28,9 @@ function formatSize(bytes) {
18
28
 
19
29
  /**
20
30
  * Format manifest stats for the list.
31
+ *
32
+ * @param {Manifest} manifest
33
+ * @returns {string}
21
34
  */
22
35
  function formatStats(manifest) {
23
36
  const m = manifest.toJSON ? manifest.toJSON() : manifest;
@@ -26,6 +39,11 @@ function formatStats(manifest) {
26
39
 
27
40
  /**
28
41
  * Render a single list item.
42
+ *
43
+ * @param {{ slug: string, treeOid: string }} entry
44
+ * @param {number} index
45
+ * @param {{ model: DashModel, width?: number }} opts
46
+ * @returns {string}
29
47
  */
30
48
  function renderListItem(entry, index, opts) {
31
49
  const prefix = index === opts.model.cursor ? '> ' : ' ';
@@ -37,6 +55,11 @@ function renderListItem(entry, index, opts) {
37
55
 
38
56
  /**
39
57
  * Compute visible window for cursor scrolling.
58
+ *
59
+ * @param {number} cursor
60
+ * @param {number} total
61
+ * @param {number} height
62
+ * @returns {{ start: number, end: number }}
40
63
  */
41
64
  function visibleRange(cursor, total, height) {
42
65
  const start = Math.max(0, Math.min(cursor - Math.floor(height / 2), total - height));
@@ -45,6 +68,10 @@ function visibleRange(cursor, total, height) {
45
68
 
46
69
  /**
47
70
  * Render the header line.
71
+ *
72
+ * @param {DashModel} model
73
+ * @param {BijouContext} ctx
74
+ * @returns {string}
48
75
  */
49
76
  function renderHeader(model, ctx) {
50
77
  const parts = [];
@@ -58,9 +85,13 @@ function renderHeader(model, ctx) {
58
85
 
59
86
  /**
60
87
  * Render the list pane.
88
+ *
89
+ * @param {DashModel} model
90
+ * @param {{ height: number, width?: number }} size
91
+ * @returns {string}
61
92
  */
62
93
  function renderListPane(model, size) {
63
- const clamp = (s) => (size.width ? s.slice(0, size.width) : s);
94
+ const clamp = (/** @type {string} */ s) => (typeof size.width === 'number' && size.width > 0 ? s.slice(0, size.width) : s);
64
95
  const filterLine = model.filtering ? clamp(`/${model.filterText}\u2588`) : '';
65
96
  const listHeight = model.filtering ? size.height - 1 : size.height;
66
97
  const items = model.filtered;
@@ -86,6 +117,11 @@ function renderListPane(model, size) {
86
117
 
87
118
  /**
88
119
  * Pad content to target height, optionally appending a suffix line.
120
+ *
121
+ * @param {string} content
122
+ * @param {number} height
123
+ * @param {string} suffix
124
+ * @returns {string}
89
125
  */
90
126
  function padToHeight(content, height, suffix) {
91
127
  const lines = content.split('\n');
@@ -95,6 +131,10 @@ function padToHeight(content, height, suffix) {
95
131
 
96
132
  /**
97
133
  * Render the detail pane with viewport scrolling.
134
+ *
135
+ * @param {DashModel} model
136
+ * @param {{ width: number, height: number, ctx: BijouContext }} opts
137
+ * @returns {string}
98
138
  */
99
139
  function renderDetailPane(model, opts) {
100
140
  const entry = model.filtered[model.cursor];
@@ -107,26 +147,35 @@ function renderDetailPane(model, opts) {
107
147
 
108
148
  /**
109
149
  * Render the body with list and detail panes.
150
+ *
151
+ * @param {DashModel} model
152
+ * @param {DashDeps} deps
153
+ * @param {{ width: number, height: number }} size
154
+ * @returns {string}
110
155
  */
111
156
  function renderBody(model, deps, size) {
112
157
  const listBasis = Math.floor(size.width * 0.35);
113
158
  return flex(
114
159
  { direction: 'row', width: size.width, height: size.height, gap: 1 },
115
- { content: (w, h) => renderListPane(model, { height: h, width: w }), basis: listBasis },
116
- { content: (w, h) => renderDetailPane(model, { width: w, height: h, ctx: deps.ctx }), flex: 1 },
160
+ { content: (/** @type {number} */ w, /** @type {number} */ h) => renderListPane(model, { height: h, width: w }), basis: listBasis },
161
+ { content: (/** @type {number} */ w, /** @type {number} */ h) => renderDetailPane(model, { width: w, height: h, ctx: deps.ctx }), flex: 1 },
117
162
  );
118
163
  }
119
164
 
120
165
  /**
121
166
  * Render the full dashboard layout.
167
+ *
168
+ * @param {DashModel} model
169
+ * @param {DashDeps} deps
170
+ * @returns {string}
122
171
  */
123
172
  export function renderDashboard(model, deps) {
124
173
  return flex(
125
174
  { direction: 'column', width: model.columns, height: model.rows },
126
175
  { content: renderHeader(model, deps.ctx), basis: 1 },
127
- { content: (w, _h) => '\u2500'.repeat(w), basis: 1 },
128
- { content: (w, h) => renderBody(model, deps, { width: w, height: h }), flex: 1 },
129
- { content: (w, _h) => '\u2500'.repeat(w), basis: 1 },
176
+ { content: (/** @type {number} */ w, /** @type {number} */ _h) => '\u2500'.repeat(w), basis: 1 },
177
+ { content: (/** @type {number} */ w, /** @type {number} */ h) => renderBody(model, deps, { width: w, height: h }), flex: 1 },
178
+ { content: (/** @type {number} */ w, /** @type {number} */ _h) => '\u2500'.repeat(w), basis: 1 },
130
179
  { content: 'j/k Navigate enter Load / Filter J/K Scroll q Quit', basis: 1 },
131
180
  );
132
181
  }