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/esbuild.cjs CHANGED
@@ -159,30 +159,76 @@ function extractValue(text, start) {
159
159
  }
160
160
  return text.slice(start, i).trim();
161
161
  }
162
- function scanDeclarations(css, selectors, onProperty) {
163
- const stripped = stripComments(css);
164
- const allSelectors = [":root", "@theme", ...selectors ?? []];
165
- for (const sel of allSelectors) {
162
+ function forEachProperty(block, onProperty) {
163
+ const masked = maskQuotedContent(block);
164
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
165
+ const name = prop[0];
166
+ const colonIndex = block.indexOf(":", prop.index + name.length);
167
+ onProperty(name, extractValue(block, colonIndex + 1));
168
+ }
169
+ }
170
+ function forEachSelectorBlock(stripped, selectors, onBlock) {
171
+ for (const sel of selectors) {
166
172
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
167
173
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
168
174
  let match;
169
175
  while (match = openRegex.exec(stripped)) {
170
176
  const start = match.index + match[0].length;
171
177
  const block = extractBlock(stripped, start);
172
- const masked = maskQuotedContent(block);
173
- for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
174
- const name = prop[0];
175
- const colonIndex = block.indexOf(":", prop.index + name.length);
176
- onProperty(name, extractValue(block, colonIndex + 1));
177
- }
178
- openRegex.lastIndex = start + block.length + 1;
178
+ const end = start + block.length + 1;
179
+ onBlock(block, [start, end]);
180
+ openRegex.lastIndex = end;
181
+ }
182
+ }
183
+ }
184
+ var BASE_SELECTORS = [":root", "@theme"];
185
+ function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
186
+ forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
187
+ if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
188
+ forEachProperty(block, onProperty);
189
+ });
190
+ }
191
+ var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
192
+ function forEachMediaBlock(stripped, media, onBlock) {
193
+ const wanted = normalizePrelude(media.replace(/^@media/i, ""));
194
+ const openRegex = /@media([^{;]*)\{/gi;
195
+ let match;
196
+ while (match = openRegex.exec(stripped)) {
197
+ const start = match.index + match[0].length;
198
+ const block = extractBlock(stripped, start);
199
+ const end = start + block.length + 1;
200
+ if (normalizePrelude(match[1]) === wanted) {
201
+ onBlock(block, [start, end]);
202
+ openRegex.lastIndex = end;
203
+ } else {
204
+ openRegex.lastIndex = start;
179
205
  }
180
206
  }
181
207
  }
182
- function parseVarDeclarations(css, selectors) {
208
+ function parseThemedDeclarations(css, selectors, themes) {
209
+ const stripped = stripComments(css);
210
+ const themeValues = /* @__PURE__ */ new Map();
211
+ const skip = [];
212
+ for (const [themeName, themeSelector] of Object.entries(themes)) {
213
+ const values = /* @__PURE__ */ new Map();
214
+ themeValues.set(themeName, values);
215
+ const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
216
+ const selector = themeSelector.trim();
217
+ if (/^@media\b/i.test(selector)) {
218
+ forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
219
+ skip.push(range);
220
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
221
+ });
222
+ } else {
223
+ forEachSelectorBlock(stripped, [selector], (block, range) => {
224
+ skip.push(range);
225
+ collect(block);
226
+ });
227
+ }
228
+ }
183
229
  const declarations = /* @__PURE__ */ new Map();
184
- scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
185
- return declarations;
230
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
231
+ return { declarations, themes: themeValues };
186
232
  }
187
233
  var PROPERTY_DESCRIPTORS = [
188
234
  ["syntax", "syntax"],
@@ -218,7 +264,14 @@ function parsePropertyRules(css) {
218
264
  function normalizePatterns(patterns) {
219
265
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
220
266
  }
221
- async function scanCss(patterns, exclude, selectors) {
267
+ function collectVarNames(scanned) {
268
+ const names = new Set(scanned.declarations.keys());
269
+ for (const values of scanned.themes.values()) {
270
+ for (const name of values.keys()) names.add(name);
271
+ }
272
+ return [...names].sort();
273
+ }
274
+ async function scanCss(patterns, exclude, selectors, themes = {}) {
222
275
  const normalized = normalizePatterns(patterns);
223
276
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
224
277
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -229,48 +282,58 @@ async function scanCss(patterns, exclude, selectors) {
229
282
  css = await (0, import_promises.readFile)(file, "utf8");
230
283
  } catch (err) {
231
284
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
232
- return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
285
+ return null;
233
286
  }
234
- return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
287
+ return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
235
288
  })
236
289
  );
237
290
  const declarations = /* @__PURE__ */ new Map();
238
291
  const properties = /* @__PURE__ */ new Map();
292
+ const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
239
293
  for (const result of perFile) {
294
+ if (!result) continue;
240
295
  for (const [name, value] of result.declarations) declarations.set(name, value);
241
296
  for (const [name, rule] of result.properties) properties.set(name, rule);
297
+ for (const [theme, values] of result.themes) {
298
+ for (const [name, value] of values) themeValues.get(theme).set(name, value);
299
+ }
242
300
  }
243
- return { declarations, properties };
244
- }
245
- var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
246
- function extractUsedKeys(text, into) {
247
- for (const match of text.matchAll(USAGE_RE)) {
248
- into.add(match[1] ?? match[3]);
301
+ return { declarations, properties, themes: themeValues };
302
+ }
303
+ var ROOT_RE = /\bcssVars\b/g;
304
+ var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
305
+ function readAccess(text, from) {
306
+ ACCESS_RE.lastIndex = from;
307
+ const match = ACCESS_RE.exec(text);
308
+ return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
309
+ }
310
+ function extractUsage(text, into) {
311
+ for (const root of text.matchAll(ROOT_RE)) {
312
+ const first = readAccess(text, root.index + root[0].length);
313
+ if (!first) continue;
314
+ into.keys.add(first.key);
315
+ const second = readAccess(text, first.end);
316
+ if (second) into.paths.add(`${first.key}\0${second.key}`);
317
+ else into.wholeKeys.add(first.key);
249
318
  }
250
319
  }
251
- async function scanUsedKeys(patterns, exclude) {
320
+ async function scanUsage(patterns, exclude) {
252
321
  const normalized = normalizePatterns(patterns);
253
322
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
254
323
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
255
- const perFile = await Promise.all(
324
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
325
+ const texts = await Promise.all(
256
326
  files.map(async (file) => {
257
- const used = /* @__PURE__ */ new Set();
258
- let text;
259
327
  try {
260
- text = await (0, import_promises.readFile)(file, "utf8");
328
+ return await (0, import_promises.readFile)(file, "utf8");
261
329
  } catch (err) {
262
330
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
263
- return used;
331
+ return "";
264
332
  }
265
- extractUsedKeys(text, used);
266
- return used;
267
333
  })
268
334
  );
269
- const all = /* @__PURE__ */ new Set();
270
- for (const used of perFile) {
271
- for (const key of used) all.add(key);
272
- }
273
- return all;
335
+ for (const text of texts) extractUsage(text, usage);
336
+ return usage;
274
337
  }
275
338
 
276
339
  // src/generator.ts
@@ -333,6 +396,12 @@ function formatKey(key, naming = "camelCase") {
333
396
  function computeKey(cssVarName, prefix, naming) {
334
397
  return applyPrefix(toKey(cssVarName, naming), prefix, naming);
335
398
  }
399
+ function computeKeyPath(cssVarName, prefix, naming, group) {
400
+ if (!group) return [computeKey(cssVarName, prefix, naming)];
401
+ const split = splitGroupKey(cssVarName);
402
+ if (!split) return [toKey(cssVarName, naming)];
403
+ return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
404
+ }
336
405
  function findKeyCollisions(varNames, prefix, naming) {
337
406
  const byKey = /* @__PURE__ */ new Map();
338
407
  for (const name of varNames) {
@@ -351,23 +420,37 @@ function warnOnCollisions(varNames, prefix, naming) {
351
420
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
352
421
  }
353
422
  }
354
- function buildEntries(varNames, prefix, naming, declarations, properties) {
423
+ function entryMeta(name, options) {
424
+ const themes = [];
425
+ for (const [theme, values] of options.themes ?? []) {
426
+ const value = values.get(name);
427
+ if (value !== void 0) themes.push([theme, value]);
428
+ }
429
+ return {
430
+ name,
431
+ value: options.declarations?.get(name),
432
+ syntax: options.properties?.get(name)?.syntax,
433
+ ...themes.length > 0 ? { themes } : {}
434
+ };
435
+ }
436
+ function buildEntries(varNames, options) {
437
+ const { prefix, naming } = options;
355
438
  const byKey = /* @__PURE__ */ new Map();
356
439
  for (const name of varNames) {
357
440
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
358
- byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
441
+ byKey.set(key, entryMeta(name, options));
359
442
  }
360
443
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
361
444
  }
362
- function buildGroupedEntries(varNames, naming, declarations, properties) {
445
+ function buildGroupedEntries(varNames, options) {
446
+ const { naming } = options;
363
447
  const groupMap = /* @__PURE__ */ new Map();
364
448
  const ungroupedMap = /* @__PURE__ */ new Map();
365
449
  for (const name of varNames) {
366
- const value = declarations?.get(name);
367
- const syntax = properties?.get(name)?.syntax;
450
+ const meta = entryMeta(name, options);
368
451
  const split = splitGroupKey(name);
369
452
  if (!split) {
370
- ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
453
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
371
454
  continue;
372
455
  }
373
456
  const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
@@ -377,7 +460,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
377
460
  leafMap = /* @__PURE__ */ new Map();
378
461
  groupMap.set(groupKey, leafMap);
379
462
  }
380
- leafMap.set(leafKey, { name, value, syntax });
463
+ leafMap.set(leafKey, meta);
381
464
  }
382
465
  for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
383
466
  const groups = [...groupMap].map(([key, leafMap]) => ({
@@ -400,6 +483,9 @@ function unquoteCssString(value) {
400
483
  function formatSyntaxComment(syntax, indent = " ") {
401
484
  return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
402
485
  }
486
+ function formatThemeComment(theme, value, indent = " ") {
487
+ return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
488
+ }
403
489
  var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
404
490
  function parseEnumSyntax(syntax) {
405
491
  const unquoted = unquoteCssString(syntax).trim();
@@ -430,14 +516,15 @@ function buildTailBlocks(varNames, group, properties) {
430
516
  return blocks;
431
517
  }
432
518
  function renderEntryLines(entries, indent, lineFor) {
433
- return entries.flatMap(({ key, name, value, syntax }) => [
519
+ return entries.flatMap(({ key, name, value, syntax, themes }) => [
434
520
  ...value ? [formatDefaultComment(value, indent)] : [],
521
+ ...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
435
522
  ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
436
523
  `${indent}${lineFor(key, name)}`
437
524
  ]);
438
525
  }
439
- function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
440
- const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
526
+ function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
527
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
441
528
  const lines = [];
442
529
  for (const group of groups) {
443
530
  lines.push(`${indent}${group.key}: {`);
@@ -454,21 +541,55 @@ function assertGroupPrefixCompatible(prefix, group) {
454
541
  }
455
542
  var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
456
543
  var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
457
- function generateJs(varNames, prefix, naming, declarations, group, properties) {
458
- assertGroupPrefixCompatible(prefix, group);
459
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
544
+ function normalizeOptions(args) {
545
+ const [first] = args;
546
+ if (first !== null && typeof first === "object") return first;
547
+ const [prefix, naming, declarations, group, properties] = args;
548
+ return { prefix, naming, declarations, group, properties };
549
+ }
550
+ function renderEntries(varNames, options, closeSuffix, lineFor) {
551
+ assertGroupPrefixCompatible(options.prefix, options.group);
552
+ return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
553
+ }
554
+ function emittedNames(varNames, options) {
555
+ if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
556
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
557
+ return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
558
+ }
559
+ function renderRefType(varNames, options) {
560
+ const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
561
+ return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
562
+ }
563
+ var HELPERS_JS = [
564
+ "export function getCssVar(ref, el = document.documentElement) {",
565
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
566
+ "}",
567
+ "",
568
+ "export function setCssVar(ref, value, el = document.documentElement) {",
569
+ " el.style.setProperty(ref.slice(4, -1), value);",
570
+ "}"
571
+ ];
572
+ var HELPERS_DTS = [
573
+ "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
574
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
575
+ ];
576
+ function generateJs(varNames, ...args) {
577
+ const options = normalizeOptions(args);
578
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
460
579
  return [
461
580
  "// generated \u2014 do not edit",
462
581
  "export const cssVars = {",
463
582
  ...entries,
464
583
  "};",
584
+ ...options.helpers ? ["", ...HELPERS_JS] : [],
465
585
  ""
466
586
  ].join("\n");
467
587
  }
468
- function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
469
- assertGroupPrefixCompatible(prefix, group);
470
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
471
- const blocks = buildTailBlocks(varNames, group, properties);
588
+ function generateDeclaration(varNames, ...args) {
589
+ const options = normalizeOptions(args);
590
+ const entries = renderEntries(varNames, options, ";", declarationLineFor);
591
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
592
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
472
593
  const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
473
594
  return [
474
595
  "export declare const cssVars: {",
@@ -478,6 +599,66 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
478
599
  ""
479
600
  ].join("\n");
480
601
  }
602
+ var TOKEN_TYPES = {
603
+ "<color>": "color",
604
+ "<length>": "dimension",
605
+ "<length-percentage>": "dimension",
606
+ "<number>": "number",
607
+ "<integer>": "number",
608
+ "<time>": "duration"
609
+ };
610
+ var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
611
+ function generateTokens(varNames, options = {}) {
612
+ assertGroupPrefixCompatible(options.prefix, options.group);
613
+ const tokens = emittedNames(varNames, options).flatMap((name) => {
614
+ const meta = entryMeta(name, options);
615
+ const value = meta.value ?? options.properties?.get(name)?.initialValue;
616
+ return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
617
+ });
618
+ const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
619
+ const resolve2 = (value) => {
620
+ const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
621
+ return target ? `{${target.join(".")}}` : value;
622
+ };
623
+ const root = {};
624
+ for (const { meta, value, path } of tokens) {
625
+ const token = { $value: resolve2(value) };
626
+ const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
627
+ if (type) token.$type = type;
628
+ if (meta.themes) {
629
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
630
+ token.$extensions = { "css-typed-vars": { themes } };
631
+ }
632
+ const [key, leaf] = path;
633
+ if (leaf === void 0) {
634
+ root[key] = token;
635
+ } else {
636
+ const group = root[key] ?? (root[key] = {});
637
+ group[leaf] = token;
638
+ }
639
+ }
640
+ return JSON.stringify(root, null, 2) + "\n";
641
+ }
642
+
643
+ // src/prune.ts
644
+ function assertPruneCompatible(options) {
645
+ if (options.prune && !options.usage) {
646
+ throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
647
+ }
648
+ }
649
+ function isUsed(name, usage, options) {
650
+ const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
651
+ if (leaf === void 0) return usage.keys.has(key);
652
+ return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
653
+ }
654
+ function partitionUnused(names, usage, options) {
655
+ const used = [];
656
+ const unused = [];
657
+ for (const name of names) {
658
+ (isUsed(name, usage, options) ? used : unused).push(name);
659
+ }
660
+ return { used, unused };
661
+ }
481
662
 
482
663
  // src/unplugin.ts
483
664
  var VIRTUAL_ID = "css-typed-vars/vars";
@@ -486,25 +667,37 @@ function getDtsPath(options) {
486
667
  if (options.dts === false) return null;
487
668
  return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
488
669
  }
670
+ function outputFiles(options, names, generatorOptions) {
671
+ const files = [];
672
+ const dtsPath = getDtsPath(options);
673
+ if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
674
+ if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
675
+ return files;
676
+ }
489
677
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
490
- if (options.prune) {
491
- if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
492
- if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
493
- }
678
+ assertPruneCompatible(options);
494
679
  let cachedScan = null;
495
- const scan = () => scanCss(options.input, options.exclude, options.selectors);
680
+ const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
496
681
  const applyPrune = async (names) => {
497
682
  if (!options.prune) return names;
498
- const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
499
- const isUsed = (name) => usedKeys.has(computeKey(name, options.prefix, options.naming));
500
- const unused = names.filter((name) => !isUsed(name));
683
+ const usage = await scanUsage(options.usage, options.usageExclude);
684
+ const { used, unused } = partitionUnused(names, usage, options);
501
685
  if (unused.length > 0) {
502
686
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
503
687
  }
504
- return names.filter(isUsed);
688
+ return used;
505
689
  };
506
- const resolveNames = async (declarations) => {
507
- const names = [...declarations.keys()].sort();
690
+ const generatorOptions = ({ declarations, properties, themes }) => ({
691
+ prefix: options.prefix,
692
+ naming: options.naming,
693
+ declarations,
694
+ group: options.group,
695
+ properties,
696
+ helpers: options.helpers,
697
+ themes
698
+ });
699
+ const resolveNames = async (scanned) => {
700
+ const names = collectVarNames(scanned);
508
701
  warnOnCollisions(names, options.prefix, options.naming);
509
702
  return applyPrune(names);
510
703
  };
@@ -520,16 +713,17 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
520
713
  const myGeneration = ++generation;
521
714
  const scanPromise = scan();
522
715
  cachedScan = scanPromise;
523
- const { declarations, properties } = await scanPromise;
716
+ const scanned = await scanPromise;
524
717
  if (myGeneration !== generation) return;
525
- const names = await resolveNames(declarations);
718
+ const names = await resolveNames(scanned);
526
719
  if (myGeneration !== generation) return;
527
- const dtsPath = getDtsPath(options);
528
- if (dtsPath) {
529
- const content = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
720
+ const files = outputFiles(options, names, generatorOptions(scanned));
721
+ if (files.length > 0) {
530
722
  writeQueue = writeQueue.then(async () => {
531
- if (myGeneration !== generation) return;
532
- await (0, import_promises2.writeFile)(dtsPath, content, "utf8");
723
+ for (const [path, content] of files) {
724
+ if (myGeneration !== generation) return;
725
+ await (0, import_promises2.writeFile)(path, content, "utf8");
726
+ }
533
727
  }).catch(console.error);
534
728
  await writeQueue;
535
729
  }
@@ -555,20 +749,20 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
555
749
  },
556
750
  async buildStart() {
557
751
  cachedScan = scan();
558
- const { declarations, properties } = await cachedScan;
559
- const names = await resolveNames(declarations);
560
- const dtsPath = getDtsPath(options);
561
- if (!dtsPath) return;
562
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties), "utf8");
752
+ const scanned = await cachedScan;
753
+ const names = await resolveNames(scanned);
754
+ for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
755
+ await (0, import_promises2.writeFile)(path, content, "utf8");
756
+ }
563
757
  },
564
758
  resolveId(id) {
565
759
  if (id === VIRTUAL_ID) return RESOLVED_ID;
566
760
  },
567
761
  async load(id) {
568
762
  if (id === RESOLVED_ID) {
569
- const { declarations, properties } = await (cachedScan ?? scan());
570
- const names = await applyPrune([...declarations.keys()].sort());
571
- return generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
763
+ const scanned = await (cachedScan ?? scan());
764
+ const names = await applyPrune(collectVarNames(scanned));
765
+ return generateJs(names, generatorOptions(scanned));
572
766
  }
573
767
  }
574
768
  };
@@ -1,7 +1,7 @@
1
1
  import * as esbuild from 'esbuild';
2
2
  import { Options } from './unplugin.cjs';
3
3
  import 'unplugin';
4
- import './generator-C2AppeJL.cjs';
4
+ import './generator-C1iVNsry.cjs';
5
5
 
6
6
  declare const _default: (options: Options) => esbuild.Plugin;
7
7
 
package/dist/esbuild.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as esbuild from 'esbuild';
2
2
  import { Options } from './unplugin.js';
3
3
  import 'unplugin';
4
- import './generator-C2AppeJL.js';
4
+ import './generator-C1iVNsry.js';
5
5
 
6
6
  declare const _default: (options: Options) => esbuild.Plugin;
7
7
 
package/dist/esbuild.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-TD7SYMDA.js";
4
- import "./chunk-LH53WYFF.js";
3
+ } from "./chunk-HBUSLYYB.js";
4
+ import "./chunk-6YWE4A6S.js";
5
5
 
6
6
  // src/esbuild.ts
7
7
  var esbuild_default = unplugin_default.esbuild;
@@ -0,0 +1,49 @@
1
+ declare function parseVarNames(css: string, selectors?: string[]): string[];
2
+ declare function parseVarDeclarations(css: string, selectors?: string[]): Map<string, string>;
3
+ interface ThemedDeclarations {
4
+ /** Base values, from `:root`/`@theme`/`selectors` blocks outside any theme block. */
5
+ declarations: Map<string, string>;
6
+ /** Per theme name, the values declared inside that theme's blocks. */
7
+ themes: Map<string, Map<string, string>>;
8
+ }
9
+ declare function parseThemedDeclarations(css: string, selectors: string[] | undefined, themes: Record<string, string>): ThemedDeclarations;
10
+ interface PropertyRule {
11
+ syntax?: string;
12
+ inherits?: string;
13
+ initialValue?: string;
14
+ }
15
+ declare function parsePropertyRules(css: string): Map<string, PropertyRule>;
16
+
17
+ type NamingConvention = 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal';
18
+ interface GeneratorOptions {
19
+ prefix?: string;
20
+ naming?: NamingConvention;
21
+ /** Declared value per var name, emitted as a `@default` JSDoc tag. */
22
+ declarations?: Map<string, string>;
23
+ group?: boolean;
24
+ /** `@property` rules per var name, emitted as `@syntax` JSDoc tags and enum union types. */
25
+ properties?: Map<string, PropertyRule>;
26
+ /** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
27
+ helpers?: boolean;
28
+ /** Per theme name, the values declared for it, emitted as `@theme <name> <value>` JSDoc tags. */
29
+ themes?: Map<string, Map<string, string>>;
30
+ }
31
+ type LegacyArgs = [
32
+ prefix?: string,
33
+ naming?: NamingConvention,
34
+ declarations?: Map<string, string>,
35
+ group?: boolean,
36
+ properties?: Map<string, PropertyRule>
37
+ ];
38
+ declare function generateCode(varNames: string[], options?: GeneratorOptions): string;
39
+ /** @deprecated Pass a `GeneratorOptions` object as the second argument instead. */
40
+ declare function generateCode(varNames: string[], ...args: LegacyArgs): string;
41
+ declare function generateJs(varNames: string[], options?: GeneratorOptions): string;
42
+ /** @deprecated Pass a `GeneratorOptions` object as the second argument instead. */
43
+ declare function generateJs(varNames: string[], ...args: LegacyArgs): string;
44
+ declare function generateDeclaration(varNames: string[], options?: GeneratorOptions): string;
45
+ /** @deprecated Pass a `GeneratorOptions` object as the second argument instead. */
46
+ declare function generateDeclaration(varNames: string[], ...args: LegacyArgs): string;
47
+ declare function generateTokens(varNames: string[], options?: GeneratorOptions): string;
48
+
49
+ export { type GeneratorOptions as G, type NamingConvention as N, type PropertyRule as P, type ThemedDeclarations as T, generateDeclaration as a, generateJs as b, generateTokens as c, parseThemedDeclarations as d, parseVarDeclarations as e, parseVarNames as f, generateCode as g, parsePropertyRules as p };
@@ -0,0 +1,49 @@
1
+ declare function parseVarNames(css: string, selectors?: string[]): string[];
2
+ declare function parseVarDeclarations(css: string, selectors?: string[]): Map<string, string>;
3
+ interface ThemedDeclarations {
4
+ /** Base values, from `:root`/`@theme`/`selectors` blocks outside any theme block. */
5
+ declarations: Map<string, string>;
6
+ /** Per theme name, the values declared inside that theme's blocks. */
7
+ themes: Map<string, Map<string, string>>;
8
+ }
9
+ declare function parseThemedDeclarations(css: string, selectors: string[] | undefined, themes: Record<string, string>): ThemedDeclarations;
10
+ interface PropertyRule {
11
+ syntax?: string;
12
+ inherits?: string;
13
+ initialValue?: string;
14
+ }
15
+ declare function parsePropertyRules(css: string): Map<string, PropertyRule>;
16
+
17
+ type NamingConvention = 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal';
18
+ interface GeneratorOptions {
19
+ prefix?: string;
20
+ naming?: NamingConvention;
21
+ /** Declared value per var name, emitted as a `@default` JSDoc tag. */
22
+ declarations?: Map<string, string>;
23
+ group?: boolean;
24
+ /** `@property` rules per var name, emitted as `@syntax` JSDoc tags and enum union types. */
25
+ properties?: Map<string, PropertyRule>;
26
+ /** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
27
+ helpers?: boolean;
28
+ /** Per theme name, the values declared for it, emitted as `@theme <name> <value>` JSDoc tags. */
29
+ themes?: Map<string, Map<string, string>>;
30
+ }
31
+ type LegacyArgs = [
32
+ prefix?: string,
33
+ naming?: NamingConvention,
34
+ declarations?: Map<string, string>,
35
+ group?: boolean,
36
+ properties?: Map<string, PropertyRule>
37
+ ];
38
+ declare function generateCode(varNames: string[], options?: GeneratorOptions): string;
39
+ /** @deprecated Pass a `GeneratorOptions` object as the second argument instead. */
40
+ declare function generateCode(varNames: string[], ...args: LegacyArgs): string;
41
+ declare function generateJs(varNames: string[], options?: GeneratorOptions): string;
42
+ /** @deprecated Pass a `GeneratorOptions` object as the second argument instead. */
43
+ declare function generateJs(varNames: string[], ...args: LegacyArgs): string;
44
+ declare function generateDeclaration(varNames: string[], options?: GeneratorOptions): string;
45
+ /** @deprecated Pass a `GeneratorOptions` object as the second argument instead. */
46
+ declare function generateDeclaration(varNames: string[], ...args: LegacyArgs): string;
47
+ declare function generateTokens(varNames: string[], options?: GeneratorOptions): string;
48
+
49
+ export { type GeneratorOptions as G, type NamingConvention as N, type PropertyRule as P, type ThemedDeclarations as T, generateDeclaration as a, generateJs as b, generateTokens as c, parseThemedDeclarations as d, parseVarDeclarations as e, parseVarNames as f, generateCode as g, parsePropertyRules as p };