@git-stunts/git-cas 6.3.0 → 6.4.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.
@@ -0,0 +1,545 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import parseApplicationHandle from '../value-objects/ApplicationHandle.js';
4
+ import CollectionNamespace from '../value-objects/CollectionNamespace.js';
5
+ import PageHandle from '../value-objects/PageHandle.js';
6
+ import WorkspaceRef from '../value-objects/WorkspaceRef.js';
7
+ import RootSet from './RootSet.js';
8
+ import RootSetMetadataCodec from './RootSetMetadataCodec.js';
9
+ import RootSetPersistence from './RootSetPersistence.js';
10
+ import StagingWorkspace from './StagingWorkspace.js';
11
+ import WorkspaceDescriptorCodec, {
12
+ WORKSPACE_DESCRIPTOR_ENTRY,
13
+ } from './WorkspaceDescriptorCodec.js';
14
+
15
+ export const DEFAULT_WORKSPACE_TTL_MS = 2 * 60 * 60 * 1000;
16
+ export const MAX_WORKSPACE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
17
+ export const DEFAULT_WORKSPACE_INSPECTION_LIMIT = 100;
18
+ export const MAX_WORKSPACE_INSPECTION_LIMIT = 1000;
19
+ const NONCE_BYTES = 16;
20
+ const TARGET_ENTRY_PREFIX = 'target:';
21
+ const TARGET_ROOT_TYPES = Object.freeze({
22
+ asset: 'tree',
23
+ bundle: 'tree',
24
+ page: 'blob',
25
+ });
26
+ const DEFAULT_CLOCK = Object.freeze({ now: () => new Date() });
27
+
28
+ /** Creates staging workspaces and provides bounded abandoned-workspace operations. */
29
+ export default class StagingWorkspaceRegistry {
30
+ #assets;
31
+ #bundles;
32
+ #clock;
33
+ #crypto;
34
+ #descriptorCodec;
35
+ #pages;
36
+ #persistence;
37
+ #publications;
38
+ #ref;
39
+ #resolveHandle;
40
+
41
+ constructor({ persistence, ref, assets, pages, bundles, publications, resolveHandle, crypto,
42
+ clock = DEFAULT_CLOCK, descriptorCodec = new WorkspaceDescriptorCodec() }) {
43
+ StagingWorkspaceRegistry.#assertDependencies({
44
+ persistence,
45
+ ref,
46
+ assets,
47
+ pages,
48
+ bundles,
49
+ resolveHandle,
50
+ crypto,
51
+ clock,
52
+ descriptorCodec,
53
+ });
54
+ this.#persistence = persistence;
55
+ this.#ref = ref;
56
+ this.#assets = assets;
57
+ this.#pages = pages;
58
+ this.#bundles = bundles;
59
+ this.#publications = publications;
60
+ this.#resolveHandle = resolveHandle;
61
+ this.#crypto = crypto;
62
+ this.#clock = clock;
63
+ this.#descriptorCodec = descriptorCodec;
64
+ Object.freeze(this);
65
+ }
66
+
67
+ async open({ namespace: value, ttlMs = DEFAULT_WORKSPACE_TTL_MS } = {}) {
68
+ const namespace = CollectionNamespace.from(value).toString();
69
+ StagingWorkspaceRegistry.#assertTtl(ttlMs);
70
+ const createdAt = this.#observedAt();
71
+ const nonce = await this.#crypto.randomBytes(NONCE_BYTES);
72
+ const workspaceRef = WorkspaceRef.create({ namespace, createdAt, nonce });
73
+ return new StagingWorkspace({
74
+ workspaceRef,
75
+ ttlMs,
76
+ rootSet: this.#rootSet(workspaceRef),
77
+ refs: this.#ref,
78
+ assets: this.#assets,
79
+ pages: this.#pages,
80
+ bundles: this.#bundles,
81
+ publications: this.#publications,
82
+ resolveHandle: this.#resolveHandle,
83
+ descriptorCodec: this.#descriptorCodec,
84
+ clock: this.#clock,
85
+ });
86
+ }
87
+
88
+ async inspect({
89
+ namespace: value,
90
+ limit = DEFAULT_WORKSPACE_INSPECTION_LIMIT,
91
+ cursor: cursorValue = null,
92
+ } = {}) {
93
+ const namespace = CollectionNamespace.from(value).toString();
94
+ StagingWorkspaceRegistry.#assertLimit(limit);
95
+ const cursor = StagingWorkspaceRegistry.#cursor(cursorValue, namespace);
96
+ const records = [];
97
+ for await (const record of this.#ref.iterateRefs({
98
+ prefix: WorkspaceRef.prefixForNamespace(namespace),
99
+ after: cursor,
100
+ limit: limit + 1,
101
+ })) {
102
+ records.push(record);
103
+ }
104
+ const truncated = records.length > limit;
105
+ const selected = truncated ? records.slice(0, limit) : records;
106
+ const workspaces = [];
107
+ for (const record of selected) {
108
+ workspaces.push(await this.inspectRecord(record));
109
+ }
110
+ return Object.freeze({
111
+ namespace,
112
+ returned: workspaces.length,
113
+ truncated,
114
+ nextCursor: truncated ? selected.at(-1).ref : null,
115
+ workspaces: Object.freeze(workspaces),
116
+ });
117
+ }
118
+
119
+ async sweep(options = {}) {
120
+ const inspection = await this.inspect(options);
121
+ const totals = { changed: 0, conflicted: 0, missing: 0 };
122
+ const results = [];
123
+ for (const workspace of inspection.workspaces) {
124
+ const outcome = await this.#sweepWorkspace(workspace);
125
+ if (outcome === null) {
126
+ continue;
127
+ }
128
+ totals.changed += outcome.changed ? 1 : 0;
129
+ totals.conflicted += outcome.conflict ? 1 : 0;
130
+ totals.missing += outcome.missing ? 1 : 0;
131
+ results.push(outcome.result);
132
+ }
133
+ return Object.freeze({
134
+ namespace: inspection.namespace,
135
+ inspected: inspection.returned,
136
+ ...totals,
137
+ truncated: inspection.truncated,
138
+ nextCursor: inspection.nextCursor,
139
+ results: Object.freeze(results),
140
+ });
141
+ }
142
+
143
+ async #sweepWorkspace(workspace) {
144
+ const inspectionOutcome = StagingWorkspaceRegistry.#inspectionSweepOutcome(workspace);
145
+ if (inspectionOutcome !== undefined) {
146
+ return inspectionOutcome;
147
+ }
148
+ if (workspace.posture !== 'expired' || workspace.symref !== null) {
149
+ return null;
150
+ }
151
+ try {
152
+ const changed = await this.#ref.deleteRef({
153
+ ref: workspace.ref,
154
+ expectedOldOid: workspace.generation,
155
+ });
156
+ return StagingWorkspaceRegistry.#sweepOutcome(workspace, {
157
+ changed,
158
+ missing: !changed,
159
+ });
160
+ } catch (error) {
161
+ if (![ErrorCodes.GIT_REF_CONFLICT, ErrorCodes.WORKSPACE_CONFLICT].includes(error?.code)) {
162
+ throw error;
163
+ }
164
+ return StagingWorkspaceRegistry.#sweepOutcome(workspace, { conflict: true });
165
+ }
166
+ }
167
+
168
+ async inspectRecord(record) {
169
+ let workspaceRef;
170
+ try {
171
+ workspaceRef = WorkspaceRef.from(record.ref);
172
+ return await this.#readRecord(record, workspaceRef);
173
+ } catch (error) {
174
+ return StagingWorkspaceRegistry.#invalidRecord(record, workspaceRef, error);
175
+ }
176
+ }
177
+
178
+ async #readRecord(record, workspaceRef) {
179
+ StagingWorkspaceRegistry.#assertDirectRef(record);
180
+ const state = await this.#rootSet(workspaceRef).read();
181
+ StagingWorkspaceRegistry.#assertObservedGeneration(record, state);
182
+ const descriptor = await this.#readDescriptor(record, state.entries);
183
+ const targets = state.entries.filter((entry) => entry.name !== WORKSPACE_DESCRIPTOR_ENTRY);
184
+ StagingWorkspaceRegistry.#assertTargetCount(record, descriptor, targets);
185
+ const usage = await this.#usage(record, targets);
186
+ const now = Date.parse(this.#observedAt());
187
+ return Object.freeze({
188
+ id: workspaceRef.id,
189
+ namespace: workspaceRef.namespace,
190
+ ref: record.ref,
191
+ generation: record.oid,
192
+ symref: record.symref,
193
+ rootCount: targets.length,
194
+ logicalBytes: usage.logicalBytes,
195
+ rootObjectBytes: usage.rootObjectBytes,
196
+ createdAt: descriptor.createdAt,
197
+ ageMs: Math.max(0, now - Date.parse(descriptor.createdAt)),
198
+ expiresAt: descriptor.expiresAt,
199
+ posture: now >= Date.parse(descriptor.expiresAt) ? 'expired' : 'active',
200
+ issue: null,
201
+ });
202
+ }
203
+
204
+ async #readDescriptor(record, entries) {
205
+ const descriptorEntry = entries.find((entry) => entry.name === WORKSPACE_DESCRIPTOR_ENTRY);
206
+ if (!descriptorEntry || descriptorEntry.type !== 'blob') {
207
+ throw createCasError(
208
+ 'Workspace generation is missing its lease descriptor',
209
+ ErrorCodes.WORKSPACE_STATE_INVALID,
210
+ { ref: record.ref },
211
+ );
212
+ }
213
+ const bytes = await this.#pages.get({ handle: new PageHandle({ oid: descriptorEntry.oid }) });
214
+ return this.#descriptorCodec.decode(bytes, { expectedRef: record.ref });
215
+ }
216
+
217
+ async #usage(record, targets) {
218
+ let logicalBytes = 0;
219
+ const rootOids = new Set();
220
+ for (const target of targets) {
221
+ const targetLogicalBytes = await this.#targetLogicalBytes(record, target);
222
+ logicalBytes = StagingWorkspaceRegistry.#addBytes({
223
+ total: logicalBytes,
224
+ value: targetLogicalBytes,
225
+ label: 'logical bytes',
226
+ ref: record.ref,
227
+ });
228
+ rootOids.add(target.oid);
229
+ }
230
+ let rootObjectBytes = 0;
231
+ for (const oid of rootOids) {
232
+ rootObjectBytes = StagingWorkspaceRegistry.#addBytes({
233
+ total: rootObjectBytes,
234
+ value: await this.#persistence.readObjectSize(oid),
235
+ label: 'root-object bytes',
236
+ ref: record.ref,
237
+ });
238
+ }
239
+ return Object.freeze({ logicalBytes, rootObjectBytes });
240
+ }
241
+
242
+ async #targetLogicalBytes(record, target) {
243
+ const handle = StagingWorkspaceRegistry.#targetHandle(record, target);
244
+ const resolved = await this.#resolveHandle(handle);
245
+ const resolvedHandle = StagingWorkspaceRegistry.#resolvedHandle({
246
+ record,
247
+ target,
248
+ handle,
249
+ resolved,
250
+ });
251
+ StagingWorkspaceRegistry.#assertResolvedTarget({
252
+ record,
253
+ target,
254
+ handle,
255
+ resolved,
256
+ resolvedHandle,
257
+ });
258
+ const logicalBytes = resolved.logicalBytes ?? resolved.size;
259
+ StagingWorkspaceRegistry.#assertByteCount(
260
+ logicalBytes,
261
+ 'Workspace target logical byte count is invalid',
262
+ { ref: record.ref, handle: handle.toString(), logicalBytes },
263
+ );
264
+ return logicalBytes;
265
+ }
266
+
267
+ #rootSet(workspaceRef) {
268
+ const ref = WorkspaceRef.from(workspaceRef).toString();
269
+ const metadataCodec = new RootSetMetadataCodec({ refType: WorkspaceRef });
270
+ const persistence = new RootSetPersistence({
271
+ rootSetRef: ref,
272
+ persistence: this.#persistence,
273
+ ref: this.#ref,
274
+ refType: WorkspaceRef,
275
+ metadataCodec,
276
+ });
277
+ return new RootSet({
278
+ ref,
279
+ persistence,
280
+ refType: WorkspaceRef,
281
+ metadataCodec,
282
+ });
283
+ }
284
+
285
+ #observedAt() {
286
+ const now = this.#clock.now();
287
+ if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
288
+ throw createCasError(
289
+ 'Workspace registry clock returned an invalid Date',
290
+ ErrorCodes.INVALID_OPTIONS,
291
+ );
292
+ }
293
+ return now.toISOString();
294
+ }
295
+
296
+ static #assertTtl(ttlMs) {
297
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0 || ttlMs > MAX_WORKSPACE_TTL_MS) {
298
+ throw createCasError(
299
+ 'Workspace ttlMs must be a positive safe integer within the supported maximum',
300
+ ErrorCodes.WORKSPACE_TTL_INVALID,
301
+ { ttlMs, maxTtlMs: MAX_WORKSPACE_TTL_MS },
302
+ );
303
+ }
304
+ }
305
+
306
+ static #assertLimit(limit) {
307
+ if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_WORKSPACE_INSPECTION_LIMIT) {
308
+ throw createCasError(
309
+ 'Workspace inspection limit is outside supported bounds',
310
+ ErrorCodes.INVALID_OPTIONS,
311
+ { limit, maxLimit: MAX_WORKSPACE_INSPECTION_LIMIT },
312
+ );
313
+ }
314
+ }
315
+
316
+ static #cursor(value, namespace) {
317
+ if (value === null) {
318
+ return null;
319
+ }
320
+ let cursor;
321
+ try {
322
+ cursor = WorkspaceRef.from(value);
323
+ } catch (error) {
324
+ throw createCasError(
325
+ 'Workspace cursor must be a cursor returned for the requested namespace',
326
+ ErrorCodes.INVALID_OPTIONS,
327
+ { cursor: value, namespace, originalError: error },
328
+ );
329
+ }
330
+ if (cursor.namespace !== namespace) {
331
+ throw createCasError(
332
+ 'Workspace cursor belongs to a different namespace',
333
+ ErrorCodes.INVALID_OPTIONS,
334
+ { cursor: cursor.toString(), namespace, cursorNamespace: cursor.namespace },
335
+ );
336
+ }
337
+ return cursor.toString();
338
+ }
339
+
340
+ static #inspectionSweepOutcome(workspace) {
341
+ if (workspace.issue?.code === ErrorCodes.WORKSPACE_CONFLICT) {
342
+ return StagingWorkspaceRegistry.#sweepOutcome(workspace, { conflict: true });
343
+ }
344
+ if (workspace.issue?.code === ErrorCodes.GIT_REF_NOT_FOUND) {
345
+ return StagingWorkspaceRegistry.#sweepOutcome(workspace, { missing: true });
346
+ }
347
+ return undefined;
348
+ }
349
+
350
+ static #sweepOutcome(workspace, { changed = false, conflict = false, missing = false }) {
351
+ return Object.freeze({
352
+ changed,
353
+ conflict,
354
+ missing,
355
+ result: Object.freeze({
356
+ id: workspace.id,
357
+ ref: workspace.ref,
358
+ generation: workspace.generation,
359
+ changed,
360
+ conflict,
361
+ }),
362
+ });
363
+ }
364
+
365
+ static #assertDependencies({ persistence, ref, assets, pages, bundles, resolveHandle, crypto,
366
+ clock, descriptorCodec }) {
367
+ const dependencies = [
368
+ ['persistence', StagingWorkspaceRegistry.#hasMethods(persistence, [
369
+ 'writeBlob', 'writeTree', 'readBlob', 'readTree', 'readObjectType', 'readObjectSize',
370
+ ])],
371
+ ['ref', StagingWorkspaceRegistry.#hasMethods(ref, [
372
+ 'resolveRef', 'resolveTree', 'resolveParents', 'createCommit', 'updateRef', 'deleteRef',
373
+ 'iterateRefs',
374
+ ])],
375
+ ['assets', StagingWorkspaceRegistry.#hasMethods(assets, ['put', 'adopt'])],
376
+ ['pages', StagingWorkspaceRegistry.#hasMethods(pages, ['put', 'get'])],
377
+ ['bundles', StagingWorkspaceRegistry.#hasMethods(bundles, ['put', 'putOrdered'])],
378
+ ['resolveHandle', typeof resolveHandle === 'function'],
379
+ ['crypto', StagingWorkspaceRegistry.#hasMethods(crypto, ['randomBytes'])],
380
+ ['clock', StagingWorkspaceRegistry.#hasMethods(clock, ['now'])],
381
+ ['descriptorCodec', StagingWorkspaceRegistry.#hasMethods(descriptorCodec, ['encode', 'decode'])],
382
+ ];
383
+ const missing = dependencies.filter(([, valid]) => !valid).map(([name]) => name);
384
+ if (missing.length > 0) {
385
+ throw createCasError(
386
+ 'StagingWorkspaceRegistry requires complete dependencies',
387
+ ErrorCodes.INVALID_OPTIONS,
388
+ { missing },
389
+ );
390
+ }
391
+ }
392
+
393
+ static #hasMethods(value, methods) {
394
+ return value && methods.every((method) => typeof value[method] === 'function');
395
+ }
396
+
397
+ static #assertDirectRef(record) {
398
+ if (record.symref !== null) {
399
+ throw createCasError(
400
+ 'Workspace ref must be direct',
401
+ ErrorCodes.WORKSPACE_STATE_INVALID,
402
+ { ref: record.ref, symref: record.symref },
403
+ );
404
+ }
405
+ }
406
+
407
+ static #assertObservedGeneration(record, state) {
408
+ if (state.headOid !== record.oid) {
409
+ throw createCasError(
410
+ 'Workspace ref changed during inspection',
411
+ ErrorCodes.WORKSPACE_CONFLICT,
412
+ { ref: record.ref, expectedHeadOid: record.oid, actualHeadOid: state.headOid },
413
+ );
414
+ }
415
+ }
416
+
417
+ static #assertTargetCount(record, descriptor, targets) {
418
+ if (targets.length !== descriptor.targetCount) {
419
+ throw createCasError(
420
+ 'Workspace descriptor target count does not match its generation',
421
+ ErrorCodes.WORKSPACE_STATE_INVALID,
422
+ { ref: record.ref, expected: descriptor.targetCount, actual: targets.length },
423
+ );
424
+ }
425
+ }
426
+
427
+ static #targetHandle(record, target) {
428
+ if (typeof target.name !== 'string' || !target.name.startsWith(TARGET_ENTRY_PREFIX)) {
429
+ throw StagingWorkspaceRegistry.#invalidTarget({
430
+ record,
431
+ target,
432
+ message: 'Workspace target entry is missing its canonical name prefix',
433
+ });
434
+ }
435
+ let handle;
436
+ try {
437
+ handle = parseApplicationHandle(target.name.slice(TARGET_ENTRY_PREFIX.length));
438
+ } catch (error) {
439
+ throw StagingWorkspaceRegistry.#invalidTarget({
440
+ record,
441
+ target,
442
+ message: 'Workspace target entry contains an invalid application handle',
443
+ meta: { originalError: error },
444
+ });
445
+ }
446
+ if (`${TARGET_ENTRY_PREFIX}${handle.toString()}` !== target.name) {
447
+ throw StagingWorkspaceRegistry.#invalidTarget({
448
+ record,
449
+ target,
450
+ message: 'Workspace target entry name is not canonical',
451
+ meta: { handle: handle.toString() },
452
+ });
453
+ }
454
+ return handle;
455
+ }
456
+
457
+ static #resolvedHandle({ record, target, handle, resolved }) {
458
+ try {
459
+ return parseApplicationHandle(resolved?.handle ?? handle);
460
+ } catch (error) {
461
+ throw StagingWorkspaceRegistry.#invalidTarget({
462
+ record,
463
+ target,
464
+ message: 'Workspace handle resolver returned an invalid handle',
465
+ meta: { originalError: error },
466
+ });
467
+ }
468
+ }
469
+
470
+ static #assertResolvedTarget({ record, target, handle, resolved, resolvedHandle }) {
471
+ const expectedType = TARGET_ROOT_TYPES[handle.kind];
472
+ const mismatch = [
473
+ !resolved,
474
+ resolvedHandle.toString() !== handle.toString(),
475
+ resolved?.oid !== handle.oid,
476
+ target.oid !== handle.oid,
477
+ resolved?.type !== expectedType,
478
+ target.type !== expectedType,
479
+ ].some(Boolean);
480
+ if (mismatch) {
481
+ throw StagingWorkspaceRegistry.#invalidTarget({
482
+ record,
483
+ target,
484
+ message: 'Workspace target does not match its typed application handle',
485
+ meta: {
486
+ handle: handle.toString(),
487
+ expectedType,
488
+ resolvedHandle: resolvedHandle.toString(),
489
+ resolvedOid: resolved?.oid,
490
+ resolvedType: resolved?.type,
491
+ },
492
+ });
493
+ }
494
+ }
495
+
496
+ static #addBytes({ total, value, label, ref }) {
497
+ StagingWorkspaceRegistry.#assertByteCount(
498
+ value,
499
+ `Workspace ${label} value is invalid`,
500
+ { ref, value },
501
+ );
502
+ const result = total + value;
503
+ StagingWorkspaceRegistry.#assertByteCount(
504
+ result,
505
+ `Workspace ${label} total exceeds supported bounds`,
506
+ { ref, total, value },
507
+ );
508
+ return result;
509
+ }
510
+
511
+ static #assertByteCount(value, message, meta) {
512
+ if (!Number.isSafeInteger(value) || value < 0) {
513
+ throw createCasError(message, ErrorCodes.WORKSPACE_STATE_INVALID, meta);
514
+ }
515
+ }
516
+
517
+ static #invalidTarget({ record, target, message, meta = {} }) {
518
+ return createCasError(message, ErrorCodes.WORKSPACE_STATE_INVALID, {
519
+ ref: record.ref,
520
+ target,
521
+ ...meta,
522
+ });
523
+ }
524
+
525
+ static #invalidRecord(record, workspaceRef, error) {
526
+ return Object.freeze({
527
+ id: workspaceRef?.id ?? null,
528
+ namespace: workspaceRef?.namespace ?? null,
529
+ ref: record.ref,
530
+ generation: record.oid,
531
+ symref: record.symref,
532
+ rootCount: null,
533
+ logicalBytes: null,
534
+ rootObjectBytes: null,
535
+ createdAt: workspaceRef?.createdAt ?? null,
536
+ ageMs: null,
537
+ expiresAt: null,
538
+ posture: 'invalid',
539
+ issue: Object.freeze({
540
+ code: error?.code ?? ErrorCodes.WORKSPACE_STATE_INVALID,
541
+ message: error instanceof Error ? error.message : String(error),
542
+ }),
543
+ });
544
+ }
545
+ }
@@ -0,0 +1,144 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import { ErrorCodes } from '../errors/index.js';
3
+ import { utf8Decode, utf8Encode } from '../encoding/utf8.js';
4
+ import WorkspaceRef from '../value-objects/WorkspaceRef.js';
5
+
6
+ export const WORKSPACE_DESCRIPTOR_ENTRY = '@workspace/lease';
7
+ export const WORKSPACE_DESCRIPTOR_VERSION = 1;
8
+ export const MAX_WORKSPACE_TARGETS = 100_000;
9
+
10
+ /** Canonical codec for the lease page retained by every installed workspace. */
11
+ export default class WorkspaceDescriptorCodec {
12
+ encode(value) {
13
+ return utf8Encode(JSON.stringify(this.create(value), null, 2));
14
+ }
15
+
16
+ decode(bytes, { expectedRef } = {}) {
17
+ let value;
18
+ try {
19
+ value = JSON.parse(utf8Decode(bytes));
20
+ } catch (error) {
21
+ throw WorkspaceDescriptorCodec.#invalid('Workspace descriptor is not valid JSON', {
22
+ originalError: error,
23
+ });
24
+ }
25
+ const canonical = this.create(value);
26
+ if (expectedRef !== undefined && canonical.ref !== WorkspaceRef.from(expectedRef).toString()) {
27
+ throw WorkspaceDescriptorCodec.#invalid(
28
+ 'Workspace descriptor does not match the requested ref',
29
+ { expectedRef, actualRef: canonical.ref },
30
+ );
31
+ }
32
+ if (JSON.stringify(value) !== JSON.stringify(canonical)) {
33
+ throw WorkspaceDescriptorCodec.#invalid('Workspace descriptor is not canonical', { value });
34
+ }
35
+ return canonical;
36
+ }
37
+
38
+ create(value) {
39
+ WorkspaceDescriptorCodec.#assertObject(value);
40
+ const {
41
+ version = WORKSPACE_DESCRIPTOR_VERSION,
42
+ ref: refValue,
43
+ workspaceId,
44
+ namespace,
45
+ createdAt,
46
+ expiresAt,
47
+ targetCount,
48
+ } = value;
49
+ const ref = WorkspaceDescriptorCodec.#workspaceRef(refValue);
50
+ WorkspaceDescriptorCodec.#assertVersion(version);
51
+ WorkspaceDescriptorCodec.#assertIdentity({ ref, workspaceId, namespace });
52
+ WorkspaceDescriptorCodec.#assertTimeRange({ ref, createdAt, expiresAt });
53
+ WorkspaceDescriptorCodec.#assertTargetCount(targetCount);
54
+ return {
55
+ version: WORKSPACE_DESCRIPTOR_VERSION,
56
+ ref: ref.toString(),
57
+ workspaceId: ref.id,
58
+ namespace: ref.namespace,
59
+ createdAt,
60
+ expiresAt,
61
+ targetCount,
62
+ };
63
+ }
64
+
65
+ static #assertObject(value) {
66
+ const prototype = value && typeof value === 'object' ? Object.getPrototypeOf(value) : null;
67
+ if (!value || Array.isArray(value)
68
+ || (prototype !== Object.prototype && prototype !== null)) {
69
+ throw WorkspaceDescriptorCodec.#invalid('Workspace descriptor must be a plain object', {
70
+ value,
71
+ });
72
+ }
73
+ }
74
+
75
+ static #workspaceRef(value) {
76
+ try {
77
+ return WorkspaceRef.from(value);
78
+ } catch (error) {
79
+ throw WorkspaceDescriptorCodec.#invalid('Workspace descriptor ref is invalid', {
80
+ ref: value,
81
+ originalError: error,
82
+ });
83
+ }
84
+ }
85
+
86
+ static #assertVersion(version) {
87
+ if (version !== WORKSPACE_DESCRIPTOR_VERSION) {
88
+ throw WorkspaceDescriptorCodec.#invalid(
89
+ `Unsupported workspace descriptor version: ${version}`,
90
+ { version },
91
+ );
92
+ }
93
+ }
94
+
95
+ static #assertIdentity({ ref, workspaceId, namespace }) {
96
+ if (workspaceId !== undefined && workspaceId !== ref.id) {
97
+ throw WorkspaceDescriptorCodec.#invalid('Workspace descriptor ID does not match its ref', {
98
+ workspaceId,
99
+ ref: ref.toString(),
100
+ });
101
+ }
102
+ if (namespace !== undefined && namespace !== ref.namespace) {
103
+ throw WorkspaceDescriptorCodec.#invalid(
104
+ 'Workspace descriptor namespace does not match its ref',
105
+ { namespace, ref: ref.toString() },
106
+ );
107
+ }
108
+ }
109
+
110
+ static #assertTimeRange({ ref, createdAt, expiresAt }) {
111
+ WorkspaceDescriptorCodec.#assertTimestamp(createdAt, 'creation');
112
+ WorkspaceDescriptorCodec.#assertTimestamp(expiresAt, 'expiry');
113
+ if (createdAt !== ref.createdAt || Date.parse(expiresAt) <= Date.parse(createdAt)) {
114
+ throw WorkspaceDescriptorCodec.#invalid('Workspace descriptor time range is invalid', {
115
+ createdAt,
116
+ expiresAt,
117
+ ref: ref.toString(),
118
+ });
119
+ }
120
+ }
121
+
122
+ static #assertTargetCount(targetCount) {
123
+ if (!Number.isSafeInteger(targetCount) || targetCount < 0 || targetCount > MAX_WORKSPACE_TARGETS) {
124
+ throw WorkspaceDescriptorCodec.#invalid('Workspace target count is outside supported bounds', {
125
+ targetCount,
126
+ maxTargetCount: MAX_WORKSPACE_TARGETS,
127
+ });
128
+ }
129
+ }
130
+
131
+ static #assertTimestamp(value, label) {
132
+ const date = typeof value === 'string' ? new Date(value) : null;
133
+ if (!date || Number.isNaN(date.getTime()) || date.toISOString() !== value) {
134
+ throw WorkspaceDescriptorCodec.#invalid(
135
+ `Workspace ${label} time must be a canonical UTC timestamp`,
136
+ { value },
137
+ );
138
+ }
139
+ }
140
+
141
+ static #invalid(message, meta) {
142
+ return createCasError(message, ErrorCodes.WORKSPACE_DESCRIPTOR_INVALID, meta);
143
+ }
144
+ }