css-typed-vars 0.6.0 → 0.7.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/dist/cli.cjs CHANGED
@@ -157,30 +157,76 @@ function extractValue(text, start) {
157
157
  }
158
158
  return text.slice(start, i).trim();
159
159
  }
160
- function scanDeclarations(css, selectors, onProperty) {
161
- const stripped = stripComments(css);
162
- const allSelectors = [":root", "@theme", ...selectors ?? []];
163
- for (const sel of allSelectors) {
160
+ function forEachProperty(block, onProperty) {
161
+ const masked = maskQuotedContent(block);
162
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
163
+ const name = prop[0];
164
+ const colonIndex = block.indexOf(":", prop.index + name.length);
165
+ onProperty(name, extractValue(block, colonIndex + 1));
166
+ }
167
+ }
168
+ function forEachSelectorBlock(stripped, selectors, onBlock) {
169
+ for (const sel of selectors) {
164
170
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
165
171
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
166
172
  let match;
167
173
  while (match = openRegex.exec(stripped)) {
168
174
  const start = match.index + match[0].length;
169
175
  const block = extractBlock(stripped, start);
170
- const masked = maskQuotedContent(block);
171
- for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
172
- const name = prop[0];
173
- const colonIndex = block.indexOf(":", prop.index + name.length);
174
- onProperty(name, extractValue(block, colonIndex + 1));
175
- }
176
- openRegex.lastIndex = start + block.length + 1;
176
+ const end = start + block.length + 1;
177
+ onBlock(block, [start, end]);
178
+ openRegex.lastIndex = end;
179
+ }
180
+ }
181
+ }
182
+ var BASE_SELECTORS = [":root", "@theme"];
183
+ function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
184
+ forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
185
+ if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
186
+ forEachProperty(block, onProperty);
187
+ });
188
+ }
189
+ var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
190
+ function forEachMediaBlock(stripped, media, onBlock) {
191
+ const wanted = normalizePrelude(media.replace(/^@media/i, ""));
192
+ const openRegex = /@media([^{;]*)\{/gi;
193
+ let match;
194
+ while (match = openRegex.exec(stripped)) {
195
+ const start = match.index + match[0].length;
196
+ const block = extractBlock(stripped, start);
197
+ const end = start + block.length + 1;
198
+ if (normalizePrelude(match[1]) === wanted) {
199
+ onBlock(block, [start, end]);
200
+ openRegex.lastIndex = end;
201
+ } else {
202
+ openRegex.lastIndex = start;
177
203
  }
178
204
  }
179
205
  }
180
- function parseVarDeclarations(css, selectors) {
206
+ function parseThemedDeclarations(css, selectors, themes) {
207
+ const stripped = stripComments(css);
208
+ const themeValues = /* @__PURE__ */ new Map();
209
+ const skip = [];
210
+ for (const [themeName, themeSelector] of Object.entries(themes)) {
211
+ const values = /* @__PURE__ */ new Map();
212
+ themeValues.set(themeName, values);
213
+ const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
214
+ const selector = themeSelector.trim();
215
+ if (/^@media\b/i.test(selector)) {
216
+ forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
217
+ skip.push(range);
218
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
219
+ });
220
+ } else {
221
+ forEachSelectorBlock(stripped, [selector], (block, range) => {
222
+ skip.push(range);
223
+ collect(block);
224
+ });
225
+ }
226
+ }
181
227
  const declarations = /* @__PURE__ */ new Map();
182
- scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
183
- return declarations;
228
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
229
+ return { declarations, themes: themeValues };
184
230
  }
185
231
  var PROPERTY_DESCRIPTORS = [
186
232
  ["syntax", "syntax"],
@@ -216,7 +262,14 @@ function parsePropertyRules(css) {
216
262
  function normalizePatterns(patterns) {
217
263
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
218
264
  }
219
- async function scanCss(patterns, exclude, selectors) {
265
+ function collectVarNames(scanned) {
266
+ const names = new Set(scanned.declarations.keys());
267
+ for (const values of scanned.themes.values()) {
268
+ for (const name of values.keys()) names.add(name);
269
+ }
270
+ return [...names].sort();
271
+ }
272
+ async function scanCss(patterns, exclude, selectors, themes = {}) {
220
273
  const normalized = normalizePatterns(patterns);
221
274
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
222
275
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -227,51 +280,58 @@ async function scanCss(patterns, exclude, selectors) {
227
280
  css = await (0, import_promises.readFile)(file, "utf8");
228
281
  } catch (err) {
229
282
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
230
- return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
283
+ return null;
231
284
  }
232
- return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
285
+ return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
233
286
  })
234
287
  );
235
288
  const declarations = /* @__PURE__ */ new Map();
236
289
  const properties = /* @__PURE__ */ new Map();
290
+ const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
237
291
  for (const result of perFile) {
292
+ if (!result) continue;
238
293
  for (const [name, value] of result.declarations) declarations.set(name, value);
239
294
  for (const [name, rule] of result.properties) properties.set(name, rule);
295
+ for (const [theme, values] of result.themes) {
296
+ for (const [name, value] of values) themeValues.get(theme).set(name, value);
297
+ }
240
298
  }
241
- return { declarations, properties };
299
+ return { declarations, properties, themes: themeValues };
242
300
  }
243
- async function scanVarDeclarations(patterns, exclude, selectors) {
244
- return (await scanCss(patterns, exclude, selectors)).declarations;
301
+ var ROOT_RE = /\bcssVars\b/g;
302
+ var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
303
+ function readAccess(text, from) {
304
+ ACCESS_RE.lastIndex = from;
305
+ const match = ACCESS_RE.exec(text);
306
+ return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
245
307
  }
246
- var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
247
- function extractUsedKeys(text, into) {
248
- for (const match of text.matchAll(USAGE_RE)) {
249
- into.add(match[1] ?? match[3]);
308
+ function extractUsage(text, into) {
309
+ for (const root of text.matchAll(ROOT_RE)) {
310
+ const first = readAccess(text, root.index + root[0].length);
311
+ if (!first) continue;
312
+ into.keys.add(first.key);
313
+ const second = readAccess(text, first.end);
314
+ if (second) into.paths.add(`${first.key}\0${second.key}`);
315
+ else into.wholeKeys.add(first.key);
250
316
  }
251
317
  }
252
- async function scanUsedKeys(patterns, exclude) {
318
+ async function scanUsage(patterns, exclude) {
253
319
  const normalized = normalizePatterns(patterns);
254
320
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
255
321
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
256
- const perFile = await Promise.all(
322
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
323
+ const texts = await Promise.all(
257
324
  files.map(async (file) => {
258
- const used = /* @__PURE__ */ new Set();
259
- let text;
260
325
  try {
261
- text = await (0, import_promises.readFile)(file, "utf8");
326
+ return await (0, import_promises.readFile)(file, "utf8");
262
327
  } catch (err) {
263
328
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
264
- return used;
329
+ return "";
265
330
  }
266
- extractUsedKeys(text, used);
267
- return used;
268
331
  })
269
332
  );
270
- const all = /* @__PURE__ */ new Set();
271
- for (const used of perFile) {
272
- for (const key of used) all.add(key);
273
- }
274
- return all;
333
+ for (const text of texts) extractUsage(text, usage);
334
+ return usage;
275
335
  }
276
336
 
277
337
  // src/generator.ts
@@ -334,6 +394,12 @@ function formatKey(key, naming = "camelCase") {
334
394
  function computeKey(cssVarName, prefix, naming) {
335
395
  return applyPrefix(toKey(cssVarName, naming), prefix, naming);
336
396
  }
397
+ function computeKeyPath(cssVarName, prefix, naming, group) {
398
+ if (!group) return [computeKey(cssVarName, prefix, naming)];
399
+ const split = splitGroupKey(cssVarName);
400
+ if (!split) return [toKey(cssVarName, naming)];
401
+ return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
402
+ }
337
403
  function findKeyCollisions(varNames, prefix, naming) {
338
404
  const byKey = /* @__PURE__ */ new Map();
339
405
  for (const name of varNames) {
@@ -352,23 +418,37 @@ function warnOnCollisions(varNames, prefix, naming) {
352
418
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
353
419
  }
354
420
  }
355
- function buildEntries(varNames, prefix, naming, declarations, properties) {
421
+ function entryMeta(name, options) {
422
+ const themes = [];
423
+ for (const [theme, values] of options.themes ?? []) {
424
+ const value = values.get(name);
425
+ if (value !== void 0) themes.push([theme, value]);
426
+ }
427
+ return {
428
+ name,
429
+ value: options.declarations?.get(name),
430
+ syntax: options.properties?.get(name)?.syntax,
431
+ ...themes.length > 0 ? { themes } : {}
432
+ };
433
+ }
434
+ function buildEntries(varNames, options) {
435
+ const { prefix, naming } = options;
356
436
  const byKey = /* @__PURE__ */ new Map();
357
437
  for (const name of varNames) {
358
438
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
359
- byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
439
+ byKey.set(key, entryMeta(name, options));
360
440
  }
361
441
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
362
442
  }
363
- function buildGroupedEntries(varNames, naming, declarations, properties) {
443
+ function buildGroupedEntries(varNames, options) {
444
+ const { naming } = options;
364
445
  const groupMap = /* @__PURE__ */ new Map();
365
446
  const ungroupedMap = /* @__PURE__ */ new Map();
366
447
  for (const name of varNames) {
367
- const value = declarations?.get(name);
368
- const syntax = properties?.get(name)?.syntax;
448
+ const meta = entryMeta(name, options);
369
449
  const split = splitGroupKey(name);
370
450
  if (!split) {
371
- ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
451
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
372
452
  continue;
373
453
  }
374
454
  const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
@@ -378,7 +458,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
378
458
  leafMap = /* @__PURE__ */ new Map();
379
459
  groupMap.set(groupKey, leafMap);
380
460
  }
381
- leafMap.set(leafKey, { name, value, syntax });
461
+ leafMap.set(leafKey, meta);
382
462
  }
383
463
  for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
384
464
  const groups = [...groupMap].map(([key, leafMap]) => ({
@@ -401,6 +481,9 @@ function unquoteCssString(value) {
401
481
  function formatSyntaxComment(syntax, indent = " ") {
402
482
  return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
403
483
  }
484
+ function formatThemeComment(theme, value, indent = " ") {
485
+ return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
486
+ }
404
487
  var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
405
488
  function parseEnumSyntax(syntax) {
406
489
  const unquoted = unquoteCssString(syntax).trim();
@@ -431,14 +514,15 @@ function buildTailBlocks(varNames, group, properties) {
431
514
  return blocks;
432
515
  }
433
516
  function renderEntryLines(entries, indent, lineFor) {
434
- return entries.flatMap(({ key, name, value, syntax }) => [
517
+ return entries.flatMap(({ key, name, value, syntax, themes }) => [
435
518
  ...value ? [formatDefaultComment(value, indent)] : [],
519
+ ...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
436
520
  ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
437
521
  `${indent}${lineFor(key, name)}`
438
522
  ]);
439
523
  }
440
- function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
441
- const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
524
+ function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
525
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
442
526
  const lines = [];
443
527
  for (const group of groups) {
444
528
  lines.push(`${indent}${group.key}: {`);
@@ -455,10 +539,52 @@ function assertGroupPrefixCompatible(prefix, group) {
455
539
  }
456
540
  var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
457
541
  var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
458
- function generateCode(varNames, prefix, naming, declarations, group, properties) {
459
- assertGroupPrefixCompatible(prefix, group);
460
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
461
- const blocks = buildTailBlocks(varNames, group, properties);
542
+ function normalizeOptions(args2) {
543
+ const [first] = args2;
544
+ if (first !== null && typeof first === "object") return first;
545
+ const [prefix, naming, declarations, group, properties] = args2;
546
+ return { prefix, naming, declarations, group, properties };
547
+ }
548
+ function renderEntries(varNames, options, closeSuffix, lineFor) {
549
+ assertGroupPrefixCompatible(options.prefix, options.group);
550
+ return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
551
+ }
552
+ function emittedNames(varNames, options) {
553
+ if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
554
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
555
+ return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
556
+ }
557
+ function renderRefType(varNames, options) {
558
+ const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
559
+ return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
560
+ }
561
+ var HELPERS_TS = [
562
+ "export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
563
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
564
+ "}",
565
+ "",
566
+ "export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
567
+ " el.style.setProperty(ref.slice(4, -1), value);",
568
+ "}"
569
+ ];
570
+ var HELPERS_JS = [
571
+ "export function getCssVar(ref, el = document.documentElement) {",
572
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
573
+ "}",
574
+ "",
575
+ "export function setCssVar(ref, value, el = document.documentElement) {",
576
+ " el.style.setProperty(ref.slice(4, -1), value);",
577
+ "}"
578
+ ];
579
+ var HELPERS_DTS = [
580
+ "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
581
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
582
+ ];
583
+ function generateCode(varNames, ...args2) {
584
+ const options = normalizeOptions(args2);
585
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
586
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
587
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
462
588
  const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
463
589
  return [
464
590
  "// generated \u2014 do not edit",
@@ -469,21 +595,23 @@ function generateCode(varNames, prefix, naming, declarations, group, properties)
469
595
  ""
470
596
  ].join("\n");
471
597
  }
472
- function generateJs(varNames, prefix, naming, declarations, group, properties) {
473
- assertGroupPrefixCompatible(prefix, group);
474
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
598
+ function generateJs(varNames, ...args2) {
599
+ const options = normalizeOptions(args2);
600
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
475
601
  return [
476
602
  "// generated \u2014 do not edit",
477
603
  "export const cssVars = {",
478
604
  ...entries,
479
605
  "};",
606
+ ...options.helpers ? ["", ...HELPERS_JS] : [],
480
607
  ""
481
608
  ].join("\n");
482
609
  }
483
- function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
484
- assertGroupPrefixCompatible(prefix, group);
485
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
486
- const blocks = buildTailBlocks(varNames, group, properties);
610
+ function generateDeclaration(varNames, ...args2) {
611
+ const options = normalizeOptions(args2);
612
+ const entries = renderEntries(varNames, options, ";", declarationLineFor);
613
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
614
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
487
615
  const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
488
616
  return [
489
617
  "export declare const cssVars: {",
@@ -493,55 +621,115 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
493
621
  ""
494
622
  ].join("\n");
495
623
  }
624
+ var TOKEN_TYPES = {
625
+ "<color>": "color",
626
+ "<length>": "dimension",
627
+ "<length-percentage>": "dimension",
628
+ "<number>": "number",
629
+ "<integer>": "number",
630
+ "<time>": "duration"
631
+ };
632
+ var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
633
+ function generateTokens(varNames, options = {}) {
634
+ assertGroupPrefixCompatible(options.prefix, options.group);
635
+ const tokens = emittedNames(varNames, options).flatMap((name) => {
636
+ const meta = entryMeta(name, options);
637
+ const value = meta.value ?? options.properties?.get(name)?.initialValue;
638
+ return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
639
+ });
640
+ const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
641
+ const resolve3 = (value) => {
642
+ const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
643
+ return target ? `{${target.join(".")}}` : value;
644
+ };
645
+ const root = {};
646
+ for (const { meta, value, path } of tokens) {
647
+ const token = { $value: resolve3(value) };
648
+ const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
649
+ if (type) token.$type = type;
650
+ if (meta.themes) {
651
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
652
+ token.$extensions = { "css-typed-vars": { themes } };
653
+ }
654
+ const [key, leaf] = path;
655
+ if (leaf === void 0) {
656
+ root[key] = token;
657
+ } else {
658
+ const group = root[key] ?? (root[key] = {});
659
+ group[leaf] = token;
660
+ }
661
+ }
662
+ return JSON.stringify(root, null, 2) + "\n";
663
+ }
496
664
 
497
- // src/index.ts
665
+ // src/prune.ts
498
666
  function assertPruneCompatible(options) {
499
- if (!options.prune) return;
500
- if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
501
- if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
667
+ if (options.prune && !options.usage) {
668
+ throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
669
+ }
670
+ }
671
+ function isUsed(name, usage, options) {
672
+ const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
673
+ if (leaf === void 0) return usage.keys.has(key);
674
+ return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
502
675
  }
503
- function partitionUnused(names, usedKeys, prefix, naming) {
676
+ function partitionUnused(names, usage, options) {
504
677
  const used = [];
505
678
  const unused = [];
506
679
  for (const name of names) {
507
- (usedKeys.has(computeKey(name, prefix, naming)) ? used : unused).push(name);
680
+ (isUsed(name, usage, options) ? used : unused).push(name);
508
681
  }
509
682
  return { used, unused };
510
683
  }
684
+
685
+ // src/index.ts
511
686
  async function findUnusedVars(options) {
512
687
  if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
513
- const [declarations, usedKeys] = await Promise.all([
514
- scanVarDeclarations(options.input, options.exclude, options.selectors),
515
- scanUsedKeys(options.usage, options.usageExclude)
688
+ const [scanned, usage] = await Promise.all([
689
+ scanCss(options.input, options.exclude, options.selectors, options.themes),
690
+ scanUsage(options.usage, options.usageExclude)
516
691
  ]);
517
- const names = [...declarations.keys()].sort();
518
- return partitionUnused(names, usedKeys, options.prefix, options.naming).unused;
692
+ const names = collectVarNames(scanned);
693
+ return partitionUnused(names, usage, options).unused;
519
694
  }
520
695
  async function computeOutputs(options) {
521
696
  assertPruneCompatible(options);
522
- const { declarations, properties } = await scanCss(options.input, options.exclude, options.selectors);
523
- let names = [...declarations.keys()].sort();
697
+ const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
698
+ const { declarations, properties } = scanned;
699
+ let names = collectVarNames(scanned);
524
700
  if (names.length === 0) {
525
701
  console.warn("css-typed-vars: no CSS custom properties found.");
526
702
  }
527
703
  warnOnCollisions(names, options.prefix, options.naming);
528
704
  if (options.prune) {
529
- const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
530
- const { used, unused } = partitionUnused(names, usedKeys, options.prefix, options.naming);
705
+ const usage = await scanUsage(options.usage, options.usageExclude);
706
+ const { used, unused } = partitionUnused(names, usage, options);
531
707
  if (unused.length > 0) {
532
708
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
533
709
  }
534
710
  names = used;
535
711
  }
536
712
  const outPath = (0, import_node_path.resolve)(options.output);
713
+ const generatorOptions = {
714
+ prefix: options.prefix,
715
+ naming: options.naming,
716
+ declarations,
717
+ group: options.group,
718
+ properties,
719
+ helpers: options.helpers,
720
+ themes: scanned.themes
721
+ };
722
+ if (/\.json$/i.test(options.output)) {
723
+ return { outPath, content: generateTokens(names, generatorOptions) };
724
+ }
537
725
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
538
726
  if (jsExtMatch) {
539
- const content = generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
727
+ const content = generateJs(names, generatorOptions);
540
728
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
541
- const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
729
+ const dtsContent = generateDeclaration(names, generatorOptions);
542
730
  return { outPath, content, dtsPath, dtsContent };
543
731
  }
544
- return { outPath, content: generateCode(names, options.prefix, options.naming, declarations, options.group, properties) };
732
+ return { outPath, content: generateCode(names, generatorOptions) };
545
733
  }
546
734
  async function generate(options) {
547
735
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
@@ -583,6 +771,7 @@ var checkMode = args.includes("--check");
583
771
  var groupFlag = args.includes("--group");
584
772
  var pruneFlag = args.includes("--prune");
585
773
  var pruneCheckMode = args.includes("--prune-check");
774
+ var helpersFlag = args.includes("--helpers");
586
775
  async function loadConfig() {
587
776
  const candidates = [
588
777
  "css-typed-vars.config.js",
@@ -632,14 +821,23 @@ async function main() {
632
821
  const naming = namingRaw;
633
822
  const selectorArgs = getArgs("--selector");
634
823
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
824
+ const themeArgs = getArgs("--theme");
825
+ for (const arg of themeArgs) {
826
+ if (!/^[^=]+=.+$/.test(arg)) {
827
+ console.error(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
828
+ process.exit(1);
829
+ }
830
+ }
831
+ const themes = themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes;
635
832
  const group = groupFlag || config.group;
636
833
  const prune = pruneFlag || config.prune;
637
834
  const usageArgs = getArgs("--usage");
638
835
  const usage = usageArgs.length > 0 ? usageArgs : config.usage;
639
836
  const usageExcludeArgs = getArgs("--usage-exclude");
640
837
  const usageExclude = usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude;
838
+ const helpers = helpersFlag || config.helpers;
641
839
  if (!input || !output) {
642
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--prune --usage <glob>] [--prune-check --usage <glob>]");
840
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>]");
643
841
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
644
842
  process.exit(1);
645
843
  }
@@ -655,16 +853,12 @@ async function main() {
655
853
  console.error("css-typed-vars: --group cannot be combined with --prefix.");
656
854
  process.exit(1);
657
855
  }
658
- if ((prune || pruneCheckMode) && group) {
659
- console.error("css-typed-vars: --prune/--prune-check cannot be combined with --group.");
660
- process.exit(1);
661
- }
662
856
  if ((prune || pruneCheckMode) && !usage) {
663
857
  console.error("css-typed-vars: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).");
664
858
  process.exit(1);
665
859
  }
666
860
  if (pruneCheckMode) {
667
- const unused = await findUnusedVars({ input, exclude, selectors, prefix, naming, usage, usageExclude });
861
+ const unused = await findUnusedVars({ input, exclude, selectors, themes, prefix, naming, group, usage, usageExclude });
668
862
  if (unused.length > 0) {
669
863
  console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
670
864
  process.exit(1);
@@ -672,7 +866,7 @@ async function main() {
672
866
  console.log("css-typed-vars: no unused variables.");
673
867
  return;
674
868
  }
675
- const runOptions = { input, output, exclude, prefix, naming, selectors, group, prune, usage, usageExclude };
869
+ const runOptions = { input, output, exclude, prefix, naming, selectors, themes, group, prune, usage, usageExclude, helpers };
676
870
  if (checkMode) {
677
871
  const upToDate = await checkGenerated(runOptions);
678
872
  if (!upToDate) {
package/dist/cli.js CHANGED
@@ -3,10 +3,10 @@ import {
3
3
  checkGenerated,
4
4
  findUnusedVars,
5
5
  generate
6
- } from "./chunk-VZ2BHHXD.js";
6
+ } from "./chunk-PLO2JWR7.js";
7
7
  import {
8
8
  VALID_NAMINGS
9
- } from "./chunk-LH53WYFF.js";
9
+ } from "./chunk-6YWE4A6S.js";
10
10
 
11
11
  // src/cli.ts
12
12
  import { readFile } from "fs/promises";
@@ -33,6 +33,7 @@ var checkMode = args.includes("--check");
33
33
  var groupFlag = args.includes("--group");
34
34
  var pruneFlag = args.includes("--prune");
35
35
  var pruneCheckMode = args.includes("--prune-check");
36
+ var helpersFlag = args.includes("--helpers");
36
37
  async function loadConfig() {
37
38
  const candidates = [
38
39
  "css-typed-vars.config.js",
@@ -82,14 +83,23 @@ async function main() {
82
83
  const naming = namingRaw;
83
84
  const selectorArgs = getArgs("--selector");
84
85
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
86
+ const themeArgs = getArgs("--theme");
87
+ for (const arg of themeArgs) {
88
+ if (!/^[^=]+=.+$/.test(arg)) {
89
+ console.error(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
90
+ process.exit(1);
91
+ }
92
+ }
93
+ const themes = themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes;
85
94
  const group = groupFlag || config.group;
86
95
  const prune = pruneFlag || config.prune;
87
96
  const usageArgs = getArgs("--usage");
88
97
  const usage = usageArgs.length > 0 ? usageArgs : config.usage;
89
98
  const usageExcludeArgs = getArgs("--usage-exclude");
90
99
  const usageExclude = usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude;
100
+ const helpers = helpersFlag || config.helpers;
91
101
  if (!input || !output) {
92
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--prune --usage <glob>] [--prune-check --usage <glob>]");
102
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>]");
93
103
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
94
104
  process.exit(1);
95
105
  }
@@ -105,16 +115,12 @@ async function main() {
105
115
  console.error("css-typed-vars: --group cannot be combined with --prefix.");
106
116
  process.exit(1);
107
117
  }
108
- if ((prune || pruneCheckMode) && group) {
109
- console.error("css-typed-vars: --prune/--prune-check cannot be combined with --group.");
110
- process.exit(1);
111
- }
112
118
  if ((prune || pruneCheckMode) && !usage) {
113
119
  console.error("css-typed-vars: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).");
114
120
  process.exit(1);
115
121
  }
116
122
  if (pruneCheckMode) {
117
- const unused = await findUnusedVars({ input, exclude, selectors, prefix, naming, usage, usageExclude });
123
+ const unused = await findUnusedVars({ input, exclude, selectors, themes, prefix, naming, group, usage, usageExclude });
118
124
  if (unused.length > 0) {
119
125
  console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
120
126
  process.exit(1);
@@ -122,7 +128,7 @@ async function main() {
122
128
  console.log("css-typed-vars: no unused variables.");
123
129
  return;
124
130
  }
125
- const runOptions = { input, output, exclude, prefix, naming, selectors, group, prune, usage, usageExclude };
131
+ const runOptions = { input, output, exclude, prefix, naming, selectors, themes, group, prune, usage, usageExclude, helpers };
126
132
  if (checkMode) {
127
133
  const upToDate = await checkGenerated(runOptions);
128
134
  if (!upToDate) {