css-typed-vars 0.6.0 → 0.8.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,15 +31,21 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  checkGenerated: () => checkGenerated,
34
+ findUndefinedRefs: () => findUndefinedRefs,
34
35
  findUnusedVars: () => findUnusedVars,
35
36
  generate: () => generate,
36
37
  generateCode: () => generateCode,
37
38
  generateDeclaration: () => generateDeclaration,
38
39
  generateJs: () => generateJs,
40
+ generateTokens: () => generateTokens,
41
+ parseDeclaredNames: () => parseDeclaredNames,
39
42
  parsePropertyRules: () => parsePropertyRules,
43
+ parseThemedDeclarations: () => parseThemedDeclarations,
40
44
  parseVarDeclarations: () => parseVarDeclarations,
41
45
  parseVarNames: () => parseVarNames,
46
+ parseVarReferences: () => parseVarReferences,
42
47
  scanCss: () => scanCss,
48
+ scanReferences: () => scanReferences,
43
49
  scanUsedKeys: () => scanUsedKeys,
44
50
  scanVarDeclarations: () => scanVarDeclarations,
45
51
  scanVarNames: () => scanVarNames
@@ -60,6 +66,11 @@ function stepQuote(text, i, quote) {
60
66
  return { consumed: 1, closed: false };
61
67
  }
62
68
  function stripComments(text) {
69
+ return stripCommentsWithMap(text).text;
70
+ }
71
+ function stripCommentsWithMap(text) {
72
+ const removed = [];
73
+ const comments = [];
63
74
  let result = "";
64
75
  let quote = null;
65
76
  let urlDepth = 0;
@@ -94,17 +105,20 @@ function stripComments(text) {
94
105
  result += char;
95
106
  continue;
96
107
  }
108
+ comments.push([i, end + 2]);
109
+ removed.push({ at: result.length, length: end + 2 - i });
97
110
  i = end + 1;
98
111
  continue;
99
112
  }
100
113
  if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
101
114
  const nl = text.indexOf("\n", i);
115
+ removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
102
116
  i = nl === -1 ? text.length - 1 : nl - 1;
103
117
  continue;
104
118
  }
105
119
  result += char;
106
120
  }
107
- return result;
121
+ return { text: result, removed, comments };
108
122
  }
109
123
  function extractBlock(text, start) {
110
124
  let depth = 1;
@@ -168,26 +182,35 @@ function extractValue(text, start) {
168
182
  }
169
183
  return text.slice(start, i).trim();
170
184
  }
171
- function scanDeclarations(css, selectors, onProperty) {
172
- const stripped = stripComments(css);
173
- const allSelectors = [":root", "@theme", ...selectors ?? []];
174
- for (const sel of allSelectors) {
185
+ function forEachProperty(block, onProperty, offset = 0) {
186
+ const masked = maskQuotedContent(block);
187
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
188
+ const name = prop[0];
189
+ const colonIndex = block.indexOf(":", prop.index + name.length);
190
+ onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
191
+ }
192
+ }
193
+ function forEachSelectorBlock(stripped, selectors, onBlock) {
194
+ for (const sel of selectors) {
175
195
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
176
196
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
177
197
  let match;
178
198
  while (match = openRegex.exec(stripped)) {
179
199
  const start = match.index + match[0].length;
180
200
  const block = extractBlock(stripped, start);
181
- const masked = maskQuotedContent(block);
182
- for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
183
- const name = prop[0];
184
- const colonIndex = block.indexOf(":", prop.index + name.length);
185
- onProperty(name, extractValue(block, colonIndex + 1));
186
- }
187
- openRegex.lastIndex = start + block.length + 1;
201
+ const end = start + block.length + 1;
202
+ onBlock(block, [start, end]);
203
+ openRegex.lastIndex = end;
188
204
  }
189
205
  }
190
206
  }
207
+ var BASE_SELECTORS = [":root", "@theme"];
208
+ function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
209
+ forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
210
+ if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
211
+ forEachProperty(block, onProperty, bodyStart);
212
+ });
213
+ }
191
214
  function parseVarNames(css, selectors) {
192
215
  const names = /* @__PURE__ */ new Set();
193
216
  scanDeclarations(css, selectors, (name) => names.add(name));
@@ -198,6 +221,91 @@ function parseVarDeclarations(css, selectors) {
198
221
  scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
199
222
  return declarations;
200
223
  }
224
+ var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
225
+ function forEachMediaBlock(stripped, media, onBlock) {
226
+ const wanted = normalizePrelude(media.replace(/^@media/i, ""));
227
+ const openRegex = /@media([^{;]*)\{/gi;
228
+ let match;
229
+ while (match = openRegex.exec(stripped)) {
230
+ const start = match.index + match[0].length;
231
+ const block = extractBlock(stripped, start);
232
+ const end = start + block.length + 1;
233
+ if (normalizePrelude(match[1]) === wanted) {
234
+ onBlock(block, [start, end]);
235
+ openRegex.lastIndex = end;
236
+ } else {
237
+ openRegex.lastIndex = start;
238
+ }
239
+ }
240
+ }
241
+ function parseDocComment(body) {
242
+ const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
243
+ const doc = {};
244
+ const description = [];
245
+ let inTags = false;
246
+ for (const line of lines) {
247
+ const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
248
+ if (tag) {
249
+ inTags = true;
250
+ if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
251
+ } else if (!inTags) {
252
+ description.push(line);
253
+ }
254
+ }
255
+ const text = description.join("\n").trim();
256
+ if (text) doc.description = text;
257
+ return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
258
+ }
259
+ function makeDocReader(css, stripped) {
260
+ const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
261
+ return (strippedPos) => {
262
+ let end = toRawPosition(stripped, strippedPos);
263
+ while (end > 0 && /\s/.test(css[end - 1])) end--;
264
+ const start = commentStartByEnd.get(end);
265
+ if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
266
+ return parseDocComment(css.slice(start + 3, end - 2));
267
+ };
268
+ }
269
+ function parseThemedDeclarations(css, selectors, themes) {
270
+ const strippedCss = stripCommentsWithMap(css);
271
+ const stripped = strippedCss.text;
272
+ const docAt = makeDocReader(css, strippedCss);
273
+ const themeDocs = /* @__PURE__ */ new Map();
274
+ const themeValues = /* @__PURE__ */ new Map();
275
+ const skip = [];
276
+ for (const [themeName, themeSelector] of Object.entries(themes)) {
277
+ const values = /* @__PURE__ */ new Map();
278
+ themeValues.set(themeName, values);
279
+ const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
280
+ values.set(name, value);
281
+ const doc = docAt(position);
282
+ if (doc) themeDocs.set(name, doc);
283
+ }, offset);
284
+ const selector = themeSelector.trim();
285
+ if (/^@media\b/i.test(selector)) {
286
+ forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
287
+ skip.push(range);
288
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
289
+ });
290
+ } else {
291
+ forEachSelectorBlock(stripped, [selector], (block, range) => {
292
+ skip.push(range);
293
+ collect(block, range[0]);
294
+ });
295
+ }
296
+ }
297
+ const declarations = /* @__PURE__ */ new Map();
298
+ const docs = /* @__PURE__ */ new Map();
299
+ scanDeclarations(css, selectors, (name, value, position) => {
300
+ declarations.set(name, value);
301
+ const doc = docAt(position);
302
+ if (doc) docs.set(name, doc);
303
+ }, skip, stripped);
304
+ for (const [name, doc] of themeDocs) {
305
+ if (!docs.has(name)) docs.set(name, doc);
306
+ }
307
+ return { declarations, themes: themeValues, docs };
308
+ }
201
309
  var PROPERTY_DESCRIPTORS = [
202
310
  ["syntax", "syntax"],
203
311
  ["inherits", "inherits"],
@@ -227,12 +335,48 @@ function parsePropertyRules(css) {
227
335
  }
228
336
  return rules;
229
337
  }
338
+ function toRawPosition(stripped, strippedPos) {
339
+ let rawPos = strippedPos;
340
+ for (const { at, length } of stripped.removed) {
341
+ if (at > strippedPos) break;
342
+ rawPos += length;
343
+ }
344
+ return rawPos;
345
+ }
346
+ function parseVarReferences(css) {
347
+ const stripped = stripCommentsWithMap(css);
348
+ const masked = maskQuotedContent(stripped.text);
349
+ const lineStarts = [0];
350
+ for (let i = 0; i < css.length; i++) if (css[i] === "\n") lineStarts.push(i + 1);
351
+ const refs = [];
352
+ for (const match of masked.matchAll(/\bvar\(\s*(--[\w-]+)\s*(,)?/gi)) {
353
+ const rawPos = toRawPosition(stripped, match.index);
354
+ let line = lineStarts.length - 1;
355
+ while (lineStarts[line] > rawPos) line--;
356
+ refs.push({ name: match[1], hasFallback: match[2] === ",", line: line + 1, column: rawPos - lineStarts[line] + 1 });
357
+ }
358
+ return refs;
359
+ }
360
+ function parseDeclaredNames(css) {
361
+ const masked = maskQuotedContent(stripComments(css));
362
+ const names = /* @__PURE__ */ new Set();
363
+ for (const match of masked.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) names.add(match[1]);
364
+ for (const match of masked.matchAll(/@property\s+(--[\w-]+)/g)) names.add(match[1]);
365
+ return names;
366
+ }
230
367
 
231
368
  // src/scanner.ts
232
369
  function normalizePatterns(patterns) {
233
370
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
234
371
  }
235
- async function scanCss(patterns, exclude, selectors) {
372
+ function collectVarNames(scanned) {
373
+ const names = new Set(scanned.declarations.keys());
374
+ for (const values of scanned.themes.values()) {
375
+ for (const name of values.keys()) names.add(name);
376
+ }
377
+ return [...names].sort();
378
+ }
379
+ async function scanCss(patterns, exclude, selectors, themes = {}) {
236
380
  const normalized = normalizePatterns(patterns);
237
381
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
238
382
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -243,18 +387,25 @@ async function scanCss(patterns, exclude, selectors) {
243
387
  css = await (0, import_promises.readFile)(file, "utf8");
244
388
  } catch (err) {
245
389
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
246
- return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
390
+ return null;
247
391
  }
248
- return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
392
+ return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
249
393
  })
250
394
  );
251
395
  const declarations = /* @__PURE__ */ new Map();
252
396
  const properties = /* @__PURE__ */ new Map();
397
+ const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
398
+ const docs = /* @__PURE__ */ new Map();
253
399
  for (const result of perFile) {
400
+ if (!result) continue;
254
401
  for (const [name, value] of result.declarations) declarations.set(name, value);
255
402
  for (const [name, rule] of result.properties) properties.set(name, rule);
403
+ for (const [name, doc] of result.docs) docs.set(name, doc);
404
+ for (const [theme, values] of result.themes) {
405
+ for (const [name, value] of values) themeValues.get(theme).set(name, value);
406
+ }
256
407
  }
257
- return { declarations, properties };
408
+ return { declarations, properties, themes: themeValues, docs };
258
409
  }
259
410
  async function scanVarDeclarations(patterns, exclude, selectors) {
260
411
  return (await scanCss(patterns, exclude, selectors)).declarations;
@@ -263,35 +414,66 @@ async function scanVarNames(patterns, exclude, selectors) {
263
414
  const declarations = await scanVarDeclarations(patterns, exclude, selectors);
264
415
  return [...declarations.keys()].sort();
265
416
  }
266
- var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
267
- function extractUsedKeys(text, into) {
268
- for (const match of text.matchAll(USAGE_RE)) {
269
- into.add(match[1] ?? match[3]);
417
+ var ROOT_RE = /\bcssVars\b/g;
418
+ var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
419
+ function readAccess(text, from) {
420
+ ACCESS_RE.lastIndex = from;
421
+ const match = ACCESS_RE.exec(text);
422
+ return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
423
+ }
424
+ function extractUsage(text, into) {
425
+ for (const root of text.matchAll(ROOT_RE)) {
426
+ const first = readAccess(text, root.index + root[0].length);
427
+ if (!first) continue;
428
+ into.keys.add(first.key);
429
+ const second = readAccess(text, first.end);
430
+ if (second) into.paths.add(`${first.key}\0${second.key}`);
431
+ else into.wholeKeys.add(first.key);
270
432
  }
271
433
  }
272
- async function scanUsedKeys(patterns, exclude) {
434
+ async function scanUsage(patterns, exclude) {
273
435
  const normalized = normalizePatterns(patterns);
274
436
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
275
437
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
438
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
439
+ const texts = await Promise.all(
440
+ files.map(async (file) => {
441
+ try {
442
+ return await (0, import_promises.readFile)(file, "utf8");
443
+ } catch (err) {
444
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
445
+ return "";
446
+ }
447
+ })
448
+ );
449
+ for (const text of texts) extractUsage(text, usage);
450
+ return usage;
451
+ }
452
+ async function scanReferences(patterns, exclude) {
453
+ const normalized = normalizePatterns(patterns);
454
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
455
+ const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
276
456
  const perFile = await Promise.all(
277
457
  files.map(async (file) => {
278
- const used = /* @__PURE__ */ new Set();
279
- let text;
280
458
  try {
281
- text = await (0, import_promises.readFile)(file, "utf8");
459
+ return { file, css: await (0, import_promises.readFile)(file, "utf8") };
282
460
  } catch (err) {
283
461
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
284
- return used;
462
+ return null;
285
463
  }
286
- extractUsedKeys(text, used);
287
- return used;
288
464
  })
289
465
  );
290
- const all = /* @__PURE__ */ new Set();
291
- for (const used of perFile) {
292
- for (const key of used) all.add(key);
466
+ const references = [];
467
+ const declared = /* @__PURE__ */ new Set();
468
+ for (const result of perFile) {
469
+ if (!result) continue;
470
+ for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
471
+ for (const name of parseDeclaredNames(result.css)) declared.add(name);
293
472
  }
294
- return all;
473
+ return { references, declared };
474
+ }
475
+ async function scanUsedKeys(patterns, exclude) {
476
+ return (await scanUsage(patterns, exclude)).keys;
295
477
  }
296
478
 
297
479
  // src/generator.ts
@@ -354,6 +536,12 @@ function formatKey(key, naming = "camelCase") {
354
536
  function computeKey(cssVarName, prefix, naming) {
355
537
  return applyPrefix(toKey(cssVarName, naming), prefix, naming);
356
538
  }
539
+ function computeKeyPath(cssVarName, prefix, naming, group) {
540
+ if (!group) return [computeKey(cssVarName, prefix, naming)];
541
+ const split = splitGroupKey(cssVarName);
542
+ if (!split) return [toKey(cssVarName, naming)];
543
+ return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
544
+ }
357
545
  function findKeyCollisions(varNames, prefix, naming) {
358
546
  const byKey = /* @__PURE__ */ new Map();
359
547
  for (const name of varNames) {
@@ -372,23 +560,38 @@ function warnOnCollisions(varNames, prefix, naming) {
372
560
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
373
561
  }
374
562
  }
375
- function buildEntries(varNames, prefix, naming, declarations, properties) {
563
+ function entryMeta(name, options) {
564
+ const themes = [];
565
+ for (const [theme, values] of options.themes ?? []) {
566
+ const value = values.get(name);
567
+ if (value !== void 0) themes.push([theme, value]);
568
+ }
569
+ return {
570
+ name,
571
+ value: options.declarations?.get(name),
572
+ syntax: options.properties?.get(name)?.syntax,
573
+ ...themes.length > 0 ? { themes } : {},
574
+ ...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
575
+ };
576
+ }
577
+ function buildEntries(varNames, options) {
578
+ const { prefix, naming } = options;
376
579
  const byKey = /* @__PURE__ */ new Map();
377
580
  for (const name of varNames) {
378
581
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
379
- byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
582
+ byKey.set(key, entryMeta(name, options));
380
583
  }
381
584
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
382
585
  }
383
- function buildGroupedEntries(varNames, naming, declarations, properties) {
586
+ function buildGroupedEntries(varNames, options) {
587
+ const { naming } = options;
384
588
  const groupMap = /* @__PURE__ */ new Map();
385
589
  const ungroupedMap = /* @__PURE__ */ new Map();
386
590
  for (const name of varNames) {
387
- const value = declarations?.get(name);
388
- const syntax = properties?.get(name)?.syntax;
591
+ const meta = entryMeta(name, options);
389
592
  const split = splitGroupKey(name);
390
593
  if (!split) {
391
- ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
594
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
392
595
  continue;
393
596
  }
394
597
  const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
@@ -398,7 +601,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
398
601
  leafMap = /* @__PURE__ */ new Map();
399
602
  groupMap.set(groupKey, leafMap);
400
603
  }
401
- leafMap.set(leafKey, { name, value, syntax });
604
+ leafMap.set(leafKey, meta);
402
605
  }
403
606
  for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
404
607
  const groups = [...groupMap].map(([key, leafMap]) => ({
@@ -408,8 +611,12 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
408
611
  const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
409
612
  return { groups, ungrouped };
410
613
  }
411
- function formatDefaultComment(value, indent = " ") {
412
- return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
614
+ var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
615
+ function renderJsDoc(tags, indent) {
616
+ if (tags.length === 0) return [];
617
+ if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
618
+ const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
619
+ return [`${indent}/**`, ...body, `${indent} */`];
413
620
  }
414
621
  function unquoteCssString(value) {
415
622
  const quote = value[0];
@@ -418,8 +625,15 @@ function unquoteCssString(value) {
418
625
  }
419
626
  return value;
420
627
  }
421
- function formatSyntaxComment(syntax, indent = " ") {
422
- return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
628
+ function entryTags({ value, syntax, themes, doc }) {
629
+ const deprecated = doc?.deprecated;
630
+ return [
631
+ ...doc?.description ? [doc.description] : [],
632
+ ...value ? [`@default ${value}`] : [],
633
+ ...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
634
+ ...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
635
+ ...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
636
+ ];
423
637
  }
424
638
  var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
425
639
  function parseEnumSyntax(syntax) {
@@ -451,14 +665,13 @@ function buildTailBlocks(varNames, group, properties) {
451
665
  return blocks;
452
666
  }
453
667
  function renderEntryLines(entries, indent, lineFor) {
454
- return entries.flatMap(({ key, name, value, syntax }) => [
455
- ...value ? [formatDefaultComment(value, indent)] : [],
456
- ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
457
- `${indent}${lineFor(key, name)}`
668
+ return entries.flatMap((entry) => [
669
+ ...renderJsDoc(entryTags(entry), indent),
670
+ `${indent}${lineFor(entry.key, entry.name)}`
458
671
  ]);
459
672
  }
460
- function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
461
- const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
673
+ function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
674
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
462
675
  const lines = [];
463
676
  for (const group of groups) {
464
677
  lines.push(`${indent}${group.key}: {`);
@@ -475,10 +688,64 @@ function assertGroupPrefixCompatible(prefix, group) {
475
688
  }
476
689
  var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
477
690
  var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
478
- function generateCode(varNames, prefix, naming, declarations, group, properties) {
479
- assertGroupPrefixCompatible(prefix, group);
480
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
481
- const blocks = buildTailBlocks(varNames, group, properties);
691
+ function normalizeOptions(args) {
692
+ const [first] = args;
693
+ if (first !== null && typeof first === "object") return first;
694
+ const [prefix, naming, declarations, group, properties] = args;
695
+ return { prefix, naming, declarations, group, properties };
696
+ }
697
+ function renderEntries(varNames, options, closeSuffix, lineFor) {
698
+ assertGroupPrefixCompatible(options.prefix, options.group);
699
+ return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
700
+ }
701
+ function emittedNames(varNames, options) {
702
+ if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
703
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
704
+ return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
705
+ }
706
+ function renderRefType(varNames, options) {
707
+ const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
708
+ return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
709
+ }
710
+ var HELPERS_TS = [
711
+ "export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
712
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
713
+ "}",
714
+ "",
715
+ "export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
716
+ " el.style.setProperty(ref.slice(4, -1), value);",
717
+ "}",
718
+ "",
719
+ "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
720
+ "",
721
+ "export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
722
+ " return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
723
+ "}"
724
+ ];
725
+ var HELPERS_JS = [
726
+ "export function getCssVar(ref, el = document.documentElement) {",
727
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
728
+ "}",
729
+ "",
730
+ "export function setCssVar(ref, value, el = document.documentElement) {",
731
+ " el.style.setProperty(ref.slice(4, -1), value);",
732
+ "}",
733
+ "",
734
+ "export function withFallback(ref, fallback) {",
735
+ " return `${ref.slice(0, -1)}, ${fallback})`;",
736
+ "}"
737
+ ];
738
+ var HELPERS_DTS = [
739
+ "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
740
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
741
+ "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
742
+ "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
743
+ ];
744
+ function generateCode(varNames, ...args) {
745
+ const options = normalizeOptions(args);
746
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
747
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
748
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
482
749
  const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
483
750
  return [
484
751
  "// generated \u2014 do not edit",
@@ -489,21 +756,23 @@ function generateCode(varNames, prefix, naming, declarations, group, properties)
489
756
  ""
490
757
  ].join("\n");
491
758
  }
492
- function generateJs(varNames, prefix, naming, declarations, group, properties) {
493
- assertGroupPrefixCompatible(prefix, group);
494
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
759
+ function generateJs(varNames, ...args) {
760
+ const options = normalizeOptions(args);
761
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
495
762
  return [
496
763
  "// generated \u2014 do not edit",
497
764
  "export const cssVars = {",
498
765
  ...entries,
499
766
  "};",
767
+ ...options.helpers ? ["", ...HELPERS_JS] : [],
500
768
  ""
501
769
  ].join("\n");
502
770
  }
503
- function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
504
- assertGroupPrefixCompatible(prefix, group);
505
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
506
- const blocks = buildTailBlocks(varNames, group, properties);
771
+ function generateDeclaration(varNames, ...args) {
772
+ const options = normalizeOptions(args);
773
+ const entries = renderEntries(varNames, options, ";", declarationLineFor);
774
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
775
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
507
776
  const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
508
777
  return [
509
778
  "export declare const cssVars: {",
@@ -513,55 +782,126 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
513
782
  ""
514
783
  ].join("\n");
515
784
  }
785
+ var TOKEN_TYPES = {
786
+ "<color>": "color",
787
+ "<length>": "dimension",
788
+ "<length-percentage>": "dimension",
789
+ "<number>": "number",
790
+ "<integer>": "number",
791
+ "<time>": "duration"
792
+ };
793
+ var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
794
+ function generateTokens(varNames, options = {}) {
795
+ assertGroupPrefixCompatible(options.prefix, options.group);
796
+ const tokens = emittedNames(varNames, options).flatMap((name) => {
797
+ const meta = entryMeta(name, options);
798
+ const value = meta.value ?? options.properties?.get(name)?.initialValue;
799
+ return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
800
+ });
801
+ const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
802
+ const resolve2 = (value) => {
803
+ const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
804
+ return target ? `{${target.join(".")}}` : value;
805
+ };
806
+ const root = {};
807
+ for (const { meta, value, path } of tokens) {
808
+ const token = { $value: resolve2(value) };
809
+ const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
810
+ if (type) token.$type = type;
811
+ if (meta.doc?.description) token.$description = meta.doc.description;
812
+ if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
813
+ if (meta.themes) {
814
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
815
+ token.$extensions = { "css-typed-vars": { themes } };
816
+ }
817
+ const [key, leaf] = path;
818
+ if (leaf === void 0) {
819
+ root[key] = token;
820
+ } else {
821
+ const group = root[key] ?? (root[key] = {});
822
+ group[leaf] = token;
823
+ }
824
+ }
825
+ return JSON.stringify(root, null, 2) + "\n";
826
+ }
516
827
 
517
- // src/index.ts
828
+ // src/prune.ts
518
829
  function assertPruneCompatible(options) {
519
- if (!options.prune) return;
520
- if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
521
- if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
830
+ if (options.prune && !options.usage) {
831
+ throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
832
+ }
833
+ }
834
+ function isUsed(name, usage, options) {
835
+ const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
836
+ if (leaf === void 0) return usage.keys.has(key);
837
+ return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
522
838
  }
523
- function partitionUnused(names, usedKeys, prefix, naming) {
839
+ function partitionUnused(names, usage, options) {
524
840
  const used = [];
525
841
  const unused = [];
526
842
  for (const name of names) {
527
- (usedKeys.has(computeKey(name, prefix, naming)) ? used : unused).push(name);
843
+ (isUsed(name, usage, options) ? used : unused).push(name);
528
844
  }
529
845
  return { used, unused };
530
846
  }
847
+
848
+ // src/index.ts
531
849
  async function findUnusedVars(options) {
532
850
  if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
533
- const [declarations, usedKeys] = await Promise.all([
534
- scanVarDeclarations(options.input, options.exclude, options.selectors),
535
- scanUsedKeys(options.usage, options.usageExclude)
851
+ const [scanned, usage] = await Promise.all([
852
+ scanCss(options.input, options.exclude, options.selectors, options.themes),
853
+ scanUsage(options.usage, options.usageExclude)
536
854
  ]);
537
- const names = [...declarations.keys()].sort();
538
- return partitionUnused(names, usedKeys, options.prefix, options.naming).unused;
855
+ const names = collectVarNames(scanned);
856
+ return partitionUnused(names, usage, options).unused;
857
+ }
858
+ function matchesIgnore(name, patterns) {
859
+ return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
860
+ }
861
+ async function findUndefinedRefs(options) {
862
+ const { references, declared } = await scanReferences(options.input, options.exclude);
863
+ const ignore = options.refsIgnore ?? [];
864
+ return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
539
865
  }
540
866
  async function computeOutputs(options) {
541
867
  assertPruneCompatible(options);
542
- const { declarations, properties } = await scanCss(options.input, options.exclude, options.selectors);
543
- let names = [...declarations.keys()].sort();
868
+ const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
869
+ const { declarations, properties } = scanned;
870
+ let names = collectVarNames(scanned);
544
871
  if (names.length === 0) {
545
872
  console.warn("css-typed-vars: no CSS custom properties found.");
546
873
  }
547
874
  warnOnCollisions(names, options.prefix, options.naming);
548
875
  if (options.prune) {
549
- const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
550
- const { used, unused } = partitionUnused(names, usedKeys, options.prefix, options.naming);
876
+ const usage = await scanUsage(options.usage, options.usageExclude);
877
+ const { used, unused } = partitionUnused(names, usage, options);
551
878
  if (unused.length > 0) {
552
879
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
553
880
  }
554
881
  names = used;
555
882
  }
556
883
  const outPath = (0, import_node_path.resolve)(options.output);
884
+ const generatorOptions = {
885
+ prefix: options.prefix,
886
+ naming: options.naming,
887
+ declarations,
888
+ group: options.group,
889
+ properties,
890
+ helpers: options.helpers,
891
+ themes: scanned.themes,
892
+ docs: scanned.docs
893
+ };
894
+ if (/\.json$/i.test(options.output)) {
895
+ return { outPath, content: generateTokens(names, generatorOptions) };
896
+ }
557
897
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
558
898
  if (jsExtMatch) {
559
- const content = generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
899
+ const content = generateJs(names, generatorOptions);
560
900
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
561
- const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
901
+ const dtsContent = generateDeclaration(names, generatorOptions);
562
902
  return { outPath, content, dtsPath, dtsContent };
563
903
  }
564
- return { outPath, content: generateCode(names, options.prefix, options.naming, declarations, options.group, properties) };
904
+ return { outPath, content: generateCode(names, generatorOptions) };
565
905
  }
566
906
  async function generate(options) {
567
907
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
@@ -584,15 +924,21 @@ async function checkGenerated(options) {
584
924
  // Annotate the CommonJS export names for ESM import in node:
585
925
  0 && (module.exports = {
586
926
  checkGenerated,
927
+ findUndefinedRefs,
587
928
  findUnusedVars,
588
929
  generate,
589
930
  generateCode,
590
931
  generateDeclaration,
591
932
  generateJs,
933
+ generateTokens,
934
+ parseDeclaredNames,
592
935
  parsePropertyRules,
936
+ parseThemedDeclarations,
593
937
  parseVarDeclarations,
594
938
  parseVarNames,
939
+ parseVarReferences,
595
940
  scanCss,
941
+ scanReferences,
596
942
  scanUsedKeys,
597
943
  scanVarDeclarations,
598
944
  scanVarNames