@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,197 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolveExistingRepositoryPath } from './config.mjs';
3
+ import { ConfigError, parseYamlSubset } from './yaml.mjs';
4
+
5
+ const TIERS = new Set(['primary', 'secondary', 'tertiary']);
6
+ const EFFECTS = new Set(['read', 'create', 'change']);
7
+ const REQUIRED = ['id', 'title', 'persona', 'tier', 'effect', 'owner', 'goal', 'success', 'starts'];
8
+ const TEXT_FIELDS = ['title', 'persona', 'owner', 'goal', 'success'];
9
+
10
+ // Object literals that declare a string `id` and an absolute string `route`
11
+ // are navigation surfaces.
12
+ export function navSurfaces(ts, fileName, text) {
13
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
14
+ const surfaces = [];
15
+ const visit = (node) => {
16
+ if (ts.isObjectLiteralExpression(node)) {
17
+ const fields = {};
18
+ for (const property of node.properties) {
19
+ if (!ts.isPropertyAssignment(property)) continue;
20
+ const name = propertyName(ts, property.name);
21
+ if (!name) continue;
22
+ const init = property.initializer;
23
+ if (ts.isStringLiteralLike(init)) fields[name] = init.text;
24
+ else if (init.kind === ts.SyntaxKind.TrueKeyword) fields[name] = true;
25
+ else if (init.kind === ts.SyntaxKind.FalseKeyword) fields[name] = false;
26
+ }
27
+ if (typeof fields.id === 'string' && typeof fields.route === 'string' && fields.route.startsWith('/')) {
28
+ surfaces.push({
29
+ id: fields.id,
30
+ label: typeof fields.label === 'string' ? fields.label : '',
31
+ route: fields.route,
32
+ hidden: fields.hiddenInMenu === true,
33
+ destination: fields.destination !== false,
34
+ file: fileName,
35
+ });
36
+ }
37
+ }
38
+ ts.forEachChild(node, visit);
39
+ };
40
+ visit(source);
41
+ return surfaces;
42
+ }
43
+
44
+ function propertyName(ts, name) {
45
+ if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text;
46
+ return null;
47
+ }
48
+
49
+ export function loadCatalog(root, config) {
50
+ return parseYamlSubset(readInput(root, config.catalog.path, 'catalog'));
51
+ }
52
+
53
+ export function loadSurfaces(ts, root, config) {
54
+ const surfaces = [];
55
+ for (const file of config.catalog.navigation) {
56
+ surfaces.push(...navSurfaces(ts, file, readInput(root, file, 'navigation source')));
57
+ }
58
+ if (surfaces.length === 0) throw new ConfigError('no navigation surfaces found');
59
+ const seen = new Map();
60
+ for (const surface of surfaces) {
61
+ const prior = seen.get(surface.id);
62
+ if (prior) {
63
+ throw new ConfigError(`navigation id ${surface.id} is declared in ${prior.file} and ${surface.file}`);
64
+ }
65
+ seen.set(surface.id, surface);
66
+ }
67
+ return surfaces;
68
+ }
69
+
70
+ export function catalogPolicy(catalog) {
71
+ if (!isMap(catalog) || catalog.version !== 1) throw new ConfigError('trusted catalog version must be 1');
72
+ if (catalog.inventory !== 'partial' && catalog.inventory !== 'complete') {
73
+ throw new ConfigError('trusted catalog inventory must be partial or complete');
74
+ }
75
+ return { inventory: catalog.inventory };
76
+ }
77
+
78
+ export function validateCatalog(catalog, surfaces) {
79
+ if (!isMap(catalog)) throw new ConfigError('catalog must be a mapping');
80
+ if (catalog.version !== 1) throw new ConfigError('catalog version must be 1');
81
+ if (catalog.inventory !== 'partial' && catalog.inventory !== 'complete') {
82
+ throw new ConfigError('catalog inventory must be partial or complete');
83
+ }
84
+ const cases = catalog.use_cases;
85
+ if (!Array.isArray(cases) || cases.length === 0) {
86
+ throw new ConfigError('use_cases must be a non-empty list');
87
+ }
88
+
89
+ const byId = new Map(surfaces.map((surface) => [surface.id, surface]));
90
+ const ids = new Set();
91
+ const covered = new Set();
92
+ for (const useCase of cases) {
93
+ if (!isMap(useCase)) throw new ConfigError('each use case must be a mapping');
94
+ const label = typeof useCase.id === 'string' ? useCase.id : '<unknown>';
95
+ const missing = REQUIRED.filter((field) => !Object.hasOwn(useCase, field));
96
+ if (missing.length) throw new ConfigError(`${label}: missing ${missing.join(', ')}`);
97
+ if (typeof useCase.id !== 'string' || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(useCase.id)) {
98
+ throw new ConfigError(`invalid use-case id ${JSON.stringify(useCase.id)}`);
99
+ }
100
+ if (ids.has(useCase.id)) throw new ConfigError(`duplicate use-case id ${useCase.id}`);
101
+ ids.add(useCase.id);
102
+ if (!TIERS.has(useCase.tier)) {
103
+ throw new ConfigError(`${useCase.id}: tier must be primary, secondary, or tertiary`);
104
+ }
105
+ if (!EFFECTS.has(useCase.effect)) {
106
+ throw new ConfigError(`${useCase.id}: effect must be read, create, or change`);
107
+ }
108
+ for (const field of TEXT_FIELDS) {
109
+ if (typeof useCase[field] !== 'string' || !useCase[field].trim()) {
110
+ throw new ConfigError(`${useCase.id}: ${field} must be text`);
111
+ }
112
+ }
113
+ if (!Array.isArray(useCase.starts) || useCase.starts.length === 0) {
114
+ throw new ConfigError(`${useCase.id}: starts must be a non-empty list`);
115
+ }
116
+ for (const start of useCase.starts) {
117
+ for (const id of checkStart(useCase.id, start, byId)) covered.add(id);
118
+ }
119
+ for (const field of ['requirements', 'gaps']) {
120
+ const values = useCase[field] ?? [];
121
+ if (!Array.isArray(values) || values.some((item) => typeof item !== 'string' || !item.trim())) {
122
+ throw new ConfigError(`${useCase.id}: ${field} must be a list of text`);
123
+ }
124
+ }
125
+ }
126
+
127
+ return {
128
+ inventory: catalog.inventory,
129
+ useCases: cases,
130
+ surfaces,
131
+ unmapped: surfaces.filter((surface) => !covered.has(surface.id)),
132
+ };
133
+ }
134
+
135
+ function checkStart(caseId, start, byId) {
136
+ if (!isMap(start)) throw new ConfigError(`${caseId}: each start must be a mapping`);
137
+ if (start.entry === 'assistant') {
138
+ if (typeof start.prompt !== 'string' || !start.prompt.trim()) {
139
+ throw new ConfigError(`${caseId}: an assistant start needs a prompt`);
140
+ }
141
+ if (!sameKeys(start, ['entry', 'prompt'])) {
142
+ throw new ConfigError(`${caseId}: an assistant start has entry and prompt only`);
143
+ }
144
+ return [];
145
+ }
146
+ if (!sameKeys(start, ['nav_id', 'route'])) {
147
+ throw new ConfigError(`${caseId}: a navigation start has nav_id and route only`);
148
+ }
149
+ const surface = byId.get(start.nav_id);
150
+ if (!surface) throw new ConfigError(`${caseId}: start names unknown navigation id ${JSON.stringify(start.nav_id)}`);
151
+ if (typeof start.route !== 'string' || !start.route.startsWith('/')) {
152
+ throw new ConfigError(`${caseId}: start ${start.nav_id} needs an absolute route`);
153
+ }
154
+ const base = surface.route.replace(/\/+$/, '');
155
+ if (start.route !== surface.route && !start.route.startsWith(`${base}/`)) {
156
+ throw new ConfigError(`${caseId}: route ${start.route} is outside navigation surface ${surface.route}`);
157
+ }
158
+ return [start.nav_id];
159
+ }
160
+
161
+ function sameKeys(value, keys) {
162
+ const actual = Object.keys(value).sort();
163
+ return actual.length === keys.length && [...keys].sort().every((key, index) => key === actual[index]);
164
+ }
165
+
166
+ function isMap(value) {
167
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
168
+ }
169
+
170
+ function readInput(root, path, kind) {
171
+ try {
172
+ return readFileSync(resolveExistingRepositoryPath(root, path, `${kind} ${path}`), 'utf8');
173
+ } catch (error) {
174
+ if (error instanceof ConfigError) throw error;
175
+ throw new ConfigError(`${kind} ${path} could not be read from the working tree`);
176
+ }
177
+ }
178
+
179
+ export function renderCatalog(report) {
180
+ const lines = [
181
+ `Use-case catalog: ${report.inventory}, ${report.useCases.length} recorded`,
182
+ `Navigation surfaces: ${report.surfaces.length}`,
183
+ `Unmapped surfaces: ${report.unmapped.length}`,
184
+ ];
185
+ if (report.inventory === 'partial') {
186
+ lines.push('Unmapped surfaces are expected until the owner finishes the inventory.');
187
+ }
188
+ lines.push('', 'Recorded:');
189
+ for (const useCase of report.useCases) {
190
+ lines.push(` - ${useCase.id}: ${useCase.title} (${useCase.tier}, ${useCase.effect})`);
191
+ }
192
+ lines.push('', 'Unmapped:');
193
+ for (const surface of report.unmapped) {
194
+ lines.push(` - ${surface.id}: ${surface.label} ${surface.route}${surface.hidden ? ' hidden' : ''}`);
195
+ }
196
+ return `${lines.join('\n')}\n`;
197
+ }