@edjbarron/ux-guard 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1263 @@
1
+ import { createHash } from 'node:crypto';
2
+ import {
3
+ copyFileSync,
4
+ existsSync,
5
+ lstatSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ realpathSync,
9
+ writeFileSync,
10
+ } from 'node:fs';
11
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
12
+ import { canonicalize } from './run-contract.mjs';
13
+
14
+ export const VISUAL_PROFILE_SET_KIND = 'ux-guard-visual-profile-set';
15
+ export const VISUAL_PROFILE_SET_VERSION = 1;
16
+ export const VISUAL_CHECKPOINT_POLICY_KIND = 'ux-guard-visual-checkpoint-policy';
17
+ export const VISUAL_CHECKPOINT_POLICY_VERSION = 1;
18
+ export const VISUAL_MANIFEST_KIND = 'ux-guard-visual-manifest';
19
+ export const VISUAL_MANIFEST_VERSION = 1;
20
+ export const VISUAL_COMPARISON_KIND = 'ux-guard-visual-comparison';
21
+ export const VISUAL_COMPARISON_VERSION = 1;
22
+
23
+ const ID = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
24
+ const USE_CASE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
25
+ const HASH = /^sha256:[a-f0-9]{64}$/;
26
+ const RAW_HASH = /^[a-f0-9]{64}$/;
27
+
28
+ export class VisualContractError extends Error {
29
+ constructor(message) {
30
+ super(message);
31
+ this.name = 'VisualContractError';
32
+ }
33
+ }
34
+
35
+ export const VISUAL_PROFILE_SET_SCHEMA = Object.freeze({
36
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
37
+ $id: 'urn:ux-guard:visual-profile-set:v1',
38
+ type: 'object',
39
+ additionalProperties: false,
40
+ required: ['kind', 'version', 'profiles', 'canonicalHash'],
41
+ });
42
+
43
+ export const VISUAL_MANIFEST_SCHEMA = Object.freeze({
44
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
45
+ $id: 'urn:ux-guard:visual-manifest:v1',
46
+ type: 'object',
47
+ additionalProperties: false,
48
+ required: [
49
+ 'kind',
50
+ 'version',
51
+ 'approval',
52
+ 'profiles',
53
+ 'policy',
54
+ 'capture',
55
+ 'images',
56
+ 'canonicalHash',
57
+ ],
58
+ });
59
+
60
+ export function canonicalHash(value) {
61
+ const copy = structuredClone(value);
62
+ delete copy.canonicalHash;
63
+ return `sha256:${createHash('sha256')
64
+ .update(JSON.stringify(canonicalize(copy)))
65
+ .digest('hex')}`;
66
+ }
67
+
68
+ export function parseVisualProfileSet(text) {
69
+ return validateVisualProfileSet(parseJson(text, 'visual profile set'));
70
+ }
71
+
72
+ export function validateVisualProfileSet(value) {
73
+ assertMap(value, 'visual profile set');
74
+ assertExactKeys(
75
+ value,
76
+ ['kind', 'version', 'profiles', 'canonicalHash'],
77
+ 'visual profile set',
78
+ );
79
+ if (
80
+ value.kind !== VISUAL_PROFILE_SET_KIND ||
81
+ value.version !== VISUAL_PROFILE_SET_VERSION
82
+ ) {
83
+ throw new VisualContractError('visual profile set generation is unsupported');
84
+ }
85
+ if (!Array.isArray(value.profiles) || value.profiles.length === 0) {
86
+ throw new VisualContractError('visual profile set profiles must be non-empty');
87
+ }
88
+ const ids = new Set();
89
+ for (const [index, profile] of value.profiles.entries()) {
90
+ validateVisualProfile(profile, `visual profile set.profiles[${index}]`);
91
+ if (ids.has(profile.id)) {
92
+ throw new VisualContractError(`visual profile set repeats ${profile.id}`);
93
+ }
94
+ ids.add(profile.id);
95
+ }
96
+ if (
97
+ !value.profiles.some((profile) => profile.colorScheme === 'light') ||
98
+ !value.profiles.some((profile) => profile.colorScheme === 'dark')
99
+ ) {
100
+ throw new VisualContractError('visual profile set must include light and dark profiles');
101
+ }
102
+ assertCanonicalHash(value, 'visual profile set');
103
+ return value;
104
+ }
105
+
106
+ export function validateVisualProfile(profile, path = 'visual profile') {
107
+ assertMap(profile, path);
108
+ assertExactKeys(
109
+ profile,
110
+ [
111
+ 'id',
112
+ 'version',
113
+ 'browser',
114
+ 'runtime',
115
+ 'viewport',
116
+ 'fonts',
117
+ 'locale',
118
+ 'timezone',
119
+ 'colorScheme',
120
+ 'clock',
121
+ 'reducedMotion',
122
+ 'rendering',
123
+ 'network',
124
+ 'screenshot',
125
+ 'adapters',
126
+ 'canonicalHash',
127
+ ],
128
+ path,
129
+ );
130
+ assertId(profile.id, `${path}.id`);
131
+ if (profile.version !== 1) throw new VisualContractError(`${path}.version must be 1`);
132
+ assertExactMap(
133
+ profile.browser,
134
+ ['engine', 'version', 'revision', 'channel'],
135
+ `${path}.browser`,
136
+ );
137
+ if (
138
+ profile.browser.engine !== 'chromium' ||
139
+ !/^\d+\.\d+\.\d+\.\d+$/.test(profile.browser.version) ||
140
+ !/^[1-9]\d*$/.test(profile.browser.revision) ||
141
+ profile.browser.channel !== 'chrome-for-testing'
142
+ ) {
143
+ throw new VisualContractError(`${path}.browser is invalid`);
144
+ }
145
+ assertExactMap(
146
+ profile.runtime,
147
+ ['os', 'distribution', 'release', 'architecture', 'container'],
148
+ `${path}.runtime`,
149
+ );
150
+ assertExactMap(
151
+ profile.runtime.container,
152
+ ['image', 'digest', 'indexDigest'],
153
+ `${path}.runtime.container`,
154
+ );
155
+ for (const field of ['os', 'distribution', 'release', 'architecture']) {
156
+ assertText(profile.runtime[field], `${path}.runtime.${field}`);
157
+ }
158
+ assertText(profile.runtime.container.image, `${path}.runtime.container.image`);
159
+ assertHash(profile.runtime.container.digest, `${path}.runtime.container.digest`);
160
+ assertHash(profile.runtime.container.indexDigest, `${path}.runtime.container.indexDigest`);
161
+ assertExactMap(
162
+ profile.viewport,
163
+ ['width', 'height', 'deviceScaleFactor'],
164
+ `${path}.viewport`,
165
+ );
166
+ for (const field of ['width', 'height', 'deviceScaleFactor']) {
167
+ assertPositiveInteger(profile.viewport[field], `${path}.viewport.${field}`);
168
+ }
169
+ if (!Array.isArray(profile.fonts) || profile.fonts.length === 0) {
170
+ throw new VisualContractError(`${path}.fonts must be non-empty`);
171
+ }
172
+ for (const [index, font] of profile.fonts.entries()) {
173
+ const fontPath = `${path}.fonts[${index}]`;
174
+ assertExactMap(font, ['family', 'style', 'weight', 'path', 'sha256'], fontPath);
175
+ assertText(font.family, `${fontPath}.family`);
176
+ if (!['normal', 'italic'].includes(font.style)) {
177
+ throw new VisualContractError(`${fontPath}.style is invalid`);
178
+ }
179
+ assertPositiveInteger(font.weight, `${fontPath}.weight`);
180
+ assertAbsoluteNormalizedPath(font.path, `${fontPath}.path`);
181
+ assertHash(font.sha256, `${fontPath}.sha256`);
182
+ }
183
+ assertText(profile.locale, `${path}.locale`);
184
+ assertText(profile.timezone, `${path}.timezone`);
185
+ if (!['light', 'dark'].includes(profile.colorScheme)) {
186
+ throw new VisualContractError(`${path}.colorScheme is invalid`);
187
+ }
188
+ if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.000Z$/.test(profile.clock)) {
189
+ throw new VisualContractError(`${path}.clock must be a fixed UTC timestamp`);
190
+ }
191
+ if (profile.reducedMotion !== 'reduce') {
192
+ throw new VisualContractError(`${path}.reducedMotion must be reduce`);
193
+ }
194
+ assertExactMap(
195
+ profile.rendering,
196
+ ['animations', 'transitions', 'carets'],
197
+ `${path}.rendering`,
198
+ );
199
+ if (
200
+ profile.rendering.animations !== 'disabled' ||
201
+ profile.rendering.transitions !== 'disabled' ||
202
+ profile.rendering.carets !== 'hidden'
203
+ ) {
204
+ throw new VisualContractError(`${path}.rendering is not deterministic`);
205
+ }
206
+ assertExactMap(profile.network, ['mode'], `${path}.network`);
207
+ if (profile.network.mode !== 'mocked-only') {
208
+ throw new VisualContractError(`${path}.network.mode must be mocked-only`);
209
+ }
210
+ assertExactMap(
211
+ profile.screenshot,
212
+ ['fullPage', 'animations', 'caret', 'scale', 'omitBackground', 'maskColor'],
213
+ `${path}.screenshot`,
214
+ );
215
+ if (
216
+ profile.screenshot.fullPage !== false ||
217
+ profile.screenshot.animations !== 'disabled' ||
218
+ profile.screenshot.caret !== 'hide' ||
219
+ profile.screenshot.scale !== 'css' ||
220
+ profile.screenshot.omitBackground !== false ||
221
+ !/^#[a-f0-9]{6}$/i.test(profile.screenshot.maskColor)
222
+ ) {
223
+ throw new VisualContractError(`${path}.screenshot is invalid`);
224
+ }
225
+ assertExactMap(
226
+ profile.adapters,
227
+ ['uxGuard', 'visual', 'playwright', 'schema'],
228
+ `${path}.adapters`,
229
+ );
230
+ for (const [field, value] of Object.entries(profile.adapters)) {
231
+ if (typeof value !== 'string' || !value) {
232
+ throw new VisualContractError(`${path}.adapters.${field} is invalid`);
233
+ }
234
+ }
235
+ assertCanonicalHash(profile, path);
236
+ return profile;
237
+ }
238
+
239
+ export function parseVisualCheckpointPolicy(text) {
240
+ return validateVisualCheckpointPolicy(parseJson(text, 'visual checkpoint policy'));
241
+ }
242
+
243
+ export function validateVisualCheckpointPolicy(value) {
244
+ assertMap(value, 'visual checkpoint policy');
245
+ assertExactKeys(
246
+ value,
247
+ ['kind', 'version', 'checkpoints', 'canonicalHash'],
248
+ 'visual checkpoint policy',
249
+ );
250
+ if (
251
+ value.kind !== VISUAL_CHECKPOINT_POLICY_KIND ||
252
+ value.version !== VISUAL_CHECKPOINT_POLICY_VERSION
253
+ ) {
254
+ throw new VisualContractError('visual checkpoint policy generation is unsupported');
255
+ }
256
+ if (!Array.isArray(value.checkpoints) || value.checkpoints.length === 0) {
257
+ throw new VisualContractError('visual checkpoint policy must be non-empty');
258
+ }
259
+ const keys = new Set();
260
+ for (const [index, checkpoint] of value.checkpoints.entries()) {
261
+ const path = `visual checkpoint policy.checkpoints[${index}]`;
262
+ assertExactMap(
263
+ checkpoint,
264
+ [
265
+ 'useCaseId',
266
+ 'journeyId',
267
+ 'checkpointId',
268
+ 'tier',
269
+ 'purpose',
270
+ 'profiles',
271
+ 'masks',
272
+ 'tolerance',
273
+ ],
274
+ path,
275
+ );
276
+ assertId(checkpoint.useCaseId, `${path}.useCaseId`, USE_CASE_ID);
277
+ assertId(checkpoint.journeyId, `${path}.journeyId`);
278
+ assertId(checkpoint.checkpointId, `${path}.checkpointId`);
279
+ if (!['primary', 'secondary', 'representative'].includes(checkpoint.tier)) {
280
+ throw new VisualContractError(`${path}.tier is invalid`);
281
+ }
282
+ if (!['success', 'detail', 'form'].includes(checkpoint.purpose)) {
283
+ throw new VisualContractError(`${path}.purpose is invalid`);
284
+ }
285
+ if (
286
+ !Array.isArray(checkpoint.profiles) ||
287
+ checkpoint.profiles.length === 0 ||
288
+ checkpoint.profiles.some((id) => typeof id !== 'string' || !ID.test(id)) ||
289
+ new Set(checkpoint.profiles).size !== checkpoint.profiles.length
290
+ ) {
291
+ throw new VisualContractError(`${path}.profiles is invalid`);
292
+ }
293
+ if (
294
+ !Array.isArray(checkpoint.masks) ||
295
+ checkpoint.masks.some((mask) => {
296
+ try {
297
+ assertExactMap(mask, ['id', 'selector'], `${path}.masks`);
298
+ assertId(mask.id, `${path}.masks.id`);
299
+ assertText(mask.selector, `${path}.masks.selector`);
300
+ return false;
301
+ } catch {
302
+ return true;
303
+ }
304
+ })
305
+ ) {
306
+ throw new VisualContractError(`${path}.masks is invalid`);
307
+ }
308
+ assertExactMap(checkpoint.tolerance, ['mode'], `${path}.tolerance`);
309
+ if (checkpoint.tolerance.mode !== 'exact') {
310
+ throw new VisualContractError(
311
+ `${path}.tolerance must be explicitly exact; no global threshold exists`,
312
+ );
313
+ }
314
+ const key = checkpointKey(checkpoint);
315
+ if (keys.has(key)) throw new VisualContractError(`${path} is duplicated`);
316
+ keys.add(key);
317
+ }
318
+ assertCanonicalHash(value, 'visual checkpoint policy');
319
+ return value;
320
+ }
321
+
322
+ export function createVisualManifest({
323
+ profileSet,
324
+ checkpointPolicy,
325
+ profilePath,
326
+ policyPath,
327
+ images,
328
+ repetitions = 3,
329
+ approval = { status: 'unapproved' },
330
+ } = {}) {
331
+ validateVisualProfileSet(profileSet);
332
+ validateVisualCheckpointPolicy(checkpointPolicy);
333
+ assertSafePath(profilePath, 'visual profile path');
334
+ assertSafePath(policyPath, 'visual checkpoint policy path');
335
+ const manifest = {
336
+ kind: VISUAL_MANIFEST_KIND,
337
+ version: VISUAL_MANIFEST_VERSION,
338
+ approval: structuredClone(approval),
339
+ profiles: { path: profilePath, canonicalHash: profileSet.canonicalHash },
340
+ policy: { path: policyPath, canonicalHash: checkpointPolicy.canonicalHash },
341
+ capture: { repetitions, deterministic: true },
342
+ images: structuredClone(images).sort((left, right) => left.id.localeCompare(right.id)),
343
+ canonicalHash: '',
344
+ };
345
+ manifest.canonicalHash = canonicalHash(manifest);
346
+ return validateVisualManifest(manifest, { profileSet, checkpointPolicy });
347
+ }
348
+
349
+ export function parseVisualManifest(text, options = {}) {
350
+ return validateVisualManifest(parseJson(text, 'visual manifest'), options);
351
+ }
352
+
353
+ export function validateVisualManifest(
354
+ manifest,
355
+ {
356
+ profileSet = null,
357
+ checkpointPolicy = null,
358
+ bundleRoot = null,
359
+ readImage = null,
360
+ requireFiles = false,
361
+ } = {},
362
+ ) {
363
+ assertMap(manifest, 'visual manifest');
364
+ assertExactKeys(
365
+ manifest,
366
+ [
367
+ 'kind',
368
+ 'version',
369
+ 'approval',
370
+ 'profiles',
371
+ 'policy',
372
+ 'capture',
373
+ 'images',
374
+ 'canonicalHash',
375
+ ],
376
+ 'visual manifest',
377
+ );
378
+ if (
379
+ manifest.kind !== VISUAL_MANIFEST_KIND ||
380
+ manifest.version !== VISUAL_MANIFEST_VERSION
381
+ ) {
382
+ throw new VisualContractError('visual manifest generation is unsupported');
383
+ }
384
+ validateApproval(manifest.approval);
385
+ for (const [field, value] of [
386
+ ['profiles', manifest.profiles],
387
+ ['policy', manifest.policy],
388
+ ]) {
389
+ assertExactMap(value, ['path', 'canonicalHash'], `visual manifest.${field}`);
390
+ assertSafePath(value.path, `visual manifest.${field}.path`);
391
+ assertHash(value.canonicalHash, `visual manifest.${field}.canonicalHash`);
392
+ }
393
+ assertExactMap(
394
+ manifest.capture,
395
+ ['repetitions', 'deterministic'],
396
+ 'visual manifest.capture',
397
+ );
398
+ assertPositiveInteger(
399
+ manifest.capture.repetitions,
400
+ 'visual manifest.capture.repetitions',
401
+ );
402
+ if (manifest.capture.deterministic !== true) {
403
+ throw new VisualContractError('visual manifest must attest deterministic capture');
404
+ }
405
+ if (!Array.isArray(manifest.images)) {
406
+ throw new VisualContractError('visual manifest.images must be an array');
407
+ }
408
+ const profiles = profileSet
409
+ ? new Map(
410
+ validateVisualProfileSet(profileSet).profiles.map((profile) => [
411
+ profile.id,
412
+ profile,
413
+ ]),
414
+ )
415
+ : null;
416
+ if (profileSet && manifest.profiles.canonicalHash !== profileSet.canonicalHash) {
417
+ throw new VisualContractError('visual manifest profile hash is incompatible');
418
+ }
419
+ if (
420
+ checkpointPolicy &&
421
+ manifest.policy.canonicalHash !==
422
+ validateVisualCheckpointPolicy(checkpointPolicy).canonicalHash
423
+ ) {
424
+ throw new VisualContractError('visual manifest checkpoint policy hash is incompatible');
425
+ }
426
+ if (checkpointPolicy && !profiles) {
427
+ throw new VisualContractError(
428
+ 'checkpoint policy validation also requires the visual profile set',
429
+ );
430
+ }
431
+ const expected = checkpointPolicy
432
+ ? expectedImagePolicies(checkpointPolicy, profiles)
433
+ : null;
434
+ const keys = new Set();
435
+ const ids = new Set();
436
+ for (const [index, image] of manifest.images.entries()) {
437
+ const path = `visual manifest.images[${index}]`;
438
+ validateImageRecord(image, path);
439
+ if (ids.has(image.id)) throw new VisualContractError(`${path}.id is duplicated`);
440
+ ids.add(image.id);
441
+ const key = visualImageKey(image);
442
+ if (keys.has(key)) throw new VisualContractError(`${path} is duplicated`);
443
+ keys.add(key);
444
+ if (profiles) {
445
+ const profile = profiles.get(image.profileId);
446
+ if (!profile || profile.canonicalHash !== image.profileHash) {
447
+ throw new VisualContractError(`${path} has a profile mismatch`);
448
+ }
449
+ if (profile.colorScheme !== image.scheme) {
450
+ throw new VisualContractError(`${path}.scheme does not match its profile`);
451
+ }
452
+ }
453
+ if (expected) {
454
+ const approved = expected.get(key);
455
+ if (!approved) {
456
+ throw new VisualContractError(`${path} is not an approved checkpoint`);
457
+ }
458
+ if (
459
+ image.tier !== approved.tier ||
460
+ image.purpose !== approved.purpose ||
461
+ JSON.stringify(image.masks) !==
462
+ JSON.stringify(approved.masks.map(({ id }) => id)) ||
463
+ JSON.stringify(image.tolerance) !== JSON.stringify(approved.tolerance)
464
+ ) {
465
+ throw new VisualContractError(
466
+ `${path} attempts to override trusted checkpoint policy`,
467
+ );
468
+ }
469
+ }
470
+ if (requireFiles || bundleRoot || readImage) {
471
+ const bytes = readImage
472
+ ? readImage(image.path)
473
+ : readRegularContainedFile(bundleRoot, image.path, path);
474
+ const actualHash = createHash('sha256').update(bytes).digest('hex');
475
+ if (actualHash !== image.sha256) {
476
+ throw new VisualContractError(`${path} image hash does not match`);
477
+ }
478
+ const dimensions = pngDimensions(bytes, `${path} image`);
479
+ if (dimensions.width !== image.width || dimensions.height !== image.height) {
480
+ throw new VisualContractError(`${path} image dimensions do not match`);
481
+ }
482
+ }
483
+ }
484
+ if (expected) {
485
+ const missing = [...expected.keys()].filter((key) => !keys.has(key));
486
+ if (missing.length) {
487
+ throw new VisualContractError(
488
+ `visual manifest is missing ${missing.length} required checkpoint image(s)`,
489
+ );
490
+ }
491
+ }
492
+ assertCanonicalHash(manifest, 'visual manifest');
493
+ return manifest;
494
+ }
495
+
496
+ export function compareVisualManifests(baseline, candidate) {
497
+ try {
498
+ validateVisualManifest(baseline);
499
+ validateVisualManifest(candidate);
500
+ if (baseline.approval.status !== 'reviewed') {
501
+ throw new VisualContractError('visual baseline is not owner reviewed');
502
+ }
503
+ if (
504
+ baseline.profiles.canonicalHash !== candidate.profiles.canonicalHash ||
505
+ baseline.policy.canonicalHash !== candidate.policy.canonicalHash
506
+ ) {
507
+ return visualComparison('incompatible', {
508
+ reason: 'candidate profile or checkpoint policy differs from the reviewed baseline',
509
+ });
510
+ }
511
+ const before = new Map(baseline.images.map((image) => [visualImageKey(image), image]));
512
+ const after = new Map(candidate.images.map((image) => [visualImageKey(image), image]));
513
+ const checkpoints = [...new Set([...before.keys(), ...after.keys()])]
514
+ .sort()
515
+ .map((key) => {
516
+ const left = before.get(key);
517
+ const right = after.get(key);
518
+ const status = !left
519
+ ? 'added'
520
+ : !right
521
+ ? 'missing'
522
+ : left.sha256 !== right.sha256 ||
523
+ left.width !== right.width ||
524
+ left.height !== right.height
525
+ ? 'changed'
526
+ : 'unchanged';
527
+ return {
528
+ key,
529
+ status,
530
+ baseline: left ? imageReference(left) : null,
531
+ candidate: right ? imageReference(right) : null,
532
+ };
533
+ });
534
+ const counts = countStatuses(checkpoints);
535
+ const status = counts.missing
536
+ ? 'missing'
537
+ : counts.changed
538
+ ? 'changed'
539
+ : counts.added
540
+ ? 'added'
541
+ : 'unchanged';
542
+ return visualComparison(status, {
543
+ reason:
544
+ status === 'unchanged'
545
+ ? 'every reviewed checkpoint image is byte-identical'
546
+ : 'checkpoint changes require individual owner review',
547
+ baselineHash: baseline.canonicalHash,
548
+ candidateHash: candidate.canonicalHash,
549
+ checkpoints,
550
+ counts,
551
+ });
552
+ } catch (error) {
553
+ return visualComparison('error', {
554
+ reason: error instanceof Error ? error.message : String(error),
555
+ });
556
+ }
557
+ }
558
+
559
+ export function unavailableVisualComparison(reason, candidate = null) {
560
+ assertText(reason, 'visual comparison reason');
561
+ return {
562
+ kind: VISUAL_COMPARISON_KIND,
563
+ version: VISUAL_COMPARISON_VERSION,
564
+ status: 'not-evaluated',
565
+ reason,
566
+ baselineHash: null,
567
+ candidateHash: candidate?.canonicalHash ?? null,
568
+ counts: {
569
+ added: 0,
570
+ missing: 0,
571
+ changed: 0,
572
+ unchanged: candidate?.images?.length ?? 0,
573
+ incompatible: 0,
574
+ error: 0,
575
+ },
576
+ checkpoints: [],
577
+ };
578
+ }
579
+
580
+ export function renderVisualManifestMarkdown(manifest) {
581
+ validateVisualManifest(manifest);
582
+ const lines = [
583
+ '# ux-guard visual candidate',
584
+ '',
585
+ `- **Approval:** ${manifest.approval.status}`,
586
+ `- **Canonical hash:** \`${manifest.canonicalHash}\``,
587
+ `- **Profile set:** \`${manifest.profiles.canonicalHash}\``,
588
+ `- **Checkpoint policy:** \`${manifest.policy.canonicalHash}\``,
589
+ `- **Stable repetitions:** ${manifest.capture.repetitions}`,
590
+ `- **Images:** ${manifest.images.length}`,
591
+ '',
592
+ '## Checkpoint images',
593
+ '',
594
+ ];
595
+ for (const image of manifest.images) {
596
+ lines.push(
597
+ `- \`${image.id}\` — ${image.width}×${image.height}; \`${image.sha256}\`; \`${image.path}\``,
598
+ );
599
+ }
600
+ lines.push('');
601
+ return lines.join('\n');
602
+ }
603
+
604
+ export function renderVisualComparisonMarkdown(comparison) {
605
+ validateVisualComparison(comparison);
606
+ const lines = [
607
+ '# ux-guard visual comparison',
608
+ '',
609
+ `- **Status:** ${comparison.status}`,
610
+ `- **Reason:** ${comparison.reason}`,
611
+ `- **Baseline:** ${comparison.baselineHash ?? 'not available'}`,
612
+ `- **Candidate:** ${comparison.candidateHash ?? 'not available'}`,
613
+ '',
614
+ ];
615
+ if (comparison.checkpoints.length) {
616
+ lines.push('## Per-checkpoint evidence', '');
617
+ for (const checkpoint of comparison.checkpoints) {
618
+ lines.push(
619
+ `- \`${checkpoint.key}\` — **${checkpoint.status}**; baseline: ${
620
+ checkpoint.baseline
621
+ ? `\`${checkpoint.baseline.path}\` / \`${checkpoint.baseline.sha256}\` / ${checkpoint.baseline.width}×${checkpoint.baseline.height}`
622
+ : 'none'
623
+ }; candidate: ${
624
+ checkpoint.candidate
625
+ ? `\`${checkpoint.candidate.path}\` / \`${checkpoint.candidate.sha256}\` / ${checkpoint.candidate.width}×${checkpoint.candidate.height}`
626
+ : 'none'
627
+ }`,
628
+ );
629
+ }
630
+ lines.push('');
631
+ }
632
+ return lines.join('\n');
633
+ }
634
+
635
+ export function validateVisualComparison(comparison) {
636
+ assertMap(comparison, 'visual comparison');
637
+ assertExactKeys(
638
+ comparison,
639
+ [
640
+ 'kind',
641
+ 'version',
642
+ 'status',
643
+ 'reason',
644
+ 'baselineHash',
645
+ 'candidateHash',
646
+ 'counts',
647
+ 'checkpoints',
648
+ ],
649
+ 'visual comparison',
650
+ );
651
+ if (
652
+ comparison.kind !== VISUAL_COMPARISON_KIND ||
653
+ comparison.version !== VISUAL_COMPARISON_VERSION
654
+ ) {
655
+ throw new VisualContractError('visual comparison generation is unsupported');
656
+ }
657
+ if (
658
+ ![
659
+ 'not-evaluated',
660
+ 'unchanged',
661
+ 'added',
662
+ 'missing',
663
+ 'changed',
664
+ 'incompatible',
665
+ 'error',
666
+ ].includes(comparison.status)
667
+ ) {
668
+ throw new VisualContractError('visual comparison status is invalid');
669
+ }
670
+ assertText(comparison.reason, 'visual comparison reason');
671
+ for (const [field, value] of [
672
+ ['baselineHash', comparison.baselineHash],
673
+ ['candidateHash', comparison.candidateHash],
674
+ ]) {
675
+ if (value !== null) assertHash(value, `visual comparison.${field}`);
676
+ }
677
+ assertExactMap(
678
+ comparison.counts,
679
+ ['added', 'missing', 'changed', 'unchanged', 'incompatible', 'error'],
680
+ 'visual comparison.counts',
681
+ );
682
+ for (const [field, value] of Object.entries(comparison.counts)) {
683
+ assertNonNegativeInteger(value, `visual comparison.counts.${field}`);
684
+ }
685
+ if (!Array.isArray(comparison.checkpoints)) {
686
+ throw new VisualContractError('visual comparison.checkpoints must be an array');
687
+ }
688
+ for (const [index, checkpoint] of comparison.checkpoints.entries()) {
689
+ const path = `visual comparison.checkpoints[${index}]`;
690
+ assertExactMap(
691
+ checkpoint,
692
+ ['key', 'status', 'baseline', 'candidate'],
693
+ path,
694
+ );
695
+ assertText(checkpoint.key, `${path}.key`);
696
+ if (!['added', 'missing', 'changed', 'unchanged'].includes(checkpoint.status)) {
697
+ throw new VisualContractError(`${path}.status is invalid`);
698
+ }
699
+ for (const field of ['baseline', 'candidate']) {
700
+ const reference = checkpoint[field];
701
+ if (reference === null) continue;
702
+ assertExactMap(
703
+ reference,
704
+ ['id', 'path', 'sha256', 'width', 'height'],
705
+ `${path}.${field}`,
706
+ );
707
+ assertId(reference.id, `${path}.${field}.id`);
708
+ assertSafePath(reference.path, `${path}.${field}.path`);
709
+ if (!RAW_HASH.test(reference.sha256)) {
710
+ throw new VisualContractError(`${path}.${field}.sha256 is invalid`);
711
+ }
712
+ assertPositiveInteger(reference.width, `${path}.${field}.width`);
713
+ assertPositiveInteger(reference.height, `${path}.${field}.height`);
714
+ }
715
+ }
716
+ return comparison;
717
+ }
718
+
719
+ export function promoteVisualManifest(manifest, { reviewer, reviewedAt, rationale } = {}) {
720
+ validateVisualManifest(manifest);
721
+ if (manifest.approval.status !== 'unapproved') {
722
+ throw new VisualContractError('only an unapproved visual candidate can be promoted');
723
+ }
724
+ assertText(reviewer, 'visual reviewer');
725
+ assertText(rationale, 'visual review rationale');
726
+ if (
727
+ typeof reviewedAt !== 'string' ||
728
+ !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(reviewedAt) ||
729
+ Number.isNaN(Date.parse(reviewedAt))
730
+ ) {
731
+ throw new VisualContractError('visual reviewedAt must be an explicit UTC timestamp');
732
+ }
733
+ const promoted = structuredClone(manifest);
734
+ promoted.approval = {
735
+ status: 'reviewed',
736
+ reviewer,
737
+ reviewedAt,
738
+ rationale,
739
+ };
740
+ promoted.canonicalHash = canonicalHash(promoted);
741
+ return validateVisualManifest(promoted);
742
+ }
743
+
744
+ export function writeVisualCandidateBundle({
745
+ root,
746
+ manifestPath,
747
+ manifest,
748
+ sourceImages,
749
+ } = {}) {
750
+ validateVisualManifest(manifest);
751
+ if (manifest.approval.status !== 'unapproved') {
752
+ throw new VisualContractError('candidate visual manifest must be unapproved');
753
+ }
754
+ const targetManifest = safeDestination(root, manifestPath, 'visual candidate manifest');
755
+ if (existsSync(targetManifest)) {
756
+ throw new VisualContractError(`${manifestPath} already exists; refusing to overwrite it`);
757
+ }
758
+ const bundleRoot = dirname(targetManifest);
759
+ ensureSafeDirectory(root, bundleRoot, true);
760
+ for (const image of manifest.images) {
761
+ const source = sourceImages.get(image.id);
762
+ if (!source) throw new VisualContractError(`source image ${image.id} is missing`);
763
+ const bytes = readRegularContainedFile(root, source, `source image ${image.id}`);
764
+ if (createHash('sha256').update(bytes).digest('hex') !== image.sha256) {
765
+ throw new VisualContractError(`source image ${image.id} hash changed`);
766
+ }
767
+ const destination = safeDestination(bundleRoot, image.path, `image ${image.id}`);
768
+ ensureSafeDirectory(bundleRoot, dirname(destination), true);
769
+ try {
770
+ copyFileSync(resolve(root, source), destination, 1);
771
+ } catch (error) {
772
+ if (error?.code === 'EEXIST') {
773
+ throw new VisualContractError(`${image.path} already exists; refusing to overwrite it`);
774
+ }
775
+ throw new VisualContractError(`could not write visual image ${image.id}`);
776
+ }
777
+ }
778
+ try {
779
+ writeFileSync(targetManifest, serializeVisualManifest(manifest), {
780
+ flag: 'wx',
781
+ mode: 0o600,
782
+ });
783
+ } catch (error) {
784
+ if (error?.code === 'EEXIST') {
785
+ throw new VisualContractError(`${manifestPath} already exists; refusing to overwrite it`);
786
+ }
787
+ throw new VisualContractError('could not write visual candidate manifest');
788
+ }
789
+ }
790
+
791
+ export function promoteVisualBundle({
792
+ root,
793
+ candidatePath,
794
+ baselinePath,
795
+ reviewer,
796
+ reviewedAt,
797
+ rationale,
798
+ profileSet,
799
+ checkpointPolicy,
800
+ } = {}) {
801
+ const candidateFull = safeExistingFile(root, candidatePath, 'visual candidate');
802
+ const candidateRoot = dirname(candidateFull);
803
+ const candidate = parseVisualManifest(readFileSync(candidateFull, 'utf8'), {
804
+ profileSet,
805
+ checkpointPolicy,
806
+ bundleRoot: candidateRoot,
807
+ requireFiles: true,
808
+ });
809
+ const promoted = promoteVisualManifest(candidate, {
810
+ reviewer,
811
+ reviewedAt,
812
+ rationale,
813
+ });
814
+ const baselineFull = safeDestination(root, baselinePath, 'visual baseline');
815
+ if (existsSync(baselineFull)) {
816
+ throw new VisualContractError(`${baselinePath} already exists; promotion never overwrites`);
817
+ }
818
+ const baselineRoot = dirname(baselineFull);
819
+ ensureSafeDirectory(root, baselineRoot, true);
820
+ for (const image of promoted.images) {
821
+ const source = safeExistingFile(candidateRoot, image.path, `candidate image ${image.id}`);
822
+ const destination = safeDestination(baselineRoot, image.path, `baseline image ${image.id}`);
823
+ ensureSafeDirectory(baselineRoot, dirname(destination), true);
824
+ copyFileSync(source, destination, 1);
825
+ }
826
+ writeFileSync(baselineFull, serializeVisualManifest(promoted), {
827
+ flag: 'wx',
828
+ mode: 0o600,
829
+ });
830
+ return promoted;
831
+ }
832
+
833
+ export function serializeVisualManifest(manifest) {
834
+ validateVisualManifest(manifest);
835
+ return `${JSON.stringify(canonicalize(manifest), null, 2)}\n`;
836
+ }
837
+
838
+ export function runVisualComparisonCanaries() {
839
+ const image = {
840
+ id: 'visual.example.journey.checkpoint.light.profile',
841
+ useCaseId: 'example',
842
+ journeyId: 'journey',
843
+ checkpointId: 'checkpoint',
844
+ scheme: 'light',
845
+ profileId: 'profile',
846
+ profileHash: `sha256:${'1'.repeat(64)}`,
847
+ tier: 'primary',
848
+ purpose: 'detail',
849
+ path: 'images/example.png',
850
+ sha256: '2'.repeat(64),
851
+ width: 100,
852
+ height: 40,
853
+ masks: [],
854
+ tolerance: { mode: 'exact' },
855
+ };
856
+ const base = syntheticManifest(image, 'reviewed');
857
+ const changedImage = { ...image, sha256: '3'.repeat(64), height: 41 };
858
+ const changed = compareVisualManifests(
859
+ base,
860
+ syntheticManifest(changedImage, 'unapproved'),
861
+ );
862
+ if (
863
+ changed.status !== 'changed' ||
864
+ changed.counts.changed !== 1 ||
865
+ changed.checkpoints[0]?.status !== 'changed'
866
+ ) {
867
+ throw new VisualContractError('one-pixel visual canary was not detected');
868
+ }
869
+ const missing = compareVisualManifests(
870
+ base,
871
+ syntheticManifest([], 'unapproved'),
872
+ );
873
+ if (missing.status !== 'missing' || missing.counts.missing !== 1) {
874
+ throw new VisualContractError('missing visual checkpoint canary was not detected');
875
+ }
876
+ const incompatibleCandidate = syntheticManifest(image, 'unapproved');
877
+ incompatibleCandidate.profiles.canonicalHash = `sha256:${'4'.repeat(64)}`;
878
+ incompatibleCandidate.canonicalHash = canonicalHash(incompatibleCandidate);
879
+ const incompatible = compareVisualManifests(base, incompatibleCandidate);
880
+ if (incompatible.status !== 'incompatible') {
881
+ throw new VisualContractError('visual profile mismatch canary was not detected');
882
+ }
883
+ return {
884
+ onePixelSystemicChange: 'passed',
885
+ missingCheckpoint: 'passed',
886
+ profileMismatch: 'passed',
887
+ failClosed: 'passed',
888
+ };
889
+ }
890
+
891
+ export function pngDimensions(bytes, path = 'PNG') {
892
+ if (
893
+ !Buffer.isBuffer(bytes) ||
894
+ bytes.length < 24 ||
895
+ bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a' ||
896
+ bytes.subarray(12, 16).toString('ascii') !== 'IHDR'
897
+ ) {
898
+ throw new VisualContractError(`${path} is not a valid PNG`);
899
+ }
900
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
901
+ }
902
+
903
+ export function visualImageId(value) {
904
+ return `visual.${value.useCaseId}.${value.journeyId}.${value.checkpointId}.${value.scheme}.${value.profileId}`;
905
+ }
906
+
907
+ export function visualImageKey(value) {
908
+ return [
909
+ value.useCaseId,
910
+ value.journeyId,
911
+ value.checkpointId,
912
+ value.scheme,
913
+ value.profileId,
914
+ ].join('/');
915
+ }
916
+
917
+ export function checkpointKey(value) {
918
+ return [value.useCaseId, value.journeyId, value.checkpointId].join('/');
919
+ }
920
+
921
+ function validateImageRecord(image, path) {
922
+ assertMap(image, path);
923
+ assertExactKeys(
924
+ image,
925
+ [
926
+ 'id',
927
+ 'useCaseId',
928
+ 'journeyId',
929
+ 'checkpointId',
930
+ 'scheme',
931
+ 'profileId',
932
+ 'profileHash',
933
+ 'tier',
934
+ 'purpose',
935
+ 'path',
936
+ 'sha256',
937
+ 'width',
938
+ 'height',
939
+ 'masks',
940
+ 'tolerance',
941
+ ],
942
+ path,
943
+ );
944
+ assertId(image.id, `${path}.id`);
945
+ assertId(image.useCaseId, `${path}.useCaseId`, USE_CASE_ID);
946
+ assertId(image.journeyId, `${path}.journeyId`);
947
+ assertId(image.checkpointId, `${path}.checkpointId`);
948
+ if (!['light', 'dark'].includes(image.scheme)) {
949
+ throw new VisualContractError(`${path}.scheme is invalid`);
950
+ }
951
+ assertId(image.profileId, `${path}.profileId`);
952
+ assertHash(image.profileHash, `${path}.profileHash`);
953
+ if (!['primary', 'secondary', 'representative'].includes(image.tier)) {
954
+ throw new VisualContractError(`${path}.tier is invalid`);
955
+ }
956
+ if (!['success', 'detail', 'form'].includes(image.purpose)) {
957
+ throw new VisualContractError(`${path}.purpose is invalid`);
958
+ }
959
+ assertSafePath(image.path, `${path}.path`);
960
+ if (!RAW_HASH.test(image.sha256)) {
961
+ throw new VisualContractError(`${path}.sha256 is invalid`);
962
+ }
963
+ assertPositiveInteger(image.width, `${path}.width`);
964
+ assertPositiveInteger(image.height, `${path}.height`);
965
+ if (
966
+ !Array.isArray(image.masks) ||
967
+ image.masks.some((mask) => typeof mask !== 'string' || !ID.test(mask))
968
+ ) {
969
+ throw new VisualContractError(`${path}.masks is invalid`);
970
+ }
971
+ assertExactMap(image.tolerance, ['mode'], `${path}.tolerance`);
972
+ if (image.tolerance.mode !== 'exact') {
973
+ throw new VisualContractError(`${path}.tolerance must be exact`);
974
+ }
975
+ if (image.id !== visualImageId(image)) {
976
+ throw new VisualContractError(`${path}.id is not derived from checkpoint identity`);
977
+ }
978
+ }
979
+
980
+ function expectedImagePolicies(policy, profiles) {
981
+ const keys = new Map();
982
+ for (const checkpoint of policy.checkpoints) {
983
+ for (const profileId of checkpoint.profiles) {
984
+ const profile = profiles.get(profileId);
985
+ if (!profile) {
986
+ throw new VisualContractError(
987
+ `visual checkpoint references unknown profile ${profileId}`,
988
+ );
989
+ }
990
+ keys.set(
991
+ [
992
+ checkpoint.useCaseId,
993
+ checkpoint.journeyId,
994
+ checkpoint.checkpointId,
995
+ profile.colorScheme,
996
+ profileId,
997
+ ].join('/'),
998
+ checkpoint,
999
+ );
1000
+ }
1001
+ }
1002
+ return keys;
1003
+ }
1004
+
1005
+ function validateApproval(approval) {
1006
+ assertMap(approval, 'visual manifest.approval');
1007
+ if (approval.status === 'unapproved') {
1008
+ assertExactKeys(approval, ['status'], 'visual manifest.approval');
1009
+ return;
1010
+ }
1011
+ assertExactKeys(
1012
+ approval,
1013
+ ['status', 'reviewer', 'reviewedAt', 'rationale'],
1014
+ 'visual manifest.approval',
1015
+ );
1016
+ if (approval.status !== 'reviewed') {
1017
+ throw new VisualContractError('visual manifest approval status is invalid');
1018
+ }
1019
+ assertText(approval.reviewer, 'visual manifest.approval.reviewer');
1020
+ assertText(approval.rationale, 'visual manifest.approval.rationale');
1021
+ if (
1022
+ typeof approval.reviewedAt !== 'string' ||
1023
+ !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(approval.reviewedAt)
1024
+ ) {
1025
+ throw new VisualContractError('visual manifest.approval.reviewedAt is invalid');
1026
+ }
1027
+ }
1028
+
1029
+ function visualComparison(status, overrides = {}) {
1030
+ const checkpoints = overrides.checkpoints ?? [];
1031
+ const comparison = {
1032
+ kind: VISUAL_COMPARISON_KIND,
1033
+ version: VISUAL_COMPARISON_VERSION,
1034
+ status,
1035
+ reason: overrides.reason ?? 'visual comparison completed',
1036
+ baselineHash: overrides.baselineHash ?? null,
1037
+ candidateHash: overrides.candidateHash ?? null,
1038
+ counts:
1039
+ overrides.counts ??
1040
+ {
1041
+ added: 0,
1042
+ missing: 0,
1043
+ changed: 0,
1044
+ unchanged: 0,
1045
+ incompatible: status === 'incompatible' ? 1 : 0,
1046
+ error: status === 'error' ? 1 : 0,
1047
+ },
1048
+ checkpoints,
1049
+ };
1050
+ return validateVisualComparison(comparison);
1051
+ }
1052
+
1053
+ function countStatuses(checkpoints) {
1054
+ const counts = {
1055
+ added: 0,
1056
+ missing: 0,
1057
+ changed: 0,
1058
+ unchanged: 0,
1059
+ incompatible: 0,
1060
+ error: 0,
1061
+ };
1062
+ for (const checkpoint of checkpoints) counts[checkpoint.status] += 1;
1063
+ return counts;
1064
+ }
1065
+
1066
+ function imageReference(image) {
1067
+ return {
1068
+ id: image.id,
1069
+ path: image.path,
1070
+ sha256: image.sha256,
1071
+ width: image.width,
1072
+ height: image.height,
1073
+ };
1074
+ }
1075
+
1076
+ function syntheticManifest(images, status) {
1077
+ const list = Array.isArray(images) ? images : [images];
1078
+ const manifest = {
1079
+ kind: VISUAL_MANIFEST_KIND,
1080
+ version: VISUAL_MANIFEST_VERSION,
1081
+ approval:
1082
+ status === 'reviewed'
1083
+ ? {
1084
+ status,
1085
+ reviewer: 'visual-owner',
1086
+ reviewedAt: '2026-11-16T18:00:00Z',
1087
+ rationale: 'Known-bad comparison canary.',
1088
+ }
1089
+ : { status },
1090
+ profiles: {
1091
+ path: 'ux/visual-profiles.json',
1092
+ canonicalHash: `sha256:${'a'.repeat(64)}`,
1093
+ },
1094
+ policy: {
1095
+ path: 'ux/visual-checkpoints.json',
1096
+ canonicalHash: `sha256:${'b'.repeat(64)}`,
1097
+ },
1098
+ capture: { repetitions: 3, deterministic: true },
1099
+ images: list,
1100
+ canonicalHash: '',
1101
+ };
1102
+ manifest.canonicalHash = canonicalHash(manifest);
1103
+ return validateVisualManifest(manifest);
1104
+ }
1105
+
1106
+ function readRegularContainedFile(root, path, label) {
1107
+ if (!root) throw new VisualContractError(`${label} has no bundle root`);
1108
+ const full = safeExistingFile(root, path, label);
1109
+ return readFileSync(full);
1110
+ }
1111
+
1112
+ function safeExistingFile(root, path, label) {
1113
+ assertSafePath(path, `${label} path`);
1114
+ const rootReal = realDirectory(root, `${label} root`);
1115
+ const full = resolve(rootReal, path);
1116
+ let stats;
1117
+ let real;
1118
+ try {
1119
+ stats = lstatSync(full);
1120
+ real = realpathSync(full);
1121
+ } catch {
1122
+ throw new VisualContractError(`${label} does not exist`);
1123
+ }
1124
+ if (stats.isSymbolicLink() || !stats.isFile()) {
1125
+ throw new VisualContractError(`${label} must be a regular file, not a symbolic link`);
1126
+ }
1127
+ ensureContained(rootReal, real, label);
1128
+ return real;
1129
+ }
1130
+
1131
+ function safeDestination(root, path, label) {
1132
+ assertSafePath(path, `${label} path`);
1133
+ const full = resolve(root, path);
1134
+ ensureContained(resolve(root), full, label);
1135
+ return full;
1136
+ }
1137
+
1138
+ function ensureSafeDirectory(root, directory, create) {
1139
+ const rootFull = resolve(root);
1140
+ ensureContained(rootFull, resolve(directory), 'visual directory');
1141
+ const fromRoot = relative(rootFull, resolve(directory));
1142
+ let current = rootFull;
1143
+ for (const part of fromRoot ? fromRoot.split(sep) : []) {
1144
+ current = join(current, part);
1145
+ if (!existsSync(current)) {
1146
+ if (!create) throw new VisualContractError('visual parent directory is missing');
1147
+ mkdirSync(current, { mode: 0o700 });
1148
+ }
1149
+ const stats = lstatSync(current);
1150
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
1151
+ throw new VisualContractError('visual parent must not be a symbolic link');
1152
+ }
1153
+ }
1154
+ }
1155
+
1156
+ function realDirectory(path, label) {
1157
+ try {
1158
+ const real = realpathSync(resolve(path));
1159
+ if (!lstatSync(real).isDirectory()) throw new Error('not directory');
1160
+ return real;
1161
+ } catch {
1162
+ throw new VisualContractError(`${label} must be an existing directory`);
1163
+ }
1164
+ }
1165
+
1166
+ function ensureContained(root, target, label) {
1167
+ const value = relative(resolve(root), resolve(target));
1168
+ if (value === '..' || value.startsWith(`..${sep}`) || isAbsolute(value)) {
1169
+ throw new VisualContractError(`${label} escapes its allowed root`);
1170
+ }
1171
+ }
1172
+
1173
+ function assertSafePath(path, label) {
1174
+ if (
1175
+ typeof path !== 'string' ||
1176
+ !path ||
1177
+ path.includes('\\') ||
1178
+ path.includes('\0') ||
1179
+ isAbsolute(path) ||
1180
+ path.split('/').some((part) => !part || part === '.' || part === '..')
1181
+ ) {
1182
+ throw new VisualContractError(`${label} must be a normalized relative path`);
1183
+ }
1184
+ }
1185
+
1186
+ function assertAbsoluteNormalizedPath(path, label) {
1187
+ if (
1188
+ typeof path !== 'string' ||
1189
+ !path.startsWith('/') ||
1190
+ path.includes('\0') ||
1191
+ path.split('/').some((part, index) => index > 0 && (!part || part === '.' || part === '..'))
1192
+ ) {
1193
+ throw new VisualContractError(`${label} must be a normalized absolute path`);
1194
+ }
1195
+ }
1196
+
1197
+ function parseJson(text, label) {
1198
+ if (typeof text !== 'string') throw new VisualContractError(`${label} must be JSON text`);
1199
+ try {
1200
+ return JSON.parse(text);
1201
+ } catch {
1202
+ throw new VisualContractError(`${label} is not valid JSON`);
1203
+ }
1204
+ }
1205
+
1206
+ function assertCanonicalHash(value, path) {
1207
+ assertHash(value.canonicalHash, `${path}.canonicalHash`);
1208
+ if (value.canonicalHash !== canonicalHash(value)) {
1209
+ throw new VisualContractError(`${path}.canonicalHash does not match canonical content`);
1210
+ }
1211
+ }
1212
+
1213
+ function assertHash(value, path) {
1214
+ if (typeof value !== 'string' || !HASH.test(value)) {
1215
+ throw new VisualContractError(`${path} is not a sha256 hash`);
1216
+ }
1217
+ }
1218
+
1219
+ function assertMap(value, path) {
1220
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
1221
+ throw new VisualContractError(`${path} must be an object`);
1222
+ }
1223
+ }
1224
+
1225
+ function assertExactMap(value, keys, path) {
1226
+ assertMap(value, path);
1227
+ assertExactKeys(value, keys, path);
1228
+ }
1229
+
1230
+ function assertExactKeys(value, keys, path) {
1231
+ const actual = Object.keys(value).sort();
1232
+ const expected = [...keys].sort();
1233
+ if (
1234
+ actual.length !== expected.length ||
1235
+ actual.some((key, index) => key !== expected[index])
1236
+ ) {
1237
+ throw new VisualContractError(`${path} must contain ${expected.join(', ')} only`);
1238
+ }
1239
+ }
1240
+
1241
+ function assertId(value, path, pattern = ID) {
1242
+ if (typeof value !== 'string' || !pattern.test(value)) {
1243
+ throw new VisualContractError(`${path} is not a safe id`);
1244
+ }
1245
+ }
1246
+
1247
+ function assertText(value, path) {
1248
+ if (typeof value !== 'string' || !value.trim()) {
1249
+ throw new VisualContractError(`${path} must be non-empty text`);
1250
+ }
1251
+ }
1252
+
1253
+ function assertPositiveInteger(value, path) {
1254
+ if (!Number.isSafeInteger(value) || value < 1) {
1255
+ throw new VisualContractError(`${path} must be a positive integer`);
1256
+ }
1257
+ }
1258
+
1259
+ function assertNonNegativeInteger(value, path) {
1260
+ if (!Number.isSafeInteger(value) || value < 0) {
1261
+ throw new VisualContractError(`${path} must be a non-negative integer`);
1262
+ }
1263
+ }