@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.
package/lib/config.mjs ADDED
@@ -0,0 +1,209 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { ConfigError } from './yaml.mjs';
6
+
7
+ export const CONFIG_FILE = '.uxguard.json';
8
+
9
+ const require = createRequire(import.meta.url);
10
+
11
+ // Resolve an untrusted ref to a commit before constructing object names. Besides
12
+ // producing consistent reads, this prevents ref text from being interpreted as
13
+ // an option or as part of a different rev/path expression.
14
+ export function resolveTrustedRevision(root, ref) {
15
+ if (!ref) return null;
16
+ try {
17
+ const commit = execFileSync('git', ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`], {
18
+ cwd: root,
19
+ encoding: 'utf8',
20
+ stdio: ['ignore', 'pipe', 'pipe'],
21
+ }).trim();
22
+ if (!/^[0-9a-f]{40,64}$/i.test(commit)) throw new Error('unexpected object id');
23
+ return { ref, commit };
24
+ } catch {
25
+ throw new ConfigError(`trusted revision ${ref} is not a commit`);
26
+ }
27
+ }
28
+
29
+ // readTrusted returns a file from the working tree, or from a previously
30
+ // resolved trusted commit. A missing trusted file is an error, never an empty
31
+ // policy.
32
+ export function readTrusted(root, path, trust) {
33
+ if (!trust) {
34
+ const full = resolveExistingRepositoryPath(root, path, path);
35
+ if (!existsSync(full)) throw new ConfigError(`${path} does not exist`);
36
+ return readFileSync(full, 'utf8');
37
+ }
38
+ try {
39
+ return execFileSync('git', ['show', `${trust.commit}:${path}`], {
40
+ cwd: root,
41
+ encoding: 'utf8',
42
+ stdio: ['ignore', 'pipe', 'pipe'],
43
+ });
44
+ } catch {
45
+ throw new ConfigError(`${path} is not present at trusted revision ${trust.ref}`);
46
+ }
47
+ }
48
+
49
+ export function trustedFileExists(root, path, trust) {
50
+ resolveRepositoryPath(root, path, path);
51
+ if (!trust) return existsSync(join(root, path));
52
+ try {
53
+ execFileSync('git', ['cat-file', '-e', `${trust.commit}:${path}`], {
54
+ cwd: root,
55
+ stdio: ['ignore', 'ignore', 'ignore'],
56
+ });
57
+ return true;
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+
63
+ export function loadConfig(root, trust) {
64
+ let config;
65
+ try {
66
+ config = JSON.parse(readTrusted(root, CONFIG_FILE, trust));
67
+ } catch (error) {
68
+ if (error instanceof ConfigError) throw error;
69
+ throw new ConfigError(`${CONFIG_FILE} is not valid JSON`);
70
+ }
71
+ return validateConfig(config);
72
+ }
73
+
74
+ export function validateConfig(config) {
75
+ const fail = (message) => {
76
+ throw new ConfigError(`${CONFIG_FILE}: ${message}`);
77
+ };
78
+ const strings = (value) => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'string' && item);
79
+ if (config?.version !== 2) fail('version must be 2');
80
+ if (Object.hasOwn(config, 'typescript')) {
81
+ fail('typescript paths are not accepted; ux-guard uses its exact package dependency');
82
+ }
83
+ const { catalog, journeys, visuals, patterns } = config;
84
+ if (typeof catalog?.path !== 'string' || !strings(catalog.navigation)) {
85
+ fail('catalog needs path and navigation files');
86
+ }
87
+ assertPolicyPath(catalog.path, 'catalog.path', fail);
88
+ for (const path of catalog.navigation) assertPolicyPath(path, 'catalog.navigation entries', fail);
89
+ if (journeys !== undefined) {
90
+ if (
91
+ journeys === null ||
92
+ typeof journeys !== 'object' ||
93
+ Array.isArray(journeys) ||
94
+ typeof journeys.policy !== 'string' ||
95
+ typeof journeys.report !== 'string'
96
+ ) {
97
+ fail('journeys needs policy and report paths');
98
+ }
99
+ assertPolicyPath(journeys.policy, 'journeys.policy', fail);
100
+ assertPolicyPath(journeys.report, 'journeys.report', fail);
101
+ for (const field of ['targets', 'baseline']) {
102
+ if (journeys[field] !== undefined) {
103
+ if (typeof journeys[field] !== 'string' || !journeys[field]) {
104
+ fail(`journeys.${field} must be a repository-relative path`);
105
+ }
106
+ assertPolicyPath(journeys[field], `journeys.${field}`, fail);
107
+ }
108
+ }
109
+ const journeyPaths = [
110
+ journeys.policy,
111
+ journeys.report,
112
+ journeys.targets,
113
+ journeys.baseline,
114
+ ].filter(Boolean);
115
+ if (journeyPaths.includes(CONFIG_FILE)) {
116
+ fail(`journey paths cannot be ${CONFIG_FILE}`);
117
+ }
118
+ if (new Set(journeyPaths).size !== journeyPaths.length) {
119
+ fail('journey policy, report, targets, and baseline paths must be different');
120
+ }
121
+ }
122
+ if (visuals !== undefined) {
123
+ if (
124
+ visuals === null ||
125
+ typeof visuals !== 'object' ||
126
+ Array.isArray(visuals) ||
127
+ !['profiles', 'checkpoints', 'candidate', 'baseline'].every(
128
+ (field) => typeof visuals?.[field] === 'string' && visuals[field],
129
+ )
130
+ ) {
131
+ fail('visuals needs profiles, checkpoints, candidate, and baseline paths');
132
+ }
133
+ for (const field of ['profiles', 'checkpoints', 'candidate', 'baseline']) {
134
+ assertPolicyPath(visuals[field], `visuals.${field}`, fail);
135
+ }
136
+ if (new Set(Object.values(visuals)).size !== 4) {
137
+ fail('visual profile, checkpoint, candidate, and baseline paths must be different');
138
+ }
139
+ if (Object.values(visuals).includes(CONFIG_FILE)) {
140
+ fail(`visual paths cannot be ${CONFIG_FILE}`);
141
+ }
142
+ }
143
+ if (!strings(patterns?.roots) || !strings(patterns.extensions) || !Array.isArray(patterns.exclude)) {
144
+ fail('patterns needs roots, extensions, and exclude');
145
+ }
146
+ for (const path of patterns.roots) assertPolicyPath(path, 'patterns.roots entries', fail, true);
147
+ if (!patterns.extensions.every((value) => /^\.[a-z0-9]+$/i.test(value))) {
148
+ fail('patterns.extensions entries must be file extensions');
149
+ }
150
+ if (!patterns.exclude.every((value) => typeof value === 'string' && value)) {
151
+ fail('patterns.exclude entries must be non-empty strings');
152
+ }
153
+ if (typeof patterns.baseline !== 'string' || !patterns.baseline) fail('patterns needs a baseline path');
154
+ assertPolicyPath(patterns.baseline, 'patterns.baseline', fail);
155
+ if (patterns.baseline === CONFIG_FILE) fail(`patterns.baseline cannot be ${CONFIG_FILE}`);
156
+ const { components, icons } = patterns;
157
+ if (typeof components?.module !== 'string' || !strings(components.names) || !strings(components.props)) {
158
+ fail('patterns.components needs module, names, and props');
159
+ }
160
+ if (!strings(icons?.modules) || !Array.isArray(icons.allowed)) fail('patterns.icons needs modules and allowed');
161
+ return config;
162
+ }
163
+
164
+ export function resolveRepositoryPath(root, path, label, allowDot = false) {
165
+ const fail = (message) => {
166
+ throw new ConfigError(message);
167
+ };
168
+ assertPolicyPath(path, label, fail, allowDot);
169
+ return resolve(root, path);
170
+ }
171
+
172
+ export function resolveExistingRepositoryPath(root, path, label, allowDot = false) {
173
+ const full = resolveRepositoryPath(root, path, label, allowDot);
174
+ let realRoot;
175
+ let realPath;
176
+ try {
177
+ realRoot = realpathSync(root);
178
+ realPath = realpathSync(full);
179
+ } catch {
180
+ throw new ConfigError(`${label} does not exist in the working tree`);
181
+ }
182
+ const fromRoot = relative(realRoot, realPath);
183
+ if (fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
184
+ throw new ConfigError(`${label} resolves outside the repository`);
185
+ }
186
+ return full;
187
+ }
188
+
189
+ function assertPolicyPath(value, label, fail, allowDot = false) {
190
+ if (typeof value !== 'string' || !value || value.includes('\0')) fail(`${label} must be a repository-relative path`);
191
+ if (isAbsolute(value) || /^[a-z]:[\\/]/i.test(value) || value.startsWith('\\\\')) {
192
+ fail(`${label} must be a repository-relative path`);
193
+ }
194
+ if (value.includes('\\')) fail(`${label} must use forward slashes`);
195
+ const parts = value.split('/');
196
+ if (parts.some((part) => part === '' || part === '..') || (!allowDot && parts.every((part) => part === '.'))) {
197
+ fail(`${label} must stay within the repository`);
198
+ }
199
+ }
200
+
201
+ export function loadTypeScript() {
202
+ try {
203
+ const ts = require('typescript');
204
+ if (typeof ts.createSourceFile !== 'function') throw new Error('invalid compiler API');
205
+ return ts;
206
+ } catch {
207
+ throw new ConfigError('ux-guard exact TypeScript dependency is not installed');
208
+ }
209
+ }