css-typed-vars 0.11.0 → 0.13.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.
package/README.md CHANGED
@@ -139,11 +139,12 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
139
139
  | `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
140
140
  | `--theme` | Named theme block, kept out of the default value and emitted as `@theme <name> <value>` JSDoc tags (repeatable: `--theme dark='[data-theme="dark"]' --theme contrast='@media (prefers-contrast: more)'`) — see [Theme values](#theme-values) |
141
141
  | `--group` | Nest keys under an object named after each variable's first hyphen segment: `--color-primary`/`--color-secondary` → `cssVars.color.primary`/`cssVars.color.secondary`. A variable with no hyphen stays top-level. Can't be combined with `--prefix`. |
142
- | `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)`/`withFallback(ref, fallback)` helpers — see [Usage](#usage). |
142
+ | `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)`/`withFallback(ref, fallback)`/`varName(ref)` helpers — see [Usage](#usage). |
143
143
  | `--prune` | Drop generated vars with no detected `cssVars.<key>` usage. Requires `--usage <glob>` (repeatable). With `--group`, matches `cssVars.<group>.<key>` and keeps a whole group referenced as `cssVars.<group>`. |
144
144
  | `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Doesn't need `--output`. Useful in CI. |
145
145
  | `--lint-refs` | Report `var(--name)` references to variables not declared anywhere in the input; exits 1 if any (without a fallback) are found — see [Linting var() references](#linting-var-references) |
146
146
  | `--refs-ignore` | Name or `--prefix-*` pattern for `--lint-refs` to skip (repeatable) |
147
+ | `--refs-source` | Source files whose `var()` references `--lint-refs` checks too (repeatable) — see [below](#in-source-files) |
147
148
  | `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
148
149
  | `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
149
150
  | `--watch` | Watch the `input` files (and, with `--prune`, the `--usage` files) and regenerate on change |
@@ -183,6 +184,24 @@ css-typed-vars: 2 reference(s) to undeclared variables:
183
184
  - References inside comments and strings are ignored; positions point to the original file.
184
185
  - Variables set from JavaScript or defined by another stylesheet you don't scan can be skipped with `--refs-ignore` (repeatable, a trailing `*` matches a prefix): `--refs-ignore "--tw-*" --refs-ignore --app-height`, or `refsIgnore` in the config file.
185
186
 
187
+ #### In source files
188
+
189
+ `var(--name)` strings in components are just as easy to get wrong. Add `--refs-source` (repeatable, or `refsSource` in the config file) to check them against the same declarations:
190
+
191
+ ```sh
192
+ npx css-typed-vars --input "src/**/*.css" --lint-refs --refs-source "src/**/*.{ts,tsx,vue,html}"
193
+ ```
194
+
195
+ ```
196
+ css-typed-vars: 1 reference(s) to undeclared variables:
197
+ src/Card.tsx:14:22 var(--colr-primary)
198
+ ```
199
+
200
+ - Finds `var(--name)` anywhere in the file — in strings, template literals, Tailwind classes like `bg-[var(--brand)]` — and Tailwind v4's `bg-(--brand)` shorthand.
201
+ - Variables a source file sets itself count as declared: an object key (`{ '--gap': '4px' }`), a `style` attribute (`style="--gap: 4px"`), `setProperty('--gap', ...)` or a Tailwind arbitrary property (`[--gap:4px]`). This applies to the CSS references too.
202
+ - Like the `--prune` usage scan, this is textual: a reference inside a comment counts too.
203
+ - The target's own output file is skipped even if the glob matches it — `--check` is what tells whether it's stale.
204
+
186
205
  ### Config file
187
206
 
188
207
  The CLI looks for a config file in the current working directory (in order):
@@ -212,6 +231,7 @@ export default defineConfig({
212
231
  group: false,
213
232
  helpers: false,
214
233
  refsIgnore: ['--tw-*'],
234
+ refsSource: 'src/**/*.{ts,tsx}',
215
235
  prune: false,
216
236
  usage: 'src/**/*.{ts,tsx}',
217
237
  });
@@ -345,7 +365,7 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
345
365
  | `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
346
366
  | `themes` | `Record<string, string>` | — | Theme name → selector or `@media` prelude; values become `@theme` JSDoc tags — see [Theme values](#theme-values) |
347
367
  | `group` | `boolean` | `false` | Nest keys by each variable's first hyphen segment, e.g. `cssVars.color.primary`. Can't be combined with `prefix` |
348
- | `helpers` | `boolean` | `false` | Also export the `CssVarRef` type and `getCssVar`/`setCssVar`/`withFallback` helpers from `css-typed-vars/vars` |
368
+ | `helpers` | `boolean` | `false` | Also export the `CssVarRef` type and `getCssVar`/`setCssVar`/`withFallback`/`varName` helpers from `css-typed-vars/vars` |
349
369
  | `prune` | `boolean` | `false` | Drop vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>` with `group`) usage. Requires `usage` |
350
370
  | `usage` | `string \| string[]` | — | Glob(s) of source files to scan for `cssVars` usage, for `prune` |
351
371
  | `usageExclude` | `string \| string[]` | — | Glob(s) of source files to exclude from the usage scan |
@@ -415,6 +435,17 @@ withFallback(cssVars.spacingMd, 0); // 'var(--spacing-md, 0)'
415
435
  withFallback(cssVars.colorLink, cssVars.colorPrimary); // 'var(--color-link, var(--color-primary))'
416
436
  ```
417
437
 
438
+ `varName` returns the custom property's own name, typed as the exact literal — for setting a variable from a style object (React inline styles, Vue `:style`), where you'd otherwise type the `--name` string by hand. Also a pure string helper:
439
+
440
+ ```tsx
441
+ import { cssVars, varName } from './cssVars';
442
+
443
+ varName(cssVars.colorPrimary); // '--color-primary'
444
+
445
+ const style = { [varName(cssVars.colorPrimary)]: brandColor };
446
+ <div style={style} /> // sets --color-primary on this element
447
+ ```
448
+
418
449
  ---
419
450
 
420
451
  ## Programmatic API
@@ -431,7 +462,7 @@ await generate({
431
462
  selectors: ['.dark', '[data-theme="dark"]'],
432
463
  themes: { dark: '[data-theme="dark"]' }, // per-theme values as @theme JSDoc tags
433
464
  group: false, // nest keys by first hyphen segment, e.g. cssVars.color.primary
434
- helpers: false, // also emit getCssVar/setCssVar/withFallback helpers
465
+ helpers: false, // also emit getCssVar/setCssVar/withFallback/varName helpers
435
466
  prune: false, // drop vars with no detected cssVars.<key> usage (requires `usage`)
436
467
  usage: 'src/**/*.{ts,tsx}',
437
468
  });
@@ -439,7 +470,7 @@ await generate({
439
470
 
440
471
  `checkGenerated(options)` takes the same options and returns `Promise<boolean>` — `true` if the existing output already matches what would be generated, without writing anything. Same thing `--check` does on the CLI.
441
472
 
442
- `findUndefinedRefs({ input, exclude?, refsIgnore? })` returns `Promise<FileReference[]>` — each undeclared `var()` reference with its `file`, `line`, `column` and `hasFallback`. Same thing `--lint-refs` does on the CLI.
473
+ `findUndefinedRefs({ input, exclude?, refsIgnore?, refsSource? })` returns `Promise<FileReference[]>` — each undeclared `var()` reference with its `file`, `line`, `column` and `hasFallback`. Same thing `--lint-refs` does on the CLI.
443
474
 
444
475
  `findUnusedVars(options)` takes `input`/`exclude`/`selectors`/`prefix`/`naming`/`group`/`usage`/`usageExclude` and returns `Promise<string[]>` — the CSS variable names with no detected `cssVars.<key>` usage, without writing or pruning anything. Same thing `--prune-check` does on the CLI.
445
476
 
@@ -461,6 +492,8 @@ By default, variables are scanned from `:root {}` blocks (including attribute se
461
492
 
462
493
  ## Theme values
463
494
 
495
+ When a variable is declared in several files, the last file read wins. Files are read in `input` order (a file matched by several globs counts at the last one), and within a glob a directory's files come before its subdirectories', alphabetically — so `styles/themes/dark.css` overrides `styles/tokens.css`.
496
+
464
497
  By default, a variable redeclared in another block (`:root[data-theme="dark"]`, or a `selectors` entry) simply overwrites its `@default` value — last one wins. The `themes` option names those blocks instead, so each theme's value is kept separately:
465
498
 
466
499
  ```js
@@ -11,7 +11,7 @@ import {
11
11
  scanUsage,
12
12
  warnOnCollisions,
13
13
  writeOutput
14
- } from "./chunk-TR53YUPE.js";
14
+ } from "./chunk-XSFYQPH6.js";
15
15
 
16
16
  // src/index.ts
17
17
  import { readFile } from "fs/promises";
@@ -32,9 +32,13 @@ function matchesIgnore(name, patterns) {
32
32
  return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
33
33
  }
34
34
  async function findUndefinedRefs(options) {
35
- const { references, declared } = await scanReferences(options.input, options.exclude);
35
+ const [css, source] = await Promise.all([
36
+ scanReferences(options.input, options.exclude),
37
+ options.refsSource ? scanReferences(options.refsSource, void 0, true) : null
38
+ ]);
39
+ const declared = /* @__PURE__ */ new Set([...css.declared, ...source?.declared ?? []]);
36
40
  const ignore = options.refsIgnore ?? [];
37
- return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
41
+ return [...css.references, ...source?.references ?? []].filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
38
42
  }
39
43
  async function computeOutputs(options) {
40
44
  assertPruneCompatible(options);
@@ -12,7 +12,7 @@ import {
12
12
  scanUsage,
13
13
  warnOnCollisions,
14
14
  writeOutput
15
- } from "./chunk-TR53YUPE.js";
15
+ } from "./chunk-XSFYQPH6.js";
16
16
 
17
17
  // src/unplugin.ts
18
18
  import { createUnplugin } from "unplugin";
@@ -121,9 +121,11 @@ function maskQuotedContent(text) {
121
121
  }
122
122
  return result;
123
123
  }
124
+ var CLOSERS = { "(": ")", "[": "]", "{": "}" };
124
125
  function extractValue(text, start) {
125
126
  let i = start;
126
127
  let quote = null;
128
+ const open = [];
127
129
  for (; i < text.length; i++) {
128
130
  const char = text[i];
129
131
  if (quote) {
@@ -136,16 +138,19 @@ function extractValue(text, start) {
136
138
  quote = char;
137
139
  continue;
138
140
  }
139
- if (char === ";" || char === "}") break;
141
+ if (char in CLOSERS) open.push(CLOSERS[char]);
142
+ else if (char === open[open.length - 1]) open.pop();
143
+ else if (char === "}" || char === ";" && open.length === 0) break;
140
144
  }
141
145
  return text.slice(start, i).trim();
142
146
  }
147
+ var IMPORTANT = /\s*!\s*important$/i;
143
148
  function forEachProperty(block, onProperty, offset = 0) {
144
149
  const masked = maskQuotedContent(block);
145
150
  for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
146
151
  const name = prop[0];
147
152
  const colonIndex = block.indexOf(":", prop.index + name.length);
148
- onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
153
+ onProperty(name, extractValue(block, colonIndex + 1).replace(IMPORTANT, ""), offset + prop.index);
149
154
  }
150
155
  }
151
156
  function forEachSelectorBlock(stripped, selectors, onBlock) {
@@ -315,6 +320,29 @@ function parseVarReferences(css) {
315
320
  }
316
321
  return refs;
317
322
  }
323
+ var SOURCE_REF_RE = /\bvar\(\s*(--[\w-]+)\s*(,)?|(?<=[\w-]-)\((?:[\w-]+:)?(--[\w-]+)\)/g;
324
+ function parseSourceVarReferences(text) {
325
+ const lineStarts = [0];
326
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") lineStarts.push(i + 1);
327
+ const refs = [];
328
+ for (const match of text.matchAll(SOURCE_REF_RE)) {
329
+ let line = lineStarts.length - 1;
330
+ while (lineStarts[line] > match.index) line--;
331
+ refs.push({
332
+ name: match[1] ?? match[3],
333
+ hasFallback: match[2] === ",",
334
+ line: line + 1,
335
+ column: match.index - lineStarts[line] + 1
336
+ });
337
+ }
338
+ return refs;
339
+ }
340
+ function parseSourceDeclaredNames(text) {
341
+ const names = /* @__PURE__ */ new Set();
342
+ for (const match of text.matchAll(/(?<![\w-])(--[\w-]+)['"`]?\s*:/g)) names.add(match[1]);
343
+ for (const match of text.matchAll(/\bsetProperty\(\s*['"`](--[\w-]+)['"`]/g)) names.add(match[1]);
344
+ return names;
345
+ }
318
346
  function parseDeclaredNames(css) {
319
347
  const masked = maskQuotedContent(stripComments(css));
320
348
  const names = /* @__PURE__ */ new Set();
@@ -325,12 +353,45 @@ function parseDeclaredNames(css) {
325
353
 
326
354
  // src/scanner.ts
327
355
  import { readFile as readFile2 } from "fs/promises";
328
- import { dirname as dirname2, relative, resolve } from "path";
329
- import fg from "fast-glob";
356
+ import { dirname as dirname2, posix, relative, resolve } from "path";
330
357
  import picomatch from "picomatch";
358
+ import { glob } from "tinyglobby";
331
359
  function normalizePatterns(patterns) {
332
360
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
333
361
  }
362
+ function comparePaths(a, b) {
363
+ const as = a.split("/");
364
+ const bs = b.split("/");
365
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
366
+ if (as[i] === bs[i]) continue;
367
+ const aIsFile = i === as.length - 1;
368
+ const bIsFile = i === bs.length - 1;
369
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
370
+ return as[i] < bs[i] ? -1 : 1;
371
+ }
372
+ return as.length - bs.length;
373
+ }
374
+ async function globFiles(pattern, ignore) {
375
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
376
+ return glob(pattern, { absolute: true, ignore, expandDirectories: false });
377
+ }
378
+ const { base, glob: rest, isGlob } = picomatch.scan(pattern);
379
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [posix.dirname(pattern), posix.basename(pattern)];
380
+ const matches = await glob(relativeGlob, { cwd, absolute: true, expandDirectories: false });
381
+ if (ignore.length === 0) return matches;
382
+ const isIgnored = picomatch(ignore, { dot: true });
383
+ return matches.filter((file) => !isIgnored(file));
384
+ }
385
+ async function findFiles(patterns, exclude) {
386
+ const normalized = normalizePatterns(patterns);
387
+ const ignore = [
388
+ ...exclude ? normalizePatterns(exclude) : [],
389
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
390
+ ];
391
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
392
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
393
+ return [...new Set(files.reverse())].reverse();
394
+ }
334
395
  function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
335
396
  const compile = (globs) => picomatch(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
336
397
  const include = compile(patterns);
@@ -345,9 +406,9 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
345
406
  function globWatchRoots(patterns, cwd = process.cwd()) {
346
407
  const roots = /* @__PURE__ */ new Map();
347
408
  for (const pattern of normalizePatterns(patterns)) {
348
- const { base, glob, isGlob } = picomatch.scan(pattern);
409
+ const { base, glob: glob2, isGlob } = picomatch.scan(pattern);
349
410
  const dir = resolve(cwd, isGlob ? base || "." : dirname2(pattern));
350
- const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob) ? void 0 : glob.split("/").length - 1;
411
+ const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob2) ? void 0 : glob2.split("/").length - 1;
351
412
  const previous = roots.get(dir);
352
413
  const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
353
414
  roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
@@ -365,9 +426,7 @@ function collectVarNames(scanned) {
365
426
  return [...names].sort();
366
427
  }
367
428
  async function scanCss(patterns, exclude, selectors, themes = {}) {
368
- const normalized = normalizePatterns(patterns);
369
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
370
- const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
429
+ const files = await findFiles(patterns, exclude);
371
430
  const perFile = await Promise.all(
372
431
  files.map(async (file) => {
373
432
  let css;
@@ -431,9 +490,7 @@ function extractUsage(text, into) {
431
490
  }
432
491
  }
433
492
  async function scanUsage(patterns, exclude) {
434
- const normalized = normalizePatterns(patterns);
435
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
436
- const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
493
+ const files = await findFiles(patterns, exclude);
437
494
  const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
438
495
  const texts = await Promise.all(
439
496
  files.map(async (file) => {
@@ -448,10 +505,10 @@ async function scanUsage(patterns, exclude) {
448
505
  for (const text of texts) extractUsage(text, usage);
449
506
  return usage;
450
507
  }
451
- async function scanReferences(patterns, exclude) {
452
- const normalized = normalizePatterns(patterns);
453
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
454
- const files = (await fg(normalized, { absolute: true, ignore: normalizedExclude })).sort();
508
+ async function scanReferences(patterns, exclude, source = false) {
509
+ const parseReferences = source ? parseSourceVarReferences : parseVarReferences;
510
+ const parseDeclared = source ? parseSourceDeclaredNames : parseDeclaredNames;
511
+ const files = (await findFiles(patterns, exclude)).sort();
455
512
  const perFile = await Promise.all(
456
513
  files.map(async (file) => {
457
514
  try {
@@ -466,8 +523,8 @@ async function scanReferences(patterns, exclude) {
466
523
  const declared = /* @__PURE__ */ new Set();
467
524
  for (const result of perFile) {
468
525
  if (!result) continue;
469
- for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
470
- for (const name of parseDeclaredNames(result.css)) declared.add(name);
526
+ for (const ref of parseReferences(result.css)) references.push({ ...ref, file: result.file });
527
+ for (const name of parseDeclared(result.css)) declared.add(name);
471
528
  }
472
529
  return { references, declared };
473
530
  }
@@ -719,6 +776,12 @@ var HELPERS_TS = [
719
776
  "",
720
777
  "export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
721
778
  " return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
779
+ "}",
780
+ "",
781
+ "export type CssVarProperty<R extends CssVarRef> = R extends `var(${infer N})` ? N : never;",
782
+ "",
783
+ "export function varName<R extends CssVarRef>(ref: R): CssVarProperty<R> {",
784
+ " return ref.slice(4, -1) as CssVarProperty<R>;",
722
785
  "}"
723
786
  ];
724
787
  var HELPERS_JS = [
@@ -732,13 +795,19 @@ var HELPERS_JS = [
732
795
  "",
733
796
  "export function withFallback(ref, fallback) {",
734
797
  " return `${ref.slice(0, -1)}, ${fallback})`;",
798
+ "}",
799
+ "",
800
+ "export function varName(ref) {",
801
+ " return ref.slice(4, -1);",
735
802
  "}"
736
803
  ];
737
804
  var HELPERS_DTS = [
738
805
  "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
739
806
  "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
740
807
  "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
741
- "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
808
+ "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;",
809
+ "export type CssVarProperty<R extends CssVarRef> = R extends `var(${infer N})` ? N : never;",
810
+ "export declare function varName<R extends CssVarRef>(ref: R): CssVarProperty<R>;"
742
811
  ];
743
812
  function generateCode(varNames, ...args) {
744
813
  const options = normalizeOptions(args);
package/dist/cli.cjs CHANGED
@@ -36,8 +36,8 @@ var import_chokidar = require("chokidar");
36
36
  // src/scanner.ts
37
37
  var import_promises = require("fs/promises");
38
38
  var import_node_path = require("path");
39
- var import_fast_glob = __toESM(require("fast-glob"), 1);
40
39
  var import_picomatch = __toESM(require("picomatch"), 1);
40
+ var import_tinyglobby = require("tinyglobby");
41
41
 
42
42
  // src/parser.ts
43
43
  function stepQuote(text, i, quote) {
@@ -144,9 +144,11 @@ function maskQuotedContent(text) {
144
144
  }
145
145
  return result;
146
146
  }
147
+ var CLOSERS = { "(": ")", "[": "]", "{": "}" };
147
148
  function extractValue(text, start) {
148
149
  let i = start;
149
150
  let quote = null;
151
+ const open = [];
150
152
  for (; i < text.length; i++) {
151
153
  const char = text[i];
152
154
  if (quote) {
@@ -159,16 +161,19 @@ function extractValue(text, start) {
159
161
  quote = char;
160
162
  continue;
161
163
  }
162
- if (char === ";" || char === "}") break;
164
+ if (char in CLOSERS) open.push(CLOSERS[char]);
165
+ else if (char === open[open.length - 1]) open.pop();
166
+ else if (char === "}" || char === ";" && open.length === 0) break;
163
167
  }
164
168
  return text.slice(start, i).trim();
165
169
  }
170
+ var IMPORTANT = /\s*!\s*important$/i;
166
171
  function forEachProperty(block, onProperty, offset = 0) {
167
172
  const masked = maskQuotedContent(block);
168
173
  for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
169
174
  const name = prop[0];
170
175
  const colonIndex = block.indexOf(":", prop.index + name.length);
171
- onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
176
+ onProperty(name, extractValue(block, colonIndex + 1).replace(IMPORTANT, ""), offset + prop.index);
172
177
  }
173
178
  }
174
179
  function forEachSelectorBlock(stripped, selectors, onBlock) {
@@ -328,6 +333,29 @@ function parseVarReferences(css) {
328
333
  }
329
334
  return refs;
330
335
  }
336
+ var SOURCE_REF_RE = /\bvar\(\s*(--[\w-]+)\s*(,)?|(?<=[\w-]-)\((?:[\w-]+:)?(--[\w-]+)\)/g;
337
+ function parseSourceVarReferences(text) {
338
+ const lineStarts = [0];
339
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") lineStarts.push(i + 1);
340
+ const refs = [];
341
+ for (const match of text.matchAll(SOURCE_REF_RE)) {
342
+ let line = lineStarts.length - 1;
343
+ while (lineStarts[line] > match.index) line--;
344
+ refs.push({
345
+ name: match[1] ?? match[3],
346
+ hasFallback: match[2] === ",",
347
+ line: line + 1,
348
+ column: match.index - lineStarts[line] + 1
349
+ });
350
+ }
351
+ return refs;
352
+ }
353
+ function parseSourceDeclaredNames(text) {
354
+ const names = /* @__PURE__ */ new Set();
355
+ for (const match of text.matchAll(/(?<![\w-])(--[\w-]+)['"`]?\s*:/g)) names.add(match[1]);
356
+ for (const match of text.matchAll(/\bsetProperty\(\s*['"`](--[\w-]+)['"`]/g)) names.add(match[1]);
357
+ return names;
358
+ }
331
359
  function parseDeclaredNames(css) {
332
360
  const masked = maskQuotedContent(stripComments(css));
333
361
  const names = /* @__PURE__ */ new Set();
@@ -340,6 +368,39 @@ function parseDeclaredNames(css) {
340
368
  function normalizePatterns(patterns) {
341
369
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
342
370
  }
371
+ function comparePaths(a, b) {
372
+ const as = a.split("/");
373
+ const bs = b.split("/");
374
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
375
+ if (as[i] === bs[i]) continue;
376
+ const aIsFile = i === as.length - 1;
377
+ const bIsFile = i === bs.length - 1;
378
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
379
+ return as[i] < bs[i] ? -1 : 1;
380
+ }
381
+ return as.length - bs.length;
382
+ }
383
+ async function globFiles(pattern, ignore) {
384
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
385
+ return (0, import_tinyglobby.glob)(pattern, { absolute: true, ignore, expandDirectories: false });
386
+ }
387
+ const { base, glob: rest, isGlob } = import_picomatch.default.scan(pattern);
388
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [import_node_path.posix.dirname(pattern), import_node_path.posix.basename(pattern)];
389
+ const matches = await (0, import_tinyglobby.glob)(relativeGlob, { cwd, absolute: true, expandDirectories: false });
390
+ if (ignore.length === 0) return matches;
391
+ const isIgnored = (0, import_picomatch.default)(ignore, { dot: true });
392
+ return matches.filter((file) => !isIgnored(file));
393
+ }
394
+ async function findFiles(patterns, exclude) {
395
+ const normalized = normalizePatterns(patterns);
396
+ const ignore = [
397
+ ...exclude ? normalizePatterns(exclude) : [],
398
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
399
+ ];
400
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
401
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
402
+ return [...new Set(files.reverse())].reverse();
403
+ }
343
404
  function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
344
405
  const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
345
406
  const include = compile(patterns);
@@ -354,9 +415,9 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
354
415
  function globWatchRoots(patterns, cwd = process.cwd()) {
355
416
  const roots = /* @__PURE__ */ new Map();
356
417
  for (const pattern of normalizePatterns(patterns)) {
357
- const { base, glob, isGlob } = import_picomatch.default.scan(pattern);
418
+ const { base, glob: glob2, isGlob } = import_picomatch.default.scan(pattern);
358
419
  const dir = (0, import_node_path.resolve)(cwd, isGlob ? base || "." : (0, import_node_path.dirname)(pattern));
359
- const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob) ? void 0 : glob.split("/").length - 1;
420
+ const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob2) ? void 0 : glob2.split("/").length - 1;
360
421
  const previous = roots.get(dir);
361
422
  const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
362
423
  roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
@@ -371,9 +432,7 @@ function collectVarNames(scanned) {
371
432
  return [...names].sort();
372
433
  }
373
434
  async function scanCss(patterns, exclude, selectors, themes = {}) {
374
- const normalized = normalizePatterns(patterns);
375
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
376
- const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
435
+ const files = await findFiles(patterns, exclude);
377
436
  const perFile = await Promise.all(
378
437
  files.map(async (file) => {
379
438
  let css;
@@ -430,9 +489,7 @@ function extractUsage(text, into) {
430
489
  }
431
490
  }
432
491
  async function scanUsage(patterns, exclude) {
433
- const normalized = normalizePatterns(patterns);
434
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
435
- const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
492
+ const files = await findFiles(patterns, exclude);
436
493
  const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
437
494
  const texts = await Promise.all(
438
495
  files.map(async (file) => {
@@ -447,10 +504,10 @@ async function scanUsage(patterns, exclude) {
447
504
  for (const text of texts) extractUsage(text, usage);
448
505
  return usage;
449
506
  }
450
- async function scanReferences(patterns, exclude) {
451
- const normalized = normalizePatterns(patterns);
452
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
453
- const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
507
+ async function scanReferences(patterns, exclude, source = false) {
508
+ const parseReferences = source ? parseSourceVarReferences : parseVarReferences;
509
+ const parseDeclared = source ? parseSourceDeclaredNames : parseDeclaredNames;
510
+ const files = (await findFiles(patterns, exclude)).sort();
454
511
  const perFile = await Promise.all(
455
512
  files.map(async (file) => {
456
513
  try {
@@ -465,8 +522,8 @@ async function scanReferences(patterns, exclude) {
465
522
  const declared = /* @__PURE__ */ new Set();
466
523
  for (const result of perFile) {
467
524
  if (!result) continue;
468
- for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
469
- for (const name of parseDeclaredNames(result.css)) declared.add(name);
525
+ for (const ref of parseReferences(result.css)) references.push({ ...ref, file: result.file });
526
+ for (const name of parseDeclared(result.css)) declared.add(name);
470
527
  }
471
528
  return { references, declared };
472
529
  }
@@ -730,6 +787,12 @@ var HELPERS_TS = [
730
787
  "",
731
788
  "export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
732
789
  " return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
790
+ "}",
791
+ "",
792
+ "export type CssVarProperty<R extends CssVarRef> = R extends `var(${infer N})` ? N : never;",
793
+ "",
794
+ "export function varName<R extends CssVarRef>(ref: R): CssVarProperty<R> {",
795
+ " return ref.slice(4, -1) as CssVarProperty<R>;",
733
796
  "}"
734
797
  ];
735
798
  var HELPERS_JS = [
@@ -743,13 +806,19 @@ var HELPERS_JS = [
743
806
  "",
744
807
  "export function withFallback(ref, fallback) {",
745
808
  " return `${ref.slice(0, -1)}, ${fallback})`;",
809
+ "}",
810
+ "",
811
+ "export function varName(ref) {",
812
+ " return ref.slice(4, -1);",
746
813
  "}"
747
814
  ];
748
815
  var HELPERS_DTS = [
749
816
  "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
750
817
  "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
751
818
  "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
752
- "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
819
+ "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;",
820
+ "export type CssVarProperty<R extends CssVarRef> = R extends `var(${infer N})` ? N : never;",
821
+ "export declare function varName<R extends CssVarRef>(ref: R): CssVarProperty<R>;"
753
822
  ];
754
823
  function generateCode(varNames, ...args2) {
755
824
  const options = normalizeOptions(args2);
@@ -869,9 +938,13 @@ function matchesIgnore(name, patterns) {
869
938
  return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
870
939
  }
871
940
  async function findUndefinedRefs(options) {
872
- const { references, declared } = await scanReferences(options.input, options.exclude);
941
+ const [css, source] = await Promise.all([
942
+ scanReferences(options.input, options.exclude),
943
+ options.refsSource ? scanReferences(options.refsSource, void 0, true) : null
944
+ ]);
945
+ const declared = /* @__PURE__ */ new Set([...css.declared, ...source?.declared ?? []]);
873
946
  const ignore = options.refsIgnore ?? [];
874
- return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
947
+ return [...css.references, ...source?.references ?? []].filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
875
948
  }
876
949
  async function computeOutputs(options) {
877
950
  assertPruneCompatible(options);
@@ -946,7 +1019,8 @@ var CONFIG_KEYS = [
946
1019
  "usage",
947
1020
  "usageExclude",
948
1021
  "helpers",
949
- "refsIgnore"
1022
+ "refsIgnore",
1023
+ "refsSource"
950
1024
  ];
951
1025
 
952
1026
  // src/cli.ts
@@ -982,7 +1056,8 @@ var OPTION_FLAGS = [
982
1056
  "--usage",
983
1057
  "--usage-exclude",
984
1058
  "--helpers",
985
- "--refs-ignore"
1059
+ "--refs-ignore",
1060
+ "--refs-source"
986
1061
  ];
987
1062
  var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
988
1063
  var VALUE_FLAGS = [
@@ -996,6 +1071,7 @@ var VALUE_FLAGS = [
996
1071
  "--usage",
997
1072
  "--usage-exclude",
998
1073
  "--refs-ignore",
1074
+ "--refs-source",
999
1075
  "--config"
1000
1076
  ];
1001
1077
  var BOOLEAN_FLAGS = [
@@ -1026,7 +1102,7 @@ Options:
1026
1102
  --selector <selector> Also scan this selector's blocks, not just :root/@theme (repeatable)
1027
1103
  --theme <name>=<sel> Theme block, emitted as @theme JSDoc tags (repeatable)
1028
1104
  --group Nest keys by the first hyphen segment (cssVars.color.primary)
1029
- --helpers Also emit CssVarRef and getCssVar/setCssVar/withFallback
1105
+ --helpers Also emit CssVarRef and getCssVar/setCssVar/withFallback/varName
1030
1106
  --prune Drop vars with no cssVars.<key> usage (needs --usage)
1031
1107
  --usage <glob> Source files to scan for cssVars usage (repeatable)
1032
1108
  --usage-exclude <glob> Source files to skip in the usage scan (repeatable)
@@ -1037,6 +1113,7 @@ Modes:
1037
1113
  --prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
1038
1114
  --lint-refs Exit 1 on var() references to undeclared variables
1039
1115
  --refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
1116
+ --refs-source <glob> Source files whose var() references --lint-refs checks too (repeatable)
1040
1117
  --version, -v Print the version
1041
1118
  --help, -h Print this help
1042
1119
 
@@ -1130,6 +1207,7 @@ function applyFlags(config) {
1130
1207
  const usageArgs = getArgs("--usage");
1131
1208
  const usageExcludeArgs = getArgs("--usage-exclude");
1132
1209
  const refsIgnoreArgs = getArgs("--refs-ignore");
1210
+ const refsSourceArgs = getArgs("--refs-source");
1133
1211
  return {
1134
1212
  ...config,
1135
1213
  input: inputArgs.length > 0 ? inputArgs : config.input,
@@ -1144,7 +1222,8 @@ function applyFlags(config) {
1144
1222
  usage: usageArgs.length > 0 ? usageArgs : config.usage,
1145
1223
  usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
1146
1224
  helpers: args.includes("--helpers") || config.helpers,
1147
- refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
1225
+ refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore,
1226
+ refsSource: refsSourceArgs.length > 0 ? refsSourceArgs : config.refsSource
1148
1227
  };
1149
1228
  }
1150
1229
  function loadTargets(config) {
@@ -1191,8 +1270,15 @@ Or add a css-typed-vars.config.js file with input and output fields. Run with --
1191
1270
  throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
1192
1271
  }
1193
1272
  }
1273
+ function outputPaths(output) {
1274
+ if (!output) return /* @__PURE__ */ new Set();
1275
+ const jsExt = /\.(m|c)?js$/i.exec(output);
1276
+ return new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => (0, import_node_path4.resolve)(path)));
1277
+ }
1194
1278
  async function lintRefs({ options, tag }) {
1195
- const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
1279
+ const { input, exclude, refsIgnore, refsSource } = options;
1280
+ const outputs = outputPaths(options.output);
1281
+ const refs = (await findUndefinedRefs({ input, exclude, refsIgnore, refsSource })).filter((ref) => !outputs.has((0, import_node_path4.resolve)(ref.file)));
1196
1282
  const format = (ref) => ` ${(0, import_node_path4.relative)(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
1197
1283
  const errors = refs.filter((ref) => !ref.hasFallback);
1198
1284
  const warnings = refs.filter((ref) => ref.hasFallback);
@@ -1232,8 +1318,7 @@ async function run({ options }) {
1232
1318
  var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
1233
1319
  function watchTarget(target) {
1234
1320
  const { input, exclude, output, prune, usage, usageExclude } = target.options;
1235
- const jsExt = /\.(m|c)?js$/i.exec(output);
1236
- const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => (0, import_node_path4.resolve)(path)));
1321
+ const outputs = outputPaths(output);
1237
1322
  let timer = null;
1238
1323
  let running = false;
1239
1324
  let pending = false;