css-typed-vars 0.6.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 +189 -9
- package/dist/{chunk-TD7SYMDA.js → chunk-32V3V6WT.js} +46 -29
- package/dist/chunk-5HPTHW7S.js +820 -0
- package/dist/{chunk-VZ2BHHXD.js → chunk-YDXCJQPL.js} +42 -29
- package/dist/cli.cjs +542 -151
- package/dist/cli.js +142 -73
- package/dist/esbuild.cjs +358 -87
- package/dist/esbuild.d.cts +1 -1
- package/dist/esbuild.d.ts +1 -1
- package/dist/esbuild.js +2 -2
- package/dist/generator-DJ9uOYBP.d.cts +69 -0
- package/dist/generator-DJ9uOYBP.d.ts +69 -0
- package/dist/index.cjs +423 -77
- package/dist/index.d.cts +29 -6
- package/dist/index.d.ts +29 -6
- package/dist/index.js +14 -2
- package/dist/rollup.cjs +358 -87
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +358 -87
- package/dist/unplugin.d.cts +12 -2
- package/dist/unplugin.d.ts +12 -2
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +358 -87
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +358 -87
- 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/chunk-LH53WYFF.js +0 -487
- package/dist/generator-C2AppeJL.d.cts +0 -15
- package/dist/generator-C2AppeJL.d.ts +0 -15
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,30 +165,119 @@ function extractValue(text, start) {
|
|
|
157
165
|
}
|
|
158
166
|
return text.slice(start, i).trim();
|
|
159
167
|
}
|
|
160
|
-
function
|
|
161
|
-
const
|
|
162
|
-
const
|
|
163
|
-
|
|
168
|
+
function forEachProperty(block, onProperty, offset = 0) {
|
|
169
|
+
const masked = maskQuotedContent(block);
|
|
170
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
171
|
+
const name = prop[0];
|
|
172
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
173
|
+
onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
177
|
+
for (const sel of selectors) {
|
|
164
178
|
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
165
179
|
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
166
180
|
let match;
|
|
167
181
|
while (match = openRegex.exec(stripped)) {
|
|
168
182
|
const start = match.index + match[0].length;
|
|
169
183
|
const block = extractBlock(stripped, start);
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
184
|
+
const end = start + block.length + 1;
|
|
185
|
+
onBlock(block, [start, end]);
|
|
186
|
+
openRegex.lastIndex = end;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
var BASE_SELECTORS = [":root", "@theme"];
|
|
191
|
+
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
192
|
+
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
193
|
+
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
194
|
+
forEachProperty(block, onProperty, bodyStart);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
198
|
+
function forEachMediaBlock(stripped, media, onBlock) {
|
|
199
|
+
const wanted = normalizePrelude(media.replace(/^@media/i, ""));
|
|
200
|
+
const openRegex = /@media([^{;]*)\{/gi;
|
|
201
|
+
let match;
|
|
202
|
+
while (match = openRegex.exec(stripped)) {
|
|
203
|
+
const start = match.index + match[0].length;
|
|
204
|
+
const block = extractBlock(stripped, start);
|
|
205
|
+
const end = start + block.length + 1;
|
|
206
|
+
if (normalizePrelude(match[1]) === wanted) {
|
|
207
|
+
onBlock(block, [start, end]);
|
|
208
|
+
openRegex.lastIndex = end;
|
|
209
|
+
} else {
|
|
210
|
+
openRegex.lastIndex = start;
|
|
177
211
|
}
|
|
178
212
|
}
|
|
179
213
|
}
|
|
180
|
-
function
|
|
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
|
+
}
|
|
242
|
+
function parseThemedDeclarations(css, selectors, themes) {
|
|
243
|
+
const strippedCss = stripCommentsWithMap(css);
|
|
244
|
+
const stripped = strippedCss.text;
|
|
245
|
+
const docAt = makeDocReader(css, strippedCss);
|
|
246
|
+
const themeDocs = /* @__PURE__ */ new Map();
|
|
247
|
+
const themeValues = /* @__PURE__ */ new Map();
|
|
248
|
+
const skip = [];
|
|
249
|
+
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
250
|
+
const values = /* @__PURE__ */ new Map();
|
|
251
|
+
themeValues.set(themeName, values);
|
|
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);
|
|
257
|
+
const selector = themeSelector.trim();
|
|
258
|
+
if (/^@media\b/i.test(selector)) {
|
|
259
|
+
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
260
|
+
skip.push(range);
|
|
261
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
|
|
262
|
+
});
|
|
263
|
+
} else {
|
|
264
|
+
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
265
|
+
skip.push(range);
|
|
266
|
+
collect(block, range[0]);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
}
|
|
181
270
|
const declarations = /* @__PURE__ */ new Map();
|
|
182
|
-
|
|
183
|
-
|
|
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 };
|
|
184
281
|
}
|
|
185
282
|
var PROPERTY_DESCRIPTORS = [
|
|
186
283
|
["syntax", "syntax"],
|
|
@@ -211,12 +308,48 @@ function parsePropertyRules(css) {
|
|
|
211
308
|
}
|
|
212
309
|
return rules;
|
|
213
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
|
+
}
|
|
214
340
|
|
|
215
341
|
// src/scanner.ts
|
|
216
342
|
function normalizePatterns(patterns) {
|
|
217
343
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
218
344
|
}
|
|
219
|
-
|
|
345
|
+
function collectVarNames(scanned) {
|
|
346
|
+
const names = new Set(scanned.declarations.keys());
|
|
347
|
+
for (const values of scanned.themes.values()) {
|
|
348
|
+
for (const name of values.keys()) names.add(name);
|
|
349
|
+
}
|
|
350
|
+
return [...names].sort();
|
|
351
|
+
}
|
|
352
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
220
353
|
const normalized = normalizePatterns(patterns);
|
|
221
354
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
222
355
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -227,51 +360,83 @@ async function scanCss(patterns, exclude, selectors) {
|
|
|
227
360
|
css = await (0, import_promises.readFile)(file, "utf8");
|
|
228
361
|
} catch (err) {
|
|
229
362
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
230
|
-
return
|
|
363
|
+
return null;
|
|
231
364
|
}
|
|
232
|
-
return {
|
|
365
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
233
366
|
})
|
|
234
367
|
);
|
|
235
368
|
const declarations = /* @__PURE__ */ new Map();
|
|
236
369
|
const properties = /* @__PURE__ */ new Map();
|
|
370
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
371
|
+
const docs = /* @__PURE__ */ new Map();
|
|
237
372
|
for (const result of perFile) {
|
|
373
|
+
if (!result) continue;
|
|
238
374
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
239
375
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
376
|
+
for (const [name, doc] of result.docs) docs.set(name, doc);
|
|
377
|
+
for (const [theme, values] of result.themes) {
|
|
378
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
379
|
+
}
|
|
240
380
|
}
|
|
241
|
-
return { declarations, properties };
|
|
381
|
+
return { declarations, properties, themes: themeValues, docs };
|
|
242
382
|
}
|
|
243
|
-
|
|
244
|
-
|
|
383
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
384
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
385
|
+
function readAccess(text, from) {
|
|
386
|
+
ACCESS_RE.lastIndex = from;
|
|
387
|
+
const match = ACCESS_RE.exec(text);
|
|
388
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
245
389
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
390
|
+
function extractUsage(text, into) {
|
|
391
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
392
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
393
|
+
if (!first) continue;
|
|
394
|
+
into.keys.add(first.key);
|
|
395
|
+
const second = readAccess(text, first.end);
|
|
396
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
397
|
+
else into.wholeKeys.add(first.key);
|
|
250
398
|
}
|
|
251
399
|
}
|
|
252
|
-
async function
|
|
400
|
+
async function scanUsage(patterns, exclude) {
|
|
253
401
|
const normalized = normalizePatterns(patterns);
|
|
254
402
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
255
403
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
404
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
405
|
+
const texts = await Promise.all(
|
|
406
|
+
files.map(async (file) => {
|
|
407
|
+
try {
|
|
408
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
409
|
+
} catch (err) {
|
|
410
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
411
|
+
return "";
|
|
412
|
+
}
|
|
413
|
+
})
|
|
414
|
+
);
|
|
415
|
+
for (const text of texts) extractUsage(text, usage);
|
|
416
|
+
return usage;
|
|
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();
|
|
256
422
|
const perFile = await Promise.all(
|
|
257
423
|
files.map(async (file) => {
|
|
258
|
-
const used = /* @__PURE__ */ new Set();
|
|
259
|
-
let text;
|
|
260
424
|
try {
|
|
261
|
-
|
|
425
|
+
return { file, css: await (0, import_promises.readFile)(file, "utf8") };
|
|
262
426
|
} catch (err) {
|
|
263
427
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
264
|
-
return
|
|
428
|
+
return null;
|
|
265
429
|
}
|
|
266
|
-
extractUsedKeys(text, used);
|
|
267
|
-
return used;
|
|
268
430
|
})
|
|
269
431
|
);
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
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);
|
|
273
438
|
}
|
|
274
|
-
return
|
|
439
|
+
return { references, declared };
|
|
275
440
|
}
|
|
276
441
|
|
|
277
442
|
// src/generator.ts
|
|
@@ -334,6 +499,12 @@ function formatKey(key, naming = "camelCase") {
|
|
|
334
499
|
function computeKey(cssVarName, prefix, naming) {
|
|
335
500
|
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
336
501
|
}
|
|
502
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
503
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
504
|
+
const split = splitGroupKey(cssVarName);
|
|
505
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
506
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
507
|
+
}
|
|
337
508
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
338
509
|
const byKey = /* @__PURE__ */ new Map();
|
|
339
510
|
for (const name of varNames) {
|
|
@@ -352,23 +523,38 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
352
523
|
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
353
524
|
}
|
|
354
525
|
}
|
|
355
|
-
function
|
|
526
|
+
function entryMeta(name, options) {
|
|
527
|
+
const themes = [];
|
|
528
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
529
|
+
const value = values.get(name);
|
|
530
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
531
|
+
}
|
|
532
|
+
return {
|
|
533
|
+
name,
|
|
534
|
+
value: options.declarations?.get(name),
|
|
535
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
536
|
+
...themes.length > 0 ? { themes } : {},
|
|
537
|
+
...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
function buildEntries(varNames, options) {
|
|
541
|
+
const { prefix, naming } = options;
|
|
356
542
|
const byKey = /* @__PURE__ */ new Map();
|
|
357
543
|
for (const name of varNames) {
|
|
358
544
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
359
|
-
byKey.set(key,
|
|
545
|
+
byKey.set(key, entryMeta(name, options));
|
|
360
546
|
}
|
|
361
547
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
362
548
|
}
|
|
363
|
-
function buildGroupedEntries(varNames,
|
|
549
|
+
function buildGroupedEntries(varNames, options) {
|
|
550
|
+
const { naming } = options;
|
|
364
551
|
const groupMap = /* @__PURE__ */ new Map();
|
|
365
552
|
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
366
553
|
for (const name of varNames) {
|
|
367
|
-
const
|
|
368
|
-
const syntax = properties?.get(name)?.syntax;
|
|
554
|
+
const meta = entryMeta(name, options);
|
|
369
555
|
const split = splitGroupKey(name);
|
|
370
556
|
if (!split) {
|
|
371
|
-
ungroupedMap.set(formatKey(toKey(name, naming), naming),
|
|
557
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
372
558
|
continue;
|
|
373
559
|
}
|
|
374
560
|
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
@@ -378,7 +564,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
378
564
|
leafMap = /* @__PURE__ */ new Map();
|
|
379
565
|
groupMap.set(groupKey, leafMap);
|
|
380
566
|
}
|
|
381
|
-
leafMap.set(leafKey,
|
|
567
|
+
leafMap.set(leafKey, meta);
|
|
382
568
|
}
|
|
383
569
|
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
384
570
|
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
@@ -388,8 +574,12 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
388
574
|
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
389
575
|
return { groups, ungrouped };
|
|
390
576
|
}
|
|
391
|
-
|
|
392
|
-
|
|
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} */`];
|
|
393
583
|
}
|
|
394
584
|
function unquoteCssString(value) {
|
|
395
585
|
const quote = value[0];
|
|
@@ -398,8 +588,15 @@ function unquoteCssString(value) {
|
|
|
398
588
|
}
|
|
399
589
|
return value;
|
|
400
590
|
}
|
|
401
|
-
function
|
|
402
|
-
|
|
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
|
+
];
|
|
403
600
|
}
|
|
404
601
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
405
602
|
function parseEnumSyntax(syntax) {
|
|
@@ -431,14 +628,13 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
431
628
|
return blocks;
|
|
432
629
|
}
|
|
433
630
|
function renderEntryLines(entries, indent, lineFor) {
|
|
434
|
-
return entries.flatMap((
|
|
435
|
-
...
|
|
436
|
-
|
|
437
|
-
`${indent}${lineFor(key, name)}`
|
|
631
|
+
return entries.flatMap((entry) => [
|
|
632
|
+
...renderJsDoc(entryTags(entry), indent),
|
|
633
|
+
`${indent}${lineFor(entry.key, entry.name)}`
|
|
438
634
|
]);
|
|
439
635
|
}
|
|
440
|
-
function renderGroupedBlock(varNames,
|
|
441
|
-
const { groups, ungrouped } = buildGroupedEntries(varNames,
|
|
636
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
637
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
442
638
|
const lines = [];
|
|
443
639
|
for (const group of groups) {
|
|
444
640
|
lines.push(`${indent}${group.key}: {`);
|
|
@@ -455,10 +651,64 @@ function assertGroupPrefixCompatible(prefix, group) {
|
|
|
455
651
|
}
|
|
456
652
|
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
457
653
|
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
458
|
-
function
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
const
|
|
654
|
+
function normalizeOptions(args2) {
|
|
655
|
+
const [first] = args2;
|
|
656
|
+
if (first !== null && typeof first === "object") return first;
|
|
657
|
+
const [prefix, naming, declarations, group, properties] = args2;
|
|
658
|
+
return { prefix, naming, declarations, group, properties };
|
|
659
|
+
}
|
|
660
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
661
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
662
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
663
|
+
}
|
|
664
|
+
function emittedNames(varNames, options) {
|
|
665
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
666
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
667
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
668
|
+
}
|
|
669
|
+
function renderRefType(varNames, options) {
|
|
670
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
671
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
672
|
+
}
|
|
673
|
+
var HELPERS_TS = [
|
|
674
|
+
"export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
|
|
675
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
676
|
+
"}",
|
|
677
|
+
"",
|
|
678
|
+
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
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>;",
|
|
686
|
+
"}"
|
|
687
|
+
];
|
|
688
|
+
var HELPERS_JS = [
|
|
689
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
690
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
691
|
+
"}",
|
|
692
|
+
"",
|
|
693
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
694
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
695
|
+
"}",
|
|
696
|
+
"",
|
|
697
|
+
"export function withFallback(ref, fallback) {",
|
|
698
|
+
" return `${ref.slice(0, -1)}, ${fallback})`;",
|
|
699
|
+
"}"
|
|
700
|
+
];
|
|
701
|
+
var HELPERS_DTS = [
|
|
702
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
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>;"
|
|
706
|
+
];
|
|
707
|
+
function generateCode(varNames, ...args2) {
|
|
708
|
+
const options = normalizeOptions(args2);
|
|
709
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
710
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
711
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
|
|
462
712
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
463
713
|
return [
|
|
464
714
|
"// generated \u2014 do not edit",
|
|
@@ -469,21 +719,23 @@ function generateCode(varNames, prefix, naming, declarations, group, properties)
|
|
|
469
719
|
""
|
|
470
720
|
].join("\n");
|
|
471
721
|
}
|
|
472
|
-
function generateJs(varNames,
|
|
473
|
-
|
|
474
|
-
const entries =
|
|
722
|
+
function generateJs(varNames, ...args2) {
|
|
723
|
+
const options = normalizeOptions(args2);
|
|
724
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
475
725
|
return [
|
|
476
726
|
"// generated \u2014 do not edit",
|
|
477
727
|
"export const cssVars = {",
|
|
478
728
|
...entries,
|
|
479
729
|
"};",
|
|
730
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
480
731
|
""
|
|
481
732
|
].join("\n");
|
|
482
733
|
}
|
|
483
|
-
function generateDeclaration(varNames,
|
|
484
|
-
|
|
485
|
-
const entries =
|
|
486
|
-
const blocks = buildTailBlocks(varNames, group, properties);
|
|
734
|
+
function generateDeclaration(varNames, ...args2) {
|
|
735
|
+
const options = normalizeOptions(args2);
|
|
736
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
737
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
738
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
487
739
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
488
740
|
return [
|
|
489
741
|
"export declare const cssVars: {",
|
|
@@ -493,55 +745,126 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
|
|
|
493
745
|
""
|
|
494
746
|
].join("\n");
|
|
495
747
|
}
|
|
748
|
+
var TOKEN_TYPES = {
|
|
749
|
+
"<color>": "color",
|
|
750
|
+
"<length>": "dimension",
|
|
751
|
+
"<length-percentage>": "dimension",
|
|
752
|
+
"<number>": "number",
|
|
753
|
+
"<integer>": "number",
|
|
754
|
+
"<time>": "duration"
|
|
755
|
+
};
|
|
756
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
757
|
+
function generateTokens(varNames, options = {}) {
|
|
758
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
759
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
760
|
+
const meta = entryMeta(name, options);
|
|
761
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
762
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
763
|
+
});
|
|
764
|
+
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
765
|
+
const resolve3 = (value) => {
|
|
766
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
767
|
+
return target ? `{${target.join(".")}}` : value;
|
|
768
|
+
};
|
|
769
|
+
const root = {};
|
|
770
|
+
for (const { meta, value, path } of tokens) {
|
|
771
|
+
const token = { $value: resolve3(value) };
|
|
772
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
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;
|
|
776
|
+
if (meta.themes) {
|
|
777
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
|
|
778
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
779
|
+
}
|
|
780
|
+
const [key, leaf] = path;
|
|
781
|
+
if (leaf === void 0) {
|
|
782
|
+
root[key] = token;
|
|
783
|
+
} else {
|
|
784
|
+
const group = root[key] ?? (root[key] = {});
|
|
785
|
+
group[leaf] = token;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
789
|
+
}
|
|
496
790
|
|
|
497
|
-
// src/
|
|
791
|
+
// src/prune.ts
|
|
498
792
|
function assertPruneCompatible(options) {
|
|
499
|
-
if (!options.
|
|
500
|
-
|
|
501
|
-
|
|
793
|
+
if (options.prune && !options.usage) {
|
|
794
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
function isUsed(name, usage, options) {
|
|
798
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
799
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
800
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
502
801
|
}
|
|
503
|
-
function partitionUnused(names,
|
|
802
|
+
function partitionUnused(names, usage, options) {
|
|
504
803
|
const used = [];
|
|
505
804
|
const unused = [];
|
|
506
805
|
for (const name of names) {
|
|
507
|
-
(
|
|
806
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
508
807
|
}
|
|
509
808
|
return { used, unused };
|
|
510
809
|
}
|
|
810
|
+
|
|
811
|
+
// src/index.ts
|
|
511
812
|
async function findUnusedVars(options) {
|
|
512
813
|
if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
|
|
513
|
-
const [
|
|
514
|
-
|
|
515
|
-
|
|
814
|
+
const [scanned, usage] = await Promise.all([
|
|
815
|
+
scanCss(options.input, options.exclude, options.selectors, options.themes),
|
|
816
|
+
scanUsage(options.usage, options.usageExclude)
|
|
516
817
|
]);
|
|
517
|
-
const names =
|
|
518
|
-
return partitionUnused(names,
|
|
818
|
+
const names = collectVarNames(scanned);
|
|
819
|
+
return partitionUnused(names, usage, options).unused;
|
|
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));
|
|
519
828
|
}
|
|
520
829
|
async function computeOutputs(options) {
|
|
521
830
|
assertPruneCompatible(options);
|
|
522
|
-
const
|
|
523
|
-
|
|
831
|
+
const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
832
|
+
const { declarations, properties } = scanned;
|
|
833
|
+
let names = collectVarNames(scanned);
|
|
524
834
|
if (names.length === 0) {
|
|
525
835
|
console.warn("css-typed-vars: no CSS custom properties found.");
|
|
526
836
|
}
|
|
527
837
|
warnOnCollisions(names, options.prefix, options.naming);
|
|
528
838
|
if (options.prune) {
|
|
529
|
-
const
|
|
530
|
-
const { used, unused } = partitionUnused(names,
|
|
839
|
+
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
840
|
+
const { used, unused } = partitionUnused(names, usage, options);
|
|
531
841
|
if (unused.length > 0) {
|
|
532
842
|
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
533
843
|
}
|
|
534
844
|
names = used;
|
|
535
845
|
}
|
|
536
846
|
const outPath = (0, import_node_path.resolve)(options.output);
|
|
847
|
+
const generatorOptions = {
|
|
848
|
+
prefix: options.prefix,
|
|
849
|
+
naming: options.naming,
|
|
850
|
+
declarations,
|
|
851
|
+
group: options.group,
|
|
852
|
+
properties,
|
|
853
|
+
helpers: options.helpers,
|
|
854
|
+
themes: scanned.themes,
|
|
855
|
+
docs: scanned.docs
|
|
856
|
+
};
|
|
857
|
+
if (/\.json$/i.test(options.output)) {
|
|
858
|
+
return { outPath, content: generateTokens(names, generatorOptions) };
|
|
859
|
+
}
|
|
537
860
|
const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
|
|
538
861
|
if (jsExtMatch) {
|
|
539
|
-
const content = generateJs(names,
|
|
862
|
+
const content = generateJs(names, generatorOptions);
|
|
540
863
|
const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
|
|
541
|
-
const dtsContent = generateDeclaration(names,
|
|
864
|
+
const dtsContent = generateDeclaration(names, generatorOptions);
|
|
542
865
|
return { outPath, content, dtsPath, dtsContent };
|
|
543
866
|
}
|
|
544
|
-
return { outPath, content: generateCode(names,
|
|
867
|
+
return { outPath, content: generateCode(names, generatorOptions) };
|
|
545
868
|
}
|
|
546
869
|
async function generate(options) {
|
|
547
870
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
@@ -580,9 +903,26 @@ var getArgs = (flag) => {
|
|
|
580
903
|
};
|
|
581
904
|
var watchMode = args.includes("--watch");
|
|
582
905
|
var checkMode = args.includes("--check");
|
|
583
|
-
var groupFlag = args.includes("--group");
|
|
584
|
-
var pruneFlag = args.includes("--prune");
|
|
585
906
|
var pruneCheckMode = args.includes("--prune-check");
|
|
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
|
+
};
|
|
586
926
|
async function loadConfig() {
|
|
587
927
|
const candidates = [
|
|
588
928
|
"css-typed-vars.config.js",
|
|
@@ -607,94 +947,145 @@ async function loadConfig() {
|
|
|
607
947
|
}
|
|
608
948
|
return {};
|
|
609
949
|
}
|
|
610
|
-
|
|
611
|
-
await generate(options);
|
|
612
|
-
console.log(`Generated \u2192 ${options.output}`);
|
|
613
|
-
}
|
|
614
|
-
async function main() {
|
|
615
|
-
if (args.includes("--version") || args.includes("-v")) {
|
|
616
|
-
const pkg = JSON.parse(await (0, import_promises3.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
|
|
617
|
-
console.log(pkg.version);
|
|
618
|
-
process.exit(0);
|
|
619
|
-
}
|
|
620
|
-
const config = await loadConfig();
|
|
950
|
+
function applyFlags(config) {
|
|
621
951
|
const inputArgs = getArgs("--input");
|
|
622
|
-
const input = inputArgs.length > 0 ? inputArgs : config.input;
|
|
623
|
-
const output = getArg("--output") ?? config.output;
|
|
624
952
|
const excludeArgs = getArgs("--exclude");
|
|
625
|
-
const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
|
|
626
|
-
const prefix = getArg("--prefix") ?? config.prefix;
|
|
627
|
-
const namingRaw = getArg("--naming") ?? config.naming;
|
|
628
|
-
if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
|
|
629
|
-
console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
630
|
-
process.exit(1);
|
|
631
|
-
}
|
|
632
|
-
const naming = namingRaw;
|
|
633
953
|
const selectorArgs = getArgs("--selector");
|
|
634
|
-
const
|
|
635
|
-
const
|
|
636
|
-
|
|
954
|
+
const themeArgs = getArgs("--theme");
|
|
955
|
+
for (const arg of themeArgs) {
|
|
956
|
+
if (!/^[^=]+=.+$/.test(arg)) {
|
|
957
|
+
throw new CliError(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
637
960
|
const usageArgs = getArgs("--usage");
|
|
638
|
-
const usage = usageArgs.length > 0 ? usageArgs : config.usage;
|
|
639
961
|
const usageExcludeArgs = getArgs("--usage-exclude");
|
|
640
|
-
const
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
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.`);
|
|
645
986
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
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.");
|
|
649
992
|
}
|
|
993
|
+
if (checkMode && watchMode) throw new CliError("css-typed-vars: --check cannot be combined with --watch.");
|
|
650
994
|
if (pruneCheckMode && (watchMode || checkMode)) {
|
|
651
|
-
|
|
652
|
-
process.exit(1);
|
|
995
|
+
throw new CliError("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
|
|
653
996
|
}
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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;
|
|
657
1006
|
}
|
|
658
|
-
if (
|
|
659
|
-
|
|
660
|
-
|
|
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".`);
|
|
661
1010
|
}
|
|
1011
|
+
if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
|
|
662
1012
|
if ((prune || pruneCheckMode) && !usage) {
|
|
663
|
-
|
|
664
|
-
process.exit(1);
|
|
1013
|
+
throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
|
|
665
1014
|
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
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);
|
|
674
1069
|
}
|
|
675
|
-
const
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
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;
|
|
681
1078
|
}
|
|
682
|
-
|
|
1079
|
+
if (!ok) process.exit(1);
|
|
683
1080
|
return;
|
|
684
1081
|
}
|
|
685
|
-
await run(
|
|
1082
|
+
for (const target of targets) await run(target);
|
|
686
1083
|
if (watchMode) {
|
|
687
|
-
const
|
|
688
|
-
const makeHandler = (label) => (file) => {
|
|
689
|
-
console.log(`${label}: ${file}`);
|
|
690
|
-
run(runOptions).catch(console.error);
|
|
691
|
-
};
|
|
692
|
-
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
693
|
-
(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);
|
|
694
1085
|
console.log("Watching for changes...");
|
|
695
1086
|
}
|
|
696
1087
|
}
|
|
697
1088
|
main().catch((err) => {
|
|
698
|
-
console.error(err);
|
|
1089
|
+
console.error(err instanceof CliError ? err.message : err);
|
|
699
1090
|
process.exit(1);
|
|
700
1091
|
});
|