css-typed-vars 0.7.0 → 0.9.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/rollup.cjs CHANGED
@@ -36,12 +36,26 @@ module.exports = __toCommonJS(rollup_exports);
36
36
 
37
37
  // src/unplugin.ts
38
38
  var import_unplugin = require("unplugin");
39
- var import_promises2 = require("fs/promises");
39
+
40
+ // src/write.ts
41
+ var import_promises = require("fs/promises");
40
42
  var import_node_path = require("path");
43
+ async function writeOutput(path, content) {
44
+ const current = await (0, import_promises.readFile)(path, "utf8").catch(() => null);
45
+ if (current === content) return false;
46
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
47
+ await (0, import_promises.writeFile)(path, content, "utf8");
48
+ return true;
49
+ }
50
+
51
+ // src/unplugin.ts
52
+ var import_node_path3 = require("path");
41
53
 
42
54
  // src/scanner.ts
43
- var import_promises = require("fs/promises");
55
+ var import_promises2 = require("fs/promises");
56
+ var import_node_path2 = require("path");
44
57
  var import_fast_glob = __toESM(require("fast-glob"), 1);
58
+ var import_picomatch = __toESM(require("picomatch"), 1);
45
59
 
46
60
  // src/parser.ts
47
61
  function stepQuote(text, i, quote) {
@@ -51,6 +65,11 @@ function stepQuote(text, i, quote) {
51
65
  return { consumed: 1, closed: false };
52
66
  }
53
67
  function stripComments(text) {
68
+ return stripCommentsWithMap(text).text;
69
+ }
70
+ function stripCommentsWithMap(text) {
71
+ const removed = [];
72
+ const comments = [];
54
73
  let result = "";
55
74
  let quote = null;
56
75
  let urlDepth = 0;
@@ -85,17 +104,20 @@ function stripComments(text) {
85
104
  result += char;
86
105
  continue;
87
106
  }
107
+ comments.push([i, end + 2]);
108
+ removed.push({ at: result.length, length: end + 2 - i });
88
109
  i = end + 1;
89
110
  continue;
90
111
  }
91
112
  if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
92
113
  const nl = text.indexOf("\n", i);
114
+ removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
93
115
  i = nl === -1 ? text.length - 1 : nl - 1;
94
116
  continue;
95
117
  }
96
118
  result += char;
97
119
  }
98
- return result;
120
+ return { text: result, removed, comments };
99
121
  }
100
122
  function extractBlock(text, start) {
101
123
  let depth = 1;
@@ -159,12 +181,12 @@ function extractValue(text, start) {
159
181
  }
160
182
  return text.slice(start, i).trim();
161
183
  }
162
- function forEachProperty(block, onProperty) {
184
+ function forEachProperty(block, onProperty, offset = 0) {
163
185
  const masked = maskQuotedContent(block);
164
186
  for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
165
187
  const name = prop[0];
166
188
  const colonIndex = block.indexOf(":", prop.index + name.length);
167
- onProperty(name, extractValue(block, colonIndex + 1));
189
+ onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
168
190
  }
169
191
  }
170
192
  function forEachSelectorBlock(stripped, selectors, onBlock) {
@@ -185,7 +207,7 @@ var BASE_SELECTORS = [":root", "@theme"];
185
207
  function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
186
208
  forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
187
209
  if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
188
- forEachProperty(block, onProperty);
210
+ forEachProperty(block, onProperty, bodyStart);
189
211
  });
190
212
  }
191
213
  var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
@@ -205,30 +227,73 @@ function forEachMediaBlock(stripped, media, onBlock) {
205
227
  }
206
228
  }
207
229
  }
230
+ function parseDocComment(body) {
231
+ const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
232
+ const doc = {};
233
+ const description = [];
234
+ let inTags = false;
235
+ for (const line of lines) {
236
+ const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
237
+ if (tag) {
238
+ inTags = true;
239
+ if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
240
+ } else if (!inTags) {
241
+ description.push(line);
242
+ }
243
+ }
244
+ const text = description.join("\n").trim();
245
+ if (text) doc.description = text;
246
+ return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
247
+ }
248
+ function makeDocReader(css, stripped) {
249
+ const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
250
+ return (strippedPos) => {
251
+ let end = toRawPosition(stripped, strippedPos);
252
+ while (end > 0 && /\s/.test(css[end - 1])) end--;
253
+ const start = commentStartByEnd.get(end);
254
+ if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
255
+ return parseDocComment(css.slice(start + 3, end - 2));
256
+ };
257
+ }
208
258
  function parseThemedDeclarations(css, selectors, themes) {
209
- const stripped = stripComments(css);
259
+ const strippedCss = stripCommentsWithMap(css);
260
+ const stripped = strippedCss.text;
261
+ const docAt = makeDocReader(css, strippedCss);
262
+ const themeDocs = /* @__PURE__ */ new Map();
210
263
  const themeValues = /* @__PURE__ */ new Map();
211
264
  const skip = [];
212
265
  for (const [themeName, themeSelector] of Object.entries(themes)) {
213
266
  const values = /* @__PURE__ */ new Map();
214
267
  themeValues.set(themeName, values);
215
- const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
268
+ const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
269
+ values.set(name, value);
270
+ const doc = docAt(position);
271
+ if (doc) themeDocs.set(name, doc);
272
+ }, offset);
216
273
  const selector = themeSelector.trim();
217
274
  if (/^@media\b/i.test(selector)) {
218
275
  forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
219
276
  skip.push(range);
220
- forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
277
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
221
278
  });
222
279
  } else {
223
280
  forEachSelectorBlock(stripped, [selector], (block, range) => {
224
281
  skip.push(range);
225
- collect(block);
282
+ collect(block, range[0]);
226
283
  });
227
284
  }
228
285
  }
229
286
  const declarations = /* @__PURE__ */ new Map();
230
- scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
231
- return { declarations, themes: themeValues };
287
+ const docs = /* @__PURE__ */ new Map();
288
+ scanDeclarations(css, selectors, (name, value, position) => {
289
+ declarations.set(name, value);
290
+ const doc = docAt(position);
291
+ if (doc) docs.set(name, doc);
292
+ }, skip, stripped);
293
+ for (const [name, doc] of themeDocs) {
294
+ if (!docs.has(name)) docs.set(name, doc);
295
+ }
296
+ return { declarations, themes: themeValues, docs };
232
297
  }
233
298
  var PROPERTY_DESCRIPTORS = [
234
299
  ["syntax", "syntax"],
@@ -259,11 +324,30 @@ function parsePropertyRules(css) {
259
324
  }
260
325
  return rules;
261
326
  }
327
+ function toRawPosition(stripped, strippedPos) {
328
+ let rawPos = strippedPos;
329
+ for (const { at, length } of stripped.removed) {
330
+ if (at > strippedPos) break;
331
+ rawPos += length;
332
+ }
333
+ return rawPos;
334
+ }
262
335
 
263
336
  // src/scanner.ts
264
337
  function normalizePatterns(patterns) {
265
338
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
266
339
  }
340
+ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
341
+ const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
342
+ const include = compile(patterns);
343
+ const ignore = exclude ? compile(exclude) : () => false;
344
+ return (file) => {
345
+ const absolute = (0, import_node_path2.resolve)(cwd, file).replace(/\\/g, "/");
346
+ const fromCwd = (0, import_node_path2.relative)(cwd, absolute).replace(/\\/g, "/");
347
+ const matches = (test) => test(fromCwd) || test(absolute);
348
+ return matches(include) && !matches(ignore);
349
+ };
350
+ }
267
351
  function collectVarNames(scanned) {
268
352
  const names = new Set(scanned.declarations.keys());
269
353
  for (const values of scanned.themes.values()) {
@@ -279,7 +363,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
279
363
  files.map(async (file) => {
280
364
  let css;
281
365
  try {
282
- css = await (0, import_promises.readFile)(file, "utf8");
366
+ css = await (0, import_promises2.readFile)(file, "utf8");
283
367
  } catch (err) {
284
368
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
285
369
  return null;
@@ -290,15 +374,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
290
374
  const declarations = /* @__PURE__ */ new Map();
291
375
  const properties = /* @__PURE__ */ new Map();
292
376
  const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
377
+ const docs = /* @__PURE__ */ new Map();
293
378
  for (const result of perFile) {
294
379
  if (!result) continue;
295
380
  for (const [name, value] of result.declarations) declarations.set(name, value);
296
381
  for (const [name, rule] of result.properties) properties.set(name, rule);
382
+ for (const [name, doc] of result.docs) docs.set(name, doc);
297
383
  for (const [theme, values] of result.themes) {
298
384
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
299
385
  }
300
386
  }
301
- return { declarations, properties, themes: themeValues };
387
+ return { declarations, properties, themes: themeValues, docs };
302
388
  }
303
389
  var ROOT_RE = /\bcssVars\b/g;
304
390
  var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
@@ -325,7 +411,7 @@ async function scanUsage(patterns, exclude) {
325
411
  const texts = await Promise.all(
326
412
  files.map(async (file) => {
327
413
  try {
328
- return await (0, import_promises.readFile)(file, "utf8");
414
+ return await (0, import_promises2.readFile)(file, "utf8");
329
415
  } catch (err) {
330
416
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
331
417
  return "";
@@ -430,7 +516,8 @@ function entryMeta(name, options) {
430
516
  name,
431
517
  value: options.declarations?.get(name),
432
518
  syntax: options.properties?.get(name)?.syntax,
433
- ...themes.length > 0 ? { themes } : {}
519
+ ...themes.length > 0 ? { themes } : {},
520
+ ...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
434
521
  };
435
522
  }
436
523
  function buildEntries(varNames, options) {
@@ -470,8 +557,12 @@ function buildGroupedEntries(varNames, options) {
470
557
  const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
471
558
  return { groups, ungrouped };
472
559
  }
473
- function formatDefaultComment(value, indent = " ") {
474
- return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
560
+ var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
561
+ function renderJsDoc(tags, indent) {
562
+ if (tags.length === 0) return [];
563
+ if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
564
+ const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
565
+ return [`${indent}/**`, ...body, `${indent} */`];
475
566
  }
476
567
  function unquoteCssString(value) {
477
568
  const quote = value[0];
@@ -480,11 +571,15 @@ function unquoteCssString(value) {
480
571
  }
481
572
  return value;
482
573
  }
483
- function formatSyntaxComment(syntax, indent = " ") {
484
- return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
485
- }
486
- function formatThemeComment(theme, value, indent = " ") {
487
- return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
574
+ function entryTags({ value, syntax, themes, doc }) {
575
+ const deprecated = doc?.deprecated;
576
+ return [
577
+ ...doc?.description ? [doc.description] : [],
578
+ ...value ? [`@default ${value}`] : [],
579
+ ...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
580
+ ...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
581
+ ...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
582
+ ];
488
583
  }
489
584
  var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
490
585
  function parseEnumSyntax(syntax) {
@@ -516,11 +611,9 @@ function buildTailBlocks(varNames, group, properties) {
516
611
  return blocks;
517
612
  }
518
613
  function renderEntryLines(entries, indent, lineFor) {
519
- return entries.flatMap(({ key, name, value, syntax, themes }) => [
520
- ...value ? [formatDefaultComment(value, indent)] : [],
521
- ...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
522
- ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
523
- `${indent}${lineFor(key, name)}`
614
+ return entries.flatMap((entry) => [
615
+ ...renderJsDoc(entryTags(entry), indent),
616
+ `${indent}${lineFor(entry.key, entry.name)}`
524
617
  ]);
525
618
  }
526
619
  function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
@@ -567,11 +660,17 @@ var HELPERS_JS = [
567
660
  "",
568
661
  "export function setCssVar(ref, value, el = document.documentElement) {",
569
662
  " el.style.setProperty(ref.slice(4, -1), value);",
663
+ "}",
664
+ "",
665
+ "export function withFallback(ref, fallback) {",
666
+ " return `${ref.slice(0, -1)}, ${fallback})`;",
570
667
  "}"
571
668
  ];
572
669
  var HELPERS_DTS = [
573
670
  "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
574
- "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
671
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
672
+ "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
673
+ "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
575
674
  ];
576
675
  function generateJs(varNames, ...args) {
577
676
  const options = normalizeOptions(args);
@@ -616,17 +715,19 @@ function generateTokens(varNames, options = {}) {
616
715
  return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
617
716
  });
618
717
  const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
619
- const resolve2 = (value) => {
718
+ const resolve3 = (value) => {
620
719
  const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
621
720
  return target ? `{${target.join(".")}}` : value;
622
721
  };
623
722
  const root = {};
624
723
  for (const { meta, value, path } of tokens) {
625
- const token = { $value: resolve2(value) };
724
+ const token = { $value: resolve3(value) };
626
725
  const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
627
726
  if (type) token.$type = type;
727
+ if (meta.doc?.description) token.$description = meta.doc.description;
728
+ if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
628
729
  if (meta.themes) {
629
- const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
730
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
630
731
  token.$extensions = { "css-typed-vars": { themes } };
631
732
  }
632
733
  const [key, leaf] = path;
@@ -665,13 +766,13 @@ var VIRTUAL_ID = "css-typed-vars/vars";
665
766
  var RESOLVED_ID = "\0css-typed-vars/vars";
666
767
  function getDtsPath(options) {
667
768
  if (options.dts === false) return null;
668
- return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
769
+ return options.dts ? (0, import_node_path3.resolve)(process.cwd(), options.dts) : (0, import_node_path3.join)(__dirname, "generated.d.ts");
669
770
  }
670
771
  function outputFiles(options, names, generatorOptions) {
671
772
  const files = [];
672
773
  const dtsPath = getDtsPath(options);
673
774
  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)]);
775
+ if (options.tokens) files.push([(0, import_node_path3.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
675
776
  return files;
676
777
  }
677
778
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
@@ -687,14 +788,15 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
687
788
  }
688
789
  return used;
689
790
  };
690
- const generatorOptions = ({ declarations, properties, themes }) => ({
791
+ const generatorOptions = ({ declarations, properties, themes, docs }) => ({
691
792
  prefix: options.prefix,
692
793
  naming: options.naming,
693
794
  declarations,
694
795
  group: options.group,
695
796
  properties,
696
797
  helpers: options.helpers,
697
- themes
798
+ themes,
799
+ docs
698
800
  });
699
801
  const resolveNames = async (scanned) => {
700
802
  const names = collectVarNames(scanned);
@@ -722,7 +824,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
722
824
  writeQueue = writeQueue.then(async () => {
723
825
  for (const [path, content] of files) {
724
826
  if (myGeneration !== generation) return;
725
- await (0, import_promises2.writeFile)(path, content, "utf8");
827
+ await writeOutput(path, content);
726
828
  }
727
829
  }).catch(console.error);
728
830
  await writeQueue;
@@ -734,8 +836,12 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
734
836
  server.ws.send({ type: "full-reload" });
735
837
  }
736
838
  };
839
+ const isInput = createFileMatcher(options.input, options.exclude);
840
+ const isUsage = options.prune ? createFileMatcher(options.usage, options.usageExclude) : () => false;
841
+ const outputs = new Set([getDtsPath(options), options.tokens && (0, import_node_path3.resolve)(process.cwd(), options.tokens)].filter((path) => !!path).map((path) => (0, import_node_path3.resolve)(path)));
737
842
  const handle = (file) => {
738
- if (!/\.(css|scss|less)$/i.test(file)) return;
843
+ if (outputs.has((0, import_node_path3.resolve)(file))) return;
844
+ if (!isInput(file) && !isUsage(file)) return;
739
845
  if (debounceTimer) clearTimeout(debounceTimer);
740
846
  debounceTimer = setTimeout(() => {
741
847
  debounceTimer = null;
@@ -752,7 +858,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
752
858
  const scanned = await cachedScan;
753
859
  const names = await resolveNames(scanned);
754
860
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
755
- await (0, import_promises2.writeFile)(path, content, "utf8");
861
+ await writeOutput(path, content);
756
862
  }
757
863
  },
758
864
  resolveId(id) {
package/dist/rollup.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as rollup from 'rollup';
2
2
  import { Options } from './unplugin.cjs';
3
3
  import 'unplugin';
4
- import './generator-C1iVNsry.cjs';
4
+ import './generator-DJ9uOYBP.cjs';
5
5
 
6
6
  declare const _default: (options: Options) => rollup.Plugin<any> | rollup.Plugin<any>[];
7
7
 
package/dist/rollup.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as rollup from 'rollup';
2
2
  import { Options } from './unplugin.js';
3
3
  import 'unplugin';
4
- import './generator-C1iVNsry.js';
4
+ import './generator-DJ9uOYBP.js';
5
5
 
6
6
  declare const _default: (options: Options) => rollup.Plugin<any> | rollup.Plugin<any>[];
7
7
 
package/dist/rollup.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-HBUSLYYB.js";
4
- import "./chunk-6YWE4A6S.js";
3
+ } from "./chunk-66NEMXYL.js";
4
+ import "./chunk-DHBPPGOE.js";
5
5
 
6
6
  // src/rollup.ts
7
7
  var rollup_default = unplugin_default.rollup;