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