@se-studio/site-check 2.14.1 → 2.15.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/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.15.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [a5a0d19]
8
+ - @se-studio/contentful-rest-api@2.7.0
9
+
10
+ ## 2.15.0
11
+
12
+ ### Minor Changes
13
+
14
+ - 24262f4: `check-cms-driven --update-baseline` snapshots existing R3 colour violations into `cms-driven.baseline.json` so a site can adopt the guard before fixing them all. New violations fail; the debt is printed on every run (with `NEEDS WORK` over 25); the baseline can only shrink and a hand-edited one is rejected. `example-empty` now ships with R3 on.
15
+ - b5ec8c4: `check-cms-driven` gains R3: an opt-in guard (`r3` in `cms-driven.config.json`) that flags colour literals anywhere in `src/` (hex, colour functions, arbitrary colour values, Tailwind default palette classes, black). The palette comes from `tailwind.config.json`; exceptions are listed in config and each needs a reason.
16
+ - 4163446: `check-cms-driven` adds R4 (a new `.css` file outside the baseline and `r3.cssAllow` fails) and an expiring remake mode (`"remake": { "until": "YYYY-MM-DD" }`, at most 120 days ahead). While the window is open R3 and R4 do not fail and `--update-baseline` may grow the baseline; after it, the guard is strict again.
17
+
18
+ ## 2.14.5
19
+
20
+ ### Patch Changes
21
+
22
+ - Updated dependencies [da6b97f]
23
+ - @se-studio/contentful-rest-api@2.6.0
24
+
25
+ ## 2.14.4
26
+
27
+ ### Patch Changes
28
+
29
+ - Updated dependencies [bd47829]
30
+ - @se-studio/contentful-rest-api@2.5.0
31
+
32
+ ## 2.14.3
33
+
34
+ ### Patch Changes
35
+
36
+ - Updated dependencies [457ed9c]
37
+ - @se-studio/contentful-rest-api@2.4.0
38
+
39
+ ## 2.14.2
40
+
41
+ ### Patch Changes
42
+
43
+ - Updated dependencies [b06b628]
44
+ - @se-studio/contentful-rest-api@2.3.0
45
+
3
46
  ## 2.14.1
4
47
 
5
48
  ### Patch Changes
package/README.md CHANGED
@@ -335,6 +335,62 @@ check-cms-driven --config cms-driven.config.json
335
335
 
336
336
  With no `--config`, a `cms-driven.config.json` next to the app root is used when it exists. R1 is still off if that file has no `r1` key.
337
337
 
338
+ ### R3 (opt-in): no colour literals in `src/`
339
+
340
+ R1 only looks at chrome. R3 covers every `.ts`, `.tsx`, `.js`, `.jsx` and `.css` file under `src/` (tests, `__tests__/` and generated code are skipped). It flags hex colours, `rgb()` / `hsl()` / `oklch()` / `oklab()`, arbitrary colour values (`bg-[#fff]`), Tailwind default palette classes (`bg-gray-100`, including side and ring-offset forms), and `black` / `white` unless the project defines them as tokens. Project palette tokens (`bg-navy`) are fine. Tokens are read from `colorOptions` in `tailwind.config.json`, so a project that defines its own `red` is not flagged for `bg-red-500`.
341
+
342
+ Fragment links (`href="#top"`), `url(#id)` references, HTML entities (`—`), URL fragments and id selectors are not colours. Text such as `Issue #123` still looks like a 3-digit hex colour: use `se-exception` on that line. `color-mix()` of palette variables is fine (a hex or `rgb()` inside one is still caught).
343
+
344
+ ```json
345
+ {
346
+ "r3": {
347
+ "tailwindConfig": "tailwind.config.json",
348
+ "exceptions": [
349
+ { "path": "src/project/externalComponents/chart-colours.ts", "reason": "Highcharts cannot read CSS variables" }
350
+ ]
351
+ }
352
+ }
353
+ ```
354
+
355
+ `r3: {}` is enough for the defaults. Every exception needs a `reason`; a path ending in `/` is a directory. A missing `tailwind.config.json` is an error, and so is a missing `src/`: the guard fails loudly instead of scanning nothing. Under `src/` only `node_modules`, `.next`, `.git` and `generated` are skipped.
356
+
357
+ ### Adopting R3 on an existing site: the baseline
358
+
359
+ `example-empty` ships with `"r3": {}` on, and a new project from it starts clean. An existing site with literals in it runs:
360
+
361
+ ```bash
362
+ pnpm exec check-cms-driven --update-baseline
363
+ ```
364
+
365
+ That writes `cms-driven.baseline.json`: a snapshot of today's R3 violations, keyed by file, rule and line text (so moving code does not churn it). Commit it. From then on:
366
+
367
+ - A violation the baseline covers passes; any new one fails. Three copies of a literal the baseline holds twice is one new violation.
368
+ - Every run prints `baseline debt: N R3 violation(s) in M file(s)`, even when it passes. Over 25, it also prints `NEEDS WORK`.
369
+ - The baseline is built to shrink. When you fix some, the run says so and `--update-baseline` rewrites it smaller; when it reaches zero the file is deleted. `--update-baseline` refuses to add entries to an existing baseline, and a baseline whose `total` does not match its entries is rejected, which catches careless edits.
370
+ - That is not tamper-proof. Deleting the file and regenerating it counts as a first baseline, and a deliberate edit that keeps `total` consistent passes. Treat `cms-driven.baseline.json` as a ratchet file: review any PR that changes it, and look at the debt line `fleet-audit` reports.
371
+ - Fixing some baselined lines and adding identical ones elsewhere in the same file is not detected: the run only reports that baselined violations are fixed. Run `--update-baseline` when you fix things, so the slack does not build up.
372
+ - Entries are keyed by a hash of the whole line, so appending a literal to a baselined line is new debt.
373
+ - R1 and R2 are never baselined.
374
+ - `fleet-audit` flags a site whose baseline is over 25, or whose baseline has not changed for 90 days with debt still in it, and any site still carrying its own `scripts/check-cms-driven.mjs`.
375
+
376
+ ### R4 and remake mode: copying a live site's styles
377
+
378
+ R4 comes with R3: a `.css` file under `src/` that is not in the baseline or in `r3.cssAllow` (default `src/app/globals.css`) fails as a new CSS island. Fix it by moving the styles into `globals.css` or the component with palette tokens.
379
+
380
+ A remake legitimately adds literals and stylesheets for a while. Open a window for that, in `cms-driven.config.json`:
381
+
382
+ ```json
383
+ { "r3": {}, "remake": { "until": "2026-12-31" } }
384
+ ```
385
+
386
+ - Until that date, R3 and R4 violations do not fail. Each run prints `REMAKE MODE until <date>` and how many are not in the baseline yet. In the last 14 days it also says the window is ending soon.
387
+ - During the window `--update-baseline` may grow the baseline, so snapshot the remaining debt before it ends.
388
+ - After the date the guard is strict again: anything not in the baseline fails, an existing baseline can no longer grow, and the run asks you to remove `remake` from the config.
389
+ - The date can be at most 120 days ahead, and `remake` needs `r3`.
390
+ - `fleet-audit` lists every site in remake mode with its deadline, and every site whose window has passed but is still in the config.
391
+
392
+ Known limit: R4 notices a new stylesheet, not a baselined one growing. Colour literals added to an old one are still caught by R3.
393
+
338
394
  ### Escape hatch
339
395
 
340
396
  A rare, explained exception stays on the offending line:
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { createHash } from 'node:crypto';
2
3
  /**
3
4
  * Guard: page-specific chrome comes from the CMS, not from a slug or type branch.
4
5
  *
@@ -14,6 +15,17 @@
14
15
  * R1 (opt-in) — literal colours in chrome files and footer/nav CSS. Off until
15
16
  * cms-driven.config.json sets `r1`. See the package README.
16
17
  *
18
+ * R4 (on with R3) — no new CSS files: a stylesheet that is not in the baseline or in
19
+ * `r3.cssAllow` (default: src/app/globals.css) is a CSS island and fails.
20
+ *
21
+ * Remake mode (`remake: { until: "YYYY-MM-DD" }`, at most 120 days ahead) lets R3 and R4
22
+ * violations through while a remake copies the live site's styles; `--update-baseline`
23
+ * may then snapshot them. After the date the guard is strict again.
24
+ *
25
+ * R3 (opt-in) — no colour literals anywhere in src/ (hex, colour functions, arbitrary
26
+ * colour values, Tailwind default palette classes). Project palette tokens come from
27
+ * tailwind.config.json. Off until cms-driven.config.json sets `r3`.
28
+ *
17
29
  * Escape hatch (needs a reason): a line comment "se-exception: <reason>",
18
30
  * or the same words inside a CSS block comment on that line.
19
31
  *
@@ -22,8 +34,15 @@
22
34
  * check-cms-driven --config cms-driven.config.json
23
35
  */
24
36
  import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
25
- import { join, relative, sep } from 'node:path';
37
+ import { isAbsolute, join, relative, sep } from 'node:path';
26
38
  import { fileURLToPath } from 'node:url';
39
+ import {
40
+ applyBaseline,
41
+ BASELINE_NAME,
42
+ DEBT_THRESHOLD,
43
+ readBaseline,
44
+ updateBaseline,
45
+ } from './cms-driven-baseline.mjs';
27
46
 
28
47
  export const DEFAULT_IMPORT_ALLOWLIST = [
29
48
  'Footer',
@@ -36,8 +55,14 @@ export const DEFAULT_IMPORT_ALLOWLIST = [
36
55
  ];
37
56
 
38
57
  const CONFIG_NAME = 'cms-driven.config.json';
39
- const TOP_LEVEL_KEYS = new Set(['importAllowlist', 'r1']);
58
+ const TOP_LEVEL_KEYS = new Set(['importAllowlist', 'r1', 'r3', 'remake']);
59
+ const R3_KEYS = new Set(['tailwindConfig', 'exceptions', 'cssAllow']);
60
+ const REMAKE_MAX_DAYS = 120;
61
+ const REMAKE_WARN_DAYS = 14;
62
+ const DAY_MS = 86_400_000;
40
63
  const R1_KEYS = new Set(['chrome', 'palette', 'paletteNames', 'skipFiles', 'cssFiles']);
64
+ /** Under src/ only build output and tooling folders are skipped: a `dist/` or `out/` there is source. */
65
+ const SRC_SKIP_DIRS = new Set(['node_modules', '.git', '.next', 'generated']);
41
66
  const SKIP_DIRS = new Set([
42
67
  'node_modules',
43
68
  '.git',
@@ -68,9 +93,15 @@ Opt in from the app root:
68
93
  and add that script to "validate".
69
94
 
70
95
  R1 (literal chrome colours) stays off until cms-driven.config.json includes "r1".
96
+ R3 (colour literals anywhere in src/) and R4 (no new CSS files) stay off until it
97
+ includes "r3". "remake": { "until": "YYYY-MM-DD" } relaxes both until that date.
71
98
  See @se-studio/site-check README, "CMS-driven layouts".
72
99
 
73
- check-cms-driven [--config <file>]
100
+ check-cms-driven [--config <file>] [--update-baseline]
101
+
102
+ --update-baseline writes ${BASELINE_NAME}: a snapshot of today's R3 violations so a site
103
+ can adopt the guard before fixing them all. New violations still fail. The baseline can
104
+ only shrink; its size is printed on every run.
74
105
  `;
75
106
 
76
107
  function escapeRegExp(value) {
@@ -92,6 +123,73 @@ function unknownKeys(object, allowed) {
92
123
  return Object.keys(object).filter((key) => !allowed.has(key));
93
124
  }
94
125
 
126
+ function parseR3(value) {
127
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
128
+ throw new Error('r3 must be an object (use {} for the defaults)');
129
+ }
130
+ const extra = unknownKeys(value, R3_KEYS);
131
+ if (extra.length > 0) throw new Error(`r3 has unknown keys: ${extra.join(', ')}`);
132
+ const tailwindConfig = value.tailwindConfig ?? 'tailwind.config.json';
133
+ if (typeof tailwindConfig !== 'string' || tailwindConfig === '') {
134
+ throw new Error('r3.tailwindConfig must be a non-empty path');
135
+ }
136
+ const exceptions = value.exceptions ?? [];
137
+ if (!Array.isArray(exceptions)) throw new Error('r3.exceptions must be a list');
138
+ for (const entry of exceptions) {
139
+ const ok =
140
+ entry &&
141
+ typeof entry === 'object' &&
142
+ typeof entry.path === 'string' &&
143
+ entry.path !== '' &&
144
+ typeof entry.reason === 'string' &&
145
+ entry.reason.trim() !== '';
146
+ if (!ok) throw new Error('each r3.exceptions entry needs a path and a reason');
147
+ }
148
+ const cssAllow =
149
+ value.cssAllow === undefined
150
+ ? ['src/app/globals.css']
151
+ : assertStringList(value.cssAllow, 'r3.cssAllow');
152
+ return { tailwindConfig, exceptions, cssAllow };
153
+ }
154
+
155
+ function parseRemake(value) {
156
+ const until = value?.until;
157
+ const extra = value && typeof value === 'object' ? unknownKeys(value, new Set(['until'])) : [];
158
+ if (extra.length > 0 || typeof until !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(until)) {
159
+ throw new Error('remake must be { "until": "YYYY-MM-DD" }');
160
+ }
161
+ const date = new Date(`${until}T00:00:00Z`);
162
+ if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== until) {
163
+ throw new Error(`remake.until is not a real date: ${until} (use YYYY-MM-DD)`);
164
+ }
165
+ return { until };
166
+ }
167
+
168
+ function daysBetween(from, to) {
169
+ return Math.round((Date.parse(to) - Date.parse(from)) / DAY_MS);
170
+ }
171
+
172
+ /**
173
+ * Project colour token names (lower-case, hyphenated) from tailwind.config.json colorOptions.
174
+ * @param {string} root
175
+ * @param {string} configFile path relative to root
176
+ */
177
+ export function loadProjectPalette(root, configFile) {
178
+ const file = join(root, configFile);
179
+ if (!existsSync(file)) throw new Error(`r3 needs ${configFile} for the project palette`);
180
+ let colours;
181
+ try {
182
+ colours = JSON.parse(readFileSync(file, 'utf8')).colorOptions;
183
+ } catch (error) {
184
+ const message = error instanceof Error ? error.message : String(error);
185
+ throw new Error(`cannot read ${configFile}: ${message}`);
186
+ }
187
+ if (!colours || typeof colours !== 'object') {
188
+ throw new Error(`${configFile} has no colorOptions`);
189
+ }
190
+ return Object.keys(colours).map((name) => name.toLowerCase().replace(/\s+/g, '-'));
191
+ }
192
+
95
193
  /**
96
194
  * @param {string} root
97
195
  * @param {string | undefined} configPath explicit path; the default file is optional
@@ -99,15 +197,17 @@ function unknownKeys(object, allowed) {
99
197
  export function loadCmsDrivenConfig(root, configPath) {
100
198
  const explicit = Boolean(configPath);
101
199
  const file = configPath
102
- ? configPath.startsWith('/')
200
+ ? isAbsolute(configPath)
103
201
  ? configPath
104
202
  : join(root, configPath)
105
203
  : join(root, CONFIG_NAME);
106
204
 
107
- /** @type {{ importAllowlist: string[], r1: null | { chrome: string[], palette: string[], paletteNames: string[], skipFiles: string[], cssFiles: string[] } }} */
205
+ /** @type {{ importAllowlist: string[], r1: null | { chrome: string[], palette: string[], paletteNames: string[], skipFiles: string[], cssFiles: string[] }, r3: null | { tailwindConfig: string, exceptions: { path: string, reason: string }[], cssAllow: string[] }, remake: null | { until: string } }} */
108
206
  const config = {
109
207
  importAllowlist: [...DEFAULT_IMPORT_ALLOWLIST],
110
208
  r1: null,
209
+ r3: null,
210
+ remake: null,
111
211
  };
112
212
 
113
213
  if (!existsSync(file)) {
@@ -135,6 +235,12 @@ export function loadCmsDrivenConfig(root, configPath) {
135
235
  config.importAllowlist = assertStringList(raw.importAllowlist, 'importAllowlist');
136
236
  }
137
237
 
238
+ if (raw.r3 !== undefined) config.r3 = parseR3(raw.r3);
239
+ if (raw.remake !== undefined) {
240
+ if (!config.r3) throw new Error('remake needs "r3": it relaxes the R3 and R4 guards');
241
+ config.remake = parseRemake(raw.remake);
242
+ }
243
+
138
244
  if (raw.r1 === undefined) return config;
139
245
  if (!raw.r1 || typeof raw.r1 !== 'object' || Array.isArray(raw.r1)) {
140
246
  throw new Error('r1 must be an object with a chrome list');
@@ -192,12 +298,15 @@ function isComment(line) {
192
298
  return /^\s*(\/\/|\*|\/\*)/.test(line);
193
299
  }
194
300
 
195
- function walk(dir, out = []) {
301
+ function walk(dir, root, srcIsSource, out = []) {
196
302
  if (!existsSync(dir)) return out;
303
+ const underSrc =
304
+ srcIsSource && (dir === join(root, 'src') || dir.startsWith(`${join(root, 'src')}${sep}`));
305
+ const skip = underSrc ? SRC_SKIP_DIRS : SKIP_DIRS;
197
306
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
198
- if (SKIP_DIRS.has(entry.name)) continue;
307
+ if (skip.has(entry.name)) continue;
199
308
  const full = join(dir, entry.name);
200
- if (entry.isDirectory()) walk(full, out);
309
+ if (entry.isDirectory()) walk(full, root, srcIsSource, out);
201
310
  else if (entry.isFile()) out.push(full);
202
311
  }
203
312
  return out;
@@ -211,29 +320,134 @@ function importedComponent(line) {
211
320
  return segment || null;
212
321
  }
213
322
 
323
+ const MOCK_START =
324
+ /^\s*(?:export\s+)?(?:const|let|var)\s+\w*(?:showcase|mock|fixture)\w*\b[^=]*=|^\s*['"]?\w*(?:showcase|mock|fixture)\w*['"]?\s*:\s*[{[(]|\bmockData\b|\bshowcaseMock/i;
325
+ const MAX_MOCK_LINES = 1000;
326
+
327
+ function stripStrings(line) {
328
+ return line.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`/g, '""');
329
+ }
330
+
331
+ function netBrackets(code) {
332
+ return (code.match(/[{[(]/g)?.length ?? 0) - (code.match(/[}\])]/g)?.length ?? 0);
333
+ }
334
+
335
+ /**
336
+ * Lines of sample CMS data (showcase mocks, fixtures). A block starts at a declaration or key
337
+ * whose name says mock/showcase/fixture and runs until its brackets balance. Brackets inside
338
+ * strings do not count, and a block that never closes stops after MAX_MOCK_LINES.
339
+ */
214
340
  function mockLineIndexes(lines) {
215
341
  const skip = new Set();
216
342
  let depth = 0;
217
- let inMock = false;
343
+ let startedAt = -1;
218
344
  for (let i = 0; i < lines.length; i++) {
219
345
  const line = lines[i] ?? '';
220
- if (
221
- !inMock &&
222
- /\b(?:showcase|mock|fixture)[A-Za-z]*\s*[:=]|\bmockData\b|\bshowcaseMock/i.test(line)
223
- ) {
224
- inMock = true;
225
- depth = 0;
346
+ const code = stripStrings(line);
347
+ if (startedAt < 0) {
348
+ if (!MOCK_START.test(line)) continue;
349
+ skip.add(i);
350
+ depth = netBrackets(code);
351
+ if (depth > 0) startedAt = i;
352
+ continue;
226
353
  }
227
- if (!inMock) continue;
228
354
  skip.add(i);
229
- const opens = line.match(/[{[(]/g)?.length ?? 0;
230
- const closes = line.match(/[}\])]/g)?.length ?? 0;
231
- depth += opens - closes;
232
- if (depth <= 0 && /[}\])];?,?\s*$/.test(line)) inMock = false;
355
+ depth += netBrackets(code);
356
+ if (depth <= 0 || i - startedAt >= MAX_MOCK_LINES) startedAt = -1;
233
357
  }
234
358
  return skip;
235
359
  }
236
360
 
361
+ const TAILWIND_DEFAULT_PALETTE = [
362
+ 'slate',
363
+ 'gray',
364
+ 'zinc',
365
+ 'neutral',
366
+ 'stone',
367
+ 'red',
368
+ 'orange',
369
+ 'amber',
370
+ 'yellow',
371
+ 'lime',
372
+ 'green',
373
+ 'emerald',
374
+ 'teal',
375
+ 'cyan',
376
+ 'sky',
377
+ 'blue',
378
+ 'indigo',
379
+ 'violet',
380
+ 'purple',
381
+ 'fuchsia',
382
+ 'pink',
383
+ 'rose',
384
+ 'mauve',
385
+ 'olive',
386
+ 'mist',
387
+ 'taupe',
388
+ ];
389
+ const COLOUR_UTILITIES =
390
+ 'bg|text|from|via|to|border(?:-[trblxyse])?|fill|stroke|outline|ring(?:-offset)?|inset-shadow|drop-shadow|shadow|text-shadow|inset-ring|decoration|accent|caret|divide|placeholder';
391
+ // color-mix() is deliberately absent: mixing palette variables is how a tint is made from tokens.
392
+ // A hex or rgb() inside one is still caught by the other rules.
393
+ const COLOUR_FUNCTIONS = 'rgba?|hsla?|hwb|lab|lch|oklch|oklab';
394
+ const COLOUR_FUNCTION_CALL = new RegExp(
395
+ `\\b(?:${COLOUR_FUNCTIONS})\\(|\\bcolor\\(\\s*(?:from\\b|srgb|display-p3|rec2020|xyz|a98-rgb|prophoto-rgb)`,
396
+ );
397
+ /** What precedes a `#fragment` that is a link, an SVG reference or a DOM lookup, not a colour. */
398
+ const NOT_A_COLOUR_BEFORE =
399
+ /(?<![\w-])(?:href|xlinkHref|htmlFor|to|aria-[a-z]+)(?:=|:\s*)["'{`]*$|url\(\s*["']?$|(?:querySelector(?:All)?|getElementById|closest|matches)\(\s*["'`]$/;
400
+
401
+ /**
402
+ * A hex literal that is a colour. Not a colour: a fragment link or SVG reference, an HTML
403
+ * entity (`&#8212;`), a URL fragment (`/page#feed`), an id selector (`#add-btn`), or a CSS
404
+ * id selector opening a rule (`#abc {`).
405
+ */
406
+ export function hasHexColour(text) {
407
+ for (const match of text.matchAll(
408
+ /(?<![\w&#])#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})(?![\w-])/g,
409
+ )) {
410
+ const before = text.slice(0, match.index);
411
+ if (NOT_A_COLOUR_BEFORE.test(before)) continue;
412
+ if (/^\s*$/.test(before) && /\{\s*$/.test(text) && !/[:;]/.test(text)) continue;
413
+ return true;
414
+ }
415
+ return false;
416
+ }
417
+
418
+ /** R3 rules. Project palette tokens are allowed; Tailwind defaults and black are not. */
419
+ function literalColourRules(projectPalette) {
420
+ const own = new Set(projectPalette);
421
+ const defaults = TAILWIND_DEFAULT_PALETTE.filter((name) => !own.has(name));
422
+ const rules = [
423
+ { test: hasHexColour, what: 'hex colour' },
424
+ { test: (text) => COLOUR_FUNCTION_CALL.test(text), what: 'colour function' },
425
+ {
426
+ test: (text) =>
427
+ new RegExp(
428
+ `(?<![\\w-])(?:${COLOUR_UTILITIES})-\\[[^\\]]*(?:#[0-9a-fA-F]{3,8}|(?:${COLOUR_FUNCTIONS})\\()`,
429
+ ).test(text),
430
+ what: 'arbitrary colour value',
431
+ },
432
+ ];
433
+ if (defaults.length > 0) {
434
+ const re = new RegExp(
435
+ `(?<![\\w-])(?:${COLOUR_UTILITIES})-(?:${defaults.join('|')})-\\d{2,3}(?:/[\\d.]+)?(?![\\w-])`,
436
+ );
437
+ rules.push({ test: (text) => re.test(text), what: 'Tailwind default palette class' });
438
+ }
439
+ for (const name of ['black', 'white']) {
440
+ if (own.has(name)) continue;
441
+ const re = new RegExp(`(?<![\\w-])(?:${COLOUR_UTILITIES})-${name}(?:/[\\d.]+)?(?![\\w-])`);
442
+ rules.push({ test: (text) => re.test(text), what: `${name} is not a palette token` });
443
+ }
444
+ return rules;
445
+ }
446
+
447
+ function isTestFile(file) {
448
+ return /\.test\.[tj]sx?$|(?:^|\/)__tests__\//.test(file);
449
+ }
450
+
237
451
  function codeColourRules(r1) {
238
452
  const rules = [
239
453
  { re: /#[0-9a-fA-F]{3,8}\b/, what: 'hex colour' },
@@ -262,12 +476,18 @@ function codeColourRules(r1) {
262
476
  return rules;
263
477
  }
264
478
 
479
+ const format = (v) => `${v.file}:${v.line} ${v.rule} ${v.what}${v.text ? `: ${v.text}` : ''}`;
480
+
481
+ /** Rules whose violations can be baselined and relaxed by remake mode. */
482
+ const BASELINED_RULES = new Set(['R3', 'R4']);
483
+
265
484
  /**
485
+ * Every violation found, before any baseline is applied.
266
486
  * @param {string} root
267
487
  * @param {{ configPath?: string }} [options]
268
- * @returns {string[]}
488
+ * @returns {{ config: ReturnType<typeof loadCmsDrivenConfig>, violations: import('./cms-driven-baseline.mjs').Violation[] }}
269
489
  */
270
- export function checkCmsDriven(root, options = {}) {
490
+ export function collectViolations(root, options = {}) {
271
491
  const config = loadCmsDrivenConfig(root, options.configPath);
272
492
  const allow = new Set(config.importAllowlist);
273
493
  const violations = [];
@@ -276,11 +496,25 @@ export function checkCmsDriven(root, options = {}) {
276
496
  ? new RegExp(`var\\(--color-(?:${config.r1.palette.map(escapeRegExp).join('|')})\\)`)
277
497
  : null;
278
498
 
499
+ if (config.r3 && !existsSync(join(root, 'src'))) {
500
+ throw new Error(
501
+ `r3 scans src/ but ${join(root, 'src')} does not exist: run it from the app root`,
502
+ );
503
+ }
504
+ const literalRules = config.r3
505
+ ? literalColourRules(loadProjectPalette(root, config.r3.tailwindConfig))
506
+ : [];
507
+ const r3Exceptions = config.r3?.exceptions.map((entry) => entry.path) ?? [];
508
+
279
509
  const report = (file, index, rule, what, text) => {
280
- violations.push(`${file}:${index + 1} ${rule} ${what}: ${text.trim().slice(0, 100)}`);
510
+ const full = text.trim();
511
+ // The hash covers the whole line, so a literal added past the 100-character preview still changes the key.
512
+ const hash = createHash('sha1').update(full).digest('hex').slice(0, 10);
513
+ violations.push({ file, line: index + 1, rule, what, text: full.slice(0, 100), hash });
281
514
  };
282
515
 
283
- for (const abs of walk(root)) {
516
+ // Only R3 treats every folder under src/ as source; R1/R2-only sites keep the old skips.
517
+ for (const abs of walk(root, root, config.r3 !== null)) {
284
518
  const file = toPosix(relative(root, abs));
285
519
  const role = r2Role(file);
286
520
  const isCss = config.r1 ? matchesAny(file, config.r1.cssFiles) : false;
@@ -290,10 +524,37 @@ export function checkCmsDriven(root, options = {}) {
290
524
  matchesAny(file, config.r1.chrome) &&
291
525
  !matchesAny(file, config.r1.skipFiles);
292
526
 
293
- if (!role && !inChrome && !isCss) continue;
527
+ const inR3 =
528
+ config.r3 !== null &&
529
+ file.startsWith('src/') &&
530
+ /\.(tsx|ts|jsx|js|css)$/.test(file) &&
531
+ !isTestFile(file) &&
532
+ !matchesAny(file, r3Exceptions);
533
+
534
+ if (
535
+ config.r3 &&
536
+ file.startsWith('src/') &&
537
+ file.endsWith('.css') &&
538
+ !matchesAny(file, config.r3.cssAllow)
539
+ ) {
540
+ report(file, 0, 'R4', 'new CSS file', '');
541
+ }
542
+
543
+ if (!role && !inChrome && !isCss && !inR3) continue;
294
544
 
295
545
  const lines = readFileSync(abs, 'utf8').split('\n');
296
546
 
547
+ if (inR3) {
548
+ const mocks = /\.css$/.test(file) ? new Set() : mockLineIndexes(lines);
549
+ for (let i = 0; i < lines.length; i++) {
550
+ const line = lines[i] ?? '';
551
+ if (excepted(line) || mocks.has(i) || isComment(line)) continue;
552
+ for (const { test, what } of literalRules) {
553
+ if (test(line)) report(file, i, 'R3', what, line);
554
+ }
555
+ }
556
+ }
557
+
297
558
  if (inChrome) {
298
559
  const mocks = mockLineIndexes(lines);
299
560
  for (let i = 0; i < lines.length; i++) {
@@ -343,16 +604,75 @@ export function checkCmsDriven(root, options = {}) {
343
604
  }
344
605
  }
345
606
 
346
- return violations;
607
+ return { config, violations };
608
+ }
609
+
610
+ /**
611
+ * @param {{ until: string } | null} remake
612
+ * @param {string} today YYYY-MM-DD
613
+ */
614
+ function remakeStatus(remake, today) {
615
+ if (!remake) return null;
616
+ const daysLeft = daysBetween(today, remake.until);
617
+ if (daysLeft > REMAKE_MAX_DAYS) {
618
+ throw new Error(
619
+ `remake.until ${remake.until} is more than ${REMAKE_MAX_DAYS} days away: a remake window is temporary`,
620
+ );
621
+ }
622
+ return {
623
+ until: remake.until,
624
+ daysLeft,
625
+ active: daysLeft >= 0,
626
+ endingSoon: daysLeft <= REMAKE_WARN_DAYS,
627
+ };
628
+ }
629
+
630
+ /**
631
+ * Violations that fail the build: all of R1/R2, and R3 beyond what the baseline covers.
632
+ * @param {string} root
633
+ * @param {{ configPath?: string }} [options]
634
+ * @returns {string[]}
635
+ */
636
+ export function checkCmsDriven(root, options = {}) {
637
+ return checkCmsDrivenReport(root, options).failures;
638
+ }
639
+
640
+ /**
641
+ * @param {string} root
642
+ * @param {{ configPath?: string }} [options]
643
+ */
644
+ export function checkCmsDrivenReport(root, options = {}) {
645
+ const { config, violations } = collectViolations(root, options);
646
+ const today = options.today ?? new Date().toISOString().slice(0, 10);
647
+ const remake = remakeStatus(config.remake, today);
648
+ const baselined = violations.filter((v) => BASELINED_RULES.has(v.rule));
649
+ const baseline = config.r3 ? readBaseline(root) : null;
650
+ const applied = applyBaseline(baselined, baseline);
651
+ // While a remake is running, new R3/R4 violations are shown but do not fail.
652
+ const failing = remake?.active ? [] : applied.fresh;
653
+ const failures = [...violations.filter((v) => !BASELINED_RULES.has(v.rule)), ...failing].map(
654
+ format,
655
+ );
656
+ return {
657
+ remake,
658
+ unbaselined: remake?.active ? applied.fresh.length : 0,
659
+ failures,
660
+ debt: applied.debt,
661
+ debtFiles: applied.files,
662
+ stale: applied.stale,
663
+ generatedAt: baseline?.generatedAt ?? null,
664
+ };
347
665
  }
348
666
 
349
667
  function parseArgs(argv) {
350
- /** @type {{ help: boolean, configPath?: string }} */
351
- const args = { help: false };
668
+ /** @type {{ help: boolean, updateBaseline: boolean, configPath?: string }} */
669
+ const args = { help: false, updateBaseline: false };
352
670
  for (let i = 0; i < argv.length; i++) {
353
671
  const arg = argv[i];
354
672
  if (arg === '--help' || arg === '-h') {
355
673
  args.help = true;
674
+ } else if (arg === '--update-baseline') {
675
+ args.updateBaseline = true;
356
676
  } else if (arg === '--config') {
357
677
  const next = argv[i + 1];
358
678
  if (!next) throw new Error('--config needs a path');
@@ -376,6 +696,28 @@ function isDirectRun() {
376
696
  }
377
697
  }
378
698
 
699
+ function updateBaselineCommand(args) {
700
+ const { config, violations } = collectViolations(process.cwd(), { configPath: args.configPath });
701
+ if (!config.r3) throw new Error('--update-baseline needs "r3" in cms-driven.config.json');
702
+ const date = new Date().toISOString().slice(0, 10);
703
+ const remake = remakeStatus(config.remake, date);
704
+ const result = updateBaseline(
705
+ process.cwd(),
706
+ violations.filter((v) => BASELINED_RULES.has(v.rule)),
707
+ date,
708
+ { allowGrow: remake?.active === true },
709
+ );
710
+ if (!result.ok) {
711
+ console.error(
712
+ `check-cms-driven: the baseline can only shrink. ${result.grew.length} new violation(s):\n`,
713
+ );
714
+ for (const violation of result.grew) console.error(` ${format(violation)}`);
715
+ console.error('\nFix them or add a listed exception with a reason.');
716
+ process.exit(1);
717
+ }
718
+ console.log(`check-cms-driven: baseline ${result.action} (${result.total} violation(s)).`);
719
+ }
720
+
379
721
  function main() {
380
722
  try {
381
723
  const args = parseArgs(process.argv.slice(2));
@@ -383,16 +725,54 @@ function main() {
383
725
  console.log(HELP);
384
726
  return;
385
727
  }
386
- const violations = checkCmsDriven(process.cwd(), { configPath: args.configPath });
728
+ if (args.updateBaseline) {
729
+ updateBaselineCommand(args);
730
+ return;
731
+ }
732
+ const report = checkCmsDrivenReport(process.cwd(), { configPath: args.configPath });
733
+ if (report.remake?.active) {
734
+ console.log(
735
+ `check-cms-driven: REMAKE MODE until ${report.remake.until} (${report.remake.daysLeft} day(s) left): R3 and R4 do not fail.` +
736
+ (report.unbaselined > 0
737
+ ? ` ${report.unbaselined} violation(s) are not in the baseline yet: fix them, or run check-cms-driven --update-baseline before the window ends.`
738
+ : ''),
739
+ );
740
+ if (report.remake.endingSoon) {
741
+ console.log('check-cms-driven: the remake window is ending soon.');
742
+ }
743
+ } else if (report.remake) {
744
+ console.log(
745
+ `check-cms-driven: remake mode expired on ${report.remake.until}; the guard is strict again. Remove "remake" from cms-driven.config.json.`,
746
+ );
747
+ }
748
+ if (report.debt > 0) {
749
+ console.log(
750
+ `check-cms-driven: baseline debt: ${report.debt} R3/R4 violation(s) in ${report.debtFiles} file(s) (${BASELINE_NAME}, ${report.generatedAt})`,
751
+ );
752
+ if (report.debt > DEBT_THRESHOLD) {
753
+ console.log(
754
+ `check-cms-driven: NEEDS WORK: baseline is over ${DEBT_THRESHOLD}. Replace literals with palette tokens, then run check-cms-driven --update-baseline.`,
755
+ );
756
+ }
757
+ if (report.stale > 0) {
758
+ console.log(
759
+ `check-cms-driven: ${report.stale} baselined violation(s) are fixed. Run check-cms-driven --update-baseline to shrink it.`,
760
+ );
761
+ }
762
+ }
763
+ const violations = report.failures;
387
764
  if (violations.length === 0) {
388
765
  console.log('check-cms-driven: ok');
389
766
  return;
390
767
  }
391
- console.error('check-cms-driven: layouts must take page-specific content from the CMS.\n');
768
+ console.error(
769
+ 'check-cms-driven: colour and page-specific content come from the CMS, not code.\n',
770
+ );
392
771
  for (const violation of violations) console.error(` ${violation}`);
393
772
  console.error(
394
773
  `\n${violations.length} violation(s). R2: make it a registered component in a CMS template. ` +
395
- 'R1 is opt-in (cms-driven.config.json). Escape hatch: // se-exception: <reason>',
774
+ 'R1/R3: use a palette token or the CMS colour field. R1 and R3 are opt-in (cms-driven.config.json). ' +
775
+ 'Escape hatch: // se-exception: <reason>',
396
776
  );
397
777
  process.exit(1);
398
778
  } catch (error) {
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Baseline for check-cms-driven: a committed snapshot of today's R3 violations, so a site
3
+ * can turn the guard on without fixing everything first. New violations fail; the debt is
4
+ * shown on every run and can only shrink.
5
+ *
6
+ * File shape (cms-driven.baseline.json):
7
+ * { "version": 1, "generatedAt": "2026-11-17", "total": 3,
8
+ * "entries": { "src/a.ts": { "R3 hex colour: const x = '#fff';": 2 } } }
9
+ * Entries are keyed by file, rule and a hash of the whole offending line (not its number), so
10
+ * moving code does not churn the file. `total` must equal the sum of the counts: editing
11
+ * the entries by hand without updating it is rejected.
12
+ */
13
+ import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
14
+ import { join } from 'node:path';
15
+
16
+ export const BASELINE_NAME = 'cms-driven.baseline.json';
17
+
18
+ /** More baselined violations than this and the site is flagged as needing work. */
19
+ export const DEBT_THRESHOLD = 25;
20
+
21
+ /** @typedef {{ file: string, line: number, rule: string, what: string, text: string, hash: string }} Violation */
22
+
23
+ const entryKey = (v) => `${v.rule} ${v.what}: ${v.text} [${v.hash}]`;
24
+
25
+ /** @param {Violation[]} violations @param {string} date YYYY-MM-DD */
26
+ export function buildBaseline(violations, date) {
27
+ /** @type {Record<string, Record<string, number>>} */
28
+ const entries = {};
29
+ for (const v of violations) {
30
+ const file = entries[v.file] ?? {};
31
+ entries[v.file] = file;
32
+ file[entryKey(v)] = (file[entryKey(v)] ?? 0) + 1;
33
+ }
34
+ const sorted = {};
35
+ for (const file of Object.keys(entries).sort()) {
36
+ sorted[file] = Object.fromEntries(
37
+ Object.entries(entries[file]).sort(([a], [b]) => a.localeCompare(b)),
38
+ );
39
+ }
40
+ return { version: 1, generatedAt: date, total: violations.length, entries: sorted };
41
+ }
42
+
43
+ /** @returns {null | { version: 1, generatedAt: string, total: number, entries: Record<string, Record<string, number>> }} */
44
+ export function readBaseline(root) {
45
+ const file = join(root, BASELINE_NAME);
46
+ if (!existsSync(file)) return null;
47
+ let raw;
48
+ try {
49
+ raw = JSON.parse(readFileSync(file, 'utf8'));
50
+ } catch (error) {
51
+ const message = error instanceof Error ? error.message : String(error);
52
+ throw new Error(`cannot read ${BASELINE_NAME}: ${message}`);
53
+ }
54
+ const ok =
55
+ raw?.version === 1 &&
56
+ typeof raw.generatedAt === 'string' &&
57
+ Number.isInteger(raw.total) &&
58
+ raw.entries &&
59
+ typeof raw.entries === 'object';
60
+ if (!ok) throw new Error(`${BASELINE_NAME} is not a version 1 baseline`);
61
+ const sum = Object.values(raw.entries)
62
+ .flatMap((file) => Object.values(file))
63
+ .reduce((a, b) => a + b, 0);
64
+ if (sum !== raw.total) {
65
+ throw new Error(
66
+ `${BASELINE_NAME} total (${raw.total}) does not match its entries (${sum}). ` +
67
+ 'Regenerate it with check-cms-driven --update-baseline instead of editing it.',
68
+ );
69
+ }
70
+ return raw;
71
+ }
72
+
73
+ /**
74
+ * Split violations into those the baseline covers and the new ones.
75
+ * @param {Violation[]} violations
76
+ * @param {ReturnType<typeof readBaseline>} baseline
77
+ */
78
+ export function applyBaseline(violations, baseline) {
79
+ if (!baseline) return { fresh: violations, debt: 0, files: 0, stale: 0 };
80
+ const remaining = structuredClone(baseline.entries);
81
+ const fresh = [];
82
+ let covered = 0;
83
+ for (const v of violations) {
84
+ const left = remaining[v.file]?.[entryKey(v)] ?? 0;
85
+ if (left > 0) {
86
+ remaining[v.file][entryKey(v)] = left - 1;
87
+ covered += 1;
88
+ } else {
89
+ fresh.push(v);
90
+ }
91
+ }
92
+ const stale = baseline.total - covered;
93
+ return { fresh, debt: baseline.total, files: Object.keys(baseline.entries).length, stale };
94
+ }
95
+
96
+ /**
97
+ * Write the baseline for the current violations. Refuses to grow an existing one unless
98
+ * `allowGrow` is set (only while a remake window is open): otherwise debt goes up only
99
+ * with the first baseline, since a hand edit is rejected by the total check. An empty
100
+ * result removes the file.
101
+ * @returns {{ ok: true, action: 'created' | 'updated' | 'cleared' | 'unchanged', total: number }
102
+ * | { ok: false, grew: Violation[] }}
103
+ */
104
+ export function updateBaseline(root, violations, date, { allowGrow = false } = {}) {
105
+ const existing = readBaseline(root);
106
+ if (existing && !allowGrow) {
107
+ const { fresh } = applyBaseline(violations, existing);
108
+ if (fresh.length > 0) return { ok: false, grew: fresh };
109
+ }
110
+ const file = join(root, BASELINE_NAME);
111
+ if (violations.length === 0) {
112
+ if (existing) unlinkSync(file);
113
+ return { ok: true, action: existing ? 'cleared' : 'unchanged', total: 0 };
114
+ }
115
+ const next = buildBaseline(violations, date);
116
+ if (existing && JSON.stringify(existing.entries) === JSON.stringify(next.entries)) {
117
+ return { ok: true, action: 'unchanged', total: next.total };
118
+ }
119
+ writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
120
+ return { ok: true, action: existing ? 'updated' : 'created', total: next.total };
121
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@se-studio/site-check",
3
- "version": "2.14.1",
3
+ "version": "2.15.1",
4
4
  "description": "Validate SE marketing sites (sitemap, llms.txt) and download markdown files preserving structure",
5
5
  "repository": {
6
6
  "type": "git",
@@ -76,6 +76,7 @@
76
76
  "check-no-context-workarounds.mjs",
77
77
  "check-publish-state.mjs",
78
78
  "check-cms-driven.mjs",
79
+ "cms-driven-baseline.mjs",
79
80
  "screaming-frog"
80
81
  ],
81
82
  "keywords": [
@@ -94,7 +95,7 @@
94
95
  "url": "https://github.com/Something-Else-Studio/se-core-product/issues"
95
96
  },
96
97
  "dependencies": {
97
- "@se-studio/contentful-rest-api": "2.2.0",
98
+ "@se-studio/contentful-rest-api": "2.7.0",
98
99
  "@se-studio/core-data-types": "2.0.5"
99
100
  },
100
101
  "devDependencies": {