@miragon/slidev-validator 0.6.0 → 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/README.md CHANGED
@@ -138,11 +138,34 @@ config, so a report — and a CI log — is self-describing.
138
138
  | `no-restyled-bullets` | source | recommended | error |
139
139
  | `excalidraw-committed-light` | source | recommended | error |
140
140
  | `excalidraw-built-transparent` | source | recommended | warn |
141
+ | `brand-palette` | source | required | error |
142
+ | `brand-logo-asset` | source | required | error |
143
+ | `brand-token-defined` | source | required | error |
141
144
  | `element-overflow` | rendered | recommended | error |
142
145
  | `heading-black` | rendered | required | error |
143
146
  | `card-white` | rendered | required | error |
144
147
  | `overlay-safe-area` | rendered | required | error |
145
148
 
149
+ `brand-palette` and `brand-logo-asset` read their expected values from
150
+ `src/rules/source/brand-palette.json` — the validator's single machine-readable copy
151
+ of the palette (five brand colours, two sanctioned derivations, four status
152
+ colours), mirroring the `miragon-brand` plugin's `corporate-design/assets/tokens.json`.
153
+ `brand-palette` scans the toolkit's own styles, components/layouts and mermaid theme
154
+ plus the deck's committed Excalidraw diagrams, and reads all three ways of writing a
155
+ colour: a hex literal, an `rgb()`/`rgba()` value, and a CSS colour keyword in value
156
+ position (`color: black`, `fill="tomato"`). Colours inside comments are ignored, so
157
+ a file may document a forbidden value. The mesh-hero stops are allowlisted to the
158
+ hero shader and the theme tokens; the logo vectors are excluded there and asserted by
159
+ `brand-logo-asset` (viewBox + the single fill each variant carries).
160
+
161
+ `brand-token-defined` asserts that every literal `var(--miragon-*)` resolves to a
162
+ token `packages/toolkit/styles/theme.css` actually defines. It exists because CSS
163
+ drops an undefined custom property silently: the element inherits instead, so the
164
+ build stays green and the breakage shows up on exactly the one slide that uses the
165
+ token, usually as something plausible-looking. A computed name
166
+ (`var(--miragon-gradient-${accent})`) cannot be resolved statically and is skipped
167
+ rather than guessed at.
168
+
146
169
  `content-heading` has a per-slide opt-out (`allowMultilineHeading: true` in the
147
170
  slide frontmatter). `overlay-safe-area` reads the toolkit-owned safe-area model and
148
171
  cannot be switched off by a deck; its only escape hatch is a per-slide
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miragon/slidev-validator",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "The Miragon Slidev deck validator: a configurable design-system linter (stable rule IDs, off/warn/error severities, extends/overrides/exceptions) shipped as a versioned CLI so central guardrail improvements reach decks over npm instead of a frozen copy.",
6
6
  "keywords": [
@@ -33,9 +33,9 @@
33
33
  "node": ">=20"
34
34
  },
35
35
  "dependencies": {
36
- "@slidev/parser": "52.18.0",
37
- "markdown-it": "14.2.0",
38
- "playwright-chromium": "1.62.1"
36
+ "@slidev/parser": "52.19.1",
37
+ "markdown-it": "15.0.2",
38
+ "playwright-chromium": "1.63.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@miragon/slidev-toolkit": ">=1.15.0 <2"
@@ -19,6 +19,9 @@ import { noInlineFont } from './source/no-inline-font.mjs'
19
19
  import { noRestyledBullets } from './source/no-restyled-bullets.mjs'
20
20
  import { excalidrawCommittedLight } from './source/excalidraw-committed-light.mjs'
21
21
  import { excalidrawBuiltTransparent } from './source/excalidraw-built-transparent.mjs'
22
+ import { brandPalette } from './source/brand-palette.mjs'
23
+ import { brandLogoAsset } from './source/brand-logo-asset.mjs'
24
+ import { brandTokenDefined } from './source/brand-token-defined.mjs'
22
25
 
23
26
  import { elementOverflow } from './rendered/element-overflow.mjs'
24
27
  import { headingBlack } from './rendered/heading-black.mjs'
@@ -38,6 +41,9 @@ export const allRules = [
38
41
  noRestyledBullets,
39
42
  excalidrawCommittedLight,
40
43
  excalidrawBuiltTransparent,
44
+ brandPalette,
45
+ brandLogoAsset,
46
+ brandTokenDefined,
41
47
  elementOverflow,
42
48
  headingBlack,
43
49
  cardWhite,
@@ -45,11 +45,21 @@ export function measureSlide(n) {
45
45
  const blueHeads = [...layout.querySelectorAll('h1, h2')].filter((h) => isBlue(rgb(getComputedStyle(h).color))).length
46
46
 
47
47
  // --- Cards stay white: no colored/gradient background, no colored left-accent border ---
48
- const badCards = [...layout.querySelectorAll('[class*="rounded-xl"]')].filter((el) => {
48
+ // `.mg-card` is what Card.vue actually renders. The `rounded-xl` selector is
49
+ // kept for deck-local card markup built from utility classes, but on its own it
50
+ // matched NOTHING in the toolkit, which made this required rule vacuously green.
51
+ // The compare/goodbad panels are deliberately coloured by their layout and carry
52
+ // their own classes, so they stay out of this selector by construction.
53
+ const badCards = [...layout.querySelectorAll('.mg-card, [class*="rounded-xl"]')].filter((el) => {
49
54
  const s = getComputedStyle(el)
50
55
  if (s.backgroundImage && s.backgroundImage !== 'none') return true
51
56
  const bg = rgb(s.backgroundColor)
52
- if (bg && bg.a > 0.01 && !(bg.r >= 250 && bg.g >= 250 && bg.b >= 250)) return true
57
+ // "White" has to include the brand's neutral surface: grau is #F9F7F7 =
58
+ // rgb(249, 247, 247), so a 250 floor would have failed the palette's own
59
+ // card colour. 247 is that value's lowest channel exactly — one step lower
60
+ // and nothing else in the palette sneaks in (the next-lightest sanctioned
61
+ // colour, blau-hell #6B8AFF, is 107 in its red channel).
62
+ if (bg && bg.a > 0.01 && !(bg.r >= 247 && bg.g >= 247 && bg.b >= 247)) return true
53
63
  const lw = parseFloat(s.borderLeftWidth) || 0
54
64
  const tw = parseFloat(s.borderTopWidth) || 0
55
65
  if (lw >= 3 && lw > tw + 1) {
@@ -0,0 +1,107 @@
1
+ import { readFileSync, existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { repoRoot } from '../../helpers.mjs'
5
+
6
+ /**
7
+ * The bundled logo vectors must stay the untouched official artwork.
8
+ *
9
+ * brand-review rule B5: a logo that is recoloured, reshaped, or redrawn is a hard
10
+ * fail — and the failure mode is quiet. A single wrong digit (#00e476 instead of
11
+ * #00e676) renders as "green" on every slide and survives review, because nobody
12
+ * eyeballs a wordmark against a swatch. So the two properties that a hand edit
13
+ * actually breaks are asserted mechanically:
14
+ *
15
+ * 1. the viewBox (proportions: a squashed or cropped mark changes it), and
16
+ * 2. the single fill each variant carries (its colour).
17
+ *
18
+ * The expected values live in `brand-palette.json` next to this file — the same
19
+ * file the `brand-palette` rule reads — so the validator keeps one machine-readable
20
+ * brand source, not two.
21
+ *
22
+ * Not asserted: the path data. Comparing a full byte hash would fail on a
23
+ * lossless re-export (formatting, id renaming) while catching nothing a human
24
+ * would call a brand violation.
25
+ */
26
+
27
+ const BRAND = JSON.parse(readFileSync(fileURLToPath(new URL('./brand-palette.json', import.meta.url)), 'utf8'))
28
+
29
+ /** Every fill declared in an SVG, as an attribute (`fill="#…"`) or in a <style> rule (`fill:#…`). */
30
+ const FILL = /\bfill\s*[:=]\s*["']?(#[0-9a-fA-F]{3,8})/g
31
+
32
+ /** 1-based line number of a character offset. */
33
+ const lineOf = (src, index) => src.slice(0, index).split('\n').length
34
+
35
+ /** `#fff` -> `#ffffff`, lowercased, so the short and long forms compare equal. */
36
+ export function normalizeFill(hex) {
37
+ let h = String(hex).replace(/^#/, '').toLowerCase()
38
+ if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('')
39
+ return `#${h}`
40
+ }
41
+
42
+ /**
43
+ * Pure core (fixture-free, testable): what is wrong with one logo SVG, given its
44
+ * manifest entry. Returns an array of `{ line, message }`, empty when the asset is
45
+ * the official vector.
46
+ */
47
+ export function checkLogoSvg(svg, asset) {
48
+ const problems = []
49
+
50
+ const vb = svg.match(/\bviewBox\s*=\s*["']([^"']*)["']/)
51
+ if (!vb) {
52
+ problems.push({ line: 1, message: 'has no viewBox (the official vector declares one)' })
53
+ } else {
54
+ const actual = vb[1].trim().replace(/\s+/g, ' ')
55
+ const expected = asset.viewBox.trim().replace(/\s+/g, ' ')
56
+ if (actual !== expected) {
57
+ problems.push({ line: lineOf(svg, vb.index), message: `viewBox "${actual}" is not the official "${expected}". The mark has been rescaled, cropped, or redrawn.` })
58
+ }
59
+ }
60
+
61
+ const fills = []
62
+ FILL.lastIndex = 0
63
+ let m
64
+ while ((m = FILL.exec(svg))) fills.push({ raw: m[1], hex: normalizeFill(m[1]), index: m.index })
65
+ const expectedFill = normalizeFill(asset.fill)
66
+ if (!fills.length) {
67
+ problems.push({ line: 1, message: `declares no fill (expected exactly one, ${asset.fill} for the "${asset.variant}" variant)` })
68
+ } else {
69
+ const distinct = [...new Set(fills.map((f) => f.hex))]
70
+ if (distinct.length > 1) {
71
+ problems.push({ line: lineOf(svg, fills[0].index), message: `declares ${distinct.length} fills (${distinct.join(', ')}); the official vector is single-colour (${asset.fill})` })
72
+ }
73
+ for (const f of fills) {
74
+ if (f.hex !== expectedFill) {
75
+ problems.push({ line: lineOf(svg, f.index), message: `fill ${f.raw} is not the official "${asset.variant}" colour ${asset.fill}. Check every digit.` })
76
+ }
77
+ }
78
+ }
79
+ return problems
80
+ }
81
+
82
+ export const brandLogoAsset = {
83
+ id: 'brand-logo-asset',
84
+ type: 'source',
85
+ title: 'brand logo assets are the official vectors',
86
+ message: 'Bundled logo SVGs must be the unaltered official vectors',
87
+ meta: { category: 'required', default: 'error' },
88
+ check() {
89
+ const present = BRAND.logo.assets.filter((a) => existsSync(join(repoRoot(), a.file)))
90
+ if (!present.length) {
91
+ // A scaffolded deck consumes the toolkit from node_modules and vendors no
92
+ // assets. Nothing to check is NOT a pass, so report it as such.
93
+ return { skipped: 'no bundled logo assets in this repo (the toolkit ships them from node_modules)' }
94
+ }
95
+ const offenders = []
96
+ for (const asset of BRAND.logo.assets) {
97
+ const file = join(repoRoot(), asset.file)
98
+ if (!existsSync(file)) {
99
+ offenders.push({ file: asset.file, message: 'missing: the toolkit must ship this official logo variant' })
100
+ continue
101
+ }
102
+ const svg = readFileSync(file, 'utf8')
103
+ for (const p of checkLogoSvg(svg, asset)) offenders.push({ file: asset.file, line: p.line, message: p.message })
104
+ }
105
+ return offenders
106
+ },
107
+ }
@@ -0,0 +1,54 @@
1
+ {
2
+ "$description": "The Miragon palette, machine-readable. This file is the ONLY place the validator keeps brand colour values, so the `brand-palette` and `brand-logo-asset` rules cannot drift apart from each other or grow a hand-maintained copy inside a rule. Mirrors the miragon-brand plugin, skill `corporate-design`, `assets/tokens.json`; where the two disagree, tokens.json wins and this file gets pulled back in line.",
3
+ "$source": "miragon-brand plugin -> skills/corporate-design/assets/tokens.json (color.*, functional.*, gradient.mesh-hero, logo.*)",
4
+ "$rule": "brand-review rule B1 (exact palette colours) is a HARD fail, hence category `required` / default `error`.",
5
+
6
+ "palette": [
7
+ { "name": "blau", "hex": "#335DE5", "role": "primary", "note": "Primary: surfaces, buttons, links, accents." },
8
+ { "name": "gruen", "hex": "#00E676", "role": "accent", "note": "Accent only: key visual, highlights, one word. Never body text on white (1.67:1, fails WCAG AA)." },
9
+ { "name": "grau", "hex": "#F9F7F7", "role": "surface", "note": "Quiet neutral surface." },
10
+ { "name": "schwarz", "hex": "#1D1D1D", "role": "text", "note": "Text on light, monochrome logo. The brand excludes pure #000000." },
11
+ { "name": "weiss", "hex": "#FFFFFF", "role": "surface", "note": "Text on colour, surfaces." },
12
+ { "name": "blau-link", "hex": "#2B50D4", "role": "interaction", "note": "Derived from blau: links and accent text on white, 6.56:1 (AA). Also tokens.json functional.info." },
13
+ { "name": "blau-hell", "hex": "#6B8AFF", "role": "interaction-dark", "note": "Derived from blau: links and accents on dark ground." },
14
+ { "name": "success", "hex": "#0B7A55", "role": "status", "note": "STATE only, never a design colour." },
15
+ { "name": "warning", "hex": "#92610A", "role": "status", "note": "STATE only, never a design colour." },
16
+ { "name": "danger", "hex": "#C92A2A", "role": "status", "note": "STATE only, never a design colour." }
17
+ ],
18
+
19
+ "restricted": [
20
+ {
21
+ "name": "mesh-hero",
22
+ "hexes": ["#1A1A4E", "#0D0D2B", "#00C853"],
23
+ "files": [
24
+ "packages/toolkit/components/BrandMeshBackground.vue",
25
+ "packages/toolkit/styles/theme.css"
26
+ ],
27
+ "note": "tokens.json gradient.mesh-hero. Deliberately outside the base palette and valid ONLY for the animated hero shader and its CSS fallback tokens. #335DE5 and #00E676 are the other two stops and are already palette values."
28
+ }
29
+ ],
30
+
31
+ "scan": {
32
+ "$note": "Repo-relative globs, matched with src/glob.mjs. Only files the toolkit ships (its own styles, components, layouts, mermaid theme) plus the deck's committed Excalidraw diagrams carry author-chosen colour; slide markdown is covered by `no-raw-html` (no hex may appear there at all).",
33
+ "include": [
34
+ "packages/toolkit/styles/*.css",
35
+ "packages/toolkit/**/*.vue",
36
+ "packages/toolkit/setup/*.ts",
37
+ "deck/**/*.excalidraw.svg"
38
+ ],
39
+ "exclude": [
40
+ "packages/toolkit/assets/*.svg"
41
+ ],
42
+ "$excludeReason": "The logo vectors are official artwork, not authored colour: they are checked byte-for-intent by the `brand-logo-asset` rule below instead."
43
+ },
44
+
45
+ "logo": {
46
+ "$note": "The official vectors, unaltered. brand-review rule B5: a recoloured or reshaped logo is a hard fail. viewBox values come from tokens.json logo.wordmarkViewBox / logo.kometViewBox; each file carries exactly one fill, declared once in its <style> block.",
47
+ "assets": [
48
+ { "file": "packages/toolkit/assets/logo.svg", "variant": "gruen", "viewBox": "0 0 316.05 48.42", "fill": "#00e676" },
49
+ { "file": "packages/toolkit/assets/logo-white.svg", "variant": "weiss", "viewBox": "0 0 316.05 48.42", "fill": "#fff" },
50
+ { "file": "packages/toolkit/assets/logo-blue.svg", "variant": "blau", "viewBox": "0 0 316.05 48.42", "fill": "#335de5" },
51
+ { "file": "packages/toolkit/assets/komet.svg", "variant": "gruen", "viewBox": "0 0 288.08 89.63", "fill": "#00e676" }
52
+ ]
53
+ }
54
+ }
@@ -0,0 +1,361 @@
1
+ import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { repoRoot, toRel } from '../../helpers.mjs'
5
+ import { matchesAny } from '../../glob.mjs'
6
+
7
+ /**
8
+ * Every colour literal must be a Miragon palette value.
9
+ *
10
+ * The palette is a closed set (brand-review rule B1, a HARD fail): five brand
11
+ * colours, two sanctioned derivations, four status colours. Anything else — a
12
+ * Tailwind slate, a hand-picked tint, pure #000000 — is a foreign hue. Shades that
13
+ * are NOT in the palette must be produced with `color-mix()` from a brand token,
14
+ * never pasted as a hex, which is exactly what `styles/theme.css` does.
15
+ *
16
+ * The allowed values live in `brand-palette.json` next to this file, not in the
17
+ * code, so the palette has ONE machine-readable home in the validator and cannot
18
+ * drift between this rule and `brand-logo-asset`.
19
+ *
20
+ * All three ways of writing a colour count: a hex literal, an `rgb()`/`rgba()`
21
+ * value, and a CSS colour keyword in value position (`color: black`).
22
+ *
23
+ * Scope (see `scan` in the JSON): the toolkit's own styles, components/layouts,
24
+ * the mermaid theme, and the deck's committed Excalidraw diagrams. Slide markdown
25
+ * is not scanned here because `no-raw-html` already forbids any hex reaching it.
26
+ * The logo vectors are excluded and covered by `brand-logo-asset`.
27
+ *
28
+ * Comments are blanked before matching. This matters more than it sounds: the
29
+ * repo documents the palette IN the files it governs — `theme.css` names #000000
30
+ * to say the brand excludes it, `cover.vue` names the mesh stops to explain why
31
+ * they are off-palette. A naive scanner reports every one of those and is turned
32
+ * off within a day.
33
+ */
34
+
35
+ const BRAND = JSON.parse(readFileSync(fileURLToPath(new URL('./brand-palette.json', import.meta.url)), 'utf8'))
36
+
37
+ /** Directory names never worth walking. */
38
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.slidev', '.vite', 'coverage'])
39
+
40
+ /**
41
+ * Which comment syntaxes a file actually has. `//` is a comment in TS/JS and in
42
+ * a `.vue` <script>, but NOT in CSS, where blanking it would silently hide real
43
+ * declarations. `.vue` gets all three because it is HTML + JS + CSS in one file.
44
+ */
45
+ const COMMENT_SYNTAX = {
46
+ '.css': ['block'],
47
+ '.ts': ['block', 'line'],
48
+ '.js': ['block', 'line'],
49
+ '.mjs': ['block', 'line'],
50
+ '.vue': ['block', 'line', 'html'],
51
+ '.svg': ['html'],
52
+ '.html': ['html'],
53
+ '.md': ['html'],
54
+ }
55
+
56
+ const SYNTAX_RE = {
57
+ block: '\\/\\*[\\s\\S]*?\\*\\/',
58
+ html: '<!--[\\s\\S]*?-->',
59
+ // `(?<!:)` keeps `https://…` and other `scheme://` URLs from swallowing the
60
+ // rest of the line. Alternation order (block, html, line) resolves nesting:
61
+ // the scanner takes whichever opener comes first, so `/* // */` and `// /*`
62
+ // both behave.
63
+ line: '(?<!:)\\/\\/[^\\n]*',
64
+ }
65
+
66
+ /** The comment-blanking regex for a file extension, or null if it has no comments. */
67
+ function commentRe(ext) {
68
+ const kinds = COMMENT_SYNTAX[ext] ?? ['block', 'html']
69
+ return kinds.length ? new RegExp(kinds.map((k) => SYNTAX_RE[k]).join('|'), 'g') : null
70
+ }
71
+
72
+ /**
73
+ * Replace every comment with blanks, preserving newlines AND column positions so
74
+ * reported line/column numbers stay true to the original file.
75
+ */
76
+ export function blankComments(source, ext) {
77
+ const re = commentRe(ext)
78
+ if (!re) return source
79
+ return source.replace(re, (m) => m.replace(/[^\n]/g, ' '))
80
+ }
81
+
82
+ /** The extension of a path, lowercased, including the dot ('' if none). */
83
+ const extOf = (p) => {
84
+ const i = String(p).lastIndexOf('.')
85
+ return i < 0 ? '' : String(p).slice(i).toLowerCase()
86
+ }
87
+
88
+ /**
89
+ * Normalise a hex literal to `{ r, g, b, a }`. Accepts #rgb, #rgba, #rrggbb and
90
+ * #rrggbbaa; the 3/4-digit short forms are expanded (`#fff` -> `#ffffff`).
91
+ * Returns null for a length CSS never defines (so `#Ebene_2`-style ids are safe).
92
+ */
93
+ export function parseHex(hex) {
94
+ let h = String(hex).replace(/^#/, '')
95
+ if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('')
96
+ if (h.length !== 6 && h.length !== 8) return null
97
+ if (!/^[0-9a-fA-F]+$/.test(h)) return null
98
+ return {
99
+ r: parseInt(h.slice(0, 2), 16),
100
+ g: parseInt(h.slice(2, 4), 16),
101
+ b: parseInt(h.slice(4, 6), 16),
102
+ a: h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
103
+ }
104
+ }
105
+
106
+ /** `{ r, g, b }` as a canonical lowercase `#rrggbb`. */
107
+ export const toHex = (c) => `#${[c.r, c.g, c.b].map((n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0')).join('')}`
108
+
109
+ /**
110
+ * Normalise the inside of an `rgb()` / `rgba()` value to `{ r, g, b, a }`.
111
+ * Handles both the legacy comma form and the modern space/slash form, and
112
+ * percentages. Returns null when a channel is not a literal number (e.g.
113
+ * `rgb(var(--x))`) — nothing to compare against the palette there.
114
+ */
115
+ export function parseRgbFn(inner) {
116
+ const parts = String(inner).split(/[\s,/]+/).filter(Boolean)
117
+ if (parts.length < 3) return null
118
+ const chan = (p, max) => {
119
+ if (/^[+-]?\d*\.?\d+%$/.test(p)) return (parseFloat(p) / 100) * max
120
+ if (/^[+-]?\d*\.?\d+$/.test(p)) return parseFloat(p)
121
+ return NaN
122
+ }
123
+ const r = chan(parts[0], 255)
124
+ const g = chan(parts[1], 255)
125
+ const b = chan(parts[2], 255)
126
+ if (![r, g, b].every((n) => Number.isFinite(n) && n >= 0 && n <= 255)) return null
127
+ const a = parts[3] === undefined ? 1 : chan(parts[3], 1)
128
+ return { r, g, b, a: Number.isFinite(a) ? a : 1 }
129
+ }
130
+
131
+ /** Longest-first so `#ffffffcc` is read as 8 digits, not `#ffffff` + junk. */
132
+ const HEX_LITERAL = /#([0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{4}|[0-9a-fA-F]{3})(?![0-9a-zA-Z_-])/g
133
+ const RGB_LITERAL = /\brgba?\(([^)]*)\)/gi
134
+
135
+ /**
136
+ * A CSS colour keyword is a colour literal too, and a hex-only scan waves it
137
+ * through: `color: black` paints #000000, the one shade the brand names
138
+ * explicitly to exclude it.
139
+ *
140
+ * The verdict never needs the keyword's value. No Miragon value has a CSS name
141
+ * except #FFFFFF, so `white` is weiss and passes, `transparent` / `currentColor`
142
+ * are absent from this list because they are not colours, and every other keyword
143
+ * is off-palette by construction. Only the sixteen basic keywords carry a hex
144
+ * below (values beyond doubt) so the report can name the nearest allowed colour;
145
+ * for the remaining keywords the hint is dropped rather than guessed.
146
+ */
147
+ const CSS_COLOR_KEYWORDS = new Set(`
148
+ aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown
149
+ burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan
150
+ darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid
151
+ darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet
152
+ deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro
153
+ ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki
154
+ lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow
155
+ lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray
156
+ lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine
157
+ mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise
158
+ mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab
159
+ orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru
160
+ pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown
161
+ seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan
162
+ teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen
163
+ `.trim().split(/\s+/))
164
+
165
+ /** The sixteen basic HTML keywords, the only ones whose value this file asserts. */
166
+ const BASIC_KEYWORD_HEX = {
167
+ black: '#000000', silver: '#c0c0c0', gray: '#808080', white: '#ffffff',
168
+ maroon: '#800000', red: '#ff0000', purple: '#800080', fuchsia: '#ff00ff',
169
+ green: '#008000', lime: '#00ff00', olive: '#808000', yellow: '#ffff00',
170
+ navy: '#000080', blue: '#0000ff', teal: '#008080', aqua: '#00ffff',
171
+ }
172
+
173
+ /** Shorthands whose value carries a colour but whose name does not end in `color`. */
174
+ const COLOR_PROPS = new Set([
175
+ 'fill', 'stroke', 'background', 'border', 'border-top', 'border-right', 'border-bottom',
176
+ 'border-left', 'border-block', 'border-inline', 'outline', 'box-shadow', 'text-shadow',
177
+ 'text-decoration', 'column-rule',
178
+ ])
179
+
180
+ /**
181
+ * Is this property's value a colour? `*color` covers CSS (`background-color`,
182
+ * `stop-color`) and camelCase theme keys alike (`primaryTextColor` in the mermaid
183
+ * setup); a custom property may hold anything, so it is always inspected.
184
+ */
185
+ function isColorProp(name) {
186
+ const p = String(name).toLowerCase()
187
+ if (p.startsWith('--')) return true
188
+ if (p.endsWith('color')) return true
189
+ return COLOR_PROPS.has(p)
190
+ }
191
+
192
+ // Keywords only count in value position, never in prose, a class name, or a
193
+ // property name: `slategray` in a comment is documentation, `--gray` is a token
194
+ // reference, `grayscale(1)` is a filter.
195
+ const DECLARATION = /(--[a-zA-Z0-9_-]+|[a-zA-Z][a-zA-Z-]*)\s*:\s*([^;{}<\n]*)/g
196
+ const COLOR_ATTR = /\b(fill|stroke|color|stop-color|flood-color|lighting-color)\s*=\s*(["'])([^"']*)\2/gi
197
+ /** A whole word, where `-` counts as a word character: `sans-serif` yields neither `sans` nor `serif`. */
198
+ const WORD = /(?<![\w-])([a-zA-Z]+)(?![\w-])/g
199
+ const blankUrls = (v) => v.replace(/url\([^)]*\)/gi, (m) => ' '.repeat(m.length))
200
+
201
+ /** Every CSS colour keyword sitting in a colour value on this line, with its column. */
202
+ export function findColorKeywords(line) {
203
+ const out = new Map()
204
+ const scanValue = (value, offset) => {
205
+ const v = blankUrls(value)
206
+ WORD.lastIndex = 0
207
+ let k
208
+ while ((k = WORD.exec(v))) {
209
+ const word = k[1].toLowerCase()
210
+ if (CSS_COLOR_KEYWORDS.has(word)) out.set(offset + k.index, { word, raw: k[1], column: offset + k.index })
211
+ }
212
+ }
213
+ let m
214
+ DECLARATION.lastIndex = 0
215
+ while ((m = DECLARATION.exec(line))) {
216
+ if (isColorProp(m[1])) scanValue(m[2], m.index + m[0].length - m[2].length)
217
+ }
218
+ COLOR_ATTR.lastIndex = 0
219
+ while ((m = COLOR_ATTR.exec(line))) scanValue(m[3], m.index + m[0].length - m[3].length - 1)
220
+ return [...out.values()]
221
+ }
222
+
223
+ /**
224
+ * The allowed colours for one repo-relative file: the palette, plus any
225
+ * restricted set this file is explicitly allowlisted for (the mesh-hero stops).
226
+ * Returns Map<'#rrggbb', label>.
227
+ */
228
+ export function allowedFor(relPath) {
229
+ const allowed = new Map()
230
+ for (const c of BRAND.palette) allowed.set(toHex(parseHex(c.hex)), c.name)
231
+ for (const r of BRAND.restricted ?? []) {
232
+ if (!matchesAny(relPath, r.files)) continue
233
+ for (const h of r.hexes) allowed.set(toHex(parseHex(h)), `${r.name}, only in ${r.files.join(' / ')}`)
234
+ }
235
+ return allowed
236
+ }
237
+
238
+ /** The allowed value closest in RGB space, to make the fix obvious. */
239
+ function nearest(color, allowed) {
240
+ let best = null
241
+ let bestD = Infinity
242
+ for (const [hex, name] of allowed) {
243
+ const c = parseHex(hex)
244
+ const d = (color.r - c.r) ** 2 + (color.g - c.g) ** 2 + (color.b - c.b) ** 2
245
+ if (d < bestD) {
246
+ bestD = d
247
+ best = { hex, name }
248
+ }
249
+ }
250
+ return best
251
+ }
252
+
253
+ /**
254
+ * Pure core (fixture-free, testable): every off-palette colour literal in
255
+ * `source`, as { line, column, value, hex, nearest }. `relPath` decides both the
256
+ * comment syntax (by extension) and the restricted-set allowlist.
257
+ *
258
+ * Fully transparent values (alpha 0) are skipped: they paint nothing and carry no
259
+ * brand colour, so `rgba(0, 0, 0, 0)` is a spelling of `transparent`, not black.
260
+ */
261
+ export function findOffPaletteColors(source, relPath) {
262
+ const allowed = allowedFor(relPath)
263
+ const clean = blankComments(source, extOf(relPath))
264
+ const found = []
265
+ clean.split('\n').forEach((line, i) => {
266
+ const hit = (index, value, color) => {
267
+ if (!color || color.a === 0) return
268
+ if (allowed.has(toHex(color))) return
269
+ found.push({ line: i + 1, column: index, value, hex: toHex(color), nearest: nearest(color, allowed) })
270
+ }
271
+ HEX_LITERAL.lastIndex = 0
272
+ let m
273
+ while ((m = HEX_LITERAL.exec(line))) hit(m.index, m[0], parseHex(m[1]))
274
+ RGB_LITERAL.lastIndex = 0
275
+ while ((m = RGB_LITERAL.exec(line))) hit(m.index, m[0], parseRgbFn(m[1]))
276
+ for (const kw of findColorKeywords(line)) {
277
+ const hex = BASIC_KEYWORD_HEX[kw.word]
278
+ if (hex && allowed.has(hex)) continue
279
+ found.push({
280
+ line: i + 1,
281
+ column: kw.column,
282
+ value: kw.raw,
283
+ hex: hex ?? null,
284
+ nearest: hex ? nearest(parseHex(hex), allowed) : null,
285
+ })
286
+ }
287
+ })
288
+ return found.sort((a, b) => a.line - b.line || a.column - b.column)
289
+ }
290
+
291
+ /** The literal path prefix of a glob, i.e. everything before its first wildcard. */
292
+ function globRoot(glob) {
293
+ const out = []
294
+ for (const seg of glob.split('/')) {
295
+ if (seg.includes('*') || seg.includes('?')) break
296
+ out.push(seg)
297
+ }
298
+ return out.join('/')
299
+ }
300
+
301
+ /** Every file under the configured `scan.include` globs, minus `scan.exclude`. */
302
+ export function scanFiles() {
303
+ const { include, exclude = [] } = BRAND.scan
304
+ const files = new Set()
305
+ const walk = (dir) => {
306
+ if (!existsSync(dir)) return
307
+ for (const name of readdirSync(dir)) {
308
+ if (SKIP_DIRS.has(name)) continue
309
+ const p = join(dir, name)
310
+ let st
311
+ try {
312
+ st = statSync(p)
313
+ } catch {
314
+ continue
315
+ }
316
+ if (st.isDirectory()) walk(p)
317
+ else {
318
+ const rel = toRel(p)
319
+ if (matchesAny(rel, include) && !matchesAny(rel, exclude)) files.add(p)
320
+ }
321
+ }
322
+ }
323
+ for (const root of new Set(include.map(globRoot))) walk(join(repoRoot(), root))
324
+ return [...files].sort()
325
+ }
326
+
327
+ /** A short, readable window of the offending line (Excalidraw SVGs are one huge line). */
328
+ function excerpt(line, column) {
329
+ const from = Math.max(0, column - 40)
330
+ const to = Math.min(line.length, column + 40)
331
+ return `${from > 0 ? '…' : ''}${line.slice(from, to).trim()}${to < line.length ? '…' : ''}`
332
+ }
333
+
334
+ export const brandPalette = {
335
+ id: 'brand-palette',
336
+ type: 'source',
337
+ title: 'colours come from the Miragon palette',
338
+ message: 'Colour literals must be Miragon palette values',
339
+ meta: { category: 'required', default: 'error' },
340
+ check() {
341
+ const files = scanFiles()
342
+ if (!files.length) {
343
+ return { skipped: 'nothing in scope (no vendored toolkit sources and no committed Excalidraw diagrams)' }
344
+ }
345
+ const offenders = []
346
+ for (const file of files) {
347
+ const rel = toRel(file)
348
+ const src = readFileSync(file, 'utf8')
349
+ const byLine = src.split('\n')
350
+ for (const v of findOffPaletteColors(src, rel)) {
351
+ const near = v.nearest ? ` (nearest allowed: ${v.nearest.hex} ${v.nearest.name})` : ''
352
+ offenders.push({
353
+ file: rel,
354
+ line: v.line,
355
+ message: `${v.value} is not a Miragon palette colour${near}. Use a brand token or derive the shade with color-mix(); the palette is src/rules/source/brand-palette.json. → ${excerpt(byLine[v.line - 1] ?? '', v.column)}`,
356
+ })
357
+ }
358
+ }
359
+ return offenders
360
+ },
361
+ }
@@ -0,0 +1,136 @@
1
+ import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { matchesAny } from '../../glob.mjs'
4
+ import { repoRoot, toRel } from '../../helpers.mjs'
5
+
6
+ /**
7
+ * Every `var(--miragon-*)` must resolve to a token that theme.css actually defines.
8
+ *
9
+ * This exists because of a real, silent regression: a palette cleanup removed
10
+ * `--miragon-blue-dark`, but `code.css` still read it. CSS does not warn about an
11
+ * undefined custom property. The declaration is simply dropped and the element
12
+ * inherits instead, so inline code on the closing slide rendered white-on-white.
13
+ * The build was green, the deck was broken, and nothing but a human eye on that
14
+ * one slide would have caught it.
15
+ *
16
+ * The failure mode is the point: an undefined token is invisible everywhere except
17
+ * the one place it renders, and it renders as "inherited", which usually looks
18
+ * plausible. So it gets asserted mechanically instead.
19
+ *
20
+ * Deliberately narrow:
21
+ * - only the `--miragon-*` namespace (the theme's own contract; a deck is free
22
+ * to define its own variables anywhere)
23
+ * - only fully closed, literal references `var(--miragon-foo)`. A computed name
24
+ * (`var(--miragon-gradient-${accent})` in a Vue binding) cannot be resolved
25
+ * statically and is skipped rather than guessed at.
26
+ */
27
+
28
+ /** Where a token may be DEFINED. theme.css is the single token file by design. */
29
+ const DEFINITION_FILES = ['packages/toolkit/styles/theme.css']
30
+
31
+ /** Where a token may be USED. */
32
+ const USAGE_GLOBS = [
33
+ 'packages/toolkit/**/*.vue',
34
+ 'packages/toolkit/**/*.css',
35
+ 'packages/toolkit/**/*.ts',
36
+ 'deck/**/*.md',
37
+ 'deck/**/*.vue',
38
+ ]
39
+
40
+ const DEFINITION = /^\s*(--miragon-[a-z0-9-]+)\s*:/gm
41
+ /** A literal, closed reference. `[^)]*` keeps `var(--x, fallback)` in scope. */
42
+ const USAGE = /var\(\s*(--miragon-[a-z0-9-]+)\s*[),]/g
43
+
44
+ /** 1-based line number of a character offset. */
45
+ const lineOf = (src, index) => src.slice(0, index).split('\n').length
46
+
47
+ /** Pure core (fixture-free, testable): the token names a stylesheet defines. */
48
+ export function definedTokens(css) {
49
+ return new Set([...css.matchAll(DEFINITION)].map((m) => m[1]))
50
+ }
51
+
52
+ /**
53
+ * Pure core: every literal `var(--miragon-*)` in a source file that is not in
54
+ * `defined`. Returns `{ token, line }[]`.
55
+ *
56
+ * A `var(--x, fallback)` with a fallback still counts as undefined: the fallback
57
+ * hides the breakage at render time, but the token is gone and the intent is lost.
58
+ * That is worth one line of report, not silence.
59
+ */
60
+ export function undefinedUsages(src, defined) {
61
+ const out = []
62
+ for (const m of src.matchAll(USAGE)) {
63
+ if (!defined.has(m[1])) out.push({ token: m[1], line: lineOf(src, m.index) })
64
+ }
65
+ return out
66
+ }
67
+
68
+ /** Directory names never worth walking. */
69
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.slidev', 'coverage'])
70
+
71
+ /** The literal path prefix of a glob, i.e. everything before its first wildcard. */
72
+ function globRoot(glob) {
73
+ const out = []
74
+ for (const seg of glob.split('/')) {
75
+ if (seg.includes('*') || seg.includes('?')) break
76
+ out.push(seg)
77
+ }
78
+ return out.join('/')
79
+ }
80
+
81
+ /** Absolute paths of every file matching USAGE_GLOBS. */
82
+ function usageFiles() {
83
+ const files = new Set()
84
+ const walk = (dir) => {
85
+ if (!existsSync(dir)) return
86
+ for (const name of readdirSync(dir)) {
87
+ if (SKIP_DIRS.has(name)) continue
88
+ const p = join(dir, name)
89
+ let st
90
+ try {
91
+ st = statSync(p)
92
+ } catch {
93
+ continue
94
+ }
95
+ if (st.isDirectory()) walk(p)
96
+ else if (matchesAny(toRel(p), USAGE_GLOBS)) files.add(p)
97
+ }
98
+ }
99
+ for (const r of new Set(USAGE_GLOBS.map(globRoot))) walk(join(repoRoot(), r))
100
+ return [...files].sort()
101
+ }
102
+
103
+ export const brandTokenDefined = {
104
+ id: 'brand-token-defined',
105
+ type: 'source',
106
+ title: 'every brand token reference resolves',
107
+ message: 'var(--miragon-*) must point at a token theme.css defines',
108
+ meta: { category: 'required', default: 'error' },
109
+ check() {
110
+ const root = repoRoot()
111
+ const themeFiles = DEFINITION_FILES.map((f) => join(root, f)).filter((f) => existsSync(f))
112
+ if (!themeFiles.length) {
113
+ // A scaffolded deck consumes the toolkit from node_modules and vendors no
114
+ // theme.css. Nothing to check is NOT a pass, so report it as such.
115
+ return { skipped: 'no bundled theme.css in this repo (the toolkit ships it from node_modules)' }
116
+ }
117
+
118
+ const defined = new Set()
119
+ for (const f of themeFiles) {
120
+ for (const t of definedTokens(readFileSync(f, 'utf8'))) defined.add(t)
121
+ }
122
+
123
+ const offenders = []
124
+ for (const abs of usageFiles()) {
125
+ const src = readFileSync(abs, 'utf8')
126
+ for (const u of undefinedUsages(src, defined)) {
127
+ offenders.push({
128
+ file: toRel(abs),
129
+ line: u.line,
130
+ message: `${u.token} is never defined in packages/toolkit/styles/theme.css. CSS drops the declaration silently and the element inherits instead, so this renders wrong on exactly the slides that use it. Define the token, or point the reference at an existing one.`,
131
+ })
132
+ }
133
+ }
134
+ return offenders
135
+ },
136
+ }