@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,590 @@
1
+ import {
2
+ EXPLICIT_JOURNEY_METRICS,
3
+ STANDARD_JOURNEY_METRICS,
4
+ validateJourneyCatalog,
5
+ validateJourneyReport,
6
+ } from './journeys.mjs';
7
+ import { validateObservationRule } from './observations.mjs';
8
+ import { canonicalize } from './run-contract.mjs';
9
+
10
+ export const JOURNEY_POLICY_KIND = 'ux-guard-journey-policy';
11
+ export const JOURNEY_POLICY_VERSION = 3;
12
+ export const JOURNEY_ARTIFACT_KIND = 'ux-guard-journey-artifact';
13
+ export const JOURNEY_ARTIFACT_VERSION = 2;
14
+
15
+ const USE_CASE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
16
+ const ID = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
17
+ const VARIANTS = new Set(['canonical', 'alternative', 'required']);
18
+ const APPROVAL_STATUSES = new Set(['candidate', 'owner-approved']);
19
+ const AUTOMATION_STATUSES = new Set(['missing', 'bound']);
20
+ const ELAPSED_SOURCES = new Set(['mocked', 'logical', 'wall-clock']);
21
+ const EXECUTION_STATUSES = new Set([
22
+ 'unmeasured',
23
+ 'successful',
24
+ 'failed',
25
+ 'skipped',
26
+ 'unexecutable',
27
+ 'infrastructure-error',
28
+ ]);
29
+
30
+ export class JourneyPolicyError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = 'JourneyPolicyError';
34
+ }
35
+ }
36
+
37
+ export function createJourneyPolicy(journeys = [], { coverage, rules = [] } = {}) {
38
+ if (!Array.isArray(journeys)) throw new JourneyPolicyError('journeys must be an array');
39
+ const normalized = structuredClone(journeys);
40
+ for (const journey of normalized) {
41
+ if (Array.isArray(journey?.measurements?.explicit)) {
42
+ journey.measurements.explicit.sort(
43
+ (left, right) =>
44
+ EXPLICIT_JOURNEY_METRICS.indexOf(left) - EXPLICIT_JOURNEY_METRICS.indexOf(right),
45
+ );
46
+ }
47
+ }
48
+ const policy = {
49
+ kind: JOURNEY_POLICY_KIND,
50
+ version: JOURNEY_POLICY_VERSION,
51
+ coverage: coverage === undefined ? defaultCoverage(normalized) : structuredClone(coverage),
52
+ rules: structuredClone(rules).sort((left, right) =>
53
+ String(left?.ruleId).localeCompare(String(right?.ruleId)),
54
+ ),
55
+ journeys: normalized.sort(compareJourneyIdentity),
56
+ };
57
+ policy.coverage.sort((left, right) => String(left?.useCaseId).localeCompare(String(right?.useCaseId)));
58
+ return validateJourneyPolicy(policy);
59
+ }
60
+
61
+ export function validateJourneyPolicy(policy) {
62
+ assertMap(policy, 'policy');
63
+ assertExactKeys(policy, ['kind', 'version', 'coverage', 'rules', 'journeys'], 'policy');
64
+ if (policy.kind !== JOURNEY_POLICY_KIND) {
65
+ throw new JourneyPolicyError(`policy.kind must be ${JOURNEY_POLICY_KIND}`);
66
+ }
67
+ if (policy.version !== JOURNEY_POLICY_VERSION) {
68
+ throw new JourneyPolicyError(
69
+ `unsupported journey policy version ${String(policy.version)}; migrate to version ${JOURNEY_POLICY_VERSION}`,
70
+ );
71
+ }
72
+ if (!Array.isArray(policy.journeys) || !Array.isArray(policy.rules)) {
73
+ throw new JourneyPolicyError('policy.journeys and policy.rules must be arrays');
74
+ }
75
+ const coverage = validateCoveragePolicy(policy.coverage);
76
+ const identities = new Set();
77
+ const canonical = new Set();
78
+ for (const [index, journey] of policy.journeys.entries()) {
79
+ validateDefinition(journey, `policy.journeys[${index}]`);
80
+ const identity = journeyIdentity(journey);
81
+ if (identities.has(identity)) {
82
+ throw new JourneyPolicyError(`duplicate journey ${journey.useCaseId}/${journey.journeyId}`);
83
+ }
84
+ identities.add(identity);
85
+ if (journey.variant === 'canonical') {
86
+ if (canonical.has(journey.useCaseId)) {
87
+ throw new JourneyPolicyError(`${journey.useCaseId} has more than one canonical journey`);
88
+ }
89
+ canonical.add(journey.useCaseId);
90
+ }
91
+ }
92
+ for (const [useCaseId, variants] of coverage) {
93
+ for (const variant of variants) {
94
+ if (!identities.has(`${useCaseId}\0${variant.journeyId}`)) {
95
+ throw new JourneyPolicyError(
96
+ `required variant ${useCaseId}/${variant.journeyId} has no journey definition`,
97
+ );
98
+ }
99
+ }
100
+ }
101
+ const ruleIds = new Set();
102
+ for (const [index, rule] of policy.rules.entries()) {
103
+ try {
104
+ validateObservationRule(rule, `policy.rules[${index}]`);
105
+ } catch (error) {
106
+ throw new JourneyPolicyError(error.message);
107
+ }
108
+ if (ruleIds.has(rule.ruleId)) throw new JourneyPolicyError(`duplicate rule ${rule.ruleId}`);
109
+ ruleIds.add(rule.ruleId);
110
+ if (!policy.journeys.some((journey) => journey.useCaseId === rule.useCaseId)) {
111
+ throw new JourneyPolicyError(`rule ${rule.ruleId} names unknown use case ${rule.useCaseId}`);
112
+ }
113
+ for (const journeyId of rule.journeyIds) {
114
+ if (!identities.has(`${rule.useCaseId}\0${journeyId}`)) {
115
+ throw new JourneyPolicyError(`rule ${rule.ruleId} names unknown journey ${journeyId}`);
116
+ }
117
+ }
118
+ }
119
+ return policy;
120
+ }
121
+
122
+ export function parseJourneyPolicy(text) {
123
+ if (typeof text !== 'string') throw new JourneyPolicyError('journey policy must be JSON text');
124
+ let policy;
125
+ try {
126
+ policy = JSON.parse(text);
127
+ } catch {
128
+ throw new JourneyPolicyError('journey policy is not valid JSON');
129
+ }
130
+ if (policy?.kind === JOURNEY_POLICY_KIND && policy.version !== JOURNEY_POLICY_VERSION) {
131
+ throw new JourneyPolicyError(
132
+ `unsupported journey policy version ${String(policy.version)}; migrate to version ${JOURNEY_POLICY_VERSION}`,
133
+ );
134
+ }
135
+ return validateJourneyPolicy(policy);
136
+ }
137
+
138
+ export function serializeJourneyPolicy(policy) {
139
+ validateJourneyPolicy(policy);
140
+ return `${JSON.stringify(canonicalize(policy), null, 2)}\n`;
141
+ }
142
+
143
+ export function createJourneyArtifact({ catalog, policy, report = null } = {}) {
144
+ validateJourneyPolicy(policy);
145
+ const catalogSet = catalogIds(catalog);
146
+ if (report !== null) {
147
+ validateJourneyReport(report);
148
+ validateJourneyCatalog(report, catalog);
149
+ }
150
+ const definitions = new Map(
151
+ policy.journeys.map((journey) => [journeyIdentity(journey), journey]),
152
+ );
153
+ for (const journey of policy.journeys) {
154
+ if (!catalogSet.has(journey.useCaseId)) {
155
+ throw new JourneyPolicyError(`journey policy names uncatalogued use case ${journey.useCaseId}`);
156
+ }
157
+ }
158
+ const measured = new Map(
159
+ (report?.journeys ?? []).map((journey) => [
160
+ `${journey.useCaseId}\0${journey.journeyId}`,
161
+ journey,
162
+ ]),
163
+ );
164
+ for (const journey of report?.journeys ?? []) {
165
+ if (!definitions.has(`${journey.useCaseId}\0${journey.journeyId}`)) {
166
+ throw new JourneyPolicyError(
167
+ `measurement has no journey policy for ${journey.useCaseId}/${journey.journeyId}`,
168
+ );
169
+ }
170
+ }
171
+
172
+ const findings = [];
173
+ const useCases = policy.coverage.map((useCase) => {
174
+ if (!catalogSet.has(useCase.useCaseId)) {
175
+ throw new JourneyPolicyError(
176
+ `journey coverage policy names uncatalogued use case ${useCase.useCaseId}`,
177
+ );
178
+ }
179
+ const variants = useCase.requiredVariants.map((required) => {
180
+ const identity = `${useCase.useCaseId}\0${required.journeyId}`;
181
+ const definition = definitions.get(identity);
182
+ const measurement = measured.get(identity);
183
+ if (definition.approval.status !== 'owner-approved') {
184
+ findings.push(finding('required-variant-owner-approval-required', useCase.useCaseId, required));
185
+ }
186
+ if (definition.automation.status !== 'bound') {
187
+ findings.push(finding('required-variant-executable-coverage-required', useCase.useCaseId, required));
188
+ }
189
+ if (!measurement) {
190
+ findings.push(finding('required-variant-measurement-missing', useCase.useCaseId, required));
191
+ } else {
192
+ if (!measurementMatchesReference(measurement, definition)) {
193
+ findings.push(finding('measurement-contract-mismatch', useCase.useCaseId, required));
194
+ }
195
+ if (measurement.status !== 'successful') {
196
+ findings.push(
197
+ finding(`required-variant-${measurement.status}`, useCase.useCaseId, required),
198
+ );
199
+ }
200
+ }
201
+ return {
202
+ variantId: required.variantId,
203
+ label: required.label,
204
+ journeyId: required.journeyId,
205
+ approval: definition.approval.status,
206
+ automation: definition.automation.status,
207
+ executionStatus: measurement?.status ?? 'unmeasured',
208
+ };
209
+ });
210
+ return { useCaseId: useCase.useCaseId, variants };
211
+ });
212
+ for (const useCaseId of catalogSet) {
213
+ if (!policy.coverage.some((entry) => entry.useCaseId === useCaseId)) {
214
+ findings.push({
215
+ rule: 'required-use-case-coverage-missing',
216
+ scope: 'final-enforcement',
217
+ useCaseId,
218
+ });
219
+ }
220
+ }
221
+ const requiredVariants = useCases.reduce((total, useCase) => total + useCase.variants.length, 0);
222
+ const measuredVariants = useCases.reduce(
223
+ (total, useCase) =>
224
+ total + useCase.variants.filter((variant) => variant.executionStatus !== 'unmeasured').length,
225
+ 0,
226
+ );
227
+ const successfulVariants = useCases.reduce(
228
+ (total, useCase) =>
229
+ total + useCase.variants.filter((variant) => variant.executionStatus === 'successful').length,
230
+ 0,
231
+ );
232
+ const artifact = {
233
+ kind: JOURNEY_ARTIFACT_KIND,
234
+ version: JOURNEY_ARTIFACT_VERSION,
235
+ rollout: 'advisory',
236
+ coverage: {
237
+ cataloguedUseCases: catalogSet.size,
238
+ requiredVariants,
239
+ measuredVariants,
240
+ successfulVariants,
241
+ useCases,
242
+ findings: findings.sort(compareFinding),
243
+ },
244
+ measurementReport: report
245
+ ? {
246
+ kind: report.kind,
247
+ version: report.version,
248
+ policyDigest: report.run.policy.digest,
249
+ }
250
+ : null,
251
+ };
252
+ return validateJourneyArtifact(artifact);
253
+ }
254
+
255
+ export function validateJourneyArtifact(artifact) {
256
+ assertMap(artifact, 'artifact');
257
+ assertExactKeys(
258
+ artifact,
259
+ ['kind', 'version', 'rollout', 'coverage', 'measurementReport'],
260
+ 'artifact',
261
+ );
262
+ if (
263
+ artifact.kind !== JOURNEY_ARTIFACT_KIND ||
264
+ artifact.version !== JOURNEY_ARTIFACT_VERSION
265
+ ) {
266
+ throw new JourneyPolicyError('journey artifact has an unsupported kind or version');
267
+ }
268
+ if (artifact.rollout !== 'advisory') {
269
+ throw new JourneyPolicyError('artifact.rollout must be advisory');
270
+ }
271
+ const coverage = artifact.coverage;
272
+ assertMap(coverage, 'artifact.coverage');
273
+ assertExactKeys(
274
+ coverage,
275
+ [
276
+ 'cataloguedUseCases',
277
+ 'requiredVariants',
278
+ 'measuredVariants',
279
+ 'successfulVariants',
280
+ 'useCases',
281
+ 'findings',
282
+ ],
283
+ 'artifact.coverage',
284
+ );
285
+ for (const field of [
286
+ 'cataloguedUseCases',
287
+ 'requiredVariants',
288
+ 'measuredVariants',
289
+ 'successfulVariants',
290
+ ]) {
291
+ assertCount(coverage[field], `artifact.coverage.${field}`);
292
+ }
293
+ if (
294
+ coverage.successfulVariants > coverage.measuredVariants ||
295
+ coverage.measuredVariants > coverage.requiredVariants
296
+ ) {
297
+ throw new JourneyPolicyError('artifact.coverage counts are inconsistent');
298
+ }
299
+ if (!Array.isArray(coverage.useCases) || !Array.isArray(coverage.findings)) {
300
+ throw new JourneyPolicyError('artifact.coverage useCases and findings must be arrays');
301
+ }
302
+ const requiredCount = coverage.useCases.reduce((total, useCase, index) => {
303
+ const path = `artifact.coverage.useCases[${index}]`;
304
+ assertMap(useCase, path);
305
+ assertExactKeys(useCase, ['useCaseId', 'variants'], path);
306
+ assertId(useCase.useCaseId, USE_CASE_ID, `${path}.useCaseId`);
307
+ if (!Array.isArray(useCase.variants) || useCase.variants.length === 0) {
308
+ throw new JourneyPolicyError(`${path}.variants must be a non-empty array`);
309
+ }
310
+ useCase.variants.forEach((variant, variantIndex) =>
311
+ validateArtifactVariant(variant, `${path}.variants[${variantIndex}]`),
312
+ );
313
+ return total + useCase.variants.length;
314
+ }, 0);
315
+ if (
316
+ coverage.useCases.length > coverage.cataloguedUseCases ||
317
+ requiredCount !== coverage.requiredVariants
318
+ ) {
319
+ throw new JourneyPolicyError('artifact.coverage inventory counts are inconsistent');
320
+ }
321
+ if (artifact.measurementReport !== null) {
322
+ assertMap(artifact.measurementReport, 'artifact.measurementReport');
323
+ assertExactKeys(
324
+ artifact.measurementReport,
325
+ ['kind', 'version', 'policyDigest'],
326
+ 'artifact.measurementReport',
327
+ );
328
+ assertText(artifact.measurementReport.kind, 'artifact.measurementReport.kind');
329
+ assertCount(artifact.measurementReport.version, 'artifact.measurementReport.version');
330
+ assertText(artifact.measurementReport.policyDigest, 'artifact.measurementReport.policyDigest');
331
+ }
332
+ return artifact;
333
+ }
334
+
335
+ export function serializeJourneyArtifact(artifact) {
336
+ validateJourneyArtifact(artifact);
337
+ return `${JSON.stringify(canonicalize(artifact), null, 2)}\n`;
338
+ }
339
+
340
+ export function parseJourneyArtifact(text) {
341
+ let artifact;
342
+ try {
343
+ artifact = JSON.parse(text);
344
+ } catch {
345
+ throw new JourneyPolicyError('journey artifact is not valid JSON');
346
+ }
347
+ if (artifact?.kind === JOURNEY_ARTIFACT_KIND && artifact.version !== JOURNEY_ARTIFACT_VERSION) {
348
+ throw new JourneyPolicyError(
349
+ `unsupported journey artifact version ${String(artifact.version)}; migrate to version ${JOURNEY_ARTIFACT_VERSION}`,
350
+ );
351
+ }
352
+ return validateJourneyArtifact(artifact);
353
+ }
354
+
355
+ export function assertJourneyEnforcementReady(artifact) {
356
+ validateJourneyArtifact(artifact);
357
+ if (artifact.coverage.findings.length) {
358
+ throw new JourneyPolicyError(
359
+ `journey coverage is not ready for final enforcement: ${artifact.coverage.findings
360
+ .map((value) => `${value.useCaseId}:${value.rule}`)
361
+ .join(', ')}`,
362
+ );
363
+ }
364
+ return artifact;
365
+ }
366
+
367
+ function defaultCoverage(journeys) {
368
+ const byUseCase = new Map();
369
+ for (const journey of journeys) {
370
+ const entry = byUseCase.get(journey.useCaseId) ?? {
371
+ useCaseId: journey.useCaseId,
372
+ requiredVariants: [],
373
+ };
374
+ entry.requiredVariants.push({
375
+ variantId: journey.journeyId,
376
+ label: journey.journeyId,
377
+ journeyId: journey.journeyId,
378
+ });
379
+ byUseCase.set(journey.useCaseId, entry);
380
+ }
381
+ return [...byUseCase.values()];
382
+ }
383
+
384
+ function validateCoveragePolicy(coverage) {
385
+ if (!Array.isArray(coverage)) throw new JourneyPolicyError('policy.coverage must be an array');
386
+ const result = new Map();
387
+ for (const [index, useCase] of coverage.entries()) {
388
+ const path = `policy.coverage[${index}]`;
389
+ assertMap(useCase, path);
390
+ assertExactKeys(useCase, ['useCaseId', 'requiredVariants'], path);
391
+ assertId(useCase.useCaseId, USE_CASE_ID, `${path}.useCaseId`);
392
+ if (result.has(useCase.useCaseId)) {
393
+ throw new JourneyPolicyError(`policy.coverage repeats ${useCase.useCaseId}`);
394
+ }
395
+ if (!Array.isArray(useCase.requiredVariants) || useCase.requiredVariants.length === 0) {
396
+ throw new JourneyPolicyError(`${path}.requiredVariants must be a non-empty array`);
397
+ }
398
+ const ids = new Set();
399
+ for (const [variantIndex, variant] of useCase.requiredVariants.entries()) {
400
+ const variantPath = `${path}.requiredVariants[${variantIndex}]`;
401
+ assertMap(variant, variantPath);
402
+ assertExactKeys(variant, ['variantId', 'label', 'journeyId'], variantPath);
403
+ assertId(variant.variantId, ID, `${variantPath}.variantId`);
404
+ assertId(variant.journeyId, ID, `${variantPath}.journeyId`);
405
+ assertText(variant.label, `${variantPath}.label`);
406
+ if (ids.has(variant.journeyId)) {
407
+ throw new JourneyPolicyError(`${path}.requiredVariants repeats ${variant.journeyId}`);
408
+ }
409
+ ids.add(variant.journeyId);
410
+ }
411
+ result.set(useCase.useCaseId, useCase.requiredVariants);
412
+ }
413
+ return result;
414
+ }
415
+
416
+ function validateDefinition(journey, path) {
417
+ assertMap(journey, path);
418
+ assertExactKeys(
419
+ journey,
420
+ ['useCaseId', 'journeyId', 'variant', 'intent', 'approval', 'automation', 'measurements'],
421
+ path,
422
+ );
423
+ assertId(journey.useCaseId, USE_CASE_ID, `${path}.useCaseId`);
424
+ assertId(journey.journeyId, ID, `${path}.journeyId`);
425
+ if (!VARIANTS.has(journey.variant)) throw new JourneyPolicyError(`${path}.variant is invalid`);
426
+ assertMap(journey.intent, `${path}.intent`);
427
+ assertExactKeys(journey.intent, ['summary', 'steps', 'success'], `${path}.intent`);
428
+ assertText(journey.intent.summary, `${path}.intent.summary`);
429
+ assertText(journey.intent.success, `${path}.intent.success`);
430
+ if (
431
+ !Array.isArray(journey.intent.steps) ||
432
+ journey.intent.steps.length === 0 ||
433
+ journey.intent.steps.some((step) => typeof step !== 'string' || !step.trim())
434
+ ) {
435
+ throw new JourneyPolicyError(`${path}.intent.steps must be a non-empty text list`);
436
+ }
437
+ assertMap(journey.approval, `${path}.approval`);
438
+ assertExactKeys(journey.approval, ['status', 'approvedBy'], `${path}.approval`);
439
+ if (!APPROVAL_STATUSES.has(journey.approval.status)) {
440
+ throw new JourneyPolicyError(`${path}.approval.status is invalid`);
441
+ }
442
+ if (journey.approval.status === 'candidate' && journey.approval.approvedBy !== null) {
443
+ throw new JourneyPolicyError(`${path}.approval.approvedBy must be null for candidates`);
444
+ }
445
+ if (journey.approval.status === 'owner-approved') {
446
+ assertText(journey.approval.approvedBy, `${path}.approval.approvedBy`);
447
+ }
448
+ assertMap(journey.automation, `${path}.automation`);
449
+ assertExactKeys(journey.automation, ['status', 'source'], `${path}.automation`);
450
+ if (!AUTOMATION_STATUSES.has(journey.automation.status)) {
451
+ throw new JourneyPolicyError(`${path}.automation.status is invalid`);
452
+ }
453
+ if (journey.automation.status === 'missing' && journey.automation.source !== null) {
454
+ throw new JourneyPolicyError(`${path}.automation.source must be null when missing`);
455
+ }
456
+ if (journey.automation.status === 'bound') {
457
+ assertText(journey.automation.source, `${path}.automation.source`);
458
+ }
459
+ validateMeasurementSelection(journey.measurements, `${path}.measurements`);
460
+ }
461
+
462
+ function validateMeasurementSelection(measurements, path) {
463
+ assertMap(measurements, path);
464
+ assertExactKeys(measurements, ['explicit', 'elapsed'], path);
465
+ if (!Array.isArray(measurements.explicit)) {
466
+ throw new JourneyPolicyError(`${path}.explicit must be an array`);
467
+ }
468
+ const selected = new Set();
469
+ for (const metric of measurements.explicit) {
470
+ if (!EXPLICIT_JOURNEY_METRICS.includes(metric) || selected.has(metric)) {
471
+ throw new JourneyPolicyError(`${path}.explicit is invalid`);
472
+ }
473
+ selected.add(metric);
474
+ }
475
+ if (selected.has('elapsedMs')) {
476
+ assertMap(measurements.elapsed, `${path}.elapsed`);
477
+ assertExactKeys(measurements.elapsed, ['source'], `${path}.elapsed`);
478
+ if (!ELAPSED_SOURCES.has(measurements.elapsed.source)) {
479
+ throw new JourneyPolicyError(`${path}.elapsed.source is invalid`);
480
+ }
481
+ } else if (measurements.elapsed !== null) {
482
+ throw new JourneyPolicyError(`${path}.elapsed must be null without elapsedMs`);
483
+ }
484
+ }
485
+
486
+ function measurementMatchesReference(measurement, definition) {
487
+ if (!measurement.metrics) return true;
488
+ const expected = new Set([
489
+ ...STANDARD_JOURNEY_METRICS,
490
+ ...definition.measurements.explicit,
491
+ ]);
492
+ const actual = Object.keys(measurement.metrics);
493
+ if (actual.length !== expected.size || actual.some((metric) => !expected.has(metric))) {
494
+ return false;
495
+ }
496
+ const elapsed = definition.measurements.elapsed;
497
+ return elapsed ? measurement.timing?.source === elapsed.source : measurement.timing === null;
498
+ }
499
+
500
+ function finding(rule, useCaseId, required) {
501
+ return {
502
+ rule,
503
+ scope: rule === 'measurement-contract-mismatch' ? 'measurement' : 'final-enforcement',
504
+ useCaseId,
505
+ variantId: required.variantId,
506
+ journeyId: required.journeyId,
507
+ };
508
+ }
509
+
510
+ function validateArtifactVariant(variant, path) {
511
+ assertMap(variant, path);
512
+ assertExactKeys(
513
+ variant,
514
+ ['variantId', 'label', 'journeyId', 'approval', 'automation', 'executionStatus'],
515
+ path,
516
+ );
517
+ assertId(variant.variantId, ID, `${path}.variantId`);
518
+ assertText(variant.label, `${path}.label`);
519
+ assertId(variant.journeyId, ID, `${path}.journeyId`);
520
+ if (!APPROVAL_STATUSES.has(variant.approval)) {
521
+ throw new JourneyPolicyError(`${path}.approval is invalid`);
522
+ }
523
+ if (!AUTOMATION_STATUSES.has(variant.automation)) {
524
+ throw new JourneyPolicyError(`${path}.automation is invalid`);
525
+ }
526
+ if (!EXECUTION_STATUSES.has(variant.executionStatus)) {
527
+ throw new JourneyPolicyError(`${path}.executionStatus is invalid`);
528
+ }
529
+ }
530
+
531
+ function catalogIds(catalog) {
532
+ let entries;
533
+ if (catalog instanceof Set || Array.isArray(catalog)) entries = [...catalog];
534
+ else if (Array.isArray(catalog?.use_cases)) entries = catalog.use_cases.map((entry) => entry?.id);
535
+ else if (Array.isArray(catalog?.useCases)) entries = catalog.useCases.map((entry) => entry?.id);
536
+ else throw new JourneyPolicyError('catalog must contain use cases');
537
+ if (entries.some((entry) => typeof entry !== 'string' || !USE_CASE_ID.test(entry))) {
538
+ throw new JourneyPolicyError('catalog contains an invalid use-case id');
539
+ }
540
+ return new Set(entries);
541
+ }
542
+
543
+ function journeyIdentity(journey) {
544
+ return `${journey.useCaseId}\0${journey.journeyId}`;
545
+ }
546
+
547
+ function compareJourneyIdentity(left, right) {
548
+ return left.useCaseId.localeCompare(right.useCaseId) || left.journeyId.localeCompare(right.journeyId);
549
+ }
550
+
551
+ function compareFinding(left, right) {
552
+ return left.useCaseId.localeCompare(right.useCaseId) ||
553
+ left.rule.localeCompare(right.rule) ||
554
+ (left.journeyId ?? '').localeCompare(right.journeyId ?? '');
555
+ }
556
+
557
+ function assertMap(value, path) {
558
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
559
+ throw new JourneyPolicyError(`${path} must be an object`);
560
+ }
561
+ }
562
+
563
+ function assertExactKeys(value, expected, path) {
564
+ const actual = Object.keys(value).sort();
565
+ const wanted = [...expected].sort();
566
+ if (
567
+ actual.length !== wanted.length ||
568
+ actual.some((key, index) => key !== wanted[index])
569
+ ) {
570
+ throw new JourneyPolicyError(`${path} must contain ${wanted.join(', ')} only`);
571
+ }
572
+ }
573
+
574
+ function assertId(value, pattern, path) {
575
+ if (typeof value !== 'string' || !pattern.test(value)) {
576
+ throw new JourneyPolicyError(`${path} has invalid id ${JSON.stringify(value)}`);
577
+ }
578
+ }
579
+
580
+ function assertText(value, path) {
581
+ if (typeof value !== 'string' || !value.trim()) {
582
+ throw new JourneyPolicyError(`${path} must be non-empty text`);
583
+ }
584
+ }
585
+
586
+ function assertCount(value, path) {
587
+ if (!Number.isSafeInteger(value) || value < 0) {
588
+ throw new JourneyPolicyError(`${path} must be a non-negative safe integer`);
589
+ }
590
+ }