@pithyjs/vite-plugin 0.1.0-beta.0 → 0.2.0-beta.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 (76) hide show
  1. package/README.md +57 -8
  2. package/dist/aotCodegen/generateBindings.d.ts +9 -2
  3. package/dist/aotCodegen/generateBindings.d.ts.map +1 -1
  4. package/dist/aotCodegen/generateBindings.js +22 -7
  5. package/dist/aotCodegen/generateBindings.js.map +1 -1
  6. package/dist/aotCodegen/generateDomFactory.d.ts +7 -2
  7. package/dist/aotCodegen/generateDomFactory.d.ts.map +1 -1
  8. package/dist/aotCodegen/generateDomFactory.js +74 -13
  9. package/dist/aotCodegen/generateDomFactory.js.map +1 -1
  10. package/dist/aotCodegen/index.d.ts +1 -1
  11. package/dist/aotCodegen/index.d.ts.map +1 -1
  12. package/dist/aotCodegen/serializeNode.d.ts.map +1 -1
  13. package/dist/aotCodegen/serializeNode.js +11 -0
  14. package/dist/aotCodegen/serializeNode.js.map +1 -1
  15. package/dist/babelPlugin/babelPlugin.d.ts +4 -3
  16. package/dist/babelPlugin/babelPlugin.d.ts.map +1 -1
  17. package/dist/babelPlugin/babelPlugin.js +257 -143
  18. package/dist/babelPlugin/babelPlugin.js.map +1 -1
  19. package/dist/babelPlugin/extractUsedIdentifiers.d.ts.map +1 -1
  20. package/dist/babelPlugin/extractUsedIdentifiers.js +62 -6
  21. package/dist/babelPlugin/extractUsedIdentifiers.js.map +1 -1
  22. package/dist/buildPlugin/plugin.d.ts +0 -25
  23. package/dist/buildPlugin/plugin.d.ts.map +1 -1
  24. package/dist/buildPlugin/plugin.js +41 -3
  25. package/dist/buildPlugin/plugin.js.map +1 -1
  26. package/dist/designSystemPlugin/channelVars.d.ts +139 -0
  27. package/dist/designSystemPlugin/channelVars.d.ts.map +1 -0
  28. package/dist/designSystemPlugin/channelVars.js +1099 -0
  29. package/dist/designSystemPlugin/channelVars.js.map +1 -0
  30. package/dist/designSystemPlugin/cssTokens.d.ts +24 -3
  31. package/dist/designSystemPlugin/cssTokens.d.ts.map +1 -1
  32. package/dist/designSystemPlugin/cssTokens.js.map +1 -1
  33. package/dist/designSystemPlugin/enumerate.d.ts.map +1 -1
  34. package/dist/designSystemPlugin/enumerate.js +14 -1
  35. package/dist/designSystemPlugin/enumerate.js.map +1 -1
  36. package/dist/designSystemPlugin/patterns/a11y.d.ts.map +1 -1
  37. package/dist/designSystemPlugin/patterns/a11y.js +27 -8
  38. package/dist/designSystemPlugin/patterns/a11y.js.map +1 -1
  39. package/dist/designSystemPlugin/patterns/borders.d.ts.map +1 -1
  40. package/dist/designSystemPlugin/patterns/borders.js +8 -3
  41. package/dist/designSystemPlugin/patterns/borders.js.map +1 -1
  42. package/dist/designSystemPlugin/patterns/colors.d.ts.map +1 -1
  43. package/dist/designSystemPlugin/patterns/colors.js +14 -2
  44. package/dist/designSystemPlugin/patterns/colors.js.map +1 -1
  45. package/dist/designSystemPlugin/patterns/radius.js +1 -1
  46. package/dist/designSystemPlugin/patterns/typography.d.ts.map +1 -1
  47. package/dist/designSystemPlugin/patterns/typography.js +114 -17
  48. package/dist/designSystemPlugin/patterns/typography.js.map +1 -1
  49. package/dist/designSystemPlugin/plugin.d.ts +33 -0
  50. package/dist/designSystemPlugin/plugin.d.ts.map +1 -1
  51. package/dist/designSystemPlugin/plugin.js +289 -9
  52. package/dist/designSystemPlugin/plugin.js.map +1 -1
  53. package/dist/designSystemPlugin/types.d.ts +96 -1
  54. package/dist/designSystemPlugin/types.d.ts.map +1 -1
  55. package/dist/designSystemPlugin/types.js +31 -2
  56. package/dist/designSystemPlugin/types.js.map +1 -1
  57. package/dist/htmlTransform/htmlTransform.d.ts +7 -4
  58. package/dist/htmlTransform/htmlTransform.d.ts.map +1 -1
  59. package/dist/htmlTransform/htmlTransform.js +19 -6
  60. package/dist/htmlTransform/htmlTransform.js.map +1 -1
  61. package/dist/iconsPlugin/plugin.d.ts +3 -0
  62. package/dist/iconsPlugin/plugin.d.ts.map +1 -1
  63. package/dist/iconsPlugin/plugin.js +12 -1
  64. package/dist/iconsPlugin/plugin.js.map +1 -1
  65. package/dist/iconsPlugin/types.d.ts +11 -0
  66. package/dist/iconsPlugin/types.d.ts.map +1 -1
  67. package/dist/iconsPlugin/types.js +11 -0
  68. package/dist/iconsPlugin/types.js.map +1 -1
  69. package/dist/ssrPlugin/plugin.d.ts.map +1 -1
  70. package/dist/ssrPlugin/plugin.js +16 -0
  71. package/dist/ssrPlugin/plugin.js.map +1 -1
  72. package/package.json +5 -5
  73. package/dist/babelPlugin/extractOriginalTagNames.d.ts +0 -20
  74. package/dist/babelPlugin/extractOriginalTagNames.d.ts.map +0 -1
  75. package/dist/babelPlugin/extractOriginalTagNames.js +0 -44
  76. package/dist/babelPlugin/extractOriginalTagNames.js.map +0 -1
@@ -0,0 +1,1099 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.vite-plugin-design-system.channel-vars",
4
+ "title": "Colour Channel Variable Usage Gate",
5
+ "category": "plugin",
6
+ "description": "Scans stylesheets for var(--color-*-rgb|-l|-c|-h) so the static palette emits only the channel variables something can read.",
7
+ "since": "0.1.0",
8
+ "stability": "experimental",
9
+ "risk": "high",
10
+ "testing": {
11
+ "unit": { "required": true, "covered": true, "file": "design-system-channel-vars.test.ts" },
12
+ "integration": { "required": true, "covered": true, "file": "design-system-channel-vars.test.ts" },
13
+ "e2e": { "required": false, "covered": false }
14
+ }
15
+ }
16
+ */
17
+ import fg from 'fast-glob';
18
+ import { readFileSync, readdirSync, statSync } from 'fs';
19
+ import { dirname, extname, isAbsolute, join, resolve } from 'path';
20
+ import { CHANNEL_SUFFIXES, } from '@pithyjs/design-system/palette';
21
+ const CHANNEL_SUFFIX_COUNT = CHANNEL_SUFFIXES.length;
22
+ /**
23
+ * The suffix alternation, BUILT from `CHANNEL_SUFFIXES` rather than retyped.
24
+ * Hard-coding it meant adding a suffix silently created a variable no regex
25
+ * could detect — and pushed `CHANNEL_SUFFIX_COUNT` past what the wildcards can
26
+ * ever hold, so the all-suffixes escape below could never fire again.
27
+ * Longest-first so `rgb` is not shadowed by a prefix of itself.
28
+ */
29
+ const SUFFIX_ALT = [...CHANNEL_SUFFIXES]
30
+ .sort((a, b) => b.length - a.length)
31
+ .join('|');
32
+ /**
33
+ * `var(--color-<anything>-<channel>)` as written in a stylesheet.
34
+ *
35
+ * Deliberately not anchored to a token list: state variants, future tokens and
36
+ * a custom prefix all have to match, and a name that matches nothing real only
37
+ * pins open a variable that was going to ship anyway.
38
+ *
39
+ * `var` is spelled case-insensitively by hand rather than with the `i` flag,
40
+ * which would also loosen the suffix alternation — custom property NAMES are
41
+ * case-sensitive, and `--color-x-RGB` is a property nothing here ever emits.
42
+ */
43
+ const CHANNEL_REF_RE = new RegExp(String.raw `[Vv][Aa][Rr]\(\s*(--[A-Za-z0-9_-]*-(?:${SUFFIX_ALT}))\b`, 'g');
44
+ /**
45
+ * A `var()` whose custom property name is BUILT — SCSS `#{}` or JS `${}` — and
46
+ * still ends in a channel suffix, e.g. `rgb(var(--color-#{$token}-rgb))` in
47
+ * `@pithyjs/design-system`'s generated `u-*` utilities.
48
+ *
49
+ * Which tokens such a loop covers is unknowable from the text, so a hit pins
50
+ * open every variable with that suffix.
51
+ *
52
+ * KNOWN BLIND SPOTS, all of which leave the gate active rather than degrading
53
+ * it — use `channelVarSafelist`, and see BACKLOG #83 for why deciding at purge
54
+ * time removes the whole class:
55
+ * - the whole name held in a variable: `$p: --color-primary-rgb;` then
56
+ * `var(#{$p})`. This is established house style in the design system's own
57
+ * mixins, so it is the likeliest of these to appear;
58
+ * - assembly other than `+`: `[a, b].join('')`, `a.concat(b)`;
59
+ * - an interpolation containing `}` before the suffix, e.g. a helper called
60
+ * with an inline object literal — `{0,500}` stops at the first `}`;
61
+ * - a name whose SUFFIX is itself interpolated.
62
+ *
63
+ * A name ending in the interpolation (`var(--color-#{$scheme})`) is not matched
64
+ * because it is a base-token reference — but note that is only true when the
65
+ * interpolation does not itself carry the suffix.
66
+ */
67
+ // `{0,500}` rather than `*`: unbounded, it rescanned to EOF from
68
+ // every `var(--X${` with no closing brace, which is quadratic in file size
69
+ // (20KB 16ms, 40KB 61ms, 80KB 248ms, 160KB 971ms). Reachable because package
70
+ // roots are deliberately scanned without the build-output ignores, so a
71
+ // dependency's minified dist is read whole. Bounding is what removes the
72
+ // quadratic term; newlines must stay IN the class, or a Prettier-wrapped
73
+ // interpolation stops matching and unpins its whole family.
74
+ //
75
+ // The TRAILING fragment needed the same treatment and did not get it: it
76
+ // excluded whitespace, so a second interpolation containing a space — a SCSS
77
+ // map lookup, a ternary, anything Prettier wrapped — matched nothing. This is
78
+ // load-bearing: all 142 surviving channel declarations rest on this regex
79
+ // matching `_color-utilities.scss`.
80
+ const DYNAMIC_CHANNEL_REF_RE = new RegExp(String.raw `[Vv][Aa][Rr]\(\s*(?:--)?[A-Za-z0-9_-]*(?:#\{[^}]{0,500}\}|\$\{[^}]{0,500}\})[^;]{0,200}?-(${SUFFIX_ALT})\b`, 'g');
81
+ /**
82
+ * A channel name assembled by string concatenation rather than interpolation
83
+ * — `'var(--color-' + token + '-rgb)'`. The opening fragment ends mid-name, so
84
+ * neither regex above can see it; this one keys on the dangling prefix.
85
+ */
86
+ // Anchored to `--color`, and it must SEE a channel suffix as the LAST segment
87
+ // of the trailing fragment. Three things were wrong before:
88
+ // - anchoring alone pinned every suffix for a base-token concat
89
+ // (`'var(--color-' + scheme + ')'`), tripping the all-suffixes escape and
90
+ // switching the gate off build-wide;
91
+ // - the trailing fragment must CLOSE the var() call: without the `)`,
92
+ // `'var(--color-' + t + ')' + 'chip-l'` matched on an unrelated adjacent
93
+ // string and switched the gate off build-wide;
94
+ // - `['"`]-(?:rgb|l|c|h)\b` required the suffix immediately after the quote,
95
+ // so `'-hover-rgb)'` and `'-focus-l)'` — real state-variant channel
96
+ // variables — were missed, while `'-l-delta)'` matched on `\b` and was a
97
+ // false positive;
98
+ // - `[^;\n]` forbade newlines, so the shape stopped matching the moment
99
+ // Prettier wrapped it — the identical bug fixed for the sibling detector,
100
+ // never applied here.
101
+ // A concat whose SUFFIX is itself dynamic still matches nothing; that is what
102
+ // `channelVarSafelist` is for, as is a palette built with a custom `prefix`.
103
+ const CONCAT_CHANNEL_REF_RE = new RegExp(String.raw `[Vv][Aa][Rr]\(\s*['"\`]?--color[A-Za-z0-9_-]*-['"\`]\s*\+[^;]{0,200}['"\`][A-Za-z0-9_-]*?-(?:${SUFFIX_ALT})\)`, 'g');
104
+ /**
105
+ * File types that can carry a `var()` in a PithyJS app.
106
+ *
107
+ * This repo has none of `tsx`/`jsx`/`vue`/`svelte`/`astro`/`sass`/`less`, but
108
+ * the plugin is PUBLISHED and its default `include` advertises `src/**\/*.tsx`
109
+ * — so `tsx` stays. A file this list omits is never opened, which drops the
110
+ * variables it reads with `degraded: false`: the one direction that is a bug.
111
+ * The rest are left out because nothing advertises them.
112
+ */
113
+ const SCAN_EXTENSIONS = [
114
+ 'css',
115
+ 'scss',
116
+ 'ts',
117
+ 'tsx',
118
+ 'mts',
119
+ 'cts',
120
+ 'js',
121
+ 'jsx',
122
+ 'mjs',
123
+ 'cjs',
124
+ 'pithy',
125
+ 'html',
126
+ // `iconsPlugin/optimize.ts` deliberately preserves `<style>` in SVGs.
127
+ 'svg',
128
+ // The sibling `packages/ssr/src/build/collect-css.ts` matches both and
129
+ // inlines them into every exported page, so a reference in one reaches a
130
+ // static page while this scan could not see it.
131
+ 'sass',
132
+ 'less',
133
+ ];
134
+ /** Extensions as a lookup, for the dev watcher's per-file relevance check. */
135
+ const SCAN_EXTENSION_SET = new Set(SCAN_EXTENSIONS.map(e => `.${e}`));
136
+ /**
137
+ * Never scanned, in any root. Unambiguous test markers only: a file named
138
+ * `*.test.*` ships no CSS anywhere, whereas a DIRECTORY called `tests` may be a
139
+ * route (`src/routes/tests/+page.scss`), which is why it is not listed here.
140
+ */
141
+ const ALWAYS_IGNORED = [
142
+ '**/node_modules/**',
143
+ '**/.git/**',
144
+ '**/coverage/**',
145
+ '**/__tests__/**',
146
+ '**/*.test.*',
147
+ '**/*.spec.*',
148
+ ];
149
+ /**
150
+ * Additionally ignored in a DEPENDENCY root: a library's nested `tests`
151
+ * directories are certainly tests, and they quote channel names as fixtures.
152
+ */
153
+ const PACKAGE_IGNORED = [...ALWAYS_IGNORED, '**/tests/**'];
154
+ /**
155
+ * Additionally ignored under the Vite root — an app's own build output, and its
156
+ * the build output directories below. `tests` is deliberately NOT here: a
157
+ * directory called `tests` may be a route, and this repo has one.
158
+ *
159
+ * All anchored to the root: unanchored, `**\/build/**` would skip
160
+ * `src/routes/build/+page.scss` on a site that has a `/build` page.
161
+ *
162
+ * NOT applied to package roots: a published `@pithyjs/ui-kit` ships its
163
+ * component SCSS inside `dist`, and skipping it there would drop a variable
164
+ * that really is read, which is the one direction this module must never fail.
165
+ */
166
+ const BUILD_OUTPUT_IGNORED = [
167
+ 'dist/**',
168
+ 'out/**',
169
+ 'build/**',
170
+ '.vite/**',
171
+ '.output/**',
172
+ ];
173
+ /**
174
+ * Channel variables composed at runtime from a string, which no scan can see.
175
+ *
176
+ * `ShadowManager.resolveTintColor()` reads `--color-${color}-rgb` through
177
+ * `getComputedStyle` for the three brand tints, so a brand-tinted shadow in an
178
+ * app that never calls `initTheme()` would otherwise read an undefined token.
179
+ */
180
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"DEFAULT_CHANNEL_VAR_SAFELIST","stability":"experimental","signature":"readonly string[]"} */
181
+ export const DEFAULT_CHANNEL_VAR_SAFELIST = [
182
+ '--color-primary-rgb',
183
+ '--color-secondary-rgb',
184
+ '--color-tertiary-rgb',
185
+ ];
186
+ /**
187
+ * Index of the unescaped quote closing the one at `start`.
188
+ *
189
+ * A template literal legitimately spans lines, and this repo writes CSS that
190
+ * way (`colors/generate-utilities.ts`). Stopping at the newline left the scan
191
+ * INSIDE the literal, where a `/*` in prose pairs with a later `*\/` and eats
192
+ * the live references between — the same loss as an unhandled line comment.
193
+ * `'`/`"` still stop at the newline so an apostrophe in prose cannot open a
194
+ * span that swallows the rest of the file.
195
+ */
196
+ function closingQuote(text, start) {
197
+ const q = text[start];
198
+ const multiline = q === '`';
199
+ for (let i = start + 1; i < text.length; i++) {
200
+ const c = text[i];
201
+ if (c === '\\')
202
+ i++;
203
+ else if (c === '\n' && !multiline)
204
+ return -1;
205
+ else if (c === q)
206
+ return i;
207
+ }
208
+ return -1;
209
+ }
210
+ /**
211
+ * Remove comments before scanning, so a documented example does not read as
212
+ * usage — `_colors.scss` shows `var(--color-primary-l)` in a docblock.
213
+ *
214
+ * Quoted spans are stepped over, so `content: "/*"` cannot pair with a later
215
+ * close and swallow the live references between them. A quote with no partner
216
+ * on its own line is ordinary text, so prose ("don't") never opens a span, and
217
+ * an unterminated `/*` leaves the rest of the file intact.
218
+ *
219
+ * A comment opener must sit where a comment can START — after input start,
220
+ * whitespace, or one of `;{}` `,` (and `(` for `/*`). Keying on which single
221
+ * character precedes it was tried twice and failed twice: requiring whitespace
222
+ * let `;//` and `}//` through, and excluding only `:`/`(` let the `/` in a
223
+ * base64 blob, an unquoted `href=//cdn/x` and `\/\/` inside a regex literal
224
+ * open one. A positive position test rejects all of those, because `src/*.scss`,
225
+ * `AA//BB` and `[^/*]` have an identifier character in front.
226
+ *
227
+ * Every ambiguity here resolves toward NOT stripping: an unstripped docblock
228
+ * over-keeps a variable, a mis-stripped span drops a live one.
229
+ */
230
+ /**
231
+ * End of a `url(` span, honouring quotes and nesting.
232
+ *
233
+ * `indexOf(')')` closed on a `)` INSIDE the quoted URL — `url("x),/*y")` — so
234
+ * the scanner resumed inside URL text, where a `/*` then opened a real block
235
+ * comment. Reachable in an unencoded inline SVG data URI, or any path with
236
+ * parentheses. Seventh position of this class, in the span added to close it.
237
+ */
238
+ function closingUrlParen(text, from) {
239
+ let depth = 1;
240
+ let quote = '';
241
+ for (let i = from; i < text.length; i++) {
242
+ const c = text[i];
243
+ if (c === '\\') {
244
+ i++;
245
+ continue;
246
+ }
247
+ if (quote) {
248
+ if (c === quote)
249
+ quote = '';
250
+ continue;
251
+ }
252
+ if (c === '"' || c === "'")
253
+ quote = c;
254
+ else if (c === '(')
255
+ depth++;
256
+ else if (c === ')' && --depth === 0)
257
+ return i;
258
+ }
259
+ return -1;
260
+ }
261
+ /**
262
+ * End of the regex literal opening at `at`, or -1.
263
+ *
264
+ * Only needed so a literal's contents cannot open a comment or a string: the
265
+ * span is emitted VERBATIM, so any `var()` inside it is still scanned and
266
+ * mistaking a division for a regex can never lose a reference. Without this,
267
+ * the backtick in this module's own `/["'`]|.../` character class read as a
268
+ * template-literal opener and misaligned the rest of the file.
269
+ */
270
+ function closingSlash(text, at) {
271
+ let inClass = false;
272
+ for (let i = at + 1; i < text.length; i++) {
273
+ const c = text[i];
274
+ if (c === '\\') {
275
+ i++;
276
+ continue;
277
+ }
278
+ if (c === '\n')
279
+ return -1;
280
+ if (inClass) {
281
+ if (c === ']')
282
+ inClass = false;
283
+ }
284
+ else if (c === '[')
285
+ inClass = true;
286
+ else if (c === '/')
287
+ return i;
288
+ }
289
+ return -1;
290
+ }
291
+ /** Whether a `/` at `at` can start a regex literal rather than divide. */
292
+ function opensRegex(text, at) {
293
+ let i = at - 1;
294
+ for (; i >= 0 && /\s/.test(text[i]); i--)
295
+ ;
296
+ if (i < 0)
297
+ return true;
298
+ if ('(,=:[!&|?{;+*%<>~^'.includes(text[i]))
299
+ return true;
300
+ // A KEYWORD position too. `return /[ /*]/.test(c)` was read as division, so
301
+ // the `/*` inside the character class opened a real block comment — the
302
+ // eighth position of this class, inside the code added to close the first six.
303
+ const word = /[A-Za-z$_]+$/.exec(text.slice(Math.max(0, i - 11), i + 1));
304
+ return word !== null && KEYWORDS_BEFORE_REGEX.has(word[0]);
305
+ }
306
+ /** Keywords a regex literal may follow; after an operand, `/` divides. */
307
+ const KEYWORDS_BEFORE_REGEX = new Set([
308
+ 'return',
309
+ 'typeof',
310
+ 'case',
311
+ 'in',
312
+ 'of',
313
+ 'new',
314
+ 'delete',
315
+ 'void',
316
+ 'instanceof',
317
+ 'do',
318
+ 'else',
319
+ 'yield',
320
+ 'await',
321
+ 'throw',
322
+ ]);
323
+ /**
324
+ * Which comment syntaxes a file's language actually has.
325
+ *
326
+ * `stripComments` had no idea what it was reading, so it applied JS/CSS rules
327
+ * to text where `//` and `/*` are ordinary characters. Two live losses came
328
+ * from exactly that: `:root{--cdn: //cdn.example.com}` in a minified `.css`
329
+ * (plain CSS has NO line comment, and package roots are deliberately scanned
330
+ * without the build-output ignores, so a dependency's minified dist is this
331
+ * shape), and `/*` written as prose in `.html`.
332
+ *
333
+ * Erring toward NOT stripping is the safe direction — an unstripped docblock
334
+ * over-keeps a variable, a mis-stripped span drops a live one — so an unknown
335
+ * extension gets both, matching the previous behaviour, and `.html`/`.svg` get
336
+ * neither. A `<style>` block inside them keeps its comments, which can only
337
+ * over-keep.
338
+ */
339
+ function commentSyntax(ext) {
340
+ switch (ext.replace(/^\./, '').toLowerCase()) {
341
+ case 'css':
342
+ return { line: false, block: true };
343
+ // `.pithy` sits with them: it is `<template>` + `<script>` + plain-CSS
344
+ // `<style>`, so prose `/*` in the template paired with the real `*/` in the
345
+ // style block and ate the rule between — the `.css` bug this function
346
+ // exists to fix, in the project's own format. `<script>` genuinely has
347
+ // `//`, so disabling both over-keeps its commented-out examples; that is
348
+ // the safe direction, and per-block handling is not worth it for 7 files.
349
+ case 'html':
350
+ case 'svg':
351
+ case 'pithy':
352
+ return { line: false, block: false };
353
+ default:
354
+ return { line: true, block: true };
355
+ }
356
+ }
357
+ /**
358
+ * Whether a comment opener at `at` is in a position a comment can start.
359
+ *
360
+ * `block` allows `(` as well, for `foo(/* x *\/ y)`. `//` must not, or
361
+ * `url(//cdn/x)` reads as a comment.
362
+ */
363
+ function opensComment(text, at, block) {
364
+ if (at === 0)
365
+ return true;
366
+ const prev = text[at - 1];
367
+ if (/\s/.test(prev))
368
+ return true;
369
+ if (prev === ';' || prev === '{' || prev === '}' || prev === ',')
370
+ return true;
371
+ return block && prev === '(';
372
+ }
373
+ function stripComments(text, ext = '') {
374
+ const syntax = commentSyntax(ext);
375
+ let noCloser = false;
376
+ const interesting = /[Uu][Rr][Ll]\(|["'`]|\/\*|\/\/|\//g;
377
+ let out = '';
378
+ let i = 0;
379
+ for (let m = interesting.exec(text); m; m = interesting.exec(text)) {
380
+ const at = m.index;
381
+ out += text.slice(i, at);
382
+ if (m[0].length === 4) {
383
+ // `url(...)` is OPAQUE, like a quote or a regex literal: emitted
384
+ // verbatim, so its contents cannot open anything. A base64 payload
385
+ // beginning `//` (a standard BMP/ICO prefix) sat right after the `,`
386
+ // that `opensComment` accepts, and on a minified one-line file the
387
+ // "comment" then ran to EOF. This also subsumes `url(//cdn/x)` and
388
+ // `url(img/*.png)`. Refs inside are still found, since the text stays.
389
+ const close = closingUrlParen(text, at + 4);
390
+ if (close === -1) {
391
+ out += m[0];
392
+ i = at + 4;
393
+ }
394
+ else {
395
+ out += text.slice(at, close + 1);
396
+ i = close + 1;
397
+ }
398
+ }
399
+ else if (m[0] === '//') {
400
+ if (!syntax.line || !opensComment(text, at, false)) {
401
+ // Emit the REST OF THE LINE verbatim, not just the two characters.
402
+ // Re-feeding the retained text let a space-preceded `/*` inside it
403
+ // open a real block comment running to the next `*/` — the loss kept
404
+ // coming back through the retained text while four rounds replaced the
405
+ // predicate. Opaque spans are what the quote and regex branches do.
406
+ const nl = text.indexOf('\n', at);
407
+ const stop = nl === -1 ? text.length : nl;
408
+ out += text.slice(at, stop);
409
+ i = stop;
410
+ }
411
+ else {
412
+ const nl = text.indexOf('\n', at);
413
+ out += ' ';
414
+ i = nl === -1 ? text.length : nl;
415
+ }
416
+ }
417
+ else if (m[0] === '/*') {
418
+ // Language and position FIRST: `.html`/`.svg` have no block comment, and
419
+ // the `indexOf` below is a scan to EOF whose result they then discard.
420
+ if (!syntax.block || noCloser || !opensComment(text, at, true)) {
421
+ out += m[0];
422
+ i = at + 2;
423
+ interesting.lastIndex = i;
424
+ continue;
425
+ }
426
+ const end = text.indexOf('*/', at + 2);
427
+ if (end === -1) {
428
+ // No `*/` after here means none after any LATER `/*` either, so stop
429
+ // searching. Without this latch every `/*` in a file with no closer
430
+ // rescanned to EOF — quadratic, 1.9 s on 70 KB of `/* `.
431
+ noCloser = true;
432
+ out += m[0];
433
+ i = at + 2;
434
+ interesting.lastIndex = i;
435
+ continue;
436
+ }
437
+ out += ' ';
438
+ i = end + 2;
439
+ }
440
+ else if (m[0] === '/') {
441
+ const end = opensRegex(text, at) ? closingSlash(text, at) : -1;
442
+ if (end === -1) {
443
+ out += m[0];
444
+ i = at + 1;
445
+ }
446
+ else {
447
+ out += text.slice(at, end + 1);
448
+ i = end + 1;
449
+ }
450
+ }
451
+ else {
452
+ const end = closingQuote(text, at);
453
+ if (end === -1) {
454
+ out += m[0];
455
+ i = at + 1;
456
+ }
457
+ else {
458
+ out += text.slice(at, end + 1);
459
+ i = end + 1;
460
+ }
461
+ }
462
+ interesting.lastIndex = i;
463
+ }
464
+ return out + text.slice(i);
465
+ }
466
+ /**
467
+ * Every channel variable `text` reads.
468
+ *
469
+ * @param text - Stylesheet or source text.
470
+ * @returns The fully-qualified custom property names referenced by `var()`.
471
+ *
472
+ * @example
473
+ * ```typescript
474
+ * collectChannelVarRefs('.m{background:rgb(var(--color-overlay-rgb) / 0.55)}');
475
+ * // Set { '--color-overlay-rgb' }
476
+ * ```
477
+ */
478
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"collectChannelVarRefs","stability":"experimental","signature":"(text: string) => Set<string>"} */
479
+ export function collectChannelVarRefs(text, ext = '') {
480
+ const refs = new Set();
481
+ for (const match of stripComments(text, ext).matchAll(CHANNEL_REF_RE)) {
482
+ refs.add(match[1]);
483
+ }
484
+ return refs;
485
+ }
486
+ /**
487
+ * Channel suffixes `text` reads through a name it BUILDS rather than writes.
488
+ *
489
+ * @param text - Stylesheet or source text.
490
+ * @returns The suffixes whose whole family must be kept; see
491
+ * {@link DYNAMIC_CHANNEL_REF_RE} for what does and does not count.
492
+ *
493
+ * @example
494
+ * ```typescript
495
+ * collectDynamicChannelSuffixes('a{b:rgb(var(--color-#{$token}-rgb))}');
496
+ * // Set { 'rgb' }
497
+ * ```
498
+ */
499
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"collectDynamicChannelSuffixes","stability":"experimental","signature":"(text: string) => Set<ChannelSuffix>"} */
500
+ export function collectDynamicChannelSuffixes(text, ext = '') {
501
+ const suffixes = new Set();
502
+ const source = stripComments(text, ext);
503
+ for (const match of source.matchAll(DYNAMIC_CHANNEL_REF_RE)) {
504
+ suffixes.add(match[1]);
505
+ }
506
+ // A concatenated name hides its suffix in a later fragment, so which family
507
+ // it reads is unknowable. Keep all of them.
508
+ if (CONCAT_CHANNEL_REF_RE.test(source)) {
509
+ CONCAT_CHANNEL_REF_RE.lastIndex = 0;
510
+ for (const suffix of CHANNEL_SUFFIXES)
511
+ suffixes.add(suffix);
512
+ }
513
+ return suffixes;
514
+ }
515
+ /** Whether a changed file could contain a channel reference — dev watcher. */
516
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"isChannelScanCandidate","stability":"experimental","signature":"(filePath: string) => boolean"} */
517
+ export function isChannelScanCandidate(filePath) {
518
+ // Lower-cased to match the glob's `caseSensitiveMatch: false`: a `.SCSS`
519
+ // the scan reads but the watcher ignores goes stale on every edit.
520
+ if (!SCAN_EXTENSION_SET.has(extname(filePath).toLowerCase()))
521
+ return false;
522
+ // A file the scan always ignores cannot change the result, so rescanning on
523
+ // it is pure cost — and saving a test file is the common case.
524
+ const unix = filePath.replace(/\\/g, '/');
525
+ return (
526
+ // ONLY what every root ignores. Adding the build-output names here was
527
+ // wrong in the other direction: the scan's `BUILD_OUTPUT_IGNORED` is
528
+ // anchored to the Vite root and is deliberately NOT applied to package
529
+ // roots, so `src/routes/build/+page.scss` and a package's `dist/*.scss`
530
+ // are both scanned — and this check was refusing to rescan them, leaving
531
+ // the dev sheet stale for the session. An extra rescan costs time; a
532
+ // missed one is wrong output, so this errs toward rescanning. (The SSG
533
+ // export's own `.html` writes still trip it — cost only, since
534
+ // `sameChannelScan` discards the result.)
535
+ !/(^|\/)(node_modules|\.git|coverage|__tests__)\//.test(unix) &&
536
+ !/\.(test|spec)\.[^/]+$/.test(unix));
537
+ }
538
+ /**
539
+ * `false` only for "not there". An EACCES or ELOOP means "cannot tell", and
540
+ * collapsing that to `false` routed a real install to `absent` — the one
541
+ * classification that keeps the gate ACTIVE. Those throw instead, so the
542
+ * caller degrades.
543
+ */
544
+ function statKind(p) {
545
+ try {
546
+ const st = statSync(p);
547
+ return st.isDirectory() ? 'dir' : st.isFile() ? 'file' : 'other';
548
+ }
549
+ catch (err) {
550
+ const code = err?.code;
551
+ if (code === 'ENOENT' || code === 'ENOTDIR')
552
+ return 'missing';
553
+ throw err;
554
+ }
555
+ }
556
+ function isDir(p) {
557
+ return statKind(p) === 'dir';
558
+ }
559
+ function isFile(p) {
560
+ return statKind(p) === 'file';
561
+ }
562
+ /**
563
+ * Locate a framework package's source tree so its component SCSS can be read.
564
+ *
565
+ * A Vite alias first (the monorepo case, pointing at `src`), then
566
+ * {@link probePackage}. Not found resolves to `absent` only when nothing
567
+ * declares the package; otherwise it degrades — see the body.
568
+ */
569
+ function resolvePackageDir(name, aliases, from) {
570
+ const aliased = aliasReplacement(name, aliases);
571
+ if (aliased) {
572
+ if (isDir(aliased))
573
+ return { kind: 'dir', dir: aliased };
574
+ // An alias may point at an entry FILE (`.../src/index.ts`). A path that is
575
+ // neither is returned as-is so the scan degrades rather than silently
576
+ // scanning its parent.
577
+ return { kind: 'dir', dir: isFile(aliased) ? dirname(aliased) : aliased };
578
+ }
579
+ const probe = probePackage(name, from);
580
+ if (probe.dir)
581
+ return { kind: 'dir', dir: probe.dir };
582
+ // `absent` means CERTAINLY not installed, and only that answer keeps the
583
+ // gate on. Everything else degrades, which keeps every channel variable:
584
+ // - a directory with no manifest — something IS installed, unreadable;
585
+ // - no `node_modules` anywhere (Yarn PnP) — nothing can be ruled out;
586
+ // - declared but not found — pnpm's isolated store, a partial install.
587
+ // Guessing `absent` in any of those leaves the gate active and blind to the
588
+ // package that reads these variables.
589
+ if (probe.dirWithoutManifest) {
590
+ return {
591
+ kind: 'unresolvable',
592
+ reason: `${probe.dirWithoutManifest} has no package.json`,
593
+ };
594
+ }
595
+ if (!probe.sawNodeModules) {
596
+ return {
597
+ kind: 'unresolvable',
598
+ reason: `no node_modules tree above ${from}`,
599
+ };
600
+ }
601
+ return isDeclaredDependency(name, from)
602
+ ? {
603
+ kind: 'unresolvable',
604
+ reason: `${name} is declared but was not found on disk from ${from}`,
605
+ }
606
+ : { kind: 'absent' };
607
+ }
608
+ /**
609
+ * `pkg@1.2.3_peer@4.5.6` → `['pkg', [1,2,3]]`.
610
+ *
611
+ * The peer suffix is cut FIRST. Reading the version from the last `@` picked
612
+ * the PEER's version instead — replayed against this repo's store, 23 of 109
613
+ * names resolved to a non-newest copy, worst case prettier 2.8.8 over 3.5.3
614
+ * via `_@changesets+apply-release-plan@7.1.1`.
615
+ */
616
+ function parseStoreEntry(entry) {
617
+ const base = entry.split('_')[0];
618
+ const at = base.lastIndexOf('@');
619
+ const pkg = at > 0 ? base.slice(0, at) : base;
620
+ const raw = at > 0 ? base.slice(at + 1) : '';
621
+ return {
622
+ pkg,
623
+ version: raw.split(/[.\-+]/).map(n => (/^\d+$/.test(n) ? Number(n) : -1)),
624
+ };
625
+ }
626
+ /**
627
+ * Orders `.pnpm` entries so the probe reads the newest copy OF THE PACKAGE it
628
+ * is looking for. An entry can host `name` nested under a different package,
629
+ * so entries whose own package IS `name` sort first — otherwise the comparator
630
+ * would be ranking unrelated versions.
631
+ */
632
+ function compareStoreEntries(name, a, b) {
633
+ const want = name.replace(/\//g, '+');
634
+ const pa = parseStoreEntry(a);
635
+ const pb = parseStoreEntry(b);
636
+ const exact = (p) => (p.pkg === want ? 0 : 1);
637
+ const byExact = exact(pa) - exact(pb);
638
+ if (byExact !== 0)
639
+ return byExact;
640
+ for (let i = 0; i < Math.max(pa.version.length, pb.version.length); i++) {
641
+ const d = (pb.version[i] ?? -1) - (pa.version[i] ?? -1);
642
+ if (d !== 0)
643
+ return d;
644
+ }
645
+ return a < b ? -1 : a > b ? 1 : 0;
646
+ }
647
+ /**
648
+ * Walk up looking for the package, recording what was seen on the way.
649
+ *
650
+ * Probes `node_modules/<name>` and pnpm's isolated store, where a transitive
651
+ * dependency lives only at `node_modules/.pnpm/<pkg>@<ver>/node_modules/<name>`
652
+ * with no top-level link.
653
+ *
654
+ * NOT `require.resolve`: `@pithyjs/ui-kit` and `@pithyjs/design-system`
655
+ * declare `exports` with an `import` condition and no `require` one, so a CJS
656
+ * resolver rejects both with `ERR_PACKAGE_PATH_NOT_EXPORTED` — the entry and
657
+ * the `package.json` subpath alike. The directory is right there either way.
658
+ */
659
+ function probePackage(name, from) {
660
+ const out = {
661
+ dir: null,
662
+ dirWithoutManifest: null,
663
+ sawNodeModules: false,
664
+ };
665
+ let dir = from;
666
+ for (;;) {
667
+ const modules = join(dir, 'node_modules');
668
+ if (isDir(modules))
669
+ out.sawNodeModules = true;
670
+ const direct = join(modules, name);
671
+ if (isFile(join(direct, 'package.json'))) {
672
+ out.dir = direct;
673
+ return out;
674
+ }
675
+ // npm nests a conflicting version under its dependent, so the package can
676
+ // live at `node_modules/<dep>/node_modules/<name>`. Missing it classified
677
+ // a real install as `absent` — the one answer that keeps the gate on.
678
+ for (const host of ['@pithyjs/ui-kit', '@pithyjs/design-system']) {
679
+ if (host === name)
680
+ continue;
681
+ const nested = join(modules, host, 'node_modules', name);
682
+ if (isFile(join(nested, 'package.json'))) {
683
+ out.dir = nested;
684
+ return out;
685
+ }
686
+ }
687
+ if (out.dirWithoutManifest === null && isDir(direct)) {
688
+ out.dirWithoutManifest = direct;
689
+ }
690
+ const store = join(modules, '.pnpm');
691
+ if (isDir(store)) {
692
+ let entries = [];
693
+ try {
694
+ // Sorted by VERSION, descending. The store holds one name at several
695
+ // versions (and under other packages' entries), and `readdirSync`
696
+ // order is filesystem dependent, so taking whichever came first made
697
+ // the palette differ between machines on one lockfile. A plain
698
+ // lexicographic sort then preferred `@1.0.0` over `@2.0.0` and `@12`
699
+ // over `@22`; this is still a guess, but the newest copy is the one a
700
+ // bundler is likeliest to have resolved.
701
+ entries = readdirSync(store).sort((x, y) => compareStoreEntries(name, x, y));
702
+ }
703
+ catch {
704
+ entries = [];
705
+ }
706
+ for (const entry of entries) {
707
+ const candidate = join(store, entry, 'node_modules', name);
708
+ if (isFile(join(candidate, 'package.json'))) {
709
+ out.dir = candidate;
710
+ return out;
711
+ }
712
+ }
713
+ }
714
+ const up = dirname(dir);
715
+ if (up === dir)
716
+ return out;
717
+ dir = up;
718
+ }
719
+ }
720
+ /** Whether any `package.json` above `from` lists `name` in a dependency field. */
721
+ function isDeclaredDependency(name, from) {
722
+ const FIELDS = [
723
+ 'dependencies',
724
+ 'devDependencies',
725
+ 'peerDependencies',
726
+ 'optionalDependencies',
727
+ ];
728
+ let dir = from;
729
+ for (;;) {
730
+ const manifest = join(dir, 'package.json');
731
+ if (isFile(manifest)) {
732
+ try {
733
+ const json = JSON.parse(readFileSync(manifest, 'utf8'));
734
+ // A non-object dependency field cannot prove absence. `in` on an
735
+ // array or null answers false, which routed a declared package to
736
+ // `absent` — strictly worse than an UNPARSEABLE manifest, which
737
+ // already fails open below.
738
+ for (const f of FIELDS) {
739
+ const field = json[f];
740
+ if (field === undefined || field === null)
741
+ continue;
742
+ if (typeof field !== 'object' || Array.isArray(field))
743
+ return true;
744
+ if (name in field)
745
+ return true;
746
+ }
747
+ }
748
+ catch {
749
+ // An unreadable manifest cannot prove absence.
750
+ return true;
751
+ }
752
+ }
753
+ const up = dirname(dir);
754
+ if (up === dir)
755
+ return false;
756
+ dir = up;
757
+ }
758
+ }
759
+ function aliasReplacement(name, aliases) {
760
+ if (!Array.isArray(aliases))
761
+ return null;
762
+ for (const entry of aliases) {
763
+ if (typeof entry.replacement !== 'string')
764
+ continue;
765
+ if (typeof entry.find === 'string') {
766
+ // Vite's own rule: equal, or a prefix ending at a `/` SEGMENT boundary
767
+ // (`importee === pattern || importee.startsWith(pattern + '/')`).
768
+ // Omitting the boundary let `{find:'@'}` — a very common config — build
769
+ // `<src>pithyjs/ui-kit` out of `@pithyjs/ui-kit`.
770
+ if (entry.find === name)
771
+ return entry.replacement;
772
+ if (name.startsWith(`${entry.find}/`)) {
773
+ return entry.replacement + name.slice(entry.find.length);
774
+ }
775
+ // A SUBPATH alias (`@pithyjs/ui-kit/styles`) names a directory inside
776
+ // the package, so peel the subpath off to get the package root. If the
777
+ // replacement does not end with that subpath — every app here maps
778
+ // `/styles` to `.../styles/index.scss` — the root cannot be derived, so
779
+ // give up on this entry rather than return the subpath. Returning it
780
+ // narrowed the scan to one directory, and which of the two happened
781
+ // depended on the ORDER of keys in the alias object.
782
+ if (entry.find.startsWith(`${name}/`)) {
783
+ const sub = entry.find.slice(name.length);
784
+ if (entry.replacement.endsWith(sub)) {
785
+ return entry.replacement.slice(0, -sub.length);
786
+ }
787
+ continue;
788
+ }
789
+ }
790
+ else if (entry.find instanceof RegExp) {
791
+ // A LOCAL CLONE. The alias object belongs to Vite, which calls
792
+ // `pattern.test(importee)` on it for every later import — and `test` and
793
+ // `[Symbol.replace]` both advance `lastIndex` on a /y or /g pattern.
794
+ // Resetting before the call was not enough: leaving it advanced AFTER
795
+ // made the user's alias stop resolving for the rest of the build, a
796
+ // module-resolution failure caused by a CSS plugin. Never mutate it.
797
+ const find = new RegExp(entry.find.source, entry.find.flags);
798
+ if (find.test(name)) {
799
+ find.lastIndex = 0;
800
+ // STRING replacement: `$1` is the documented Vite API, and
801
+ // `{find: /^@pithyjs\/(.*)$/, replacement: 'packages/$1/src'}` is the
802
+ // canonical monorepo alias.
803
+ return name.replace(find, entry.replacement);
804
+ }
805
+ }
806
+ }
807
+ return null;
808
+ }
809
+ /** Scan roots for one build: the Vite root, the framework packages, extras. */
810
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"resolveChannelScanRoots","stability":"experimental","signature":"(viteRoot: string, aliases: unknown, extraRoots?: string[]) => ChannelScanPlan"} */
811
+ export function resolveChannelScanRoots(viteRoot, aliases, extraRoots = []) {
812
+ // Validate rather than throw from deep inside. A string passed where an
813
+ // array belongs used to surface as `scan threw: TypeError: …map is not a
814
+ // function` — a config mistake reported as an internal failure, which then
815
+ // turned the feature off. Named here, it degrades with a usable message.
816
+ if (!Array.isArray(extraRoots)) {
817
+ return {
818
+ roots: [],
819
+ unresolvable: [
820
+ `channelVarScanRoots must be an array of paths, received ${typeof extraRoots}`,
821
+ ],
822
+ };
823
+ }
824
+ for (const entry of extraRoots) {
825
+ if (typeof entry !== 'string' || entry === '') {
826
+ return {
827
+ roots: [],
828
+ unresolvable: [
829
+ `channelVarScanRoots entries must be non-empty strings, received ${JSON.stringify(entry)}`,
830
+ ],
831
+ };
832
+ }
833
+ }
834
+ const roots = [
835
+ { dir: viteRoot, ignore: [...ALWAYS_IGNORED, ...BUILD_OUTPUT_IGNORED] },
836
+ // Resolved against the Vite root, like `include`/`exclude` — a relative
837
+ // entry used to be evaluated against `process.cwd()`, so a monorepo-root
838
+ // config could scan a same-named directory in the wrong tree and still
839
+ // report `degraded: false`.
840
+ //
841
+ // Only the UNIVERSAL ignores. Not the dependency set, which excludes
842
+ // `**/tests/**` while a directory called `tests` may be a route (this repo
843
+ // has `apps/basic-app/src/routes/tests/`); and not the ROOT set, which
844
+ // skips `dist/**`, where a published library's CSS exists
845
+ // nowhere else — a root someone names explicitly is one they want read.
846
+ // The dependency set is also wrong here, because it excludes
847
+ // `**/tests/**` and a directory called `tests` may be a route.
848
+ ...extraRoots.map(dir => ({
849
+ dir: isAbsolute(dir) ? dir : join(viteRoot, dir),
850
+ ignore: [...ALWAYS_IGNORED],
851
+ })),
852
+ ];
853
+ const unresolvable = [];
854
+ // UI Kit ships the component SCSS that consumes these variables, and the
855
+ // design system ships the mixins; neither lives under the Vite root.
856
+ for (const pkg of ['@pithyjs/ui-kit', '@pithyjs/design-system']) {
857
+ const found = resolvePackageDir(pkg, aliases, viteRoot);
858
+ if (found.kind === 'dir')
859
+ roots.push({ dir: found.dir, ignore: PACKAGE_IGNORED });
860
+ else if (found.kind === 'unresolvable')
861
+ unresolvable.push(found.reason);
862
+ }
863
+ // Dedupe on the RESOLVED path, and keep the WIDEST ignore set for a path
864
+ // reached twice. Exact string identity meant `channelVarScanRoots: ['.']`
865
+ // collapsed into the Vite root and silently inherited its build-output
866
+ // ignores — so `dist/**` went unread — while `'./'`, the same intent, stayed
867
+ // separate and read it. An explicitly named root is one someone wants read,
868
+ // so the narrower set must not win.
869
+ const byPath = new Map();
870
+ for (const root of roots) {
871
+ const key = resolve(root.dir);
872
+ const prev = byPath.get(key);
873
+ if (prev === undefined) {
874
+ byPath.set(key, { ...root, dir: key });
875
+ continue;
876
+ }
877
+ // INTERSECTION, not the shorter array. The two ignore sets are not nested:
878
+ // `PACKAGE_IGNORED` has fewer entries than the root set but ADDS
879
+ // `**/tests/**`, so picking it by length hid `src/routes/tests/` — the
880
+ // exact file the root set exists to keep. Only a pattern both sets ignore
881
+ // is safe to ignore here.
882
+ const both = new Set(prev.ignore);
883
+ byPath.set(key, {
884
+ ...root,
885
+ dir: key,
886
+ ignore: root.ignore.filter(p => both.has(p)),
887
+ });
888
+ }
889
+ return { roots: [...byPath.values()], unresolvable };
890
+ }
891
+ /**
892
+ * Read every scannable file under `plan.roots` and union the channel variables
893
+ * they reference.
894
+ *
895
+ * **Fails OPEN, and this is the module's one invariant.** A root that is
896
+ * missing, a root a glob matched no file in, a package that will not resolve, a
897
+ * glob that throws, a file that cannot be read — each sets `degraded`, and a
898
+ * degraded scan makes the caller emit every channel variable. A variable
899
+ * dropped by mistake renders a JavaScript-disabled page wrong; a variable kept
900
+ * by mistake costs bytes. Only one of those is a bug.
901
+ *
902
+ * @example
903
+ * ```typescript
904
+ * const scan = scanChannelVarRefs(resolveChannelScanRoots(config.root, alias));
905
+ * if (scan.degraded) console.warn(scan.reason);
906
+ * ```
907
+ */
908
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"scanChannelVarRefs","stability":"experimental","signature":"(plan: ChannelScanPlan) => ChannelVarScan"} */
909
+ export function scanChannelVarRefs(plan) {
910
+ const refs = new Set();
911
+ const wildcardSuffixes = new Set();
912
+ let filesScanned = 0;
913
+ let readFailure;
914
+ const fail = (reason) => ({
915
+ refs,
916
+ wildcardSuffixes,
917
+ degraded: true,
918
+ reason,
919
+ filesScanned,
920
+ });
921
+ if (plan.unresolvable.length > 0) {
922
+ return fail(`unresolvable package: ${plan.unresolvable.join('; ')}`);
923
+ }
924
+ for (const { dir: root, ignore } of plan.roots) {
925
+ // `statKind` rethrows EACCES/ELOOP so the caller can degrade — but this,
926
+ // the first caller, was not catching, so the module threw where its own
927
+ // invariant says it fails open. An unreadable directory is the common
928
+ // CI/Docker shape; only an unreadable FILE was covered.
929
+ let readable;
930
+ try {
931
+ readable = isDir(root);
932
+ }
933
+ catch (err) {
934
+ return fail(`unreadable root ${root}: ${String(err)}`);
935
+ }
936
+ if (!readable)
937
+ return fail(`unreadable root: ${root}`);
938
+ let files;
939
+ try {
940
+ // Every option here widens rather than narrows, because a file this
941
+ // scan does not read is a variable it drops. `dot` reaches generated
942
+ // `.generated/` trees; `caseSensitiveMatch: false` reaches `D.SCSS` on
943
+ // the case-insensitive filesystems Vite resolves it on; symlinks are
944
+ // followed because a linked source tree is source.
945
+ files = fg.sync(`**/*.{${SCAN_EXTENSIONS.join(',')}}`, {
946
+ cwd: root,
947
+ absolute: true,
948
+ ignore,
949
+ followSymbolicLinks: true,
950
+ // Bounded. `followSymbolicLinks` with no cap turns one upward link
951
+ // into exponential path growth and a cycle into a non-terminating
952
+ // walk — which hangs `buildStart` and the dev rescan, with no throw
953
+ // and so no degradation signal. No real source tree is 24 deep.
954
+ deep: 24,
955
+ // NOT suppressed. Swallowing a per-entry EACCES/ELOOP returns a
956
+ // PARTIAL list with no error, so every reference in the unreadable
957
+ // subtree is dropped while `degraded` stays false — a root-owned
958
+ // directory in a CI or Docker build ships an incomplete palette and
959
+ // says nothing. Surfacing the throw degrades instead, which keeps
960
+ // every variable.
961
+ suppressErrors: false,
962
+ dot: true,
963
+ caseSensitiveMatch: false,
964
+ });
965
+ }
966
+ catch (err) {
967
+ return fail(`glob failed in ${root}: ${String(err)}`);
968
+ }
969
+ // An empty match is uncertainty, not evidence of absence: a mis-anchored
970
+ // ignore or a tree laid out unexpectedly looks exactly like this.
971
+ if (files.length === 0)
972
+ return fail(`no scannable files under ${root}`);
973
+ for (const file of files) {
974
+ let content;
975
+ try {
976
+ content = readFileSync(file, 'utf-8');
977
+ }
978
+ catch (err) {
979
+ // Keep reading rather than abort on the first failure, so one
980
+ // unreadable file does not decide the whole scan. A file present at
981
+ // glob time and gone at read time is routine — an atomic editor save,
982
+ // an export cleaning its out dir, a dangling symlink.
983
+ //
984
+ // This does NOT remove the dev flap: `fail()` below still degrades the
985
+ // whole scan, so a transient failure still swings the sheet between
986
+ // gated and ungated between rescans. What it removes is losing the
987
+ // refs already collected. Deciding at purge time (BACKLOG #83) is what
988
+ // actually ends the flap.
989
+ readFailure ??= `unreadable file ${file}: ${String(err)}`;
990
+ continue;
991
+ }
992
+ filesScanned++;
993
+ const ext = extname(file);
994
+ for (const ref of collectChannelVarRefs(content, ext))
995
+ refs.add(ref);
996
+ for (const s of collectDynamicChannelSuffixes(content, ext)) {
997
+ wildcardSuffixes.add(s);
998
+ }
999
+ }
1000
+ }
1001
+ if (readFailure !== undefined)
1002
+ return fail(readFailure);
1003
+ return { refs, wildcardSuffixes, degraded: false, filesScanned };
1004
+ }
1005
+ /**
1006
+ * Build the emission gate from everything known about this build.
1007
+ *
1008
+ * @example
1009
+ * ```typescript
1010
+ * const gate = createChannelVarGate({ enabled: true, scan, extraRefs: utilityRefs });
1011
+ * const css = themeToCss(theme, { defaultMode, keepChannelVar: gate.keep });
1012
+ * ```
1013
+ */
1014
+ /** A description of any value that cannot itself throw. */
1015
+ function describe(v) {
1016
+ try {
1017
+ return typeof v === 'object' && v !== null
1018
+ ? Object.prototype.toString.call(v)
1019
+ : String(v);
1020
+ }
1021
+ catch {
1022
+ return typeof v;
1023
+ }
1024
+ }
1025
+ /** @codexApi {"parent":"pithy.vite-plugin-design-system.channel-vars","name":"createChannelVarGate","stability":"experimental","signature":"(input: ChannelVarGateInput) => ChannelVarGate"} */
1026
+ export function createChannelVarGate(input) {
1027
+ const keepAll = (reason, degraded = false) => ({
1028
+ keep: () => true,
1029
+ active: false,
1030
+ // `active: false` conflates three things: switched off, DEGRADED, and
1031
+ // correctly decided to keep everything. Only the middle one is a problem
1032
+ // worth warning about, so it is flagged separately.
1033
+ degraded,
1034
+ reason,
1035
+ kept: new Set(),
1036
+ });
1037
+ if (!input.enabled)
1038
+ return keepAll('disabled via gateChannelVars: false');
1039
+ if (!input.scan)
1040
+ return keepAll('no source scan ran');
1041
+ if (input.scan.degraded)
1042
+ return keepAll(input.scan.reason ?? 'scan degraded', true);
1043
+ const kept = new Set([
1044
+ ...DEFAULT_CHANNEL_VAR_SAFELIST,
1045
+ ...input.scan.refs,
1046
+ ...(input.extraRefs ?? []),
1047
+ ]);
1048
+ // Validate, then CLONE. `keep()` runs ~800 times per sheet and
1049
+ // `patterns.some` short-circuits, so testing the caller's own objects left
1050
+ // them at arbitrary `lastIndex` offsets — an app factoring one array into
1051
+ // both `safelist` and `channelVarSafelist` got silent cross-contamination.
1052
+ // Same rule as the two alias resolvers: never mutate what the caller owns.
1053
+ const safelist = input.safelist ?? [];
1054
+ if (!Array.isArray(safelist)) {
1055
+ return keepAll(`channelVarSafelist must be an array, received ${typeof safelist}`, true);
1056
+ }
1057
+ const patterns = [];
1058
+ for (const entry of safelist) {
1059
+ if (typeof entry === 'string') {
1060
+ kept.add(entry);
1061
+ }
1062
+ else if (entry instanceof RegExp) {
1063
+ // Clone WITHOUT `g`/`y`. The clone alone protects the caller's object;
1064
+ // dropping the stateful flags is what makes `test()` correct here, since
1065
+ // `lastIndex` on a global pattern makes consecutive matches skip every
1066
+ // other name. Neither flag means anything for a boolean membership test.
1067
+ patterns.push(new RegExp(entry.source, entry.flags.replace(/[gy]/g, '')));
1068
+ }
1069
+ else {
1070
+ // A config mistake must not surface as a TypeError from inside `load()`,
1071
+ // which has no try/catch. Uncertainty ships everything.
1072
+ // `String(...)`, not `JSON.stringify`: the latter throws on a BigInt and
1073
+ // on a circular object, from inside the guard whose own purpose is that a
1074
+ // config mistake must not surface as an internal failure.
1075
+ return keepAll(`channelVarSafelist entries must be strings or RegExps, received ${describe(entry)}`, true);
1076
+ }
1077
+ }
1078
+ const wildcards = input.scan.wildcardSuffixes;
1079
+ if (wildcards.size === CHANNEL_SUFFIX_COUNT) {
1080
+ // `degraded: true` so this is AUDIBLE. `active: false` alone silenced both
1081
+ // signals — the warning keys on `degraded`, the banner on `active` — so a
1082
+ // single concat anywhere switched the feature off with no output at all.
1083
+ // It is not a failure, but it is a surprise worth one line.
1084
+ return keepAll(`every suffix read through a built name`, true);
1085
+ }
1086
+ const wildcardNote = wildcards.size
1087
+ ? `, all -${[...wildcards].join('/-')} (built names)`
1088
+ : '';
1089
+ return {
1090
+ keep: (varName, suffix) => wildcards.has(suffix) ||
1091
+ kept.has(varName) ||
1092
+ patterns.some(re => re.test(varName)),
1093
+ active: true,
1094
+ reason: `${kept.size} name(s) kept from ${input.scan.filesScanned} file(s)` +
1095
+ wildcardNote,
1096
+ kept,
1097
+ };
1098
+ }
1099
+ //# sourceMappingURL=channelVars.js.map