css-typed-vars 0.5.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/index.cjs CHANGED
@@ -31,12 +31,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  checkGenerated: () => checkGenerated,
34
+ findUnusedVars: () => findUnusedVars,
34
35
  generate: () => generate,
35
36
  generateCode: () => generateCode,
36
37
  generateDeclaration: () => generateDeclaration,
37
38
  generateJs: () => generateJs,
39
+ generateTokens: () => generateTokens,
40
+ parsePropertyRules: () => parsePropertyRules,
41
+ parseThemedDeclarations: () => parseThemedDeclarations,
38
42
  parseVarDeclarations: () => parseVarDeclarations,
39
43
  parseVarNames: () => parseVarNames,
44
+ scanCss: () => scanCss,
45
+ scanUsedKeys: () => scanUsedKeys,
40
46
  scanVarDeclarations: () => scanVarDeclarations,
41
47
  scanVarNames: () => scanVarNames
42
48
  });
@@ -164,26 +170,35 @@ function extractValue(text, start) {
164
170
  }
165
171
  return text.slice(start, i).trim();
166
172
  }
167
- function scanDeclarations(css, selectors, onProperty) {
168
- const stripped = stripComments(css);
169
- const allSelectors = [":root", ...selectors ?? []];
170
- for (const sel of allSelectors) {
173
+ function forEachProperty(block, onProperty) {
174
+ const masked = maskQuotedContent(block);
175
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
176
+ const name = prop[0];
177
+ const colonIndex = block.indexOf(":", prop.index + name.length);
178
+ onProperty(name, extractValue(block, colonIndex + 1));
179
+ }
180
+ }
181
+ function forEachSelectorBlock(stripped, selectors, onBlock) {
182
+ for (const sel of selectors) {
171
183
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
172
184
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
173
185
  let match;
174
186
  while (match = openRegex.exec(stripped)) {
175
187
  const start = match.index + match[0].length;
176
188
  const block = extractBlock(stripped, start);
177
- const masked = maskQuotedContent(block);
178
- for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
179
- const name = prop[0];
180
- const colonIndex = block.indexOf(":", prop.index + name.length);
181
- onProperty(name, extractValue(block, colonIndex + 1));
182
- }
183
- openRegex.lastIndex = start + block.length + 1;
189
+ const end = start + block.length + 1;
190
+ onBlock(block, [start, end]);
191
+ openRegex.lastIndex = end;
184
192
  }
185
193
  }
186
194
  }
195
+ var BASE_SELECTORS = [":root", "@theme"];
196
+ function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
197
+ forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
198
+ if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
199
+ forEachProperty(block, onProperty);
200
+ });
201
+ }
187
202
  function parseVarNames(css, selectors) {
188
203
  const names = /* @__PURE__ */ new Set();
189
204
  scanDeclarations(css, selectors, (name) => names.add(name));
@@ -194,12 +209,90 @@ function parseVarDeclarations(css, selectors) {
194
209
  scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
195
210
  return declarations;
196
211
  }
212
+ var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
213
+ function forEachMediaBlock(stripped, media, onBlock) {
214
+ const wanted = normalizePrelude(media.replace(/^@media/i, ""));
215
+ const openRegex = /@media([^{;]*)\{/gi;
216
+ let match;
217
+ while (match = openRegex.exec(stripped)) {
218
+ const start = match.index + match[0].length;
219
+ const block = extractBlock(stripped, start);
220
+ const end = start + block.length + 1;
221
+ if (normalizePrelude(match[1]) === wanted) {
222
+ onBlock(block, [start, end]);
223
+ openRegex.lastIndex = end;
224
+ } else {
225
+ openRegex.lastIndex = start;
226
+ }
227
+ }
228
+ }
229
+ function parseThemedDeclarations(css, selectors, themes) {
230
+ const stripped = stripComments(css);
231
+ const themeValues = /* @__PURE__ */ new Map();
232
+ const skip = [];
233
+ for (const [themeName, themeSelector] of Object.entries(themes)) {
234
+ const values = /* @__PURE__ */ new Map();
235
+ themeValues.set(themeName, values);
236
+ const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
237
+ const selector = themeSelector.trim();
238
+ if (/^@media\b/i.test(selector)) {
239
+ forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
240
+ skip.push(range);
241
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
242
+ });
243
+ } else {
244
+ forEachSelectorBlock(stripped, [selector], (block, range) => {
245
+ skip.push(range);
246
+ collect(block);
247
+ });
248
+ }
249
+ }
250
+ const declarations = /* @__PURE__ */ new Map();
251
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
252
+ return { declarations, themes: themeValues };
253
+ }
254
+ var PROPERTY_DESCRIPTORS = [
255
+ ["syntax", "syntax"],
256
+ ["inherits", "inherits"],
257
+ ["initial-value", "initialValue"]
258
+ ];
259
+ function parsePropertyRules(css) {
260
+ const stripped = stripComments(css);
261
+ const rules = /* @__PURE__ */ new Map();
262
+ const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
263
+ let match;
264
+ while (match = openRegex.exec(stripped)) {
265
+ const name = match[1];
266
+ const start = match.index + match[0].length;
267
+ const block = extractBlock(stripped, start);
268
+ const masked = maskQuotedContent(block);
269
+ const rule = {};
270
+ for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
271
+ const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
272
+ const descMatch = descRegex.exec(masked);
273
+ if (!descMatch) continue;
274
+ const nameEnd = descMatch.index + descMatch[0].length;
275
+ const colonIndex = block.indexOf(":", nameEnd);
276
+ rule[key] = extractValue(block, colonIndex + 1);
277
+ }
278
+ if (Object.keys(rule).length > 0) rules.set(name, rule);
279
+ openRegex.lastIndex = start + block.length + 1;
280
+ }
281
+ return rules;
282
+ }
197
283
 
198
284
  // src/scanner.ts
199
285
  function normalizePatterns(patterns) {
200
286
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
201
287
  }
202
- async function scanVarDeclarations(patterns, exclude, selectors) {
288
+ function collectVarNames(scanned) {
289
+ const names = new Set(scanned.declarations.keys());
290
+ for (const values of scanned.themes.values()) {
291
+ for (const name of values.keys()) names.add(name);
292
+ }
293
+ return [...names].sort();
294
+ }
295
+ async function scanCss(patterns, exclude, selectors, themes = {}) {
203
296
  const normalized = normalizePatterns(patterns);
204
297
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
205
298
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -210,23 +303,69 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
210
303
  css = await (0, import_promises.readFile)(file, "utf8");
211
304
  } catch (err) {
212
305
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
213
- return /* @__PURE__ */ new Map();
306
+ return null;
214
307
  }
215
- return parseVarDeclarations(css, selectors);
308
+ return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
216
309
  })
217
310
  );
218
- const all = /* @__PURE__ */ new Map();
219
- for (const declarations of perFile) {
220
- for (const [name, value] of declarations) {
221
- all.set(name, value);
311
+ const declarations = /* @__PURE__ */ new Map();
312
+ const properties = /* @__PURE__ */ new Map();
313
+ const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
314
+ for (const result of perFile) {
315
+ if (!result) continue;
316
+ for (const [name, value] of result.declarations) declarations.set(name, value);
317
+ for (const [name, rule] of result.properties) properties.set(name, rule);
318
+ for (const [theme, values] of result.themes) {
319
+ for (const [name, value] of values) themeValues.get(theme).set(name, value);
222
320
  }
223
321
  }
224
- return all;
322
+ return { declarations, properties, themes: themeValues };
323
+ }
324
+ async function scanVarDeclarations(patterns, exclude, selectors) {
325
+ return (await scanCss(patterns, exclude, selectors)).declarations;
225
326
  }
226
327
  async function scanVarNames(patterns, exclude, selectors) {
227
328
  const declarations = await scanVarDeclarations(patterns, exclude, selectors);
228
329
  return [...declarations.keys()].sort();
229
330
  }
331
+ var ROOT_RE = /\bcssVars\b/g;
332
+ var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
333
+ function readAccess(text, from) {
334
+ ACCESS_RE.lastIndex = from;
335
+ const match = ACCESS_RE.exec(text);
336
+ return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
337
+ }
338
+ function extractUsage(text, into) {
339
+ for (const root of text.matchAll(ROOT_RE)) {
340
+ const first = readAccess(text, root.index + root[0].length);
341
+ if (!first) continue;
342
+ into.keys.add(first.key);
343
+ const second = readAccess(text, first.end);
344
+ if (second) into.paths.add(`${first.key}\0${second.key}`);
345
+ else into.wholeKeys.add(first.key);
346
+ }
347
+ }
348
+ async function scanUsage(patterns, exclude) {
349
+ const normalized = normalizePatterns(patterns);
350
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
351
+ const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
352
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
353
+ const texts = await Promise.all(
354
+ files.map(async (file) => {
355
+ try {
356
+ return await (0, import_promises.readFile)(file, "utf8");
357
+ } catch (err) {
358
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
359
+ return "";
360
+ }
361
+ })
362
+ );
363
+ for (const text of texts) extractUsage(text, usage);
364
+ return usage;
365
+ }
366
+ async function scanUsedKeys(patterns, exclude) {
367
+ return (await scanUsage(patterns, exclude)).keys;
368
+ }
230
369
 
231
370
  // src/generator.ts
232
371
  var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
@@ -240,10 +379,19 @@ function convertCase(value, naming) {
240
379
  if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
241
380
  return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
242
381
  }
243
- function toKey(cssVarName, naming = "camelCase") {
244
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
382
+ function toKeyFragment(fragment, naming = "camelCase") {
383
+ const key = convertCase(fragment, naming);
245
384
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
246
385
  }
386
+ function toKey(cssVarName, naming = "camelCase") {
387
+ return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
388
+ }
389
+ function splitGroupKey(cssVarName) {
390
+ const stripped = cssVarName.replace(/^--/, "");
391
+ const dashIndex = stripped.indexOf("-");
392
+ if (dashIndex === -1) return null;
393
+ return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
394
+ }
247
395
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
248
396
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
249
397
  var SINGLE_QUOTE_ESCAPES = {};
@@ -276,6 +424,15 @@ function formatKey(key, naming = "camelCase") {
276
424
  if (naming === "kebab") return `'${key}'`;
277
425
  return key;
278
426
  }
427
+ function computeKey(cssVarName, prefix, naming) {
428
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
429
+ }
430
+ function computeKeyPath(cssVarName, prefix, naming, group) {
431
+ if (!group) return [computeKey(cssVarName, prefix, naming)];
432
+ const split = splitGroupKey(cssVarName);
433
+ if (!split) return [toKey(cssVarName, naming)];
434
+ return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
435
+ }
279
436
  function findKeyCollisions(varNames, prefix, naming) {
280
437
  const byKey = /* @__PURE__ */ new Map();
281
438
  for (const name of varNames) {
@@ -294,76 +451,318 @@ function warnOnCollisions(varNames, prefix, naming) {
294
451
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
295
452
  }
296
453
  }
297
- function buildEntries(varNames, prefix, naming, declarations) {
454
+ function entryMeta(name, options) {
455
+ const themes = [];
456
+ for (const [theme, values] of options.themes ?? []) {
457
+ const value = values.get(name);
458
+ if (value !== void 0) themes.push([theme, value]);
459
+ }
460
+ return {
461
+ name,
462
+ value: options.declarations?.get(name),
463
+ syntax: options.properties?.get(name)?.syntax,
464
+ ...themes.length > 0 ? { themes } : {}
465
+ };
466
+ }
467
+ function buildEntries(varNames, options) {
468
+ const { prefix, naming } = options;
298
469
  const byKey = /* @__PURE__ */ new Map();
299
470
  for (const name of varNames) {
300
471
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
301
- byKey.set(key, { name, value: declarations?.get(name) });
472
+ byKey.set(key, entryMeta(name, options));
302
473
  }
303
474
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
304
475
  }
305
- function formatDefaultComment(value) {
306
- return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
476
+ function buildGroupedEntries(varNames, options) {
477
+ const { naming } = options;
478
+ const groupMap = /* @__PURE__ */ new Map();
479
+ const ungroupedMap = /* @__PURE__ */ new Map();
480
+ for (const name of varNames) {
481
+ const meta = entryMeta(name, options);
482
+ const split = splitGroupKey(name);
483
+ if (!split) {
484
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
485
+ continue;
486
+ }
487
+ const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
488
+ const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
489
+ let leafMap = groupMap.get(groupKey);
490
+ if (!leafMap) {
491
+ leafMap = /* @__PURE__ */ new Map();
492
+ groupMap.set(groupKey, leafMap);
493
+ }
494
+ leafMap.set(leafKey, meta);
495
+ }
496
+ for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
497
+ const groups = [...groupMap].map(([key, leafMap]) => ({
498
+ key,
499
+ entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
500
+ }));
501
+ const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
502
+ return { groups, ungrouped };
503
+ }
504
+ function formatDefaultComment(value, indent = " ") {
505
+ return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
506
+ }
507
+ function unquoteCssString(value) {
508
+ const quote = value[0];
509
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
510
+ return value.slice(1, -1);
511
+ }
512
+ return value;
513
+ }
514
+ function formatSyntaxComment(syntax, indent = " ") {
515
+ return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
516
+ }
517
+ function formatThemeComment(theme, value, indent = " ") {
518
+ return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
519
+ }
520
+ var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
521
+ function parseEnumSyntax(syntax) {
522
+ const unquoted = unquoteCssString(syntax).trim();
523
+ if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
524
+ return unquoted.split("|").map((v) => v.trim());
307
525
  }
308
- function generateCode(varNames, prefix, naming, declarations) {
309
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
310
- ...value ? [formatDefaultComment(value)] : [],
311
- ` ${key}: 'var(${name})',`
526
+ function syntaxTypeName(cssVarName) {
527
+ const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
528
+ return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
529
+ }
530
+ function buildSyntaxTypes(varNames, properties) {
531
+ if (!properties) return [];
532
+ const byName = /* @__PURE__ */ new Map();
533
+ for (const name of varNames) {
534
+ const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
535
+ if (values) byName.set(syntaxTypeName(name), values);
536
+ }
537
+ return [...byName].map(([name, values]) => ({ name, values }));
538
+ }
539
+ function renderSyntaxTypeLines(types) {
540
+ return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
541
+ }
542
+ function buildTailBlocks(varNames, group, properties) {
543
+ const blocks = [];
544
+ if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
545
+ const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
546
+ if (syntaxLines.length > 0) blocks.push(syntaxLines);
547
+ return blocks;
548
+ }
549
+ function renderEntryLines(entries, indent, lineFor) {
550
+ return entries.flatMap(({ key, name, value, syntax, themes }) => [
551
+ ...value ? [formatDefaultComment(value, indent)] : [],
552
+ ...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
553
+ ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
554
+ `${indent}${lineFor(key, name)}`
312
555
  ]);
556
+ }
557
+ function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
558
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
559
+ const lines = [];
560
+ for (const group of groups) {
561
+ lines.push(`${indent}${group.key}: {`);
562
+ lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
563
+ lines.push(`${indent}}${closeSuffix}`);
564
+ }
565
+ lines.push(...renderEntryLines(ungrouped, indent, lineFor));
566
+ return lines;
567
+ }
568
+ function assertGroupPrefixCompatible(prefix, group) {
569
+ if (group && prefix) {
570
+ throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
571
+ }
572
+ }
573
+ var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
574
+ var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
575
+ function normalizeOptions(args) {
576
+ const [first] = args;
577
+ if (first !== null && typeof first === "object") return first;
578
+ const [prefix, naming, declarations, group, properties] = args;
579
+ return { prefix, naming, declarations, group, properties };
580
+ }
581
+ function renderEntries(varNames, options, closeSuffix, lineFor) {
582
+ assertGroupPrefixCompatible(options.prefix, options.group);
583
+ return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
584
+ }
585
+ function emittedNames(varNames, options) {
586
+ if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
587
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
588
+ return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
589
+ }
590
+ function renderRefType(varNames, options) {
591
+ const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
592
+ return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
593
+ }
594
+ var HELPERS_TS = [
595
+ "export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
596
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
597
+ "}",
598
+ "",
599
+ "export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
600
+ " el.style.setProperty(ref.slice(4, -1), value);",
601
+ "}"
602
+ ];
603
+ var HELPERS_JS = [
604
+ "export function getCssVar(ref, el = document.documentElement) {",
605
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
606
+ "}",
607
+ "",
608
+ "export function setCssVar(ref, value, el = document.documentElement) {",
609
+ " el.style.setProperty(ref.slice(4, -1), value);",
610
+ "}"
611
+ ];
612
+ var HELPERS_DTS = [
613
+ "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
614
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
615
+ ];
616
+ function generateCode(varNames, ...args) {
617
+ const options = normalizeOptions(args);
618
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
619
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
620
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
621
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
313
622
  return [
314
623
  "// generated \u2014 do not edit",
315
624
  "export const cssVars = {",
316
625
  ...entries,
317
626
  "} as const;",
318
- "",
319
- "export type CssVarName = keyof typeof cssVars;",
627
+ ...tailBody.length > 0 ? ["", ...tailBody] : [],
320
628
  ""
321
629
  ].join("\n");
322
630
  }
323
- function generateJs(varNames, prefix, naming, declarations) {
324
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
325
- ...value ? [formatDefaultComment(value)] : [],
326
- ` ${key}: 'var(${name})',`
327
- ]);
631
+ function generateJs(varNames, ...args) {
632
+ const options = normalizeOptions(args);
633
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
328
634
  return [
329
635
  "// generated \u2014 do not edit",
330
636
  "export const cssVars = {",
331
637
  ...entries,
332
638
  "};",
639
+ ...options.helpers ? ["", ...HELPERS_JS] : [],
333
640
  ""
334
641
  ].join("\n");
335
642
  }
336
- function generateDeclaration(varNames, prefix, naming, declarations) {
337
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
338
- ...value ? [formatDefaultComment(value)] : [],
339
- ` ${key}: 'var(${name})';`
340
- ]);
643
+ function generateDeclaration(varNames, ...args) {
644
+ const options = normalizeOptions(args);
645
+ const entries = renderEntries(varNames, options, ";", declarationLineFor);
646
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
647
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
648
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
341
649
  return [
342
650
  "export declare const cssVars: {",
343
651
  ...entries,
344
652
  "};",
345
- "export type CssVarName = keyof typeof cssVars;",
653
+ ...tailBody,
346
654
  ""
347
655
  ].join("\n");
348
656
  }
657
+ var TOKEN_TYPES = {
658
+ "<color>": "color",
659
+ "<length>": "dimension",
660
+ "<length-percentage>": "dimension",
661
+ "<number>": "number",
662
+ "<integer>": "number",
663
+ "<time>": "duration"
664
+ };
665
+ var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
666
+ function generateTokens(varNames, options = {}) {
667
+ assertGroupPrefixCompatible(options.prefix, options.group);
668
+ const tokens = emittedNames(varNames, options).flatMap((name) => {
669
+ const meta = entryMeta(name, options);
670
+ const value = meta.value ?? options.properties?.get(name)?.initialValue;
671
+ return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
672
+ });
673
+ const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
674
+ const resolve2 = (value) => {
675
+ const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
676
+ return target ? `{${target.join(".")}}` : value;
677
+ };
678
+ const root = {};
679
+ for (const { meta, value, path } of tokens) {
680
+ const token = { $value: resolve2(value) };
681
+ const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
682
+ if (type) token.$type = type;
683
+ if (meta.themes) {
684
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
685
+ token.$extensions = { "css-typed-vars": { themes } };
686
+ }
687
+ const [key, leaf] = path;
688
+ if (leaf === void 0) {
689
+ root[key] = token;
690
+ } else {
691
+ const group = root[key] ?? (root[key] = {});
692
+ group[leaf] = token;
693
+ }
694
+ }
695
+ return JSON.stringify(root, null, 2) + "\n";
696
+ }
697
+
698
+ // src/prune.ts
699
+ function assertPruneCompatible(options) {
700
+ if (options.prune && !options.usage) {
701
+ throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
702
+ }
703
+ }
704
+ function isUsed(name, usage, options) {
705
+ const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
706
+ if (leaf === void 0) return usage.keys.has(key);
707
+ return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
708
+ }
709
+ function partitionUnused(names, usage, options) {
710
+ const used = [];
711
+ const unused = [];
712
+ for (const name of names) {
713
+ (isUsed(name, usage, options) ? used : unused).push(name);
714
+ }
715
+ return { used, unused };
716
+ }
349
717
 
350
718
  // src/index.ts
719
+ async function findUnusedVars(options) {
720
+ if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
721
+ const [scanned, usage] = await Promise.all([
722
+ scanCss(options.input, options.exclude, options.selectors, options.themes),
723
+ scanUsage(options.usage, options.usageExclude)
724
+ ]);
725
+ const names = collectVarNames(scanned);
726
+ return partitionUnused(names, usage, options).unused;
727
+ }
351
728
  async function computeOutputs(options) {
352
- const declarations = await scanVarDeclarations(options.input, options.exclude, options.selectors);
353
- const names = [...declarations.keys()].sort();
729
+ assertPruneCompatible(options);
730
+ const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
731
+ const { declarations, properties } = scanned;
732
+ let names = collectVarNames(scanned);
354
733
  if (names.length === 0) {
355
734
  console.warn("css-typed-vars: no CSS custom properties found.");
356
735
  }
357
736
  warnOnCollisions(names, options.prefix, options.naming);
737
+ if (options.prune) {
738
+ const usage = await scanUsage(options.usage, options.usageExclude);
739
+ const { used, unused } = partitionUnused(names, usage, options);
740
+ if (unused.length > 0) {
741
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
742
+ }
743
+ names = used;
744
+ }
358
745
  const outPath = (0, import_node_path.resolve)(options.output);
746
+ const generatorOptions = {
747
+ prefix: options.prefix,
748
+ naming: options.naming,
749
+ declarations,
750
+ group: options.group,
751
+ properties,
752
+ helpers: options.helpers,
753
+ themes: scanned.themes
754
+ };
755
+ if (/\.json$/i.test(options.output)) {
756
+ return { outPath, content: generateTokens(names, generatorOptions) };
757
+ }
359
758
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
360
759
  if (jsExtMatch) {
361
- const content = generateJs(names, options.prefix, options.naming, declarations);
760
+ const content = generateJs(names, generatorOptions);
362
761
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
363
- const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations);
762
+ const dtsContent = generateDeclaration(names, generatorOptions);
364
763
  return { outPath, content, dtsPath, dtsContent };
365
764
  }
366
- return { outPath, content: generateCode(names, options.prefix, options.naming, declarations) };
765
+ return { outPath, content: generateCode(names, generatorOptions) };
367
766
  }
368
767
  async function generate(options) {
369
768
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
@@ -386,12 +785,18 @@ async function checkGenerated(options) {
386
785
  // Annotate the CommonJS export names for ESM import in node:
387
786
  0 && (module.exports = {
388
787
  checkGenerated,
788
+ findUnusedVars,
389
789
  generate,
390
790
  generateCode,
391
791
  generateDeclaration,
392
792
  generateJs,
793
+ generateTokens,
794
+ parsePropertyRules,
795
+ parseThemedDeclarations,
393
796
  parseVarDeclarations,
394
797
  parseVarNames,
798
+ scanCss,
799
+ scanUsedKeys,
395
800
  scanVarDeclarations,
396
801
  scanVarNames
397
802
  });