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/README.md +119 -16
- package/dist/{chunk-HBUSLYYB.js → chunk-66NEMXYL.js} +14 -8
- package/dist/{chunk-6YWE4A6S.js → chunk-DHBPPGOE.js} +186 -31
- package/dist/{chunk-PLO2JWR7.js → chunk-TB5PSGEF.js} +24 -8
- package/dist/cli.cjs +464 -126
- package/dist/cli.js +280 -89
- package/dist/esbuild.cjs +145 -39
- package/dist/esbuild.d.cts +1 -1
- package/dist/esbuild.d.ts +1 -1
- package/dist/esbuild.js +2 -2
- package/dist/{generator-C1iVNsry.d.ts → generator-DJ9uOYBP.d.cts} +21 -1
- package/dist/{generator-C1iVNsry.d.cts → generator-DJ9uOYBP.d.ts} +21 -1
- package/dist/index.cjs +200 -39
- package/dist/index.d.cts +24 -4
- package/dist/index.d.ts +24 -4
- package/dist/index.js +12 -2
- package/dist/rollup.cjs +145 -39
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +145 -39
- package/dist/unplugin.d.cts +1 -1
- package/dist/unplugin.d.ts +1 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +145 -39
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +145 -39
- package/dist/webpack.d.cts +1 -1
- package/dist/webpack.d.ts +1 -1
- package/dist/webpack.js +2 -2
- package/package.json +3 -1
package/dist/index.cjs
CHANGED
|
@@ -31,28 +31,46 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var src_exports = {};
|
|
32
32
|
__export(src_exports, {
|
|
33
33
|
checkGenerated: () => checkGenerated,
|
|
34
|
+
defineConfig: () => defineConfig,
|
|
35
|
+
findUndefinedRefs: () => findUndefinedRefs,
|
|
34
36
|
findUnusedVars: () => findUnusedVars,
|
|
35
37
|
generate: () => generate,
|
|
36
38
|
generateCode: () => generateCode,
|
|
37
39
|
generateDeclaration: () => generateDeclaration,
|
|
38
40
|
generateJs: () => generateJs,
|
|
39
41
|
generateTokens: () => generateTokens,
|
|
42
|
+
parseDeclaredNames: () => parseDeclaredNames,
|
|
40
43
|
parsePropertyRules: () => parsePropertyRules,
|
|
41
44
|
parseThemedDeclarations: () => parseThemedDeclarations,
|
|
42
45
|
parseVarDeclarations: () => parseVarDeclarations,
|
|
43
46
|
parseVarNames: () => parseVarNames,
|
|
47
|
+
parseVarReferences: () => parseVarReferences,
|
|
44
48
|
scanCss: () => scanCss,
|
|
49
|
+
scanReferences: () => scanReferences,
|
|
45
50
|
scanUsedKeys: () => scanUsedKeys,
|
|
46
51
|
scanVarDeclarations: () => scanVarDeclarations,
|
|
47
52
|
scanVarNames: () => scanVarNames
|
|
48
53
|
});
|
|
49
54
|
module.exports = __toCommonJS(src_exports);
|
|
50
|
-
var
|
|
55
|
+
var import_promises3 = require("fs/promises");
|
|
56
|
+
var import_node_path3 = require("path");
|
|
57
|
+
|
|
58
|
+
// src/write.ts
|
|
59
|
+
var import_promises = require("fs/promises");
|
|
51
60
|
var import_node_path = require("path");
|
|
61
|
+
async function writeOutput(path, content) {
|
|
62
|
+
const current = await (0, import_promises.readFile)(path, "utf8").catch(() => null);
|
|
63
|
+
if (current === content) return false;
|
|
64
|
+
await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
|
|
65
|
+
await (0, import_promises.writeFile)(path, content, "utf8");
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
52
68
|
|
|
53
69
|
// src/scanner.ts
|
|
54
|
-
var
|
|
70
|
+
var import_promises2 = require("fs/promises");
|
|
71
|
+
var import_node_path2 = require("path");
|
|
55
72
|
var import_fast_glob = __toESM(require("fast-glob"), 1);
|
|
73
|
+
var import_picomatch = __toESM(require("picomatch"), 1);
|
|
56
74
|
|
|
57
75
|
// src/parser.ts
|
|
58
76
|
function stepQuote(text, i, quote) {
|
|
@@ -62,6 +80,11 @@ function stepQuote(text, i, quote) {
|
|
|
62
80
|
return { consumed: 1, closed: false };
|
|
63
81
|
}
|
|
64
82
|
function stripComments(text) {
|
|
83
|
+
return stripCommentsWithMap(text).text;
|
|
84
|
+
}
|
|
85
|
+
function stripCommentsWithMap(text) {
|
|
86
|
+
const removed = [];
|
|
87
|
+
const comments = [];
|
|
65
88
|
let result = "";
|
|
66
89
|
let quote = null;
|
|
67
90
|
let urlDepth = 0;
|
|
@@ -96,17 +119,20 @@ function stripComments(text) {
|
|
|
96
119
|
result += char;
|
|
97
120
|
continue;
|
|
98
121
|
}
|
|
122
|
+
comments.push([i, end + 2]);
|
|
123
|
+
removed.push({ at: result.length, length: end + 2 - i });
|
|
99
124
|
i = end + 1;
|
|
100
125
|
continue;
|
|
101
126
|
}
|
|
102
127
|
if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
|
|
103
128
|
const nl = text.indexOf("\n", i);
|
|
129
|
+
removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
|
|
104
130
|
i = nl === -1 ? text.length - 1 : nl - 1;
|
|
105
131
|
continue;
|
|
106
132
|
}
|
|
107
133
|
result += char;
|
|
108
134
|
}
|
|
109
|
-
return result;
|
|
135
|
+
return { text: result, removed, comments };
|
|
110
136
|
}
|
|
111
137
|
function extractBlock(text, start) {
|
|
112
138
|
let depth = 1;
|
|
@@ -170,12 +196,12 @@ function extractValue(text, start) {
|
|
|
170
196
|
}
|
|
171
197
|
return text.slice(start, i).trim();
|
|
172
198
|
}
|
|
173
|
-
function forEachProperty(block, onProperty) {
|
|
199
|
+
function forEachProperty(block, onProperty, offset = 0) {
|
|
174
200
|
const masked = maskQuotedContent(block);
|
|
175
201
|
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
176
202
|
const name = prop[0];
|
|
177
203
|
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
178
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
204
|
+
onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
|
|
179
205
|
}
|
|
180
206
|
}
|
|
181
207
|
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
@@ -196,7 +222,7 @@ var BASE_SELECTORS = [":root", "@theme"];
|
|
|
196
222
|
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
197
223
|
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
198
224
|
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
199
|
-
forEachProperty(block, onProperty);
|
|
225
|
+
forEachProperty(block, onProperty, bodyStart);
|
|
200
226
|
});
|
|
201
227
|
}
|
|
202
228
|
function parseVarNames(css, selectors) {
|
|
@@ -226,30 +252,73 @@ function forEachMediaBlock(stripped, media, onBlock) {
|
|
|
226
252
|
}
|
|
227
253
|
}
|
|
228
254
|
}
|
|
255
|
+
function parseDocComment(body) {
|
|
256
|
+
const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
|
|
257
|
+
const doc = {};
|
|
258
|
+
const description = [];
|
|
259
|
+
let inTags = false;
|
|
260
|
+
for (const line of lines) {
|
|
261
|
+
const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
|
|
262
|
+
if (tag) {
|
|
263
|
+
inTags = true;
|
|
264
|
+
if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
|
|
265
|
+
} else if (!inTags) {
|
|
266
|
+
description.push(line);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const text = description.join("\n").trim();
|
|
270
|
+
if (text) doc.description = text;
|
|
271
|
+
return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
|
|
272
|
+
}
|
|
273
|
+
function makeDocReader(css, stripped) {
|
|
274
|
+
const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
|
|
275
|
+
return (strippedPos) => {
|
|
276
|
+
let end = toRawPosition(stripped, strippedPos);
|
|
277
|
+
while (end > 0 && /\s/.test(css[end - 1])) end--;
|
|
278
|
+
const start = commentStartByEnd.get(end);
|
|
279
|
+
if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
|
|
280
|
+
return parseDocComment(css.slice(start + 3, end - 2));
|
|
281
|
+
};
|
|
282
|
+
}
|
|
229
283
|
function parseThemedDeclarations(css, selectors, themes) {
|
|
230
|
-
const
|
|
284
|
+
const strippedCss = stripCommentsWithMap(css);
|
|
285
|
+
const stripped = strippedCss.text;
|
|
286
|
+
const docAt = makeDocReader(css, strippedCss);
|
|
287
|
+
const themeDocs = /* @__PURE__ */ new Map();
|
|
231
288
|
const themeValues = /* @__PURE__ */ new Map();
|
|
232
289
|
const skip = [];
|
|
233
290
|
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
234
291
|
const values = /* @__PURE__ */ new Map();
|
|
235
292
|
themeValues.set(themeName, values);
|
|
236
|
-
const collect = (block) => forEachProperty(block, (name, value) =>
|
|
293
|
+
const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
|
|
294
|
+
values.set(name, value);
|
|
295
|
+
const doc = docAt(position);
|
|
296
|
+
if (doc) themeDocs.set(name, doc);
|
|
297
|
+
}, offset);
|
|
237
298
|
const selector = themeSelector.trim();
|
|
238
299
|
if (/^@media\b/i.test(selector)) {
|
|
239
300
|
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
240
301
|
skip.push(range);
|
|
241
|
-
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
302
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
|
|
242
303
|
});
|
|
243
304
|
} else {
|
|
244
305
|
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
245
306
|
skip.push(range);
|
|
246
|
-
collect(block);
|
|
307
|
+
collect(block, range[0]);
|
|
247
308
|
});
|
|
248
309
|
}
|
|
249
310
|
}
|
|
250
311
|
const declarations = /* @__PURE__ */ new Map();
|
|
251
|
-
|
|
252
|
-
|
|
312
|
+
const docs = /* @__PURE__ */ new Map();
|
|
313
|
+
scanDeclarations(css, selectors, (name, value, position) => {
|
|
314
|
+
declarations.set(name, value);
|
|
315
|
+
const doc = docAt(position);
|
|
316
|
+
if (doc) docs.set(name, doc);
|
|
317
|
+
}, skip, stripped);
|
|
318
|
+
for (const [name, doc] of themeDocs) {
|
|
319
|
+
if (!docs.has(name)) docs.set(name, doc);
|
|
320
|
+
}
|
|
321
|
+
return { declarations, themes: themeValues, docs };
|
|
253
322
|
}
|
|
254
323
|
var PROPERTY_DESCRIPTORS = [
|
|
255
324
|
["syntax", "syntax"],
|
|
@@ -280,6 +349,35 @@ function parsePropertyRules(css) {
|
|
|
280
349
|
}
|
|
281
350
|
return rules;
|
|
282
351
|
}
|
|
352
|
+
function toRawPosition(stripped, strippedPos) {
|
|
353
|
+
let rawPos = strippedPos;
|
|
354
|
+
for (const { at, length } of stripped.removed) {
|
|
355
|
+
if (at > strippedPos) break;
|
|
356
|
+
rawPos += length;
|
|
357
|
+
}
|
|
358
|
+
return rawPos;
|
|
359
|
+
}
|
|
360
|
+
function parseVarReferences(css) {
|
|
361
|
+
const stripped = stripCommentsWithMap(css);
|
|
362
|
+
const masked = maskQuotedContent(stripped.text);
|
|
363
|
+
const lineStarts = [0];
|
|
364
|
+
for (let i = 0; i < css.length; i++) if (css[i] === "\n") lineStarts.push(i + 1);
|
|
365
|
+
const refs = [];
|
|
366
|
+
for (const match of masked.matchAll(/\bvar\(\s*(--[\w-]+)\s*(,)?/gi)) {
|
|
367
|
+
const rawPos = toRawPosition(stripped, match.index);
|
|
368
|
+
let line = lineStarts.length - 1;
|
|
369
|
+
while (lineStarts[line] > rawPos) line--;
|
|
370
|
+
refs.push({ name: match[1], hasFallback: match[2] === ",", line: line + 1, column: rawPos - lineStarts[line] + 1 });
|
|
371
|
+
}
|
|
372
|
+
return refs;
|
|
373
|
+
}
|
|
374
|
+
function parseDeclaredNames(css) {
|
|
375
|
+
const masked = maskQuotedContent(stripComments(css));
|
|
376
|
+
const names = /* @__PURE__ */ new Set();
|
|
377
|
+
for (const match of masked.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) names.add(match[1]);
|
|
378
|
+
for (const match of masked.matchAll(/@property\s+(--[\w-]+)/g)) names.add(match[1]);
|
|
379
|
+
return names;
|
|
380
|
+
}
|
|
283
381
|
|
|
284
382
|
// src/scanner.ts
|
|
285
383
|
function normalizePatterns(patterns) {
|
|
@@ -300,7 +398,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
300
398
|
files.map(async (file) => {
|
|
301
399
|
let css;
|
|
302
400
|
try {
|
|
303
|
-
css = await (0,
|
|
401
|
+
css = await (0, import_promises2.readFile)(file, "utf8");
|
|
304
402
|
} catch (err) {
|
|
305
403
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
306
404
|
return null;
|
|
@@ -311,15 +409,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
311
409
|
const declarations = /* @__PURE__ */ new Map();
|
|
312
410
|
const properties = /* @__PURE__ */ new Map();
|
|
313
411
|
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
412
|
+
const docs = /* @__PURE__ */ new Map();
|
|
314
413
|
for (const result of perFile) {
|
|
315
414
|
if (!result) continue;
|
|
316
415
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
317
416
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
417
|
+
for (const [name, doc] of result.docs) docs.set(name, doc);
|
|
318
418
|
for (const [theme, values] of result.themes) {
|
|
319
419
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
320
420
|
}
|
|
321
421
|
}
|
|
322
|
-
return { declarations, properties, themes: themeValues };
|
|
422
|
+
return { declarations, properties, themes: themeValues, docs };
|
|
323
423
|
}
|
|
324
424
|
async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
325
425
|
return (await scanCss(patterns, exclude, selectors)).declarations;
|
|
@@ -353,7 +453,7 @@ async function scanUsage(patterns, exclude) {
|
|
|
353
453
|
const texts = await Promise.all(
|
|
354
454
|
files.map(async (file) => {
|
|
355
455
|
try {
|
|
356
|
-
return await (0,
|
|
456
|
+
return await (0, import_promises2.readFile)(file, "utf8");
|
|
357
457
|
} catch (err) {
|
|
358
458
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
359
459
|
return "";
|
|
@@ -363,6 +463,29 @@ async function scanUsage(patterns, exclude) {
|
|
|
363
463
|
for (const text of texts) extractUsage(text, usage);
|
|
364
464
|
return usage;
|
|
365
465
|
}
|
|
466
|
+
async function scanReferences(patterns, exclude) {
|
|
467
|
+
const normalized = normalizePatterns(patterns);
|
|
468
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
469
|
+
const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
|
|
470
|
+
const perFile = await Promise.all(
|
|
471
|
+
files.map(async (file) => {
|
|
472
|
+
try {
|
|
473
|
+
return { file, css: await (0, import_promises2.readFile)(file, "utf8") };
|
|
474
|
+
} catch (err) {
|
|
475
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
476
|
+
return null;
|
|
477
|
+
}
|
|
478
|
+
})
|
|
479
|
+
);
|
|
480
|
+
const references = [];
|
|
481
|
+
const declared = /* @__PURE__ */ new Set();
|
|
482
|
+
for (const result of perFile) {
|
|
483
|
+
if (!result) continue;
|
|
484
|
+
for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
|
|
485
|
+
for (const name of parseDeclaredNames(result.css)) declared.add(name);
|
|
486
|
+
}
|
|
487
|
+
return { references, declared };
|
|
488
|
+
}
|
|
366
489
|
async function scanUsedKeys(patterns, exclude) {
|
|
367
490
|
return (await scanUsage(patterns, exclude)).keys;
|
|
368
491
|
}
|
|
@@ -461,7 +584,8 @@ function entryMeta(name, options) {
|
|
|
461
584
|
name,
|
|
462
585
|
value: options.declarations?.get(name),
|
|
463
586
|
syntax: options.properties?.get(name)?.syntax,
|
|
464
|
-
...themes.length > 0 ? { themes } : {}
|
|
587
|
+
...themes.length > 0 ? { themes } : {},
|
|
588
|
+
...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
|
|
465
589
|
};
|
|
466
590
|
}
|
|
467
591
|
function buildEntries(varNames, options) {
|
|
@@ -501,8 +625,12 @@ function buildGroupedEntries(varNames, options) {
|
|
|
501
625
|
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
502
626
|
return { groups, ungrouped };
|
|
503
627
|
}
|
|
504
|
-
|
|
505
|
-
|
|
628
|
+
var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
|
|
629
|
+
function renderJsDoc(tags, indent) {
|
|
630
|
+
if (tags.length === 0) return [];
|
|
631
|
+
if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
|
|
632
|
+
const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
|
|
633
|
+
return [`${indent}/**`, ...body, `${indent} */`];
|
|
506
634
|
}
|
|
507
635
|
function unquoteCssString(value) {
|
|
508
636
|
const quote = value[0];
|
|
@@ -511,11 +639,15 @@ function unquoteCssString(value) {
|
|
|
511
639
|
}
|
|
512
640
|
return value;
|
|
513
641
|
}
|
|
514
|
-
function
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
642
|
+
function entryTags({ value, syntax, themes, doc }) {
|
|
643
|
+
const deprecated = doc?.deprecated;
|
|
644
|
+
return [
|
|
645
|
+
...doc?.description ? [doc.description] : [],
|
|
646
|
+
...value ? [`@default ${value}`] : [],
|
|
647
|
+
...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
|
|
648
|
+
...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
|
|
649
|
+
...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
|
|
650
|
+
];
|
|
519
651
|
}
|
|
520
652
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
521
653
|
function parseEnumSyntax(syntax) {
|
|
@@ -547,11 +679,9 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
547
679
|
return blocks;
|
|
548
680
|
}
|
|
549
681
|
function renderEntryLines(entries, indent, lineFor) {
|
|
550
|
-
return entries.flatMap((
|
|
551
|
-
...
|
|
552
|
-
|
|
553
|
-
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
554
|
-
`${indent}${lineFor(key, name)}`
|
|
682
|
+
return entries.flatMap((entry) => [
|
|
683
|
+
...renderJsDoc(entryTags(entry), indent),
|
|
684
|
+
`${indent}${lineFor(entry.key, entry.name)}`
|
|
555
685
|
]);
|
|
556
686
|
}
|
|
557
687
|
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
@@ -598,6 +728,12 @@ var HELPERS_TS = [
|
|
|
598
728
|
"",
|
|
599
729
|
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
600
730
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
731
|
+
"}",
|
|
732
|
+
"",
|
|
733
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
734
|
+
"",
|
|
735
|
+
"export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
|
|
736
|
+
" return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
|
|
601
737
|
"}"
|
|
602
738
|
];
|
|
603
739
|
var HELPERS_JS = [
|
|
@@ -607,11 +743,17 @@ var HELPERS_JS = [
|
|
|
607
743
|
"",
|
|
608
744
|
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
609
745
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
746
|
+
"}",
|
|
747
|
+
"",
|
|
748
|
+
"export function withFallback(ref, fallback) {",
|
|
749
|
+
" return `${ref.slice(0, -1)}, ${fallback})`;",
|
|
610
750
|
"}"
|
|
611
751
|
];
|
|
612
752
|
var HELPERS_DTS = [
|
|
613
753
|
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
614
|
-
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
754
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
|
|
755
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
756
|
+
"export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
|
|
615
757
|
];
|
|
616
758
|
function generateCode(varNames, ...args) {
|
|
617
759
|
const options = normalizeOptions(args);
|
|
@@ -671,17 +813,19 @@ function generateTokens(varNames, options = {}) {
|
|
|
671
813
|
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
672
814
|
});
|
|
673
815
|
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
674
|
-
const
|
|
816
|
+
const resolve3 = (value) => {
|
|
675
817
|
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
676
818
|
return target ? `{${target.join(".")}}` : value;
|
|
677
819
|
};
|
|
678
820
|
const root = {};
|
|
679
821
|
for (const { meta, value, path } of tokens) {
|
|
680
|
-
const token = { $value:
|
|
822
|
+
const token = { $value: resolve3(value) };
|
|
681
823
|
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
682
824
|
if (type) token.$type = type;
|
|
825
|
+
if (meta.doc?.description) token.$description = meta.doc.description;
|
|
826
|
+
if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
|
|
683
827
|
if (meta.themes) {
|
|
684
|
-
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme,
|
|
828
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
|
|
685
829
|
token.$extensions = { "css-typed-vars": { themes } };
|
|
686
830
|
}
|
|
687
831
|
const [key, leaf] = path;
|
|
@@ -716,6 +860,9 @@ function partitionUnused(names, usage, options) {
|
|
|
716
860
|
}
|
|
717
861
|
|
|
718
862
|
// src/index.ts
|
|
863
|
+
function defineConfig(config) {
|
|
864
|
+
return config;
|
|
865
|
+
}
|
|
719
866
|
async function findUnusedVars(options) {
|
|
720
867
|
if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
|
|
721
868
|
const [scanned, usage] = await Promise.all([
|
|
@@ -725,6 +872,14 @@ async function findUnusedVars(options) {
|
|
|
725
872
|
const names = collectVarNames(scanned);
|
|
726
873
|
return partitionUnused(names, usage, options).unused;
|
|
727
874
|
}
|
|
875
|
+
function matchesIgnore(name, patterns) {
|
|
876
|
+
return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
877
|
+
}
|
|
878
|
+
async function findUndefinedRefs(options) {
|
|
879
|
+
const { references, declared } = await scanReferences(options.input, options.exclude);
|
|
880
|
+
const ignore = options.refsIgnore ?? [];
|
|
881
|
+
return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
|
|
882
|
+
}
|
|
728
883
|
async function computeOutputs(options) {
|
|
729
884
|
assertPruneCompatible(options);
|
|
730
885
|
const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
@@ -742,7 +897,7 @@ async function computeOutputs(options) {
|
|
|
742
897
|
}
|
|
743
898
|
names = used;
|
|
744
899
|
}
|
|
745
|
-
const outPath = (0,
|
|
900
|
+
const outPath = (0, import_node_path3.resolve)(options.output);
|
|
746
901
|
const generatorOptions = {
|
|
747
902
|
prefix: options.prefix,
|
|
748
903
|
naming: options.naming,
|
|
@@ -750,7 +905,8 @@ async function computeOutputs(options) {
|
|
|
750
905
|
group: options.group,
|
|
751
906
|
properties,
|
|
752
907
|
helpers: options.helpers,
|
|
753
|
-
themes: scanned.themes
|
|
908
|
+
themes: scanned.themes,
|
|
909
|
+
docs: scanned.docs
|
|
754
910
|
};
|
|
755
911
|
if (/\.json$/i.test(options.output)) {
|
|
756
912
|
return { outPath, content: generateTokens(names, generatorOptions) };
|
|
@@ -766,18 +922,18 @@ async function computeOutputs(options) {
|
|
|
766
922
|
}
|
|
767
923
|
async function generate(options) {
|
|
768
924
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
769
|
-
|
|
770
|
-
await (0, import_promises2.writeFile)(outPath, content, "utf8");
|
|
925
|
+
let written = await writeOutput(outPath, content);
|
|
771
926
|
if (dtsPath && dtsContent !== void 0) {
|
|
772
|
-
|
|
927
|
+
if (await writeOutput(dtsPath, dtsContent)) written = true;
|
|
773
928
|
}
|
|
929
|
+
return written;
|
|
774
930
|
}
|
|
775
931
|
async function checkGenerated(options) {
|
|
776
932
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
777
|
-
const current = await (0,
|
|
933
|
+
const current = await (0, import_promises3.readFile)(outPath, "utf8").catch(() => null);
|
|
778
934
|
if (current !== content) return false;
|
|
779
935
|
if (dtsPath && dtsContent !== void 0) {
|
|
780
|
-
const currentDts = await (0,
|
|
936
|
+
const currentDts = await (0, import_promises3.readFile)(dtsPath, "utf8").catch(() => null);
|
|
781
937
|
if (currentDts !== dtsContent) return false;
|
|
782
938
|
}
|
|
783
939
|
return true;
|
|
@@ -785,17 +941,22 @@ async function checkGenerated(options) {
|
|
|
785
941
|
// Annotate the CommonJS export names for ESM import in node:
|
|
786
942
|
0 && (module.exports = {
|
|
787
943
|
checkGenerated,
|
|
944
|
+
defineConfig,
|
|
945
|
+
findUndefinedRefs,
|
|
788
946
|
findUnusedVars,
|
|
789
947
|
generate,
|
|
790
948
|
generateCode,
|
|
791
949
|
generateDeclaration,
|
|
792
950
|
generateJs,
|
|
793
951
|
generateTokens,
|
|
952
|
+
parseDeclaredNames,
|
|
794
953
|
parsePropertyRules,
|
|
795
954
|
parseThemedDeclarations,
|
|
796
955
|
parseVarDeclarations,
|
|
797
956
|
parseVarNames,
|
|
957
|
+
parseVarReferences,
|
|
798
958
|
scanCss,
|
|
959
|
+
scanReferences,
|
|
799
960
|
scanUsedKeys,
|
|
800
961
|
scanVarDeclarations,
|
|
801
962
|
scanVarNames
|
package/dist/index.d.cts
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
|
-
import { P as PropertyRule, N as NamingConvention } from './generator-
|
|
2
|
-
export { G as GeneratorOptions, T as ThemedDeclarations, g as generateCode,
|
|
1
|
+
import { V as VarReference, P as PropertyRule, a as VarDoc, N as NamingConvention } from './generator-DJ9uOYBP.cjs';
|
|
2
|
+
export { G as GeneratorOptions, T as ThemedDeclarations, g as generateCode, b as generateDeclaration, c as generateJs, d as generateTokens, p as parseDeclaredNames, e as parsePropertyRules, f as parseThemedDeclarations, h as parseVarDeclarations, i as parseVarNames, j as parseVarReferences } from './generator-DJ9uOYBP.cjs';
|
|
3
3
|
|
|
4
4
|
interface ScannedCss {
|
|
5
5
|
declarations: Map<string, string>;
|
|
6
6
|
properties: Map<string, PropertyRule>;
|
|
7
7
|
/** Per theme name (from the `themes` option), the values declared for it. Empty without `themes`. */
|
|
8
8
|
themes: Map<string, Map<string, string>>;
|
|
9
|
+
/** `/** ... *\/` doc comments placed directly before a declaration. */
|
|
10
|
+
docs: Map<string, VarDoc>;
|
|
9
11
|
}
|
|
10
12
|
declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[], themes?: Record<string, string>): Promise<ScannedCss>;
|
|
11
13
|
declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
|
|
12
14
|
declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
|
|
15
|
+
interface FileReference extends VarReference {
|
|
16
|
+
file: string;
|
|
17
|
+
}
|
|
18
|
+
declare function scanReferences(patterns: string | string[], exclude?: string | string[]): Promise<{
|
|
19
|
+
references: FileReference[];
|
|
20
|
+
declared: Set<string>;
|
|
21
|
+
}>;
|
|
13
22
|
declare function scanUsedKeys(patterns: string | string[], exclude?: string | string[]): Promise<Set<string>>;
|
|
14
23
|
|
|
15
24
|
interface GenerateOptions {
|
|
@@ -34,9 +43,20 @@ interface GenerateOptions {
|
|
|
34
43
|
usageExclude?: string | string[];
|
|
35
44
|
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
36
45
|
helpers?: boolean;
|
|
46
|
+
/** Names (or `--prefix-*` patterns) that `findUndefinedRefs` shouldn't report, e.g. vars set from JS. */
|
|
47
|
+
refsIgnore?: string[];
|
|
37
48
|
}
|
|
49
|
+
/** A CLI config file's options — like `GenerateOptions`, but anything may come from CLI flags instead. */
|
|
50
|
+
type Config = Partial<GenerateOptions>;
|
|
51
|
+
/**
|
|
52
|
+
* Types a config file's export (one target, or an array of targets):
|
|
53
|
+
* `export default defineConfig({ input: 'src/styles/*.css', output: 'src/cssVars.ts' })`.
|
|
54
|
+
*/
|
|
55
|
+
declare function defineConfig(config: Config): Config;
|
|
56
|
+
declare function defineConfig(config: Config[]): Config[];
|
|
38
57
|
declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
|
|
39
|
-
declare function
|
|
58
|
+
declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore'>): Promise<FileReference[]>;
|
|
59
|
+
declare function generate(options: GenerateOptions): Promise<boolean>;
|
|
40
60
|
declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
|
|
41
61
|
|
|
42
|
-
export { type GenerateOptions, NamingConvention, PropertyRule, checkGenerated, findUnusedVars, generate, scanCss, scanUsedKeys, scanVarDeclarations, scanVarNames };
|
|
62
|
+
export { type Config, type FileReference, type GenerateOptions, NamingConvention, PropertyRule, VarDoc, VarReference, checkGenerated, defineConfig, findUndefinedRefs, findUnusedVars, generate, scanCss, scanReferences, scanUsedKeys, scanVarDeclarations, scanVarNames };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
|
-
import { P as PropertyRule, N as NamingConvention } from './generator-
|
|
2
|
-
export { G as GeneratorOptions, T as ThemedDeclarations, g as generateCode,
|
|
1
|
+
import { V as VarReference, P as PropertyRule, a as VarDoc, N as NamingConvention } from './generator-DJ9uOYBP.js';
|
|
2
|
+
export { G as GeneratorOptions, T as ThemedDeclarations, g as generateCode, b as generateDeclaration, c as generateJs, d as generateTokens, p as parseDeclaredNames, e as parsePropertyRules, f as parseThemedDeclarations, h as parseVarDeclarations, i as parseVarNames, j as parseVarReferences } from './generator-DJ9uOYBP.js';
|
|
3
3
|
|
|
4
4
|
interface ScannedCss {
|
|
5
5
|
declarations: Map<string, string>;
|
|
6
6
|
properties: Map<string, PropertyRule>;
|
|
7
7
|
/** Per theme name (from the `themes` option), the values declared for it. Empty without `themes`. */
|
|
8
8
|
themes: Map<string, Map<string, string>>;
|
|
9
|
+
/** `/** ... *\/` doc comments placed directly before a declaration. */
|
|
10
|
+
docs: Map<string, VarDoc>;
|
|
9
11
|
}
|
|
10
12
|
declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[], themes?: Record<string, string>): Promise<ScannedCss>;
|
|
11
13
|
declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
|
|
12
14
|
declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
|
|
15
|
+
interface FileReference extends VarReference {
|
|
16
|
+
file: string;
|
|
17
|
+
}
|
|
18
|
+
declare function scanReferences(patterns: string | string[], exclude?: string | string[]): Promise<{
|
|
19
|
+
references: FileReference[];
|
|
20
|
+
declared: Set<string>;
|
|
21
|
+
}>;
|
|
13
22
|
declare function scanUsedKeys(patterns: string | string[], exclude?: string | string[]): Promise<Set<string>>;
|
|
14
23
|
|
|
15
24
|
interface GenerateOptions {
|
|
@@ -34,9 +43,20 @@ interface GenerateOptions {
|
|
|
34
43
|
usageExclude?: string | string[];
|
|
35
44
|
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
36
45
|
helpers?: boolean;
|
|
46
|
+
/** Names (or `--prefix-*` patterns) that `findUndefinedRefs` shouldn't report, e.g. vars set from JS. */
|
|
47
|
+
refsIgnore?: string[];
|
|
37
48
|
}
|
|
49
|
+
/** A CLI config file's options — like `GenerateOptions`, but anything may come from CLI flags instead. */
|
|
50
|
+
type Config = Partial<GenerateOptions>;
|
|
51
|
+
/**
|
|
52
|
+
* Types a config file's export (one target, or an array of targets):
|
|
53
|
+
* `export default defineConfig({ input: 'src/styles/*.css', output: 'src/cssVars.ts' })`.
|
|
54
|
+
*/
|
|
55
|
+
declare function defineConfig(config: Config): Config;
|
|
56
|
+
declare function defineConfig(config: Config[]): Config[];
|
|
38
57
|
declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
|
|
39
|
-
declare function
|
|
58
|
+
declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore'>): Promise<FileReference[]>;
|
|
59
|
+
declare function generate(options: GenerateOptions): Promise<boolean>;
|
|
40
60
|
declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
|
|
41
61
|
|
|
42
|
-
export { type GenerateOptions, NamingConvention, PropertyRule, checkGenerated, findUnusedVars, generate, scanCss, scanUsedKeys, scanVarDeclarations, scanVarNames };
|
|
62
|
+
export { type Config, type FileReference, type GenerateOptions, NamingConvention, PropertyRule, VarDoc, VarReference, checkGenerated, defineConfig, findUndefinedRefs, findUnusedVars, generate, scanCss, scanReferences, scanUsedKeys, scanVarDeclarations, scanVarNames };
|
package/dist/index.js
CHANGED
|
@@ -1,35 +1,45 @@
|
|
|
1
1
|
import {
|
|
2
2
|
checkGenerated,
|
|
3
|
+
defineConfig,
|
|
4
|
+
findUndefinedRefs,
|
|
3
5
|
findUnusedVars,
|
|
4
6
|
generate
|
|
5
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-TB5PSGEF.js";
|
|
6
8
|
import {
|
|
7
9
|
generateCode,
|
|
8
10
|
generateDeclaration,
|
|
9
11
|
generateJs,
|
|
10
12
|
generateTokens,
|
|
13
|
+
parseDeclaredNames,
|
|
11
14
|
parsePropertyRules,
|
|
12
15
|
parseThemedDeclarations,
|
|
13
16
|
parseVarDeclarations,
|
|
14
17
|
parseVarNames,
|
|
18
|
+
parseVarReferences,
|
|
15
19
|
scanCss,
|
|
20
|
+
scanReferences,
|
|
16
21
|
scanUsedKeys,
|
|
17
22
|
scanVarDeclarations,
|
|
18
23
|
scanVarNames
|
|
19
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-DHBPPGOE.js";
|
|
20
25
|
export {
|
|
21
26
|
checkGenerated,
|
|
27
|
+
defineConfig,
|
|
28
|
+
findUndefinedRefs,
|
|
22
29
|
findUnusedVars,
|
|
23
30
|
generate,
|
|
24
31
|
generateCode,
|
|
25
32
|
generateDeclaration,
|
|
26
33
|
generateJs,
|
|
27
34
|
generateTokens,
|
|
35
|
+
parseDeclaredNames,
|
|
28
36
|
parsePropertyRules,
|
|
29
37
|
parseThemedDeclarations,
|
|
30
38
|
parseVarDeclarations,
|
|
31
39
|
parseVarNames,
|
|
40
|
+
parseVarReferences,
|
|
32
41
|
scanCss,
|
|
42
|
+
scanReferences,
|
|
33
43
|
scanUsedKeys,
|
|
34
44
|
scanVarDeclarations,
|
|
35
45
|
scanVarNames
|