css-typed-vars 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -11
- package/dist/{chunk-HBUSLYYB.js → chunk-32V3V6WT.js} +4 -3
- package/dist/{chunk-6YWE4A6S.js → chunk-5HPTHW7S.js} +154 -25
- package/dist/{chunk-PLO2JWR7.js → chunk-YDXCJQPL.js} +13 -2
- package/dist/cli.cjs +294 -97
- package/dist/cli.js +138 -75
- package/dist/esbuild.cjs +104 -27
- 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 +169 -26
- package/dist/index.d.cts +15 -3
- package/dist/index.d.ts +15 -3
- package/dist/index.js +10 -2
- package/dist/rollup.cjs +104 -27
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +104 -27
- package/dist/unplugin.d.cts +1 -1
- package/dist/unplugin.d.ts +1 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +104 -27
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +104 -27
- package/dist/webpack.d.cts +1 -1
- package/dist/webpack.d.ts +1 -1
- package/dist/webpack.js +2 -2
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -49,6 +49,11 @@ function stepQuote(text, i, quote) {
|
|
|
49
49
|
return { consumed: 1, closed: false };
|
|
50
50
|
}
|
|
51
51
|
function stripComments(text) {
|
|
52
|
+
return stripCommentsWithMap(text).text;
|
|
53
|
+
}
|
|
54
|
+
function stripCommentsWithMap(text) {
|
|
55
|
+
const removed = [];
|
|
56
|
+
const comments = [];
|
|
52
57
|
let result = "";
|
|
53
58
|
let quote = null;
|
|
54
59
|
let urlDepth = 0;
|
|
@@ -83,17 +88,20 @@ function stripComments(text) {
|
|
|
83
88
|
result += char;
|
|
84
89
|
continue;
|
|
85
90
|
}
|
|
91
|
+
comments.push([i, end + 2]);
|
|
92
|
+
removed.push({ at: result.length, length: end + 2 - i });
|
|
86
93
|
i = end + 1;
|
|
87
94
|
continue;
|
|
88
95
|
}
|
|
89
96
|
if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
|
|
90
97
|
const nl = text.indexOf("\n", i);
|
|
98
|
+
removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
|
|
91
99
|
i = nl === -1 ? text.length - 1 : nl - 1;
|
|
92
100
|
continue;
|
|
93
101
|
}
|
|
94
102
|
result += char;
|
|
95
103
|
}
|
|
96
|
-
return result;
|
|
104
|
+
return { text: result, removed, comments };
|
|
97
105
|
}
|
|
98
106
|
function extractBlock(text, start) {
|
|
99
107
|
let depth = 1;
|
|
@@ -157,12 +165,12 @@ function extractValue(text, start) {
|
|
|
157
165
|
}
|
|
158
166
|
return text.slice(start, i).trim();
|
|
159
167
|
}
|
|
160
|
-
function forEachProperty(block, onProperty) {
|
|
168
|
+
function forEachProperty(block, onProperty, offset = 0) {
|
|
161
169
|
const masked = maskQuotedContent(block);
|
|
162
170
|
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
163
171
|
const name = prop[0];
|
|
164
172
|
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
165
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
173
|
+
onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
|
|
166
174
|
}
|
|
167
175
|
}
|
|
168
176
|
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
@@ -183,7 +191,7 @@ var BASE_SELECTORS = [":root", "@theme"];
|
|
|
183
191
|
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
184
192
|
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
185
193
|
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
186
|
-
forEachProperty(block, onProperty);
|
|
194
|
+
forEachProperty(block, onProperty, bodyStart);
|
|
187
195
|
});
|
|
188
196
|
}
|
|
189
197
|
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
@@ -203,30 +211,73 @@ function forEachMediaBlock(stripped, media, onBlock) {
|
|
|
203
211
|
}
|
|
204
212
|
}
|
|
205
213
|
}
|
|
214
|
+
function parseDocComment(body) {
|
|
215
|
+
const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
|
|
216
|
+
const doc = {};
|
|
217
|
+
const description = [];
|
|
218
|
+
let inTags = false;
|
|
219
|
+
for (const line of lines) {
|
|
220
|
+
const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
|
|
221
|
+
if (tag) {
|
|
222
|
+
inTags = true;
|
|
223
|
+
if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
|
|
224
|
+
} else if (!inTags) {
|
|
225
|
+
description.push(line);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const text = description.join("\n").trim();
|
|
229
|
+
if (text) doc.description = text;
|
|
230
|
+
return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
|
|
231
|
+
}
|
|
232
|
+
function makeDocReader(css, stripped) {
|
|
233
|
+
const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
|
|
234
|
+
return (strippedPos) => {
|
|
235
|
+
let end = toRawPosition(stripped, strippedPos);
|
|
236
|
+
while (end > 0 && /\s/.test(css[end - 1])) end--;
|
|
237
|
+
const start = commentStartByEnd.get(end);
|
|
238
|
+
if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
|
|
239
|
+
return parseDocComment(css.slice(start + 3, end - 2));
|
|
240
|
+
};
|
|
241
|
+
}
|
|
206
242
|
function parseThemedDeclarations(css, selectors, themes) {
|
|
207
|
-
const
|
|
243
|
+
const strippedCss = stripCommentsWithMap(css);
|
|
244
|
+
const stripped = strippedCss.text;
|
|
245
|
+
const docAt = makeDocReader(css, strippedCss);
|
|
246
|
+
const themeDocs = /* @__PURE__ */ new Map();
|
|
208
247
|
const themeValues = /* @__PURE__ */ new Map();
|
|
209
248
|
const skip = [];
|
|
210
249
|
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
211
250
|
const values = /* @__PURE__ */ new Map();
|
|
212
251
|
themeValues.set(themeName, values);
|
|
213
|
-
const collect = (block) => forEachProperty(block, (name, value) =>
|
|
252
|
+
const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
|
|
253
|
+
values.set(name, value);
|
|
254
|
+
const doc = docAt(position);
|
|
255
|
+
if (doc) themeDocs.set(name, doc);
|
|
256
|
+
}, offset);
|
|
214
257
|
const selector = themeSelector.trim();
|
|
215
258
|
if (/^@media\b/i.test(selector)) {
|
|
216
259
|
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
217
260
|
skip.push(range);
|
|
218
|
-
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
261
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
|
|
219
262
|
});
|
|
220
263
|
} else {
|
|
221
264
|
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
222
265
|
skip.push(range);
|
|
223
|
-
collect(block);
|
|
266
|
+
collect(block, range[0]);
|
|
224
267
|
});
|
|
225
268
|
}
|
|
226
269
|
}
|
|
227
270
|
const declarations = /* @__PURE__ */ new Map();
|
|
228
|
-
|
|
229
|
-
|
|
271
|
+
const docs = /* @__PURE__ */ new Map();
|
|
272
|
+
scanDeclarations(css, selectors, (name, value, position) => {
|
|
273
|
+
declarations.set(name, value);
|
|
274
|
+
const doc = docAt(position);
|
|
275
|
+
if (doc) docs.set(name, doc);
|
|
276
|
+
}, skip, stripped);
|
|
277
|
+
for (const [name, doc] of themeDocs) {
|
|
278
|
+
if (!docs.has(name)) docs.set(name, doc);
|
|
279
|
+
}
|
|
280
|
+
return { declarations, themes: themeValues, docs };
|
|
230
281
|
}
|
|
231
282
|
var PROPERTY_DESCRIPTORS = [
|
|
232
283
|
["syntax", "syntax"],
|
|
@@ -257,6 +308,35 @@ function parsePropertyRules(css) {
|
|
|
257
308
|
}
|
|
258
309
|
return rules;
|
|
259
310
|
}
|
|
311
|
+
function toRawPosition(stripped, strippedPos) {
|
|
312
|
+
let rawPos = strippedPos;
|
|
313
|
+
for (const { at, length } of stripped.removed) {
|
|
314
|
+
if (at > strippedPos) break;
|
|
315
|
+
rawPos += length;
|
|
316
|
+
}
|
|
317
|
+
return rawPos;
|
|
318
|
+
}
|
|
319
|
+
function parseVarReferences(css) {
|
|
320
|
+
const stripped = stripCommentsWithMap(css);
|
|
321
|
+
const masked = maskQuotedContent(stripped.text);
|
|
322
|
+
const lineStarts = [0];
|
|
323
|
+
for (let i = 0; i < css.length; i++) if (css[i] === "\n") lineStarts.push(i + 1);
|
|
324
|
+
const refs = [];
|
|
325
|
+
for (const match of masked.matchAll(/\bvar\(\s*(--[\w-]+)\s*(,)?/gi)) {
|
|
326
|
+
const rawPos = toRawPosition(stripped, match.index);
|
|
327
|
+
let line = lineStarts.length - 1;
|
|
328
|
+
while (lineStarts[line] > rawPos) line--;
|
|
329
|
+
refs.push({ name: match[1], hasFallback: match[2] === ",", line: line + 1, column: rawPos - lineStarts[line] + 1 });
|
|
330
|
+
}
|
|
331
|
+
return refs;
|
|
332
|
+
}
|
|
333
|
+
function parseDeclaredNames(css) {
|
|
334
|
+
const masked = maskQuotedContent(stripComments(css));
|
|
335
|
+
const names = /* @__PURE__ */ new Set();
|
|
336
|
+
for (const match of masked.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) names.add(match[1]);
|
|
337
|
+
for (const match of masked.matchAll(/@property\s+(--[\w-]+)/g)) names.add(match[1]);
|
|
338
|
+
return names;
|
|
339
|
+
}
|
|
260
340
|
|
|
261
341
|
// src/scanner.ts
|
|
262
342
|
function normalizePatterns(patterns) {
|
|
@@ -288,15 +368,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
288
368
|
const declarations = /* @__PURE__ */ new Map();
|
|
289
369
|
const properties = /* @__PURE__ */ new Map();
|
|
290
370
|
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
371
|
+
const docs = /* @__PURE__ */ new Map();
|
|
291
372
|
for (const result of perFile) {
|
|
292
373
|
if (!result) continue;
|
|
293
374
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
294
375
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
376
|
+
for (const [name, doc] of result.docs) docs.set(name, doc);
|
|
295
377
|
for (const [theme, values] of result.themes) {
|
|
296
378
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
297
379
|
}
|
|
298
380
|
}
|
|
299
|
-
return { declarations, properties, themes: themeValues };
|
|
381
|
+
return { declarations, properties, themes: themeValues, docs };
|
|
300
382
|
}
|
|
301
383
|
var ROOT_RE = /\bcssVars\b/g;
|
|
302
384
|
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
@@ -333,6 +415,29 @@ async function scanUsage(patterns, exclude) {
|
|
|
333
415
|
for (const text of texts) extractUsage(text, usage);
|
|
334
416
|
return usage;
|
|
335
417
|
}
|
|
418
|
+
async function scanReferences(patterns, exclude) {
|
|
419
|
+
const normalized = normalizePatterns(patterns);
|
|
420
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
421
|
+
const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
|
|
422
|
+
const perFile = await Promise.all(
|
|
423
|
+
files.map(async (file) => {
|
|
424
|
+
try {
|
|
425
|
+
return { file, css: await (0, import_promises.readFile)(file, "utf8") };
|
|
426
|
+
} catch (err) {
|
|
427
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
})
|
|
431
|
+
);
|
|
432
|
+
const references = [];
|
|
433
|
+
const declared = /* @__PURE__ */ new Set();
|
|
434
|
+
for (const result of perFile) {
|
|
435
|
+
if (!result) continue;
|
|
436
|
+
for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
|
|
437
|
+
for (const name of parseDeclaredNames(result.css)) declared.add(name);
|
|
438
|
+
}
|
|
439
|
+
return { references, declared };
|
|
440
|
+
}
|
|
336
441
|
|
|
337
442
|
// src/generator.ts
|
|
338
443
|
var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
|
|
@@ -428,7 +533,8 @@ function entryMeta(name, options) {
|
|
|
428
533
|
name,
|
|
429
534
|
value: options.declarations?.get(name),
|
|
430
535
|
syntax: options.properties?.get(name)?.syntax,
|
|
431
|
-
...themes.length > 0 ? { themes } : {}
|
|
536
|
+
...themes.length > 0 ? { themes } : {},
|
|
537
|
+
...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
|
|
432
538
|
};
|
|
433
539
|
}
|
|
434
540
|
function buildEntries(varNames, options) {
|
|
@@ -468,8 +574,12 @@ function buildGroupedEntries(varNames, options) {
|
|
|
468
574
|
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
469
575
|
return { groups, ungrouped };
|
|
470
576
|
}
|
|
471
|
-
|
|
472
|
-
|
|
577
|
+
var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
|
|
578
|
+
function renderJsDoc(tags, indent) {
|
|
579
|
+
if (tags.length === 0) return [];
|
|
580
|
+
if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
|
|
581
|
+
const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
|
|
582
|
+
return [`${indent}/**`, ...body, `${indent} */`];
|
|
473
583
|
}
|
|
474
584
|
function unquoteCssString(value) {
|
|
475
585
|
const quote = value[0];
|
|
@@ -478,11 +588,15 @@ function unquoteCssString(value) {
|
|
|
478
588
|
}
|
|
479
589
|
return value;
|
|
480
590
|
}
|
|
481
|
-
function
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
591
|
+
function entryTags({ value, syntax, themes, doc }) {
|
|
592
|
+
const deprecated = doc?.deprecated;
|
|
593
|
+
return [
|
|
594
|
+
...doc?.description ? [doc.description] : [],
|
|
595
|
+
...value ? [`@default ${value}`] : [],
|
|
596
|
+
...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
|
|
597
|
+
...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
|
|
598
|
+
...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
|
|
599
|
+
];
|
|
486
600
|
}
|
|
487
601
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
488
602
|
function parseEnumSyntax(syntax) {
|
|
@@ -514,11 +628,9 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
514
628
|
return blocks;
|
|
515
629
|
}
|
|
516
630
|
function renderEntryLines(entries, indent, lineFor) {
|
|
517
|
-
return entries.flatMap((
|
|
518
|
-
...
|
|
519
|
-
|
|
520
|
-
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
521
|
-
`${indent}${lineFor(key, name)}`
|
|
631
|
+
return entries.flatMap((entry) => [
|
|
632
|
+
...renderJsDoc(entryTags(entry), indent),
|
|
633
|
+
`${indent}${lineFor(entry.key, entry.name)}`
|
|
522
634
|
]);
|
|
523
635
|
}
|
|
524
636
|
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
@@ -565,6 +677,12 @@ var HELPERS_TS = [
|
|
|
565
677
|
"",
|
|
566
678
|
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
567
679
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
680
|
+
"}",
|
|
681
|
+
"",
|
|
682
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
683
|
+
"",
|
|
684
|
+
"export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
|
|
685
|
+
" return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
|
|
568
686
|
"}"
|
|
569
687
|
];
|
|
570
688
|
var HELPERS_JS = [
|
|
@@ -574,11 +692,17 @@ var HELPERS_JS = [
|
|
|
574
692
|
"",
|
|
575
693
|
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
576
694
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
695
|
+
"}",
|
|
696
|
+
"",
|
|
697
|
+
"export function withFallback(ref, fallback) {",
|
|
698
|
+
" return `${ref.slice(0, -1)}, ${fallback})`;",
|
|
577
699
|
"}"
|
|
578
700
|
];
|
|
579
701
|
var HELPERS_DTS = [
|
|
580
702
|
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
581
|
-
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
703
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
|
|
704
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
705
|
+
"export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
|
|
582
706
|
];
|
|
583
707
|
function generateCode(varNames, ...args2) {
|
|
584
708
|
const options = normalizeOptions(args2);
|
|
@@ -647,6 +771,8 @@ function generateTokens(varNames, options = {}) {
|
|
|
647
771
|
const token = { $value: resolve3(value) };
|
|
648
772
|
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
649
773
|
if (type) token.$type = type;
|
|
774
|
+
if (meta.doc?.description) token.$description = meta.doc.description;
|
|
775
|
+
if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
|
|
650
776
|
if (meta.themes) {
|
|
651
777
|
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
|
|
652
778
|
token.$extensions = { "css-typed-vars": { themes } };
|
|
@@ -692,6 +818,14 @@ async function findUnusedVars(options) {
|
|
|
692
818
|
const names = collectVarNames(scanned);
|
|
693
819
|
return partitionUnused(names, usage, options).unused;
|
|
694
820
|
}
|
|
821
|
+
function matchesIgnore(name, patterns) {
|
|
822
|
+
return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
823
|
+
}
|
|
824
|
+
async function findUndefinedRefs(options) {
|
|
825
|
+
const { references, declared } = await scanReferences(options.input, options.exclude);
|
|
826
|
+
const ignore = options.refsIgnore ?? [];
|
|
827
|
+
return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
|
|
828
|
+
}
|
|
695
829
|
async function computeOutputs(options) {
|
|
696
830
|
assertPruneCompatible(options);
|
|
697
831
|
const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
@@ -717,7 +851,8 @@ async function computeOutputs(options) {
|
|
|
717
851
|
group: options.group,
|
|
718
852
|
properties,
|
|
719
853
|
helpers: options.helpers,
|
|
720
|
-
themes: scanned.themes
|
|
854
|
+
themes: scanned.themes,
|
|
855
|
+
docs: scanned.docs
|
|
721
856
|
};
|
|
722
857
|
if (/\.json$/i.test(options.output)) {
|
|
723
858
|
return { outPath, content: generateTokens(names, generatorOptions) };
|
|
@@ -768,10 +903,26 @@ var getArgs = (flag) => {
|
|
|
768
903
|
};
|
|
769
904
|
var watchMode = args.includes("--watch");
|
|
770
905
|
var checkMode = args.includes("--check");
|
|
771
|
-
var groupFlag = args.includes("--group");
|
|
772
|
-
var pruneFlag = args.includes("--prune");
|
|
773
906
|
var pruneCheckMode = args.includes("--prune-check");
|
|
774
|
-
var
|
|
907
|
+
var lintRefsMode = args.includes("--lint-refs");
|
|
908
|
+
var OPTION_FLAGS = [
|
|
909
|
+
"--input",
|
|
910
|
+
"--output",
|
|
911
|
+
"--exclude",
|
|
912
|
+
"--prefix",
|
|
913
|
+
"--naming",
|
|
914
|
+
"--selector",
|
|
915
|
+
"--theme",
|
|
916
|
+
"--group",
|
|
917
|
+
"--prune",
|
|
918
|
+
"--usage",
|
|
919
|
+
"--usage-exclude",
|
|
920
|
+
"--helpers",
|
|
921
|
+
"--refs-ignore"
|
|
922
|
+
];
|
|
923
|
+
var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>] [--lint-refs]";
|
|
924
|
+
var CliError = class extends Error {
|
|
925
|
+
};
|
|
775
926
|
async function loadConfig() {
|
|
776
927
|
const candidates = [
|
|
777
928
|
"css-typed-vars.config.js",
|
|
@@ -796,99 +947,145 @@ async function loadConfig() {
|
|
|
796
947
|
}
|
|
797
948
|
return {};
|
|
798
949
|
}
|
|
799
|
-
|
|
800
|
-
await generate(options);
|
|
801
|
-
console.log(`Generated \u2192 ${options.output}`);
|
|
802
|
-
}
|
|
803
|
-
async function main() {
|
|
804
|
-
if (args.includes("--version") || args.includes("-v")) {
|
|
805
|
-
const pkg = JSON.parse(await (0, import_promises3.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
|
|
806
|
-
console.log(pkg.version);
|
|
807
|
-
process.exit(0);
|
|
808
|
-
}
|
|
809
|
-
const config = await loadConfig();
|
|
950
|
+
function applyFlags(config) {
|
|
810
951
|
const inputArgs = getArgs("--input");
|
|
811
|
-
const input = inputArgs.length > 0 ? inputArgs : config.input;
|
|
812
|
-
const output = getArg("--output") ?? config.output;
|
|
813
952
|
const excludeArgs = getArgs("--exclude");
|
|
814
|
-
const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
|
|
815
|
-
const prefix = getArg("--prefix") ?? config.prefix;
|
|
816
|
-
const namingRaw = getArg("--naming") ?? config.naming;
|
|
817
|
-
if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
|
|
818
|
-
console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
819
|
-
process.exit(1);
|
|
820
|
-
}
|
|
821
|
-
const naming = namingRaw;
|
|
822
953
|
const selectorArgs = getArgs("--selector");
|
|
823
|
-
const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
|
|
824
954
|
const themeArgs = getArgs("--theme");
|
|
825
955
|
for (const arg of themeArgs) {
|
|
826
956
|
if (!/^[^=]+=.+$/.test(arg)) {
|
|
827
|
-
|
|
828
|
-
process.exit(1);
|
|
957
|
+
throw new CliError(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
|
|
829
958
|
}
|
|
830
959
|
}
|
|
831
|
-
const themes = themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes;
|
|
832
|
-
const group = groupFlag || config.group;
|
|
833
|
-
const prune = pruneFlag || config.prune;
|
|
834
960
|
const usageArgs = getArgs("--usage");
|
|
835
|
-
const usage = usageArgs.length > 0 ? usageArgs : config.usage;
|
|
836
961
|
const usageExcludeArgs = getArgs("--usage-exclude");
|
|
837
|
-
const
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
962
|
+
const refsIgnoreArgs = getArgs("--refs-ignore");
|
|
963
|
+
return {
|
|
964
|
+
...config,
|
|
965
|
+
input: inputArgs.length > 0 ? inputArgs : config.input,
|
|
966
|
+
output: getArg("--output") ?? config.output,
|
|
967
|
+
exclude: excludeArgs.length > 0 ? excludeArgs : config.exclude,
|
|
968
|
+
prefix: getArg("--prefix") ?? config.prefix,
|
|
969
|
+
naming: getArg("--naming") ?? config.naming,
|
|
970
|
+
selectors: selectorArgs.length > 0 ? selectorArgs : config.selectors,
|
|
971
|
+
themes: themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes,
|
|
972
|
+
group: args.includes("--group") || config.group,
|
|
973
|
+
prune: args.includes("--prune") || config.prune,
|
|
974
|
+
usage: usageArgs.length > 0 ? usageArgs : config.usage,
|
|
975
|
+
usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
|
|
976
|
+
helpers: args.includes("--helpers") || config.helpers,
|
|
977
|
+
refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
function loadTargets(config) {
|
|
981
|
+
if (!Array.isArray(config)) return [{ options: applyFlags(config), tag: "css-typed-vars" }];
|
|
982
|
+
if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
|
|
983
|
+
const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
|
|
984
|
+
if (used.length > 0) {
|
|
985
|
+
throw new CliError(`css-typed-vars: ${used.join(", ")} can't be used with an array config \u2014 set options per target in the config file instead.`);
|
|
843
986
|
}
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
987
|
+
return config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
|
|
988
|
+
}
|
|
989
|
+
function validateModes() {
|
|
990
|
+
if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
|
|
991
|
+
throw new CliError("css-typed-vars: --lint-refs cannot be combined with --watch, --check or --prune-check.");
|
|
847
992
|
}
|
|
993
|
+
if (checkMode && watchMode) throw new CliError("css-typed-vars: --check cannot be combined with --watch.");
|
|
848
994
|
if (pruneCheckMode && (watchMode || checkMode)) {
|
|
849
|
-
|
|
850
|
-
process.exit(1);
|
|
995
|
+
throw new CliError("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
|
|
851
996
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
997
|
+
}
|
|
998
|
+
function validateTarget({ options, tag }, single) {
|
|
999
|
+
const { input, output, naming, group, prefix, prune, usage } = options;
|
|
1000
|
+
if (naming !== void 0 && !VALID_NAMINGS.includes(naming)) {
|
|
1001
|
+
throw new CliError(`${tag}: invalid --naming value "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
1002
|
+
}
|
|
1003
|
+
if (lintRefsMode) {
|
|
1004
|
+
if (!input) throw new CliError(`${tag}: --lint-refs requires --input <glob> (or "input" in the config file).`);
|
|
1005
|
+
return;
|
|
855
1006
|
}
|
|
1007
|
+
if (!input || !output) {
|
|
1008
|
+
throw new CliError(single ? `${USAGE}
|
|
1009
|
+
Or add a css-typed-vars.config.js file with input and output fields.` : `${tag}: every target needs "input" and "output".`);
|
|
1010
|
+
}
|
|
1011
|
+
if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
|
|
856
1012
|
if ((prune || pruneCheckMode) && !usage) {
|
|
857
|
-
|
|
858
|
-
process.exit(1);
|
|
1013
|
+
throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
|
|
859
1014
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
1015
|
+
}
|
|
1016
|
+
async function lintRefs({ options, tag }) {
|
|
1017
|
+
const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
|
|
1018
|
+
const format = (ref) => ` ${(0, import_node_path2.relative)(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
|
|
1019
|
+
const errors = refs.filter((ref) => !ref.hasFallback);
|
|
1020
|
+
const warnings = refs.filter((ref) => ref.hasFallback);
|
|
1021
|
+
if (warnings.length > 0) {
|
|
1022
|
+
console.warn(`${tag}: ${warnings.length} reference(s) to undeclared variables with a fallback:`);
|
|
1023
|
+
for (const ref of warnings) console.warn(format(ref));
|
|
1024
|
+
}
|
|
1025
|
+
if (errors.length > 0) {
|
|
1026
|
+
console.error(`${tag}: ${errors.length} reference(s) to undeclared variables:`);
|
|
1027
|
+
for (const ref of errors) console.error(format(ref));
|
|
1028
|
+
return false;
|
|
1029
|
+
}
|
|
1030
|
+
console.log(`${tag}: no references to undeclared variables.`);
|
|
1031
|
+
return true;
|
|
1032
|
+
}
|
|
1033
|
+
async function pruneCheck({ options, tag }) {
|
|
1034
|
+
const unused = await findUnusedVars({ ...options, input: options.input });
|
|
1035
|
+
if (unused.length > 0) {
|
|
1036
|
+
console.error(`${tag}: ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
1037
|
+
return false;
|
|
1038
|
+
}
|
|
1039
|
+
console.log(`${tag}: no unused variables.`);
|
|
1040
|
+
return true;
|
|
1041
|
+
}
|
|
1042
|
+
async function check({ options, tag }) {
|
|
1043
|
+
if (!await checkGenerated({ ...options, input: options.input, output: options.output })) {
|
|
1044
|
+
console.error(`${tag}: "${options.output}" is out of date. Run without --check to regenerate.`);
|
|
1045
|
+
return false;
|
|
1046
|
+
}
|
|
1047
|
+
console.log(`${tag}: "${options.output}" is up to date.`);
|
|
1048
|
+
return true;
|
|
1049
|
+
}
|
|
1050
|
+
async function run({ options }) {
|
|
1051
|
+
await generate({ ...options, input: options.input, output: options.output });
|
|
1052
|
+
console.log(`Generated \u2192 ${options.output}`);
|
|
1053
|
+
}
|
|
1054
|
+
function watchTarget(target) {
|
|
1055
|
+
const { input, exclude } = target.options;
|
|
1056
|
+
const patterns = Array.isArray(input) ? input : [input];
|
|
1057
|
+
const makeHandler = (label) => (file) => {
|
|
1058
|
+
console.log(`${label}: ${file}`);
|
|
1059
|
+
run(target).catch(console.error);
|
|
1060
|
+
};
|
|
1061
|
+
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
1062
|
+
(0, import_chokidar.watch)(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
1063
|
+
}
|
|
1064
|
+
async function main() {
|
|
1065
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
1066
|
+
const pkg = JSON.parse(await (0, import_promises3.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
|
|
1067
|
+
console.log(pkg.version);
|
|
1068
|
+
process.exit(0);
|
|
868
1069
|
}
|
|
869
|
-
const
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1070
|
+
const targets = loadTargets(await loadConfig());
|
|
1071
|
+
validateModes();
|
|
1072
|
+
for (const target of targets) validateTarget(target, targets.length === 1);
|
|
1073
|
+
const mode = lintRefsMode ? lintRefs : pruneCheckMode ? pruneCheck : checkMode ? check : null;
|
|
1074
|
+
if (mode) {
|
|
1075
|
+
let ok = true;
|
|
1076
|
+
for (const target of targets) {
|
|
1077
|
+
if (!await mode(target)) ok = false;
|
|
875
1078
|
}
|
|
876
|
-
|
|
1079
|
+
if (!ok) process.exit(1);
|
|
877
1080
|
return;
|
|
878
1081
|
}
|
|
879
|
-
await run(
|
|
1082
|
+
for (const target of targets) await run(target);
|
|
880
1083
|
if (watchMode) {
|
|
881
|
-
const
|
|
882
|
-
const makeHandler = (label) => (file) => {
|
|
883
|
-
console.log(`${label}: ${file}`);
|
|
884
|
-
run(runOptions).catch(console.error);
|
|
885
|
-
};
|
|
886
|
-
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
887
|
-
(0, import_chokidar.watch)(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
1084
|
+
for (const target of targets) watchTarget(target);
|
|
888
1085
|
console.log("Watching for changes...");
|
|
889
1086
|
}
|
|
890
1087
|
}
|
|
891
1088
|
main().catch((err) => {
|
|
892
|
-
console.error(err);
|
|
1089
|
+
console.error(err instanceof CliError ? err.message : err);
|
|
893
1090
|
process.exit(1);
|
|
894
1091
|
});
|