visual-regression-ci 0.0.0-stage → 0.9.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +953 -2
  3. package/package.json +76 -4
  4. package/src/ci/actionReport.js +340 -0
  5. package/src/ci/prComment.js +420 -0
  6. package/src/cli/capture.js +243 -0
  7. package/src/cli/compare.js +190 -0
  8. package/src/cli/config.js +287 -0
  9. package/src/cli/database.js +69 -0
  10. package/src/cli/display.js +119 -0
  11. package/src/cli/errors.js +17 -0
  12. package/src/cli/index.js +577 -0
  13. package/src/cli/installBrowsers.js +59 -0
  14. package/src/cli/invocation.js +66 -0
  15. package/src/cli/jsonTarget.js +100 -0
  16. package/src/cli/logger.js +15 -0
  17. package/src/cli/manifest.js +139 -0
  18. package/src/cli/naming.js +60 -0
  19. package/src/cli/reporter.js +172 -0
  20. package/src/cli/result.js +225 -0
  21. package/src/cli/serve.js +64 -0
  22. package/src/server/app.js +135 -0
  23. package/src/server/db.js +691 -0
  24. package/src/server/importRuns.js +837 -0
  25. package/src/server/paths.js +107 -0
  26. package/src/server/public/css/styles.css +2362 -0
  27. package/src/server/public/js/common.js +32 -0
  28. package/src/server/public/js/dashboard.js +140 -0
  29. package/src/server/public/js/import-upload.js +169 -0
  30. package/src/server/public/js/review-actions.js +379 -0
  31. package/src/server/public/js/shortcuts.js +242 -0
  32. package/src/server/public/js/slider.js +104 -0
  33. package/src/server/public/js/tabs.js +85 -0
  34. package/src/server/public/js/theme.js +83 -0
  35. package/src/server/routes/api.js +141 -0
  36. package/src/server/routes/views.js +68 -0
  37. package/src/server/security.js +79 -0
  38. package/src/server/uploadImport.js +227 -0
  39. package/src/server/urls.js +31 -0
  40. package/src/server/viewModels.js +366 -0
  41. package/src/server/views/history.ejs +111 -0
  42. package/src/server/views/index.ejs +283 -0
  43. package/src/server/views/layout.ejs +11 -0
  44. package/src/server/views/partials/footer.ejs +11 -0
  45. package/src/server/views/partials/header.ejs +93 -0
  46. package/src/server/views/run-detail.ejs +295 -0
  47. package/src/shared/packageSpec.js +49 -0
  48. package/src/shared/text.js +59 -0
@@ -0,0 +1,190 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import pixelmatch from 'pixelmatch';
5
+ import { PNG } from 'pngjs';
6
+ import { getSnapshotFilename } from './naming.js';
7
+
8
+ /** pixelmatch per-pixel colour sensitivity (0 = exact, 1 = lenient) used by default. */
9
+ export const DEFAULT_PIXELMATCH_THRESHOLD = 0.1;
10
+
11
+ /**
12
+ * Pads a PNG image to target dimensions if it is smaller than maxWidth or maxHeight.
13
+ * The padded canvas is transparent (RGBA: 0, 0, 0, 0).
14
+ *
15
+ * @param {PNG} png - Original decoded PNG instance
16
+ * @param {number} targetWidth - Width to pad to
17
+ * @param {number} targetHeight - Height to pad to
18
+ * @returns {PNG} The padded PNG instance or original if already matching
19
+ */
20
+ export function padImage(png, targetWidth, targetHeight) {
21
+ if (png.width === targetWidth && png.height === targetHeight) {
22
+ return png;
23
+ }
24
+
25
+ const padded = new PNG({ width: targetWidth, height: targetHeight });
26
+ // PNG instances in pngjs default to all zeros (transparent RGBA: 0, 0, 0, 0)
27
+ PNG.bitblt(png, padded, 0, 0, png.width, png.height, 0, 0);
28
+ return padded;
29
+ }
30
+
31
+ /**
32
+ * Compares two PNG buffers pixel-by-pixel, automatically normalizing canvas dimensions.
33
+ *
34
+ * @param {Buffer} baselineBuffer - Baseline PNG file buffer
35
+ * @param {Buffer} currentBuffer - Current screenshot PNG file buffer
36
+ * @param {object} [options={}] - Comparison options
37
+ * @param {number} [options.threshold=0.1] - Pixelmatch color sensitivity threshold (0 to 1)
38
+ * @returns {object} Comparison results and diff PNG
39
+ */
40
+ export function compareImages(baselineBuffer, currentBuffer, options = {}) {
41
+ const img1 = PNG.sync.read(baselineBuffer);
42
+ const img2 = PNG.sync.read(currentBuffer);
43
+
44
+ const maxWidth = Math.max(img1.width, img2.width);
45
+ const maxHeight = Math.max(img1.height, img2.height);
46
+
47
+ const padded1 = padImage(img1, maxWidth, maxHeight);
48
+ const padded2 = padImage(img2, maxWidth, maxHeight);
49
+
50
+ const diff = new PNG({ width: maxWidth, height: maxHeight });
51
+ const pixelmatchThreshold = options.threshold !== undefined ? options.threshold : DEFAULT_PIXELMATCH_THRESHOLD;
52
+
53
+ const mismatchedPixels = pixelmatch(
54
+ padded1.data,
55
+ padded2.data,
56
+ diff.data,
57
+ maxWidth,
58
+ maxHeight,
59
+ {
60
+ threshold: pixelmatchThreshold,
61
+ includeAA: false, // detect anti-aliasing to avoid false positive edge blur
62
+ diffColor: [255, 0, 0], // highlight differences in bright red
63
+ diffColorAlt: [255, 0, 0]
64
+ }
65
+ );
66
+
67
+ const totalPixels = maxWidth * maxHeight;
68
+ const mismatchPercentage = totalPixels > 0
69
+ ? Number(((mismatchedPixels / totalPixels) * 100).toFixed(4))
70
+ : 0;
71
+
72
+ return {
73
+ mismatchedPixels,
74
+ totalPixels,
75
+ mismatchPercentage,
76
+ diffPng: diff,
77
+ diffBuffer: PNG.sync.write(diff),
78
+ dimensions: {
79
+ baseline: { width: img1.width, height: img1.height },
80
+ current: { width: img2.width, height: img2.height },
81
+ diff: { width: maxWidth, height: maxHeight },
82
+ padded: img1.width !== img2.width || img1.height !== img2.height
83
+ }
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Recorded as baseline_sha256 when a run found no baseline at all, so approval can
89
+ * later require that there still is none (independent of the snapshot's status).
90
+ */
91
+ export const NO_BASELINE = 'none';
92
+
93
+ /**
94
+ * @param {Buffer} buffer
95
+ * @returns {string} Hex SHA-256 digest
96
+ */
97
+ export function sha256(buffer) {
98
+ return crypto.createHash('sha256').update(buffer).digest('hex');
99
+ }
100
+
101
+ /**
102
+ * Compares a single captured snapshot against its baseline master.
103
+ * Handles initial baseline promotion if no baseline exists yet.
104
+ *
105
+ * @param {object} snapshot - Captured snapshot metadata
106
+ * @param {string} snapshot.route - Page route
107
+ * @param {string} snapshot.viewport - Viewport name
108
+ * @param {string} snapshot.filepath - Current screenshot filepath
109
+ * @param {object} options - Execution options
110
+ * @param {string} options.baselinesDir - Directory where approved baselines live
111
+ * @param {string} options.diffDir - Directory where diff images should be saved
112
+ * @param {number} [options.allowedThreshold=0.01] - Max allowed mismatch percentage ratio (0.01 = 1%)
113
+ * @param {number} [options.pixelmatchThreshold=0.1] - Color sensitivity for pixelmatch
114
+ * @param {boolean} [options.createMissingBaselines=true] - When false (strict/CI mode), a missing
115
+ * baseline is reported as MISSING_BASELINE instead of being created from the current screenshot
116
+ * @returns {object} Snapshot comparison record. baselineSnapshotPath is a per-run copy of the
117
+ * compared baseline; baselineSha256 lets approval detect that the shared baseline moved on.
118
+ */
119
+ export function compareSnapshot(snapshot, options) {
120
+ const { route, viewport, filepath: currentPath } = snapshot;
121
+ const baselinesDir = options.baselinesDir;
122
+ const diffDir = options.diffDir;
123
+ const allowedThresholdRatio = options.allowedThreshold !== undefined ? options.allowedThreshold : 0.01;
124
+ const allowedPercentage = allowedThresholdRatio * 100;
125
+
126
+ fs.mkdirSync(baselinesDir, { recursive: true });
127
+ fs.mkdirSync(diffDir, { recursive: true });
128
+
129
+ const filename = getSnapshotFilename(route, viewport);
130
+ const baselinePath = path.join(baselinesDir, filename);
131
+ const diffFilename = `${path.parse(filename).name}-diff.png`;
132
+ const diffPath = path.join(diffDir, diffFilename);
133
+ // Copy of the exact baseline this run compared against. storage/baselines/ keeps
134
+ // changing as later runs are approved; the run's own record must not.
135
+ // Kept in a subfolder so it can't collide with another viewport's screenshot.
136
+ const baselineSnapshotPath = path.join(diffDir, 'baselines', filename);
137
+
138
+ // No baseline yet: either adopt the current screenshot (local first run) or,
139
+ // in strict mode, fail so CI can never "pass" by comparing a page to itself.
140
+ if (!fs.existsSync(baselinePath)) {
141
+ const createBaseline = options.createMissingBaselines !== false;
142
+ if (createBaseline) fs.copyFileSync(currentPath, baselinePath);
143
+ return {
144
+ // NEW_BASELINE: the baseline *is* this run's screenshot. MISSING: there is none.
145
+ baselineSnapshotPath: createBaseline ? currentPath : null,
146
+ baselineSha256: createBaseline ? sha256(fs.readFileSync(currentPath)) : NO_BASELINE,
147
+ route,
148
+ viewport,
149
+ baselinePath,
150
+ currentPath,
151
+ diffPath: null,
152
+ mismatchedPixels: 0,
153
+ totalPixels: 0,
154
+ mismatchPercentage: 0,
155
+ status: createBaseline ? 'NEW_BASELINE' : 'MISSING_BASELINE',
156
+ dimensions: null
157
+ };
158
+ }
159
+
160
+ // Baseline exists: execute pixel-by-pixel comparison
161
+ const baselineBuffer = fs.readFileSync(baselinePath);
162
+ fs.mkdirSync(path.dirname(baselineSnapshotPath), { recursive: true });
163
+ fs.writeFileSync(baselineSnapshotPath, baselineBuffer);
164
+ const currentBuffer = fs.readFileSync(currentPath);
165
+
166
+ const comparison = compareImages(baselineBuffer, currentBuffer, {
167
+ threshold: options.pixelmatchThreshold
168
+ });
169
+
170
+ // Write diff image to disk
171
+ fs.writeFileSync(diffPath, comparison.diffBuffer);
172
+
173
+ const isMatch = comparison.mismatchedPixels === 0 || comparison.mismatchPercentage <= allowedPercentage;
174
+ const status = isMatch ? 'MATCH' : 'DIFF';
175
+
176
+ return {
177
+ route,
178
+ viewport,
179
+ baselinePath,
180
+ baselineSnapshotPath,
181
+ baselineSha256: sha256(baselineBuffer),
182
+ currentPath,
183
+ diffPath,
184
+ mismatchedPixels: comparison.mismatchedPixels,
185
+ totalPixels: comparison.totalPixels,
186
+ mismatchPercentage: comparison.mismatchPercentage,
187
+ status,
188
+ dimensions: comparison.dimensions
189
+ };
190
+ }
@@ -0,0 +1,287 @@
1
+ import fs from 'node:fs'; // imports the node js file system
2
+ import path from 'node:path';//helper function that glues folder names together correctly
3
+ import { assertUniqueSnapshotFiles } from './naming.js';
4
+ import { CliError } from './errors.js';
5
+ import { toDisplayPath } from './display.js';
6
+
7
+ /**
8
+ * Validates and normalizes visual regression test configuration.
9
+ *
10
+ * @param {object} config - Configuration object to validate
11
+ * @returns {object} Normalized configuration object
12
+ * @throws {Error} If configuration fails schema validation
13
+ */
14
+ export function validateConfig(config) {// when we use the export function that means other files in our project can use this function
15
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {// if the config is not an object or is not given or is an array
16
+ // then this block of code will be executed
17
+ throw new Error('Configuration must be a valid JSON object.');
18
+ }
19
+
20
+ // 1. Validate baseUrl
21
+ if (!config.baseUrl || typeof config.baseUrl !== 'string') {// if url in config is not given or is not a string then this block of code
22
+ // is executed
23
+ throw new Error('Invalid configuration: "baseUrl" is required and must be a string.');
24
+ }
25
+
26
+ let parsedUrl;
27
+ try {// this block of code checks if the base url is valid or is just gibberish and executes further code accordingly
28
+ parsedUrl = new URL(config.baseUrl);// this url method combines valid urls and throws an error for invalid urls
29
+ } catch {
30
+ throw new Error(`Invalid configuration: "baseUrl" must be a valid URL. Received: "${config.baseUrl}"`);
31
+ }
32
+
33
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {// checks the protocol that is being used in the url
34
+ throw new Error(`Invalid configuration: "baseUrl" protocol must be http: or https:. Received: "${parsedUrl.protocol}"`);
35
+ }
36
+
37
+ // Normalize baseUrl by stripping trailing slash
38
+ const normalizedBaseUrl = config.baseUrl.replace(/\/+$/, '');//autocleaner prevents the // error
39
+
40
+ // 2. Validate routes
41
+ if (!Array.isArray(config.routes) || config.routes.length === 0) {// checks if routes exist
42
+ throw new Error('Invalid configuration: "routes" must be a non-empty array of URL paths.');
43
+ }
44
+
45
+ const normalizedRoutes = config.routes.map((route, idx) => {// const.routes is the array of all routes the user gave us
46
+ //.map is a javascript function that iterates each item from the list, run its through a code block the output is obtained as a new list
47
+ // route and idx are the routes and indexes of the routes from the list
48
+ if (typeof route !== 'string' || route.trim() === '') {// route.trim removes the spaces from the string
49
+ throw new Error(`Invalid configuration: Route at index ${idx} must be a non-empty string.`);
50
+ }
51
+ const trimmed = route.trim();
52
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`; // returnes the trimmed variable by adding / automatically if someone forgets
53
+ });
54
+
55
+ // 3. Validate viewports
56
+ if (!Array.isArray(config.viewports) || config.viewports.length === 0) {// checks if viewports exist or not
57
+ throw new Error('Invalid configuration: "viewports" must be a non-empty array of viewport definitions.');
58
+ }
59
+
60
+ const viewportNames = new Set();
61
+ const normalizedViewports = config.viewports.map((vp, idx) => {
62
+ if (!vp || typeof vp !== 'object' || Array.isArray(vp)) {
63
+ throw new Error(`Invalid configuration: Viewport at index ${idx} must be an object with name, width, and height.`);
64
+ }
65
+
66
+ if (!vp.name || typeof vp.name !== 'string' || vp.name.trim() === '') {
67
+ throw new Error(`Invalid configuration: Viewport at index ${idx} must have a non-empty "name" string.`);
68
+ }
69
+
70
+ const trimmedName = vp.name.trim();
71
+ if (!/^[a-zA-Z0-9_-]+$/.test(trimmedName)) {// the code inside the /'s is a regular expression. It defines the exact pattern of
72
+ //characters that are allowed through the value
73
+ throw new Error(`Invalid configuration: Viewport "${trimmedName}" name may only contain alphanumeric characters, hyphens, and underscores.`);
74
+ }
75
+
76
+ if (viewportNames.has(trimmedName)) {// throws an error if 2 devices have the exact same viewport name
77
+ throw new Error(`Invalid configuration: Duplicate viewport name "${trimmedName}" found.`);
78
+ }
79
+ viewportNames.add(trimmedName);
80
+
81
+ if (typeof vp.width !== 'number' || !Number.isInteger(vp.width) || vp.width <= 0) {
82
+ throw new Error(`Invalid configuration: Viewport "${trimmedName}" width must be a positive integer. Received: ${vp.width}`);
83
+ }
84
+
85
+ if (typeof vp.height !== 'number' || !Number.isInteger(vp.height) || vp.height <= 0) {
86
+ throw new Error(`Invalid configuration: Viewport "${trimmedName}" height must be a positive integer. Received: ${vp.height}`);
87
+ }
88
+
89
+ return {
90
+ name: trimmedName,
91
+ width: vp.width,
92
+ height: vp.height
93
+ };
94
+ });
95
+
96
+ // Every route/viewport pair must get its own screenshot and diff file
97
+ assertUniqueSnapshotFiles(normalizedRoutes, normalizedViewports);
98
+
99
+ // 4. Validate maskSelectors (optional, defaults to [])
100
+ let normalizedMaskSelectors = [];// an empty list for the css selectors to hide. Default initialized so that If not specified by the user
101
+ // the code do not crash
102
+ if (config.maskSelectors !== undefined) {
103
+ if (!Array.isArray(config.maskSelectors)) {
104
+ throw new Error('Invalid configuration: "maskSelectors" must be an array of CSS selector strings.');
105
+ }
106
+ normalizedMaskSelectors = config.maskSelectors.map((sel, idx) => {
107
+ if (typeof sel !== 'string' || sel.trim() === '') {
108
+ throw new Error(`Invalid configuration: Mask selector at index ${idx} must be a non-empty string.`);
109
+ }
110
+ const trimmed = sel.trim();
111
+ if (trimmed.includes('{') || trimmed.includes('}')) {// prevent a famous vulnarability css injection
112
+ throw new Error(`Invalid configuration: Mask selector at index ${idx} contains invalid characters "{" or "}".`);
113
+ }
114
+ return trimmed;
115
+ });
116
+ }
117
+
118
+ // 5. Validate threshold (optional, defaults to 0.01)
119
+ let normalizedThreshold = 0.01;
120
+ if (config.threshold !== undefined) {
121
+ if (typeof config.threshold !== 'number' || Number.isNaN(config.threshold) || config.threshold < 0 || config.threshold > 1) {
122
+ throw new Error(`Invalid configuration: "threshold" must be a number between 0 and 1. Received: ${config.threshold}`);
123
+ }
124
+ normalizedThreshold = config.threshold;
125
+ }
126
+
127
+ // 6. Optional storageDir
128
+ const storageDir = validateStorageDir(config.storageDir);
129
+
130
+ return {
131
+ baseUrl: normalizedBaseUrl,
132
+ routes: normalizedRoutes,
133
+ viewports: normalizedViewports,
134
+ maskSelectors: normalizedMaskSelectors,
135
+ threshold: normalizedThreshold,
136
+ storageDir
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Validates the optional storageDir and returns it (default "storage").
142
+ * It must be a subdirectory of the project (cwd).
143
+ *
144
+ * @param {unknown} value
145
+ * @returns {string}
146
+ */
147
+ export function validateStorageDir(value) {
148
+ const storageDir = typeof value === 'string' && value.trim() !== '' ? value.trim() : 'storage';
149
+
150
+ // Compare path segments: a prefix check would accept "/proj-evil" for "/proj".
151
+ const relativeStorage = path.relative(process.cwd(), path.resolve(process.cwd(), storageDir));
152
+ if (relativeStorage === '') {
153
+ throw new Error('Invalid configuration: "storageDir" must be a subdirectory, not the project root itself.');
154
+ }
155
+ if (relativeStorage === '..' || relativeStorage.startsWith(`..${path.sep}`) || path.isAbsolute(relativeStorage)) {
156
+ throw new Error('Invalid configuration: "storageDir" must be located inside the project workspace.');
157
+ }
158
+ return storageDir;
159
+ }
160
+
161
+ /**
162
+ * Safely strips single-line (//) and multi-line (/* ... * /) comments from JSON strings
163
+ * while strictly preserving string literals (including URLs with //).
164
+ *
165
+ * @param {string} jsonString - Raw JSON string with potential comments
166
+ * @returns {string} Clean JSON string without comments
167
+ */
168
+ export function stripJsonComments(jsonString) {
169
+ const sanitizedInput = (jsonString || '').replace(/^\uFEFF/, '');
170
+ let insideString = false;
171
+ let isEscaped = false;
172
+ let result = '';
173
+
174
+ for (let i = 0; i < sanitizedInput.length; i++) {
175
+ const char = sanitizedInput[i];
176
+ const nextChar = sanitizedInput[i + 1];
177
+
178
+ if (insideString) {
179
+ result += char;
180
+ if (isEscaped) {
181
+ isEscaped = false;
182
+ } else if (char === '\\') {
183
+ isEscaped = true;
184
+ } else if (char === '"') {
185
+ insideString = false;
186
+ }
187
+ } else {
188
+ if (char === '"') {
189
+ insideString = true;
190
+ result += char;
191
+ } else if (char === '/' && nextChar === '/') {
192
+ while (i < sanitizedInput.length && sanitizedInput[i] !== '\n' && sanitizedInput[i] !== '\r') {
193
+ i++;
194
+ }
195
+ if (i < sanitizedInput.length) {
196
+ result += sanitizedInput[i];
197
+ }
198
+ } else if (char === '/' && nextChar === '*') {
199
+ i += 2;
200
+ while (i < sanitizedInput.length - 1 && !(sanitizedInput[i] === '*' && sanitizedInput[i + 1] === '/')) {
201
+ i++;
202
+ }
203
+ i++;
204
+ } else {
205
+ result += char;
206
+ }
207
+ }
208
+ }
209
+
210
+ return result;
211
+ }
212
+
213
+ /**
214
+ * Reads only "storageDir" from a config file, for commands that don't visit a site
215
+ * (e.g. `import`), so a config without baseUrl still works.
216
+ *
217
+ * @param {string} [customPath] - Config path given by the user (must exist)
218
+ * @returns {string|null} The validated storageDir, or null when no config file is used
219
+ * (no customPath and no ./visual.config.json)
220
+ * @throws {Error} If the file is missing (customPath only), unreadable, not JSON, or
221
+ * its storageDir is invalid
222
+ */
223
+ export function readConfiguredStorageDir(customPath) {
224
+ const resolvedPath = path.resolve(process.cwd(), customPath || 'visual.config.json');
225
+ if (!fs.existsSync(resolvedPath)) {
226
+ if (customPath) throw new CliError('CONFIG_NOT_FOUND', `Configuration file not found at: ${toDisplayPath(resolvedPath)}`);
227
+ return null;
228
+ }
229
+ let parsed;
230
+ try {
231
+ parsed = JSON.parse(stripJsonComments(fs.readFileSync(resolvedPath, 'utf8')));
232
+ } catch (err) {
233
+ throw new CliError('CONFIG_INVALID', `Failed to parse configuration file ${toDisplayPath(resolvedPath)} as JSON: ${err.message}`);
234
+ }
235
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
236
+ throw new CliError('CONFIG_INVALID', `Configuration file ${toDisplayPath(resolvedPath)} must contain a JSON object.`);
237
+ }
238
+ try {
239
+ return validateStorageDir(parsed.storageDir);
240
+ } catch (err) {
241
+ throw new CliError('CONFIG_INVALID', err.message, { cause: err });
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Loads, parses, and validates the visual regression configuration file.
247
+ *
248
+ * @param {string} [customPath] - Optional path to visual.config.json
249
+ * @param {object} [overrides={}] - Optional runtime overrides (e.g. from CLI flags)
250
+ * @returns {object} Validated configuration object
251
+ */
252
+ export function loadConfig(customPath, overrides = {}) {
253
+ const resolvedPath = customPath
254
+ ? path.resolve(process.cwd(), customPath)// path.resolver glues the process current working directory with the custom path name
255
+ : path.resolve(process.cwd(), 'visual.config.json');// glues the process cwd with the visual.config.json
256
+
257
+ if (!fs.existsSync(resolvedPath)) {// fs.existsSync check the path specified as an argument exists or not
258
+ throw new CliError('CONFIG_NOT_FOUND', `Configuration file not found at: ${toDisplayPath(resolvedPath)}`);
259
+ }
260
+
261
+ let fileContent;
262
+ try {
263
+ fileContent = fs.readFileSync(resolvedPath, 'utf8');// reads the file at the address
264
+ } catch (err) {
265
+ throw new CliError('CONFIG_INVALID', `Failed to read configuration file at ${toDisplayPath(resolvedPath)}: ${err.message}`);
266
+ }
267
+
268
+ let parsedConfig;
269
+ try {
270
+ const sanitized = stripJsonComments(fileContent);
271
+ parsedConfig = JSON.parse(sanitized);// converts the file content to json format
272
+ } catch (err) {
273
+ throw new CliError('CONFIG_INVALID', `Failed to parse configuration file as JSON: ${err.message}`);
274
+ }
275
+
276
+ // Merge overrides
277
+ const mergedConfig = {// the ... are known as the spread operators in javascript. These 2 cofigs dumps their content to the mergedConfig
278
+ ...parsedConfig,
279
+ ...overrides
280
+ };
281
+
282
+ try {
283
+ return validateConfig(mergedConfig);// takes the mergedConfig and runs it into validate config for validation.
284
+ } catch (err) {
285
+ throw new CliError('CONFIG_INVALID', err.message, { cause: err });
286
+ }
287
+ }
@@ -0,0 +1,69 @@
1
+ import path from 'node:path';
2
+ import { createRequire } from 'node:module';
3
+ import { CliError } from './errors.js';
4
+ import { shellQuote } from './invocation.js';
5
+
6
+ const require = createRequire(import.meta.url);
7
+
8
+ /**
9
+ * better-sqlite3, the driver of the run database, could not be loaded: its package is
10
+ * missing, or (the usual case) its native binary is missing or was built for another
11
+ * platform or Node.js. Code INTERNAL, like other failures outside the user's input.
12
+ */
13
+ export class DatabaseDriverError extends CliError {
14
+ constructor(cause) {
15
+ const firstLine = String(cause?.message ?? cause).split('\n')[0];
16
+ super('INTERNAL', `better-sqlite3, the SQLite driver of the run database, could not be loaded (${firstLine}). ${driverAdvice()}`, { cause });
17
+ this.name = 'DatabaseDriverError';
18
+ }
19
+ }
20
+
21
+ /** Where better-sqlite3 is installed, for the build command (null if it can't be found). */
22
+ function driverDir() {
23
+ try {
24
+ return path.dirname(require.resolve('better-sqlite3/package.json'));
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * How to fix it. better-sqlite3 13 ships prebuilt binaries in its package (no download,
32
+ * no install script, so `npm rebuild` does nothing): for linux (glibc and musl), darwin
33
+ * and win32 on x64 and arm64. Anywhere else it has to be compiled.
34
+ *
35
+ * @returns {string}
36
+ */
37
+ export function driverAdvice() {
38
+ const dir = driverDir();
39
+ const where = dir ? `cd ${shellQuote(dir)}` : 'cd node_modules/better-sqlite3';
40
+ return 'It ships prebuilt binaries for Linux (glibc and musl), macOS and Windows on x64 and arm64: ' +
41
+ 'reinstall the dependencies on one of those with Node.js 22 or newer (delete node_modules, then npm install). ' +
42
+ `Elsewhere, build it from source (needs Python, make and a C++ compiler): ${where} && npm run build-release`;
43
+ }
44
+
45
+ const mentionsDriver = (err) => /better[-_]sqlite3/i.test(`${err?.message ?? err}\n${err?.stack ?? ''}`);
46
+
47
+ /**
48
+ * Imports src/server/db.js and checks that better-sqlite3 really works: it loads its
49
+ * native binary on the first `new Database()`, not on import, so importing alone
50
+ * proves nothing.
51
+ *
52
+ * @returns {Promise<typeof import('../server/db.js')>}
53
+ * @throws {DatabaseDriverError} when the driver can't be loaded
54
+ */
55
+ export async function loadDatabase() {
56
+ let db;
57
+ try {
58
+ db = await import('../server/db.js');
59
+ } catch (err) {
60
+ if (mentionsDriver(err)) throw new DatabaseDriverError(err);
61
+ throw err;
62
+ }
63
+ try {
64
+ db.assertDriverLoads();
65
+ } catch (err) {
66
+ throw new DatabaseDriverError(err);
67
+ }
68
+ return db;
69
+ }
@@ -0,0 +1,119 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Turning values into text that is safe to print or publish (the JSON result can end
6
+ * up in a PR comment, where GitHub does not mask secrets). No imports from the rest of
7
+ * the project, so config.js and capture.js can use it without an import cycle.
8
+ */
9
+
10
+ const SECRET_PARAMS = new Set([
11
+ 'token', 'access_token', 'auth', 'key', 'apikey', 'api_key', 'password', 'secret', 'sig', 'signature'
12
+ ]);
13
+ export const REDACTED = '***';
14
+
15
+ /**
16
+ * A URL without its username/password, and with the values of token-like query
17
+ * parameters (token, access_token, auth, key, apikey, api_key, password, secret, sig,
18
+ * signature; any case) replaced by ***. Text that is not a URL is returned unchanged.
19
+ *
20
+ * @param {unknown} value
21
+ * @returns {string}
22
+ */
23
+ export function redactUrl(value) {
24
+ const text = String(value ?? '');
25
+ let url;
26
+ try {
27
+ url = new URL(text);
28
+ } catch {
29
+ return text;
30
+ }
31
+ let changed = false;
32
+ if (url.username || url.password) {
33
+ url.username = '';
34
+ url.password = '';
35
+ changed = true;
36
+ }
37
+ if (url.search) {
38
+ const pairs = url.search.slice(1).split('&').map((pair) => {
39
+ const eq = pair.indexOf('=');
40
+ const rawName = eq === -1 ? pair : pair.slice(0, eq);
41
+ let name;
42
+ try {
43
+ name = decodeURIComponent(rawName.replace(/\+/g, ' '));
44
+ } catch {
45
+ name = rawName;
46
+ }
47
+ if (eq === -1 || !SECRET_PARAMS.has(name.toLowerCase())) return pair;
48
+ changed = true;
49
+ return `${rawName}=${REDACTED}`;
50
+ });
51
+ if (changed) url.search = `?${pairs.join('&')}`;
52
+ }
53
+ if (!changed) return text;
54
+ let out = url.href;
55
+ // new URL() adds a "/" path to "http://host"; don't let redaction change that.
56
+ if (url.pathname === '/' && !url.search && !url.hash && !/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*\//i.test(text)) {
57
+ out = out.replace(/\/$/, '');
58
+ }
59
+ return out;
60
+ }
61
+
62
+ const URL_IN_TEXT = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>`]+/gi;
63
+
64
+ /**
65
+ * Redacts every URL found in a piece of text (e.g. an error message that quotes one).
66
+ *
67
+ * @param {unknown} text
68
+ * @returns {string}
69
+ */
70
+ export function redactUrlsInText(text) {
71
+ return String(text ?? '').replace(URL_IN_TEXT, (match) => {
72
+ // Trailing punctuation is usually the sentence, not the URL.
73
+ const [, url, tail] = match.match(/^(.*?)([.,;:)\]]*)$/);
74
+ return redactUrl(url) + tail;
75
+ });
76
+ }
77
+
78
+ /**
79
+ * A path for display or the JSON result: relative to cwd with "/" separators, or
80
+ * absolute (still with "/") when it lies outside cwd. null stays null.
81
+ *
82
+ * @param {string|null|undefined} file
83
+ * @param {string} [cwd=process.cwd()]
84
+ * @returns {string|null}
85
+ */
86
+ export function toDisplayPath(file, cwd = process.cwd()) {
87
+ if (!file) return null;
88
+ const abs = path.resolve(cwd, file);
89
+ const rel = path.relative(cwd, abs);
90
+ if (rel === '') return '.';
91
+ const outside = rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
92
+ return (outside ? abs : rel).split(path.sep).join('/');
93
+ }
94
+
95
+ function escapeRegExp(text) {
96
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
97
+ }
98
+
99
+ /**
100
+ * Replaces the working directory with "." and the home directory with "~" in text,
101
+ * so a message doesn't reveal (or depend on) where the workspace lives on this host
102
+ * or in this container. Only whole path prefixes are replaced ("/work/app" in
103
+ * "/work/apple" is left alone).
104
+ *
105
+ * @param {unknown} text
106
+ * @param {{ cwd?: string, home?: string }} [options]
107
+ * @returns {string}
108
+ */
109
+ export function redactLocalPaths(text, { cwd = process.cwd(), home = os.homedir() } = {}) {
110
+ let out = String(text ?? '');
111
+ for (const [dir, replacement] of [[cwd, '.'], [home, '~']]) {
112
+ if (!dir || path.parse(dir).root === dir) continue; // never replace a bare "/" or "C:\"
113
+ const variants = new Set([dir, dir.split(path.sep).join('/')]);
114
+ for (const variant of variants) {
115
+ out = out.replace(new RegExp(`${escapeRegExp(variant)}(?=$|[\\\\/\\s"'):,;]|\\.(?:$|\\s))`, 'g'), replacement);
116
+ }
117
+ }
118
+ return out;
119
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * An error that carries one of the machine-readable codes of the visual-ci-result
3
+ * JSON (see result.js). It lives in its own module, with no imports, so config.js and
4
+ * capture.js can use it without an import cycle through the server modules.
5
+ */
6
+ export class CliError extends Error {
7
+ /**
8
+ * @param {string} code - e.g. 'CONFIG_NOT_FOUND' (see ERROR_CODES in result.js)
9
+ * @param {string} message
10
+ * @param {{ cause?: unknown }} [options]
11
+ */
12
+ constructor(code, message, options) {
13
+ super(message, options);
14
+ this.name = 'CliError';
15
+ this.code = code;
16
+ }
17
+ }