@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
@@ -7,8 +7,61 @@ import { createNodeContext } from '@flyingrobots/bijou-node';
7
7
  import { loadEntriesCmd, loadManifestCmd } from './dashboard-cmds.js';
8
8
  import { renderDashboard } from './dashboard-view.js';
9
9
 
10
+ /**
11
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
12
+ * @typedef {import('@flyingrobots/bijou-tui').KeyMsg} KeyMsg
13
+ * @typedef {import('@flyingrobots/bijou-tui').ResizeMsg} ResizeMsg
14
+ * @typedef {import('@flyingrobots/bijou-tui').Cmd<DashMsg>} DashCmd
15
+ * @typedef {import('@flyingrobots/bijou-tui').KeyMap<DashAction>} DashKeyMap
16
+ * @typedef {import('../../index.js').default} ContentAddressableStore
17
+ * @typedef {import('../../src/domain/value-objects/Manifest.js').default} Manifest
18
+ * @typedef {{ slug: string, treeOid: string }} VaultEntry
19
+ */
20
+
21
+ /**
22
+ * @typedef {{ type: 'quit' }
23
+ * | { type: 'move', delta: number }
24
+ * | { type: 'select' }
25
+ * | { type: 'filter-start' }
26
+ * | { type: 'scroll-detail', delta: number }
27
+ * } DashAction
28
+ */
29
+
30
+ /**
31
+ * @typedef {{ type: 'loaded-entries', entries: VaultEntry[], metadata: any }
32
+ * | { type: 'loaded-manifest', slug: string, manifest: Manifest }
33
+ * | { type: 'load-error', source: string, slug?: string, error: string }
34
+ * } DashMsg
35
+ */
36
+
37
+ /**
38
+ * @typedef {Object} DashModel
39
+ * @property {string} status
40
+ * @property {number} columns
41
+ * @property {number} rows
42
+ * @property {VaultEntry[]} entries
43
+ * @property {VaultEntry[]} filtered
44
+ * @property {number} cursor
45
+ * @property {string} filterText
46
+ * @property {boolean} filtering
47
+ * @property {any} metadata
48
+ * @property {Map<string, Manifest>} manifestCache
49
+ * @property {string | null} loadingSlug
50
+ * @property {number} detailScroll
51
+ * @property {string | null} error
52
+ */
53
+
54
+ /**
55
+ * @typedef {Object} DashDeps
56
+ * @property {DashKeyMap} keyMap
57
+ * @property {ContentAddressableStore} cas
58
+ * @property {BijouContext} ctx
59
+ */
60
+
10
61
  /**
11
62
  * Create keyboard bindings for normal mode.
63
+ *
64
+ * @returns {DashKeyMap}
12
65
  */
13
66
  export function createKeyBindings() {
14
67
  return createKeyMap()
@@ -25,6 +78,8 @@ export function createKeyBindings() {
25
78
 
26
79
  /**
27
80
  * Create the initial model.
81
+ *
82
+ * @returns {DashModel}
28
83
  */
29
84
  function createInitModel() {
30
85
  return {
@@ -46,19 +101,28 @@ function createInitModel() {
46
101
 
47
102
  /**
48
103
  * Apply filter text to entries.
104
+ *
105
+ * @param {VaultEntry[]} entries
106
+ * @param {string} text
107
+ * @returns {VaultEntry[]}
49
108
  */
50
109
  function applyFilter(entries, text) {
51
110
  if (!text) { return entries; }
52
- return entries.filter(e => e.slug.includes(text));
111
+ return entries.filter((/** @type {VaultEntry} */ e) => e.slug.includes(text));
53
112
  }
54
113
 
55
114
  /**
56
115
  * Handle the loaded-entries message.
116
+ *
117
+ * @param {DashMsg & { type: 'loaded-entries' }} msg
118
+ * @param {DashModel} model
119
+ * @param {ContentAddressableStore} cas
120
+ * @returns {[DashModel, DashCmd[]]}
57
121
  */
58
122
  function handleLoadedEntries(msg, model, cas) {
59
123
  const filtered = applyFilter(msg.entries, model.filterText);
60
124
  const cursor = Math.max(0, Math.min(model.cursor, filtered.length - 1));
61
- const cmds = msg.entries.map(e => loadManifestCmd(cas, e.slug, e.treeOid));
125
+ const cmds = /** @type {DashCmd[]} */ (msg.entries.map((/** @type {VaultEntry} */ e) => loadManifestCmd(cas, e.slug, e.treeOid)));
62
126
  return [{
63
127
  ...model,
64
128
  status: 'ready',
@@ -71,6 +135,10 @@ function handleLoadedEntries(msg, model, cas) {
71
135
 
72
136
  /**
73
137
  * Handle a loaded-manifest message.
138
+ *
139
+ * @param {DashMsg & { type: 'loaded-manifest' }} msg
140
+ * @param {DashModel} model
141
+ * @returns {[DashModel, DashCmd[]]}
74
142
  */
75
143
  function handleLoadedManifest(msg, model) {
76
144
  const cache = new Map(model.manifestCache);
@@ -80,6 +148,10 @@ function handleLoadedManifest(msg, model) {
80
148
 
81
149
  /**
82
150
  * Handle cursor movement.
151
+ *
152
+ * @param {{ type: 'move', delta: number }} msg
153
+ * @param {DashModel} model
154
+ * @returns {[DashModel, DashCmd[]]}
83
155
  */
84
156
  function handleMove(msg, model) {
85
157
  const max = model.filtered.length - 1;
@@ -89,6 +161,10 @@ function handleMove(msg, model) {
89
161
 
90
162
  /**
91
163
  * Handle filter key input in filter mode.
164
+ *
165
+ * @param {KeyMsg} msg
166
+ * @param {DashModel} model
167
+ * @returns {[DashModel, DashCmd[]]}
92
168
  */
93
169
  function handleFilterKey(msg, model) {
94
170
  if (msg.key === 'escape' || msg.key === 'enter') {
@@ -109,18 +185,27 @@ function handleFilterKey(msg, model) {
109
185
 
110
186
  /**
111
187
  * Handle select (enter key) to load manifest.
188
+ *
189
+ * @param {DashModel} model
190
+ * @param {DashDeps} deps
191
+ * @returns {[DashModel, DashCmd[]]}
112
192
  */
113
193
  function handleSelect(model, deps) {
114
194
  const entry = model.filtered[model.cursor];
115
195
  if (!entry || model.manifestCache.has(entry.slug)) {
116
196
  return [model, []];
117
197
  }
118
- const cmd = loadManifestCmd(deps.cas, entry.slug, entry.treeOid);
198
+ const cmd = /** @type {DashCmd} */ (loadManifestCmd(deps.cas, entry.slug, entry.treeOid));
119
199
  return [{ ...model, loadingSlug: entry.slug }, [cmd]];
120
200
  }
121
201
 
122
202
  /**
123
203
  * Handle keymap actions.
204
+ *
205
+ * @param {DashAction} action
206
+ * @param {DashModel} model
207
+ * @param {DashDeps} deps
208
+ * @returns {[DashModel, DashCmd[]]}
124
209
  */
125
210
  function handleAction(action, model, deps) {
126
211
  if (action.type === 'quit') { return [model, [quit()]]; }
@@ -138,6 +223,11 @@ function handleAction(action, model, deps) {
138
223
 
139
224
  /**
140
225
  * Handle app-level messages (data loading results).
226
+ *
227
+ * @param {DashMsg} msg
228
+ * @param {DashModel} model
229
+ * @param {ContentAddressableStore} cas
230
+ * @returns {[DashModel, DashCmd[]]}
141
231
  */
142
232
  function handleAppMsg(msg, model, cas) {
143
233
  if (msg.type === 'loaded-entries') { return handleLoadedEntries(msg, model, cas); }
@@ -153,6 +243,11 @@ function handleAppMsg(msg, model, cas) {
153
243
 
154
244
  /**
155
245
  * Route all update messages to the appropriate handler.
246
+ *
247
+ * @param {KeyMsg | ResizeMsg | DashMsg} msg
248
+ * @param {DashModel} model
249
+ * @param {DashDeps} deps
250
+ * @returns {[DashModel, DashCmd[]]}
156
251
  */
157
252
  function handleUpdate(msg, model, deps) {
158
253
  if (msg.type === 'key' && model.filtering) {
@@ -166,22 +261,27 @@ function handleUpdate(msg, model, deps) {
166
261
  if (msg.type === 'resize') {
167
262
  return [{ ...model, columns: msg.columns, rows: msg.rows }, []];
168
263
  }
169
- return handleAppMsg(msg, model, deps.cas);
264
+ return handleAppMsg(/** @type {DashMsg} */ (msg), model, deps.cas);
170
265
  }
171
266
 
172
267
  /**
173
268
  * Create the TEA app object for the dashboard.
269
+ *
270
+ * @param {DashDeps} deps
271
+ * @returns {import('@flyingrobots/bijou-tui').App<DashModel, DashMsg>}
174
272
  */
175
273
  export function createDashboardApp(deps) {
176
274
  return {
177
- init: () => [createInitModel(), [loadEntriesCmd(deps.cas)]],
178
- update: (msg, model) => handleUpdate(msg, model, deps),
179
- view: (model) => renderDashboard(model, deps),
275
+ init: () => /** @type {[DashModel, DashCmd[]]} */ ([createInitModel(), [/** @type {DashCmd} */ (loadEntriesCmd(deps.cas))]]),
276
+ update: (/** @type {KeyMsg | ResizeMsg | DashMsg} */ msg, /** @type {DashModel} */ model) => handleUpdate(msg, model, deps),
277
+ view: (/** @type {DashModel} */ model) => renderDashboard(model, deps),
180
278
  };
181
279
  }
182
280
 
183
281
  /**
184
282
  * Print static list for non-TTY environments.
283
+ *
284
+ * @param {ContentAddressableStore} cas
185
285
  */
186
286
  async function printStaticList(cas) {
187
287
  const entries = await cas.listVault();
@@ -192,6 +292,8 @@ async function printStaticList(cas) {
192
292
 
193
293
  /**
194
294
  * Launch the interactive vault dashboard.
295
+ *
296
+ * @param {ContentAddressableStore} cas
195
297
  */
196
298
  export async function launchDashboard(cas) {
197
299
  if (!process.stdout.isTTY) {
@@ -9,7 +9,7 @@ import { getCliContext } from './context.js';
9
9
  * Render an encryption info card for the vault.
10
10
  *
11
11
  * @param {Object} options
12
- * @param {Object|null} options.metadata - Vault metadata (from getVaultMetadata()).
12
+ * @param {import('../../index.js').VaultMetadata | null} options.metadata - Vault metadata (from getVaultMetadata()).
13
13
  * @param {boolean} [options.unlocked] - Whether a key/passphrase was provided.
14
14
  * @returns {string}
15
15
  */
@@ -33,7 +33,7 @@ export function renderEncryptionCard({ metadata, unlocked = false }) {
33
33
  ];
34
34
 
35
35
  if (kdf.algorithm === 'pbkdf2') {
36
- rows.push(` iterations ${kdf.iterations.toLocaleString()}`);
36
+ rows.push(` iterations ${/** @type {number} */ (kdf.iterations).toLocaleString()}`);
37
37
  } else if (kdf.algorithm === 'scrypt') {
38
38
  rows.push(` cost ${kdf.cost}`);
39
39
  rows.push(` blockSize ${kdf.blockSize}`);
package/bin/ui/heatmap.js CHANGED
@@ -5,6 +5,12 @@
5
5
  import { gradientText } from '@flyingrobots/bijou';
6
6
  import { getCliContext } from './context.js';
7
7
 
8
+ /**
9
+ * @typedef {import('../../src/domain/value-objects/Manifest.js').ManifestData} ManifestData
10
+ * @typedef {import('../../src/domain/value-objects/Manifest.js').SubManifestRef} SubManifestRef
11
+ */
12
+
13
+ /** @type {import('@flyingrobots/bijou').GradientStop[]} */
8
14
  const GRADIENT_STOPS = [
9
15
  { pos: 0, color: [0, 255, 255] },
10
16
  { pos: 1, color: [255, 0, 255] },
@@ -12,6 +18,9 @@ const GRADIENT_STOPS = [
12
18
 
13
19
  /**
14
20
  * Format bytes as human-readable string.
21
+ *
22
+ * @param {number} bytes
23
+ * @returns {string}
15
24
  */
16
25
  function formatBytes(bytes) {
17
26
  if (bytes < 1024) {
@@ -28,6 +37,11 @@ function formatBytes(bytes) {
28
37
 
29
38
  /**
30
39
  * Build the block grid string from chunks.
40
+ *
41
+ * @param {ManifestData['chunks']} chunks
42
+ * @param {Set<number>} boundaries
43
+ * @param {number} width
44
+ * @returns {string}
31
45
  */
32
46
  function buildGrid(chunks, boundaries, width) {
33
47
  let grid = '';
@@ -56,6 +70,10 @@ function buildGrid(chunks, boundaries, width) {
56
70
 
57
71
  /**
58
72
  * Build the legend line.
73
+ *
74
+ * @param {ManifestData['chunks']} chunks
75
+ * @param {SubManifestRef[]} subManifests
76
+ * @returns {string}
59
77
  */
60
78
  function buildLegend(chunks, subManifests) {
61
79
  const chunkSize = chunks.length > 0 ? chunks[0].size : 0;
@@ -73,12 +91,12 @@ function buildLegend(chunks, subManifests) {
73
91
  * Render a chunk heatmap for a manifest.
74
92
  *
75
93
  * @param {Object} options
76
- * @param {Object} options.manifest - The manifest (from readManifest).
94
+ * @param {ManifestData | { toJSON(): ManifestData }} options.manifest - The manifest (Manifest instance or plain ManifestData).
77
95
  * @returns {string}
78
96
  */
79
97
  export function renderHeatmap({ manifest }) {
80
98
  const ctx = getCliContext();
81
- const m = manifest.toJSON ? manifest.toJSON() : manifest;
99
+ const m = /** @type {ManifestData} */ ('toJSON' in manifest ? manifest.toJSON() : manifest);
82
100
  const chunks = m.chunks || [];
83
101
 
84
102
  if (chunks.length === 0) {
@@ -34,6 +34,7 @@ function parseCommitLine(line) {
34
34
  return { oid, operation: match[1], slug: match[2] || null };
35
35
  }
36
36
 
37
+ /** @type {Record<string, string>} */
37
38
  const STATUS_MAP = {
38
39
  init: 'info',
39
40
  add: 'success',
@@ -65,14 +66,15 @@ export function renderHistoryTimeline(gitLogOutput, options = {}) {
65
66
  const start = (page - 1) * perPage;
66
67
  const pageLines = lines.slice(start, start + perPage);
67
68
 
68
- const events = pageLines
69
- .map(parseCommitLine)
70
- .filter(Boolean)
71
- .map(({ oid, operation, slug }) => ({
69
+ const parsed = pageLines.map(parseCommitLine).filter(Boolean);
70
+ const events = parsed.map((entry) => {
71
+ const { oid, operation, slug } = /** @type {{ oid: string, operation: string, slug: string | null }} */ (entry);
72
+ return {
72
73
  label: slug ? `vault: ${operation} ${slug}` : `vault: ${operation}`,
73
74
  description: oid,
74
- status: STATUS_MAP[operation] || 'pending',
75
- }));
75
+ status: /** @type {import('@flyingrobots/bijou').BaseStatusKey} */ (STATUS_MAP[operation] || 'pending'),
76
+ };
77
+ });
76
78
 
77
79
  let output = timeline(events, { ctx });
78
80
 
@@ -5,8 +5,16 @@
5
5
  import { box, badge, table, tree, headerBox } from '@flyingrobots/bijou';
6
6
  import { getCliContext } from './context.js';
7
7
 
8
+ /**
9
+ * @typedef {import('../../src/domain/value-objects/Manifest.js').ManifestData} ManifestData
10
+ * @typedef {import('@flyingrobots/bijou').BijouContext} BijouContext
11
+ */
12
+
8
13
  /**
9
14
  * Format bytes as human-readable string.
15
+ *
16
+ * @param {number} bytes
17
+ * @returns {string}
10
18
  */
11
19
  function formatBytes(bytes) {
12
20
  if (bytes < 1024) {
@@ -23,6 +31,10 @@ function formatBytes(bytes) {
23
31
 
24
32
  /**
25
33
  * Build the header badges line.
34
+ *
35
+ * @param {ManifestData} m
36
+ * @param {BijouContext} ctx
37
+ * @returns {string}
26
38
  */
27
39
  function renderBadges(m, ctx) {
28
40
  const badges = [badge(`v${m.version}`, { ctx })];
@@ -40,6 +52,10 @@ function renderBadges(m, ctx) {
40
52
 
41
53
  /**
42
54
  * Build the encryption section.
55
+ *
56
+ * @param {NonNullable<ManifestData['encryption']>} enc
57
+ * @param {BijouContext} ctx
58
+ * @returns {string}
43
59
  */
44
60
  function renderEncryptionSection(enc, ctx) {
45
61
  const rows = [` algorithm ${enc.algorithm}`];
@@ -63,14 +79,18 @@ function renderEncryptionSection(enc, ctx) {
63
79
 
64
80
  /**
65
81
  * Build the chunks section.
82
+ *
83
+ * @param {ManifestData['chunks']} chunks
84
+ * @param {BijouContext} ctx
85
+ * @returns {string}
66
86
  */
67
87
  function renderChunksSection(chunks, ctx) {
68
88
  const displayChunks = chunks.slice(0, 20);
69
- const chunkRows = displayChunks.map(c => [
89
+ const chunkRows = displayChunks.map((/** @type {{ index: number, size: number, digest: string, blob?: string }} */ c) => [
70
90
  String(c.index),
71
91
  formatBytes(c.size),
72
- `${c.digest.slice(0, 12)}...`,
73
- `${c.blob.slice(0, 12)}...`,
92
+ typeof c.digest === 'string' ? `${c.digest.slice(0, 12)}...` : '-',
93
+ typeof c.blob === 'string' ? `${c.blob.slice(0, 12)}...` : '-',
74
94
  ]);
75
95
  const chunkTable = table({
76
96
  columns: [{ header: '#' }, { header: 'Size' }, { header: 'Digest' }, { header: 'Blob' }],
@@ -85,6 +105,10 @@ function renderChunksSection(chunks, ctx) {
85
105
 
86
106
  /**
87
107
  * Build the metadata section.
108
+ *
109
+ * @param {ManifestData} m
110
+ * @param {BijouContext} ctx
111
+ * @returns {string}
88
112
  */
89
113
  function renderMetadataSection(m, ctx) {
90
114
  const meta = [
@@ -98,24 +122,29 @@ function renderMetadataSection(m, ctx) {
98
122
 
99
123
  /**
100
124
  * Build the sub-manifests section.
125
+ *
126
+ * @param {ManifestData} m
127
+ * @param {BijouContext} ctx
128
+ * @returns {string}
101
129
  */
102
130
  function renderSubManifestsSection(m, ctx) {
103
- const nodes = m.subManifests.map((sm, i) => ({
131
+ const subs = m.subManifests || [];
132
+ const nodes = subs.map((/** @type {import('../../src/domain/value-objects/Manifest.js').SubManifestRef} */ sm, /** @type {number} */ i) => ({
104
133
  label: `sub-${i} ${sm.chunkCount} chunks start: ${sm.startIndex} oid: ${sm.oid.slice(0, 8)}...`,
105
134
  }));
106
- return `${headerBox(`Sub-manifests (${m.subManifests.length})`, { ctx })}\n${tree(nodes, { ctx })}`;
135
+ return `${headerBox(`Sub-manifests (${subs.length})`, { ctx })}\n${tree(nodes, { ctx })}`;
107
136
  }
108
137
 
109
138
  /**
110
139
  * Render a full manifest anatomy view.
111
140
  *
112
141
  * @param {Object} options
113
- * @param {Object} options.manifest - The manifest (from readManifest).
114
- * @param {Object} [options.ctx] - Optional bijou context override.
142
+ * @param {ManifestData | { toJSON(): ManifestData }} options.manifest - The manifest (Manifest instance or plain ManifestData).
143
+ * @param {BijouContext} [options.ctx] - Optional bijou context override.
115
144
  * @returns {string}
116
145
  */
117
146
  export function renderManifestView({ manifest, ctx = getCliContext() }) {
118
- const m = manifest.toJSON ? manifest.toJSON() : manifest;
147
+ const m = /** @type {ManifestData} */ ('toJSON' in manifest ? manifest.toJSON() : manifest);
119
148
  const sections = [renderBadges(m, ctx), renderMetadataSection(m, ctx)];
120
149
 
121
150
  if (m.encryption) {
@@ -9,6 +9,9 @@ import { getCliContext } from './context.js';
9
9
 
10
10
  /**
11
11
  * Format bytes as human-readable string.
12
+ *
13
+ * @param {number} bytes
14
+ * @returns {string}
12
15
  */
13
16
  function formatBytes(bytes) {
14
17
  if (bytes < 1024) {
@@ -23,6 +26,12 @@ function formatBytes(bytes) {
23
26
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
24
27
  }
25
28
 
29
+ /**
30
+ * @typedef {import('../actions.js')} ActionsModule
31
+ * @typedef {{ on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }} Observer
32
+ * @typedef {{ attach(observer: Observer): void, detach(): void }} ProgressTracker
33
+ */
34
+
26
35
  /**
27
36
  * Create a progress tracker for store operations.
28
37
  *
@@ -30,7 +39,9 @@ function formatBytes(bytes) {
30
39
  * @param {string} options.filePath - Path to the file being stored.
31
40
  * @param {number} options.chunkSize - Chunk size in bytes.
32
41
  * @param {boolean} [options.quiet] - Suppress all progress output.
33
- * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
42
+ * @param {number} [options.fileSize] - Pre-computed file size (avoids stat).
43
+ * @param {import('@flyingrobots/bijou').BijouContext} [options.ctx] - Context override.
44
+ * @returns {ProgressTracker}
34
45
  */
35
46
  export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize, ctx: providedCtx }) {
36
47
  if (quiet) {
@@ -58,7 +69,8 @@ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: prov
58
69
  * @param {Object} options
59
70
  * @param {number} options.totalChunks - Number of chunks to restore.
60
71
  * @param {boolean} [options.quiet] - Suppress all progress output.
61
- * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
72
+ * @param {import('@flyingrobots/bijou').BijouContext} [options.ctx] - Context override.
73
+ * @returns {ProgressTracker}
62
74
  */
63
75
  export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx }) {
64
76
  if (quiet || totalChunks === 0) {
@@ -73,54 +85,64 @@ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx })
73
85
  return createProgressTracker({ ctx, totalChunks, event: 'chunk:restored', label: 'Restoring' });
74
86
  }
75
87
 
88
+ /**
89
+ * @typedef {Object} TrackerState
90
+ * @property {number} chunksProcessed
91
+ * @property {number} bytesProcessed
92
+ * @property {number | null} startTime
93
+ * @property {Observer | null} service
94
+ * @property {((evt: { size: number }) => void) | null} handler
95
+ */
96
+
97
+ /**
98
+ * Handle a single chunk event (shared by store/restore).
99
+ *
100
+ * @param {{ size: number }} evt
101
+ * @param {TrackerState} state
102
+ * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, label: string, bar: { update(pct: number): void } }} deps
103
+ */
104
+ function handleChunkEvent({ size }, state, deps) {
105
+ if (!state.startTime) { state.startTime = Date.now(); }
106
+ state.chunksProcessed++;
107
+ state.bytesProcessed += size;
108
+ const pct = (state.chunksProcessed / deps.totalChunks) * 100;
109
+ const elapsed = (Date.now() - state.startTime) / 1000;
110
+ const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
111
+ if (deps.ctx.mode === 'interactive') {
112
+ const status = ` ${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${formatBytes(throughput)}/s `;
113
+ deps.ctx.io.write(`\r\x1b[K${status}`);
114
+ deps.bar.update(pct);
115
+ } else if (state.chunksProcessed === 1 || state.chunksProcessed === deps.totalChunks || state.chunksProcessed % 10 === 0) {
116
+ deps.ctx.io.write(`${deps.label} ${state.chunksProcessed}/${deps.totalChunks} ${Math.round(pct)}%\n`);
117
+ }
118
+ }
119
+
76
120
  /**
77
121
  * Internal: builds the progress tracker object.
122
+ *
123
+ * @param {{ ctx: import('@flyingrobots/bijou').BijouContext, totalChunks: number, event: string, label: string }} params
124
+ * @returns {ProgressTracker}
78
125
  */
79
126
  function createProgressTracker({ ctx, totalChunks, event, label }) {
80
127
  const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
81
128
  const bar = createAnimatedProgressBar({ width, showPercent: false, ctx });
82
-
83
- let chunksProcessed = 0;
84
- let bytesProcessed = 0;
85
- let startTime = null;
86
- let service = null;
87
- let handler = null;
88
-
89
- function onChunk({ size }) {
90
- if (!startTime) {
91
- startTime = Date.now();
92
- }
93
- chunksProcessed++;
94
- bytesProcessed += size;
95
-
96
- const pct = (chunksProcessed / totalChunks) * 100;
97
- const elapsed = (Date.now() - startTime) / 1000;
98
- const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
99
-
100
- if (ctx.mode === 'interactive') {
101
- const status = ` ${label} ${chunksProcessed}/${totalChunks} ${formatBytes(throughput)}/s `;
102
- process.stderr.write(`\r\x1b[K${status}`);
103
- bar.update(pct);
104
- } else if (chunksProcessed === 1 || chunksProcessed === totalChunks || chunksProcessed % 10 === 0) {
105
- ctx.io.write(`${label} ${chunksProcessed}/${totalChunks} ${Math.round(pct)}%\n`);
106
- }
107
- }
129
+ /** @type {TrackerState} */
130
+ const state = { chunksProcessed: 0, bytesProcessed: 0, startTime: null, service: null, handler: null };
131
+ const deps = { ctx, totalChunks, label, bar };
108
132
 
109
133
  return {
134
+ /** @param {Observer} svc */
110
135
  attach(svc) {
111
- service = svc;
112
- handler = onChunk;
136
+ state.service = svc;
137
+ state.handler = (/** @type {{ size: number }} */ evt) => handleChunkEvent(evt, state, deps);
113
138
  bar.start();
114
- service.on(event, handler);
139
+ state.service.on(event, state.handler);
115
140
  },
116
141
  detach() {
117
- if (service && handler) {
118
- service.removeListener(event, handler);
119
- }
120
- const elapsed = startTime ? (Date.now() - startTime) / 1000 : 0;
121
- const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
122
- const msg = ` ${label} ${chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`;
123
- bar.stop(msg);
142
+ if (state.service && state.handler) { state.service.removeListener(event, state.handler); }
143
+ const elapsed = state.startTime ? (Date.now() - state.startTime) / 1000 : 0;
144
+ const throughput = elapsed > 0 ? state.bytesProcessed / elapsed : 0;
145
+ bar.stop(` ${label} ${state.chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`);
124
146
  },
125
147
  };
126
148
  }
package/index.d.ts CHANGED
@@ -47,7 +47,7 @@ export declare class CdcChunker extends ChunkingPort {
47
47
 
48
48
  /** Abstract port for cryptographic operations. */
49
49
  export declare class CryptoPortBase {
50
- sha256(buf: Buffer): string | Promise<string>;
50
+ sha256(buf: Buffer): Promise<string>;
51
51
  randomBytes(n: number): Buffer;
52
52
  encryptBuffer(
53
53
  buffer: Buffer,
@@ -365,6 +365,13 @@ export default class ContentAddressableStore {
365
365
 
366
366
  listRecipients(manifest: Manifest): Promise<string[]>;
367
367
 
368
+ rotateKey(options: {
369
+ manifest: Manifest;
370
+ oldKey: Buffer;
371
+ newKey: Buffer;
372
+ label?: string;
373
+ }): Promise<Manifest>;
374
+
368
375
  // Vault — delegates to VaultService
369
376
 
370
377
  static VAULT_REF: string;
@@ -389,4 +396,18 @@ export default class ContentAddressableStore {
389
396
  resolveVaultEntry(options: { slug: string }): Promise<string>;
390
397
 
391
398
  getVaultMetadata(): Promise<VaultMetadata | null>;
399
+
400
+ rotateVaultPassphrase(options: {
401
+ oldPassphrase: string;
402
+ newPassphrase: string;
403
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
404
+ /** Maximum optimistic-concurrency retries on VAULT_CONFLICT. @default 3 */
405
+ maxRetries?: number;
406
+ /** Base delay in ms for exponential backoff between retries. @default 50 */
407
+ retryBaseMs?: number;
408
+ }): Promise<{
409
+ commitOid: string;
410
+ rotatedSlugs: string[];
411
+ skippedSlugs: string[];
412
+ }>;
392
413
  }