@edjbarron/ux-guard 0.0.0-stage → 0.6.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,268 @@
1
+ export const OBSERVATION_VERSION = 1;
2
+
3
+ const ID = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
4
+ const OBSERVATION_DEFINITIONS = Object.freeze({
5
+ 'interaction-metrics': {
6
+ required: ['metric', 'value'],
7
+ allowed: ['metric', 'value'],
8
+ },
9
+ 'field-required': {
10
+ required: ['concept', 'label', 'required', 'edited'],
11
+ allowed: ['concept', 'label', 'required', 'edited', 'order', 'defaultValue'],
12
+ },
13
+ 'accessible-name': {
14
+ required: ['concept', 'role', 'name', 'expectedName'],
15
+ allowed: ['concept', 'role', 'name', 'expectedName'],
16
+ },
17
+ 'extra-post-success-decision': {
18
+ required: ['concept', 'decision', 'beforeVisibleCompletion'],
19
+ allowed: ['concept', 'decision', 'beforeVisibleCompletion'],
20
+ },
21
+ 'visible-section': {
22
+ required: ['concept', 'visible'],
23
+ allowed: ['concept', 'visible', 'detail'],
24
+ },
25
+ terminology: {
26
+ required: ['concept', 'value', 'rawIdentifier'],
27
+ allowed: ['concept', 'value', 'rawIdentifier'],
28
+ },
29
+ 'unsupported-path': {
30
+ required: ['capability', 'currentScope', 'executable'],
31
+ allowed: ['capability', 'currentScope', 'executable'],
32
+ },
33
+ 'payload-assertion': {
34
+ required: ['concept', 'expected', 'present'],
35
+ allowed: ['concept', 'expected', 'present', 'value'],
36
+ },
37
+ 'action-result-visibility': {
38
+ required: ['concept', 'visible'],
39
+ allowed: ['concept', 'visible', 'value'],
40
+ },
41
+ });
42
+
43
+ export const OBSERVATION_TYPES = Object.freeze(Object.keys(OBSERVATION_DEFINITIONS));
44
+
45
+ export class ObservationError extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = 'ObservationError';
49
+ }
50
+ }
51
+
52
+ export function createObservation(value) {
53
+ const observation = structuredClone(value);
54
+ validateObservation(observation, 'observation');
55
+ return observation;
56
+ }
57
+
58
+ export function validateObservation(observation, path = 'observation') {
59
+ assertMap(observation, path);
60
+ assertExactKeys(observation, ['id', 'version', 'type', 'stepId', 'data'], path);
61
+ assertId(observation.id, `${path}.id`);
62
+ if (observation.version !== OBSERVATION_VERSION) {
63
+ throw new ObservationError(`${path}.version must be ${OBSERVATION_VERSION}`);
64
+ }
65
+ const definition = OBSERVATION_DEFINITIONS[observation.type];
66
+ if (!definition) throw new ObservationError(`${path}.type is unknown`);
67
+ assertId(observation.stepId, `${path}.stepId`);
68
+ assertMap(observation.data, `${path}.data`);
69
+ const keys = Object.keys(observation.data).sort();
70
+ const allowed = [...definition.allowed].sort();
71
+ if (keys.some((key) => !allowed.includes(key))) {
72
+ throw new ObservationError(`${path}.data has an unknown field`);
73
+ }
74
+ for (const key of definition.required) {
75
+ if (!Object.hasOwn(observation.data, key)) {
76
+ throw new ObservationError(`${path}.data.${key} is required`);
77
+ }
78
+ }
79
+ for (const [key, value] of Object.entries(observation.data)) {
80
+ if (!validFact(value)) {
81
+ throw new ObservationError(`${path}.data.${key} is not a factual scalar`);
82
+ }
83
+ }
84
+ return observation;
85
+ }
86
+
87
+ export function validateObservationRule(rule, path = 'rule') {
88
+ assertMap(rule, path);
89
+ assertExactKeys(
90
+ rule,
91
+ ['ruleId', 'useCaseId', 'journeyIds', 'observation', 'finding', 'policy'],
92
+ path,
93
+ );
94
+ assertId(rule.ruleId, `${path}.ruleId`);
95
+ assertId(rule.useCaseId, `${path}.useCaseId`);
96
+ if (
97
+ !Array.isArray(rule.journeyIds) ||
98
+ rule.journeyIds.some((journeyId) => typeof journeyId !== 'string' || !ID.test(journeyId))
99
+ ) {
100
+ throw new ObservationError(`${path}.journeyIds must contain safe ids`);
101
+ }
102
+ if (new Set(rule.journeyIds).size !== rule.journeyIds.length) {
103
+ throw new ObservationError(`${path}.journeyIds contains duplicates`);
104
+ }
105
+ assertMap(rule.observation, `${path}.observation`);
106
+ assertExactKeys(rule.observation, ['type', 'match'], `${path}.observation`);
107
+ const definition = OBSERVATION_DEFINITIONS[rule.observation.type];
108
+ if (!definition) throw new ObservationError(`${path}.observation.type is unknown`);
109
+ assertMap(rule.observation.match, `${path}.observation.match`);
110
+ if (Object.keys(rule.observation.match).length === 0) {
111
+ throw new ObservationError(`${path}.observation.match must not be empty`);
112
+ }
113
+ for (const [key, value] of Object.entries(rule.observation.match)) {
114
+ if (!definition.allowed.includes(key) || !validFact(value)) {
115
+ throw new ObservationError(`${path}.observation.match.${key} is invalid`);
116
+ }
117
+ }
118
+ assertMap(rule.finding, `${path}.finding`);
119
+ assertExactKeys(
120
+ rule.finding,
121
+ ['severity', 'dimension', 'type', 'summary', 'recommendation'],
122
+ `${path}.finding`,
123
+ );
124
+ if (!['low', 'medium', 'high', 'critical'].includes(rule.finding.severity)) {
125
+ throw new ObservationError(`${path}.finding.severity is invalid`);
126
+ }
127
+ if (
128
+ ![
129
+ 'efficiency',
130
+ 'clarity',
131
+ 'feedback-and-recovery',
132
+ 'accessibility',
133
+ 'consistency',
134
+ ].includes(rule.finding.dimension)
135
+ ) {
136
+ throw new ObservationError(`${path}.finding.dimension is invalid`);
137
+ }
138
+ if (!['requirement', 'recommendation'].includes(rule.finding.type)) {
139
+ throw new ObservationError(`${path}.finding.type is invalid`);
140
+ }
141
+ assertText(rule.finding.summary, `${path}.finding.summary`);
142
+ assertText(rule.finding.recommendation, `${path}.finding.recommendation`);
143
+ if (!Array.isArray(rule.policy) || rule.policy.length === 0) {
144
+ throw new ObservationError(`${path}.policy must be a non-empty array`);
145
+ }
146
+ for (const [index, reference] of rule.policy.entries()) {
147
+ const referencePath = `${path}.policy[${index}]`;
148
+ assertMap(reference, referencePath);
149
+ assertExactKeys(reference, ['source', 'field', 'statement'], referencePath);
150
+ if (!['use-case-requirement', 'owner-approved-journey'].includes(reference.source)) {
151
+ throw new ObservationError(`${referencePath}.source is invalid`);
152
+ }
153
+ if (
154
+ !['requirements', 'intent.summary', 'intent.steps', 'intent.success'].includes(
155
+ reference.field,
156
+ )
157
+ ) {
158
+ throw new ObservationError(`${referencePath}.field is invalid`);
159
+ }
160
+ if (
161
+ (reference.source === 'use-case-requirement') !==
162
+ (reference.field === 'requirements')
163
+ ) {
164
+ throw new ObservationError(`${referencePath} source and field do not agree`);
165
+ }
166
+ assertText(reference.statement, `${referencePath}.statement`);
167
+ }
168
+ return rule;
169
+ }
170
+
171
+ export function evaluateObservationPolicy(policy, journeys) {
172
+ if (!Array.isArray(policy?.rules)) {
173
+ throw new ObservationError('policy.rules must be an array');
174
+ }
175
+ if (!Array.isArray(journeys)) throw new ObservationError('journeys must be an array');
176
+ const byRule = new Map();
177
+ for (const [ruleIndex, rule] of policy.rules.entries()) {
178
+ validateObservationRule(rule, `policy.rules[${ruleIndex}]`);
179
+ for (const journey of journeys) {
180
+ if (journey.useCaseId !== rule.useCaseId) continue;
181
+ if (rule.journeyIds.length && !rule.journeyIds.includes(journey.journeyId)) continue;
182
+ const matches = (journey.observations ?? []).filter(
183
+ (observation) =>
184
+ observation.type === rule.observation.type &&
185
+ Object.entries(rule.observation.match).every(
186
+ ([key, value]) => observation.data[key] === value,
187
+ ),
188
+ );
189
+ if (matches.length === 0) continue;
190
+ const finding =
191
+ byRule.get(rule.ruleId) ??
192
+ {
193
+ id: `finding.${rule.ruleId}`,
194
+ ruleId: rule.ruleId,
195
+ severity: rule.finding.severity,
196
+ dimension: rule.finding.dimension,
197
+ type: rule.finding.type,
198
+ summary: rule.finding.summary,
199
+ policy: structuredClone(rule.policy),
200
+ recommendation: rule.finding.recommendation,
201
+ journeyRefs: [],
202
+ evidence: [],
203
+ };
204
+ const journeyRef = journeyRecordId(journey.useCaseId, journey.journeyId);
205
+ if (!finding.journeyRefs.includes(journeyRef)) finding.journeyRefs.push(journeyRef);
206
+ for (const observation of matches) {
207
+ finding.evidence.push({
208
+ id: `evidence.${rule.ruleId}.${observation.id}`,
209
+ journeyRef,
210
+ observationRef: observation.id,
211
+ stepId: observation.stepId,
212
+ facts: Object.entries(observation.data)
213
+ .sort(([left], [right]) => left.localeCompare(right))
214
+ .map(([key, value]) => ({ key, value })),
215
+ });
216
+ }
217
+ byRule.set(rule.ruleId, finding);
218
+ }
219
+ }
220
+ return [...byRule.values()]
221
+ .map((finding) => ({
222
+ ...finding,
223
+ journeyRefs: finding.journeyRefs.sort(),
224
+ evidence: finding.evidence.sort((left, right) => left.id.localeCompare(right.id)),
225
+ }))
226
+ .sort((left, right) => left.ruleId.localeCompare(right.ruleId));
227
+ }
228
+
229
+ export function journeyRecordId(useCaseId, journeyId) {
230
+ return `journey.${useCaseId}.${journeyId}`;
231
+ }
232
+
233
+ function validFact(value) {
234
+ return (
235
+ typeof value === 'string' ||
236
+ typeof value === 'boolean' ||
237
+ (Number.isSafeInteger(value) && value >= 0)
238
+ );
239
+ }
240
+
241
+ function assertMap(value, path) {
242
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
243
+ throw new ObservationError(`${path} must be an object`);
244
+ }
245
+ }
246
+
247
+ function assertExactKeys(value, expected, path) {
248
+ const actual = Object.keys(value).sort();
249
+ const wanted = [...expected].sort();
250
+ if (
251
+ actual.length !== wanted.length ||
252
+ actual.some((key, index) => key !== wanted[index])
253
+ ) {
254
+ throw new ObservationError(`${path} must contain ${wanted.join(', ')} only`);
255
+ }
256
+ }
257
+
258
+ function assertId(value, path) {
259
+ if (typeof value !== 'string' || !ID.test(value)) {
260
+ throw new ObservationError(`${path} has invalid id`);
261
+ }
262
+ }
263
+
264
+ function assertText(value, path) {
265
+ if (typeof value !== 'string' || !value.trim()) {
266
+ throw new ObservationError(`${path} must be non-empty text`);
267
+ }
268
+ }
@@ -0,0 +1,247 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { resolveExistingRepositoryPath } from './config.mjs';
4
+ import { ConfigError } from './yaml.mjs';
5
+
6
+ export const DEBT_RULES = [
7
+ 'inline-style',
8
+ 'px-literal',
9
+ 'raw-button',
10
+ 'icon-library',
11
+ 'hard-coded-color',
12
+ ];
13
+
14
+ const PX = /(?<![\w.-])\d+(?:\.\d+)?px\b/g;
15
+ const HEX = /(?:^|[\s,(:])#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{4}|[0-9a-fA-F]{3})(?![\w-])/g;
16
+ const COLOR_FUNCTION = /\b(?:rgba?|hsla?)\(/g;
17
+
18
+ export function listSourceFiles(root, config) {
19
+ const { roots, extensions, exclude } = config.patterns;
20
+ const files = [];
21
+ const walk = (dir) => {
22
+ let entries;
23
+ try {
24
+ entries = readdirSync(dir, { withFileTypes: true });
25
+ } catch {
26
+ throw new ConfigError(`pattern root ${relative(root, dir) || '.'} could not be read from the working tree`);
27
+ }
28
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
29
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
30
+ const full = join(dir, entry.name);
31
+ if (entry.isDirectory()) {
32
+ walk(full);
33
+ continue;
34
+ }
35
+ if (!extensions.some((extension) => entry.name.endsWith(extension))) continue;
36
+ if (exclude.some((suffix) => entry.name.endsWith(suffix))) continue;
37
+ files.push(relative(root, full).split(sep).join('/'));
38
+ }
39
+ };
40
+ for (const scanRoot of roots) {
41
+ walk(resolveExistingRepositoryPath(root, scanRoot, `pattern root ${scanRoot}`, true));
42
+ }
43
+ if (files.length === 0) throw new ConfigError('pattern scan found no source files');
44
+ return files.sort();
45
+ }
46
+
47
+ // scanSource returns control-prop values and debt counts for one file.
48
+ export function scanSource(ts, fileName, text, config) {
49
+ const { components, icons } = config.patterns;
50
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
51
+ const controls = [];
52
+ const debt = Object.fromEntries(DEBT_RULES.map((rule) => [rule, 0]));
53
+ const localComponents = new Map();
54
+
55
+ for (const statement of source.statements) {
56
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
57
+ const moduleName = statement.moduleSpecifier.text;
58
+ if (isIconModule(moduleName, icons) && !icons.allowed.includes(moduleName)) debt['icon-library'] += 1;
59
+ if (moduleName !== components.module) continue;
60
+ const bindings = statement.importClause?.namedBindings;
61
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
62
+ for (const element of bindings.elements) {
63
+ const imported = (element.propertyName ?? element.name).text;
64
+ if (components.names.includes(imported)) localComponents.set(element.name.text, imported);
65
+ }
66
+ }
67
+
68
+ const visit = (node) => {
69
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
70
+ const tag = node.tagName.getText(source);
71
+ if (tag === 'button') debt['raw-button'] += 1;
72
+ const component = localComponents.get(tag);
73
+ for (const attribute of node.attributes.properties) {
74
+ if (!ts.isJsxAttribute(attribute)) continue;
75
+ const name = attribute.name.getText(source);
76
+ if (name === 'style' && attribute.initializer && ts.isJsxExpression(attribute.initializer)) {
77
+ debt['inline-style'] += 1;
78
+ }
79
+ if (component && components.props.includes(name)) {
80
+ for (const value of attributeValues(ts, attribute)) {
81
+ controls.push({ key: `${component}.${name}`, value });
82
+ }
83
+ }
84
+ }
85
+ }
86
+ if (ts.isStringLiteralLike(node) && !ts.isImportDeclaration(node.parent) && !isFragmentLink(ts, node)) {
87
+ countText(node.text, debt);
88
+ } else if (ts.isTemplateExpression(node)) {
89
+ countText(node.head.text, debt);
90
+ for (const span of node.templateSpans) countText(span.literal.text, debt);
91
+ } else if (ts.isJsxText(node)) {
92
+ countText(node.text, debt);
93
+ }
94
+ ts.forEachChild(node, visit);
95
+ };
96
+ visit(source);
97
+ return { controls, debt };
98
+ }
99
+
100
+ // `href="#add"` is a fragment link, not the color #add.
101
+ function isFragmentLink(ts, node) {
102
+ return ts.isJsxAttribute(node.parent) && node.parent.name.getText() === 'href';
103
+ }
104
+
105
+ function isIconModule(moduleName, icons) {
106
+ return icons.modules.some((prefix) => moduleName === prefix || moduleName.startsWith(`${prefix}/`));
107
+ }
108
+
109
+ function countText(text, debt) {
110
+ debt['px-literal'] += text.match(PX)?.length ?? 0;
111
+ debt['hard-coded-color'] += (text.match(HEX)?.length ?? 0) + (text.match(COLOR_FUNCTION)?.length ?? 0);
112
+ }
113
+
114
+ // A conditional whose branches are literals contributes each literal, so
115
+ // `{active ? 'filled' : 'light'}` reads as filled and light.
116
+ function attributeValues(ts, attribute) {
117
+ const init = attribute.initializer;
118
+ if (!init) return ['true'];
119
+ if (ts.isStringLiteral(init)) return [init.text];
120
+ if (ts.isJsxExpression(init) && init.expression) return expressionValues(ts, init.expression);
121
+ return ['dynamic'];
122
+ }
123
+
124
+ function expressionValues(ts, expression) {
125
+ while (ts.isParenthesizedExpression(expression)) expression = expression.expression;
126
+ if (ts.isStringLiteralLike(expression) || ts.isNumericLiteral(expression)) return [expression.text];
127
+ if (ts.isConditionalExpression(expression)) {
128
+ return [...expressionValues(ts, expression.whenTrue), ...expressionValues(ts, expression.whenFalse)];
129
+ }
130
+ return ['dynamic'];
131
+ }
132
+
133
+ export function scanFiles(ts, root, config, files) {
134
+ const inventory = Object.create(null);
135
+ const debt = Object.fromEntries(DEBT_RULES.map((rule) => [rule, Object.create(null)]));
136
+ for (const file of files) {
137
+ let text;
138
+ try {
139
+ text = readFileSync(resolveExistingRepositoryPath(root, file, `pattern source ${file}`), 'utf8');
140
+ } catch (error) {
141
+ if (error instanceof ConfigError) throw error;
142
+ throw new ConfigError(`pattern source ${file} could not be read from the working tree`);
143
+ }
144
+ const result = scanSource(ts, file, text, config);
145
+ for (const { key, value } of result.controls) {
146
+ inventory[key] ??= Object.create(null);
147
+ inventory[key][value] = (inventory[key][value] ?? 0) + 1;
148
+ }
149
+ for (const rule of DEBT_RULES) {
150
+ if (result.debt[rule] > 0) debt[rule][file] = result.debt[rule];
151
+ }
152
+ }
153
+ return { files, inventory, debt };
154
+ }
155
+
156
+ export function baselineFromScan(scan) {
157
+ const controlValues = {};
158
+ for (const key of Object.keys(scan.inventory).sort()) {
159
+ controlValues[key] = Object.keys(scan.inventory[key]).sort();
160
+ }
161
+ const debt = {};
162
+ for (const rule of DEBT_RULES) {
163
+ debt[rule] = Object.fromEntries(Object.entries(scan.debt[rule]).sort(([a], [b]) => a.localeCompare(b)));
164
+ }
165
+ return { version: 1, controlValues, debt };
166
+ }
167
+
168
+ export function validateBaseline(baseline) {
169
+ if (!isRecord(baseline) || baseline.version !== 1 || !isRecord(baseline.controlValues) || !isRecord(baseline.debt)) {
170
+ throw new ConfigError('pattern baseline is malformed');
171
+ }
172
+ for (const rule of DEBT_RULES) {
173
+ const counts = baseline.debt[rule];
174
+ if (!isRecord(counts)) throw new ConfigError(`pattern baseline lacks ${rule}`);
175
+ for (const [file, count] of Object.entries(counts)) {
176
+ if (!Number.isInteger(count) || count < 1) {
177
+ throw new ConfigError(`pattern baseline has an invalid ${rule} count for ${file}`);
178
+ }
179
+ }
180
+ }
181
+ for (const [key, values] of Object.entries(baseline.controlValues)) {
182
+ if (
183
+ !Array.isArray(values) ||
184
+ values.some((value) => typeof value !== 'string') ||
185
+ new Set(values).size !== values.length
186
+ ) {
187
+ throw new ConfigError(`pattern baseline has invalid values for ${key}`);
188
+ }
189
+ }
190
+ return baseline;
191
+ }
192
+
193
+ export function compare(scan, baseline) {
194
+ const findings = [];
195
+ const stale = [];
196
+ for (const [key, counts] of Object.entries(scan.inventory).sort(([a], [b]) => a.localeCompare(b))) {
197
+ const known = new Set(Object.hasOwn(baseline.controlValues, key) ? baseline.controlValues[key] : []);
198
+ for (const [value, count] of Object.entries(counts).sort(([a], [b]) => a.localeCompare(b))) {
199
+ if (!known.has(value)) {
200
+ findings.push({ rule: 'new-control-value', key, value, count, message: `${key}=${value} is a new control value` });
201
+ }
202
+ }
203
+ }
204
+ for (const [key, values] of Object.entries(baseline.controlValues).sort(([a], [b]) => a.localeCompare(b))) {
205
+ for (const value of values) {
206
+ if (!scan.inventory[key]?.[value]) stale.push({ rule: 'unused-control-value', key, value });
207
+ }
208
+ }
209
+ for (const rule of DEBT_RULES) {
210
+ const current = scan.debt[rule];
211
+ const allowed = baseline.debt[rule];
212
+ for (const [file, count] of Object.entries(current).sort(([a], [b]) => a.localeCompare(b))) {
213
+ const limit = Object.hasOwn(allowed, file) ? allowed[file] : 0;
214
+ if (count > limit) {
215
+ findings.push({ rule, file, count, limit, message: `${file}: ${rule} grew from ${limit} to ${count}` });
216
+ }
217
+ }
218
+ for (const [file, limit] of Object.entries(allowed).sort(([a], [b]) => a.localeCompare(b))) {
219
+ const count = current[file] ?? 0;
220
+ if (count < limit) stale.push({ rule, file, count, limit });
221
+ }
222
+ }
223
+ return { findings, stale };
224
+ }
225
+
226
+ function isRecord(value) {
227
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
228
+ }
229
+
230
+ export function renderComparison(scan, result) {
231
+ const lines = [`Pattern scan: ${scan.files.length} files`];
232
+ for (const [key, counts] of Object.entries(scan.inventory).sort(([a], [b]) => a.localeCompare(b))) {
233
+ const summary = Object.entries(counts)
234
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
235
+ .map(([value, count]) => `${value} ${count}`)
236
+ .join(', ');
237
+ lines.push(` ${key}: ${summary}`);
238
+ }
239
+ for (const rule of DEBT_RULES) {
240
+ const total = Object.values(scan.debt[rule]).reduce((sum, count) => sum + count, 0);
241
+ lines.push(` ${rule}: ${total} in ${Object.keys(scan.debt[rule]).length} files`);
242
+ }
243
+ lines.push(`Findings: ${result.findings.length}`);
244
+ for (const finding of result.findings) lines.push(` - ${finding.rule}: ${finding.message}`);
245
+ lines.push(`Stale baseline entries: ${result.stale.length}`);
246
+ return `${lines.join('\n')}\n`;
247
+ }