@git-stunts/git-cas 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
 
@@ -0,0 +1,277 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import Oid from '../value-objects/Oid.js';
4
+ import RootSetRef from '../value-objects/RootSetRef.js';
5
+ import RootSetMetadataCodec from './RootSetMetadataCodec.js';
6
+ import RootSetRetryPolicy from './RootSetRetryPolicy.js';
7
+
8
+ const EXPECTED_HEAD_UNSET = Symbol('expected-head-unset');
9
+
10
+ /**
11
+ * Mutable, current-generation set of Git reachability roots.
12
+ */
13
+ export default class RootSet {
14
+ #metadataCodec;
15
+ #retry;
16
+
17
+ /**
18
+ * @param {object} options
19
+ * @param {string} options.ref
20
+ * @param {object} options.persistence
21
+ * @param {RootSetRetryPolicy|object} [options.retry]
22
+ * @param {RootSetMetadataCodec} [options.metadataCodec]
23
+ */
24
+ constructor({
25
+ ref,
26
+ persistence,
27
+ retry,
28
+ metadataCodec = new RootSetMetadataCodec(),
29
+ }) {
30
+ this.ref = RootSetRef.from(ref).toString();
31
+ RootSet.#validatePersistence(persistence);
32
+ this.persistence = persistence;
33
+ this.#metadataCodec = metadataCodec;
34
+ this.#retry = retry instanceof RootSetRetryPolicy ? retry : new RootSetRetryPolicy(retry);
35
+ Object.freeze(this);
36
+ }
37
+
38
+ /**
39
+ * @returns {Promise<{ ref: string, headOid: string|null, treeOid: string|null, entries: Array<object> }>}
40
+ */
41
+ async read() {
42
+ const state = await this.persistence.read();
43
+ return { ...state, entries: state.entries.map((entry) => ({ ...entry })) };
44
+ }
45
+
46
+ /**
47
+ * @returns {Promise<Array<object>>}
48
+ */
49
+ async list() {
50
+ return (await this.read()).entries;
51
+ }
52
+
53
+ /**
54
+ * @param {string} name
55
+ * @returns {Promise<boolean>}
56
+ */
57
+ async contains(name) {
58
+ return (await this.list()).some((entry) => entry.name === name);
59
+ }
60
+
61
+ /**
62
+ * @param {object} entry
63
+ * @returns {Promise<object>}
64
+ */
65
+ async put(entry) {
66
+ const normalizedEntry = this.#metadataCodec.normalizeEntries([entry])[0];
67
+ let previous = null;
68
+ const result = await this.#mutateEntries((entries) => {
69
+ const byName = new Map(entries.map((current) => [current.name, current]));
70
+ previous = byName.get(normalizedEntry.name) ?? null;
71
+ byName.set(normalizedEntry.name, normalizedEntry);
72
+ return byName.values();
73
+ }, `root-set: put ${normalizedEntry.name}`);
74
+ return { ...result, entry: normalizedEntry, previous };
75
+ }
76
+
77
+ /**
78
+ * @param {{ name: string }} options
79
+ * @returns {Promise<object>}
80
+ */
81
+ async remove({ name }) {
82
+ let removed = null;
83
+ const result = await this.#mutateEntries((entries) => {
84
+ const next = [];
85
+ for (const entry of entries) {
86
+ if (entry.name === name) {
87
+ removed = entry;
88
+ } else {
89
+ next.push(entry);
90
+ }
91
+ }
92
+ return next;
93
+ }, `root-set: remove ${name}`);
94
+ return { ...result, removed };
95
+ }
96
+
97
+ /**
98
+ * @param {{ entries: Iterable<object>, expectedHeadOid?: string|null }} options
99
+ * @returns {Promise<object>}
100
+ */
101
+ async replace({ entries, expectedHeadOid = EXPECTED_HEAD_UNSET }) {
102
+ const desired = this.#metadataCodec.normalizeEntries(entries);
103
+ return await this.#mutateEntries(
104
+ () => desired,
105
+ 'root-set: replace current roots',
106
+ RootSet.#normalizeExpectedHead(expectedHeadOid),
107
+ );
108
+ }
109
+
110
+ /**
111
+ * @param {(entries: ReadonlyArray<object>) => Iterable<object>|Promise<Iterable<object>>} mutator
112
+ * @param {{ expectedHeadOid?: string|null }} [options]
113
+ * @returns {Promise<object>}
114
+ */
115
+ async mutate(mutator, { expectedHeadOid = EXPECTED_HEAD_UNSET } = {}) {
116
+ if (typeof mutator !== 'function') {
117
+ throw new CasError(
118
+ 'Root-set mutator must be a function',
119
+ ErrorCodes.ROOT_SET_ENTRY_INVALID,
120
+ { mutatorType: typeof mutator },
121
+ );
122
+ }
123
+ return await this.#mutateEntries(async (entries) => (
124
+ await mutator(Object.freeze(entries.map((entry) => Object.freeze({ ...entry }))))
125
+ ), 'root-set: mutate current roots', RootSet.#normalizeExpectedHead(expectedHeadOid));
126
+ }
127
+
128
+ /**
129
+ * Reports whether the current ref, commit, metadata, and reachability tree
130
+ * agree. It does not mutate the repository.
131
+ *
132
+ * @returns {Promise<object>}
133
+ */
134
+ async doctor() {
135
+ try {
136
+ const state = await this.read();
137
+ const targetReport = await this.persistence.inspectTargets(state.entries);
138
+ return {
139
+ healthy: targetReport.healthy,
140
+ ref: this.ref,
141
+ headOid: state.headOid,
142
+ treeOid: state.treeOid,
143
+ entryCount: state.entries.length,
144
+ entries: state.entries,
145
+ policyCounts: RootSet.#policyCounts(state.entries),
146
+ reachabilityCounts: {
147
+ anchored: targetReport.targets.filter((target) => target.exists === true).length,
148
+ missing: targetReport.targets.filter((target) => target.exists === false).length,
149
+ unknown: targetReport.targets.filter((target) => target.exists === null).length,
150
+ orphaned: 0,
151
+ volatile: 0,
152
+ },
153
+ targets: targetReport.targets,
154
+ issues: targetReport.issues.map(RootSet.#publicIssue),
155
+ };
156
+ } catch (err) {
157
+ return {
158
+ healthy: false,
159
+ ref: this.ref,
160
+ error: {
161
+ code: err?.code ?? ErrorCodes.ROOT_SET_HEAD_INVALID,
162
+ message: err instanceof Error ? err.message : String(err),
163
+ },
164
+ };
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Replaces a missing or malformed head from an authoritative entry list.
170
+ * This deliberately does not trust the current metadata.
171
+ *
172
+ * @param {{ entries: Iterable<object> }} options
173
+ * @returns {Promise<object>}
174
+ */
175
+ async repair({ entries }) {
176
+ const desired = this.#metadataCodec.normalizeEntries(entries);
177
+ for (let attempt = 0; attempt < this.#retry.maxAttempts; attempt++) {
178
+ const expectedHeadOid = await this.persistence.resolveRefOnly();
179
+ try {
180
+ const written = await this.persistence.write({
181
+ entries: desired,
182
+ expectedHeadOid,
183
+ message: 'root-set: repair current roots',
184
+ });
185
+ return { repaired: true, ...written };
186
+ } catch (err) {
187
+ await this.#handleConflict(err, attempt);
188
+ }
189
+ }
190
+ throw new CasError('Root-set repair attempts exhausted', ErrorCodes.ROOT_SET_CONFLICT);
191
+ }
192
+
193
+ async #mutateEntries(transform, message, expectedHeadOid = EXPECTED_HEAD_UNSET) {
194
+ for (let attempt = 0; attempt < this.#retry.maxAttempts; attempt++) {
195
+ const state = await this.read();
196
+ this.#assertExpectedHead(state.headOid, expectedHeadOid);
197
+ const entries = this.#metadataCodec.normalizeEntries(await transform(state.entries));
198
+ if (RootSet.#entriesEqual(state.entries, entries)) {
199
+ return {
200
+ changed: false,
201
+ commitOid: state.headOid,
202
+ treeOid: state.treeOid,
203
+ entries,
204
+ };
205
+ }
206
+ try {
207
+ const written = await this.persistence.write({
208
+ entries,
209
+ expectedHeadOid: state.headOid,
210
+ message,
211
+ });
212
+ return { changed: true, ...written };
213
+ } catch (err) {
214
+ if (expectedHeadOid !== EXPECTED_HEAD_UNSET) {
215
+ throw err;
216
+ }
217
+ await this.#handleConflict(err, attempt);
218
+ }
219
+ }
220
+ throw new CasError('Root-set mutation attempts exhausted', ErrorCodes.ROOT_SET_CONFLICT);
221
+ }
222
+
223
+ async #handleConflict(err, attempt) {
224
+ const finalAttempt = attempt + 1 >= this.#retry.maxAttempts;
225
+ if (!this.#retry.isRetryable(err) || finalAttempt) {
226
+ throw err;
227
+ }
228
+ await this.#retry.waitBeforeRetry(attempt);
229
+ }
230
+
231
+ #assertExpectedHead(actualHeadOid, expectedHeadOid) {
232
+ if (expectedHeadOid === EXPECTED_HEAD_UNSET || actualHeadOid === expectedHeadOid) {
233
+ return;
234
+ }
235
+ throw new CasError(
236
+ 'Root-set head does not match the caller expectation',
237
+ ErrorCodes.ROOT_SET_CONFLICT,
238
+ { ref: this.ref, expectedHeadOid, actualHeadOid },
239
+ );
240
+ }
241
+
242
+ static #normalizeExpectedHead(expectedHeadOid) {
243
+ if (expectedHeadOid === EXPECTED_HEAD_UNSET || expectedHeadOid === null) {
244
+ return expectedHeadOid;
245
+ }
246
+ return Oid.from(expectedHeadOid).toString();
247
+ }
248
+
249
+ static #entriesEqual(left, right) {
250
+ return JSON.stringify(left) === JSON.stringify(right);
251
+ }
252
+
253
+ static #policyCounts(entries) {
254
+ return entries.reduce((counts, entry) => ({
255
+ ...counts,
256
+ [entry.retention]: counts[entry.retention] + 1,
257
+ }), { pinned: 0, evictable: 0 });
258
+ }
259
+
260
+ static #publicIssue(issue) {
261
+ return Object.fromEntries(
262
+ Object.entries(issue).filter(([key]) => key !== 'originalError'),
263
+ );
264
+ }
265
+
266
+ static #validatePersistence(persistence) {
267
+ const missing = ['read', 'write', 'resolveRefOnly', 'inspectTargets']
268
+ .filter((method) => typeof persistence?.[method] !== 'function');
269
+ if (missing.length > 0) {
270
+ throw new CasError(
271
+ 'RootSet requires a complete RootSetPersistence',
272
+ ErrorCodes.ROOT_SET_DEPENDENCY_INVALID,
273
+ { missing },
274
+ );
275
+ }
276
+ }
277
+ }
@@ -0,0 +1,253 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { utf8Decode, utf8Encode } from '../encoding/utf8.js';
4
+ import Oid from '../value-objects/Oid.js';
5
+ import RootSetRef from '../value-objects/RootSetRef.js';
6
+
7
+ export const ROOT_SET_METADATA_VERSION = 1;
8
+ export const ROOT_SET_METADATA_ENTRY = '.rootset.json';
9
+ export const ROOT_SET_ENTRY_TYPES = Object.freeze(['blob', 'tree']);
10
+ export const ROOT_SET_RETENTION_POLICIES = Object.freeze(['pinned', 'evictable']);
11
+ const SLOT_PATTERN = /^root-[0-9]{8}$/;
12
+
13
+ /**
14
+ * Canonical JSON codec for `.rootset.json` snapshots.
15
+ */
16
+ export default class RootSetMetadataCodec {
17
+ /**
18
+ * @param {{ ref: string, entries: Iterable<object> }} options
19
+ * @returns {Uint8Array}
20
+ */
21
+ encode({ ref, entries }) {
22
+ return utf8Encode(JSON.stringify(this.create({ ref, entries }), null, 2));
23
+ }
24
+
25
+ /**
26
+ * @param {{ ref: string, entries: Iterable<object> }} options
27
+ * @returns {{ version: 1, ref: string, entries: Array<object> }}
28
+ */
29
+ create({ ref, entries }) {
30
+ const rootSetRef = RootSetRef.from(ref).toString();
31
+ return {
32
+ version: ROOT_SET_METADATA_VERSION,
33
+ ref: rootSetRef,
34
+ entries: this.normalizeEntries(entries).map((entry, index) => ({
35
+ slot: RootSetMetadataCodec.slotFor(index),
36
+ ...entry,
37
+ })),
38
+ };
39
+ }
40
+
41
+ /**
42
+ * @param {Uint8Array} bytes
43
+ * @param {{ expectedRef?: string }} [options]
44
+ * @returns {{ version: 1, ref: string, entries: Array<object> }}
45
+ */
46
+ decode(bytes, { expectedRef } = {}) {
47
+ let metadata;
48
+ try {
49
+ metadata = JSON.parse(utf8Decode(bytes));
50
+ } catch (err) {
51
+ throw this.#metadataError('Failed to parse .rootset.json', { originalError: err });
52
+ }
53
+ return this.validate(metadata, { expectedRef });
54
+ }
55
+
56
+ /**
57
+ * @param {unknown} metadata
58
+ * @param {{ expectedRef?: string }} [options]
59
+ * @returns {{ version: 1, ref: string, entries: Array<object> }}
60
+ */
61
+ validate(metadata, { expectedRef } = {}) {
62
+ this.#assertMetadataEnvelope(metadata);
63
+ const canonical = this.#canonicalizeStoredMetadata(metadata);
64
+ this.#assertExpectedRef(canonical.ref, expectedRef);
65
+ this.#assertCanonicalStorage(metadata, canonical);
66
+ return canonical;
67
+ }
68
+
69
+ /**
70
+ * @param {Iterable<object>} entries
71
+ * @returns {Array<{ name: string, oid: string, type: 'blob'|'tree', retention: 'pinned'|'evictable' }>}
72
+ */
73
+ normalizeEntries(entries) {
74
+ if (!entries || typeof entries[Symbol.iterator] !== 'function') {
75
+ throw this.#entryError('Root-set entries must be iterable', { entries });
76
+ }
77
+
78
+ const normalized = [...entries].map((entry) => this.#normalizeEntry(entry));
79
+ normalized.sort(RootSetMetadataCodec.#compareNames);
80
+ for (let index = 1; index < normalized.length; index++) {
81
+ if (normalized[index - 1].name === normalized[index].name) {
82
+ throw this.#entryError('Root-set entry names must be unique', {
83
+ name: normalized[index].name,
84
+ });
85
+ }
86
+ }
87
+ return normalized;
88
+ }
89
+
90
+ /**
91
+ * @param {number} index
92
+ * @returns {string}
93
+ */
94
+ static slotFor(index) {
95
+ if (!Number.isSafeInteger(index) || index < 0 || index > 99_999_999) {
96
+ throw new CasError(
97
+ 'Root-set entry count exceeds the supported slot range',
98
+ ErrorCodes.ROOT_SET_ENTRY_INVALID,
99
+ { index },
100
+ );
101
+ }
102
+ return `root-${String(index).padStart(8, '0')}`;
103
+ }
104
+
105
+ /**
106
+ * @param {object} entry
107
+ * @returns {{ name: string, oid: string, type: 'blob'|'tree', retention: 'pinned'|'evictable' }}
108
+ */
109
+ #normalizeEntry(entry) {
110
+ this.#assertEntryObject(entry);
111
+ this.#assertEntryName(entry);
112
+ this.#assertEntryType(entry);
113
+ const retention = entry.retention ?? 'pinned';
114
+ if (!ROOT_SET_RETENTION_POLICIES.includes(retention)) {
115
+ throw this.#entryError('Root-set retention must be pinned or evictable', { entry });
116
+ }
117
+ return {
118
+ name: entry.name,
119
+ oid: this.#normalizeOid(entry),
120
+ type: entry.type,
121
+ retention,
122
+ };
123
+ }
124
+
125
+ #assertMetadataEnvelope(metadata) {
126
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
127
+ throw this.#metadataError('Root-set metadata must be an object', { metadata });
128
+ }
129
+ if (metadata.version !== ROOT_SET_METADATA_VERSION) {
130
+ throw this.#metadataError(`Unsupported root-set metadata version: ${metadata.version}`, {
131
+ metadata,
132
+ });
133
+ }
134
+ }
135
+
136
+ #canonicalizeStoredMetadata(metadata) {
137
+ try {
138
+ return this.create({ ref: metadata.ref, entries: metadata.entries });
139
+ } catch (err) {
140
+ if (err instanceof CasError && err.code === ErrorCodes.ROOT_SET_ENTRY_INVALID) {
141
+ throw err;
142
+ }
143
+ throw this.#metadataError('Root-set metadata fields are invalid', {
144
+ metadata,
145
+ originalError: err,
146
+ });
147
+ }
148
+ }
149
+
150
+ #assertExpectedRef(actualRef, expectedRef) {
151
+ if (expectedRef === undefined || actualRef === RootSetRef.from(expectedRef).toString()) {
152
+ return;
153
+ }
154
+ throw this.#metadataError('Root-set metadata ref does not match the requested ref', {
155
+ expectedRef,
156
+ actualRef,
157
+ });
158
+ }
159
+
160
+ #assertCanonicalStorage(metadata, canonical) {
161
+ if (!RootSetMetadataCodec.#isCanonicalStoredMetadata(metadata, canonical)) {
162
+ throw this.#metadataError('Root-set metadata is not canonical', { metadata });
163
+ }
164
+ }
165
+
166
+ #assertEntryObject(entry) {
167
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
168
+ throw this.#entryError('Root-set entry must be an object', { entry });
169
+ }
170
+ }
171
+
172
+ #assertEntryName(entry) {
173
+ if (
174
+ typeof entry.name !== 'string' ||
175
+ entry.name.length === 0 ||
176
+ RootSetMetadataCodec.#hasControlCharacters(entry.name)
177
+ ) {
178
+ throw this.#entryError('Root-set entry name must be a non-empty string without control characters', {
179
+ entry,
180
+ });
181
+ }
182
+ }
183
+
184
+ #assertEntryType(entry) {
185
+ if (!ROOT_SET_ENTRY_TYPES.includes(entry.type)) {
186
+ throw this.#entryError('Root-set entry type must be blob or tree', { entry });
187
+ }
188
+ }
189
+
190
+ #normalizeOid(entry) {
191
+ try {
192
+ return Oid.from(entry.oid).toString();
193
+ } catch (err) {
194
+ throw this.#entryError('Root-set entry OID is invalid', { entry, originalError: err });
195
+ }
196
+ }
197
+
198
+ static #hasControlCharacters(value) {
199
+ for (const character of value) {
200
+ const codePoint = character.codePointAt(0);
201
+ if (codePoint < 0x20 || codePoint === 0x7f) {
202
+ return true;
203
+ }
204
+ }
205
+ return false;
206
+ }
207
+
208
+ static #compareNames(left, right) {
209
+ if (left.name < right.name) {
210
+ return -1;
211
+ }
212
+ return left.name > right.name ? 1 : 0;
213
+ }
214
+
215
+ /**
216
+ * @param {unknown} stored
217
+ * @param {object} canonical
218
+ * @returns {boolean}
219
+ */
220
+ static #isCanonicalStoredMetadata(stored, canonical) {
221
+ if (Object.keys(stored).sort().join(',') !== 'entries,ref,version') {
222
+ return false;
223
+ }
224
+ if (!Array.isArray(stored.entries) || stored.entries.length !== canonical.entries.length) {
225
+ return false;
226
+ }
227
+ return stored.entries.every((entry, index) => (
228
+ entry &&
229
+ typeof entry === 'object' &&
230
+ Object.keys(entry).sort().join(',') === 'name,oid,retention,slot,type' &&
231
+ SLOT_PATTERN.test(entry.slot) &&
232
+ JSON.stringify(entry) === JSON.stringify(canonical.entries[index])
233
+ ));
234
+ }
235
+
236
+ /**
237
+ * @param {string} message
238
+ * @param {object} meta
239
+ * @returns {CasError}
240
+ */
241
+ #metadataError(message, meta) {
242
+ return new CasError(message, ErrorCodes.ROOT_SET_METADATA_INVALID, meta);
243
+ }
244
+
245
+ /**
246
+ * @param {string} message
247
+ * @param {object} meta
248
+ * @returns {CasError}
249
+ */
250
+ #entryError(message, meta) {
251
+ return new CasError(message, ErrorCodes.ROOT_SET_ENTRY_INVALID, meta);
252
+ }
253
+ }