css-typed-vars 0.6.0 → 0.7.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 +91 -6
- package/dist/{chunk-LH53WYFF.js → chunk-6YWE4A6S.js} +259 -55
- package/dist/{chunk-TD7SYMDA.js → chunk-HBUSLYYB.js} +45 -29
- package/dist/{chunk-VZ2BHHXD.js → chunk-PLO2JWR7.js} +31 -29
- package/dist/cli.cjs +277 -83
- package/dist/cli.js +15 -9
- package/dist/esbuild.cjs +273 -79
- 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.cts +49 -0
- package/dist/generator-C1iVNsry.d.ts +49 -0
- package/dist/index.cjs +274 -71
- package/dist/index.d.cts +16 -5
- package/dist/index.d.ts +16 -5
- package/dist/index.js +6 -2
- package/dist/rollup.cjs +273 -79
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +273 -79
- package/dist/unplugin.d.cts +12 -2
- package/dist/unplugin.d.ts +12 -2
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +273 -79
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +273 -79
- 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/generator-C2AppeJL.d.cts +0 -15
- package/dist/generator-C2AppeJL.d.ts +0 -15
package/dist/index.cjs
CHANGED
|
@@ -36,7 +36,9 @@ __export(src_exports, {
|
|
|
36
36
|
generateCode: () => generateCode,
|
|
37
37
|
generateDeclaration: () => generateDeclaration,
|
|
38
38
|
generateJs: () => generateJs,
|
|
39
|
+
generateTokens: () => generateTokens,
|
|
39
40
|
parsePropertyRules: () => parsePropertyRules,
|
|
41
|
+
parseThemedDeclarations: () => parseThemedDeclarations,
|
|
40
42
|
parseVarDeclarations: () => parseVarDeclarations,
|
|
41
43
|
parseVarNames: () => parseVarNames,
|
|
42
44
|
scanCss: () => scanCss,
|
|
@@ -168,26 +170,35 @@ function extractValue(text, start) {
|
|
|
168
170
|
}
|
|
169
171
|
return text.slice(start, i).trim();
|
|
170
172
|
}
|
|
171
|
-
function
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
|
|
173
|
+
function forEachProperty(block, onProperty) {
|
|
174
|
+
const masked = maskQuotedContent(block);
|
|
175
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
176
|
+
const name = prop[0];
|
|
177
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
178
|
+
onProperty(name, extractValue(block, colonIndex + 1));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
182
|
+
for (const sel of selectors) {
|
|
175
183
|
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
176
184
|
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
177
185
|
let match;
|
|
178
186
|
while (match = openRegex.exec(stripped)) {
|
|
179
187
|
const start = match.index + match[0].length;
|
|
180
188
|
const block = extractBlock(stripped, start);
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
185
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
186
|
-
}
|
|
187
|
-
openRegex.lastIndex = start + block.length + 1;
|
|
189
|
+
const end = start + block.length + 1;
|
|
190
|
+
onBlock(block, [start, end]);
|
|
191
|
+
openRegex.lastIndex = end;
|
|
188
192
|
}
|
|
189
193
|
}
|
|
190
194
|
}
|
|
195
|
+
var BASE_SELECTORS = [":root", "@theme"];
|
|
196
|
+
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
197
|
+
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
198
|
+
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
199
|
+
forEachProperty(block, onProperty);
|
|
200
|
+
});
|
|
201
|
+
}
|
|
191
202
|
function parseVarNames(css, selectors) {
|
|
192
203
|
const names = /* @__PURE__ */ new Set();
|
|
193
204
|
scanDeclarations(css, selectors, (name) => names.add(name));
|
|
@@ -198,6 +209,48 @@ function parseVarDeclarations(css, selectors) {
|
|
|
198
209
|
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
|
|
199
210
|
return declarations;
|
|
200
211
|
}
|
|
212
|
+
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
213
|
+
function forEachMediaBlock(stripped, media, onBlock) {
|
|
214
|
+
const wanted = normalizePrelude(media.replace(/^@media/i, ""));
|
|
215
|
+
const openRegex = /@media([^{;]*)\{/gi;
|
|
216
|
+
let match;
|
|
217
|
+
while (match = openRegex.exec(stripped)) {
|
|
218
|
+
const start = match.index + match[0].length;
|
|
219
|
+
const block = extractBlock(stripped, start);
|
|
220
|
+
const end = start + block.length + 1;
|
|
221
|
+
if (normalizePrelude(match[1]) === wanted) {
|
|
222
|
+
onBlock(block, [start, end]);
|
|
223
|
+
openRegex.lastIndex = end;
|
|
224
|
+
} else {
|
|
225
|
+
openRegex.lastIndex = start;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function parseThemedDeclarations(css, selectors, themes) {
|
|
230
|
+
const stripped = stripComments(css);
|
|
231
|
+
const themeValues = /* @__PURE__ */ new Map();
|
|
232
|
+
const skip = [];
|
|
233
|
+
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
234
|
+
const values = /* @__PURE__ */ new Map();
|
|
235
|
+
themeValues.set(themeName, values);
|
|
236
|
+
const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
|
|
237
|
+
const selector = themeSelector.trim();
|
|
238
|
+
if (/^@media\b/i.test(selector)) {
|
|
239
|
+
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
240
|
+
skip.push(range);
|
|
241
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
242
|
+
});
|
|
243
|
+
} else {
|
|
244
|
+
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
245
|
+
skip.push(range);
|
|
246
|
+
collect(block);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
251
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
|
|
252
|
+
return { declarations, themes: themeValues };
|
|
253
|
+
}
|
|
201
254
|
var PROPERTY_DESCRIPTORS = [
|
|
202
255
|
["syntax", "syntax"],
|
|
203
256
|
["inherits", "inherits"],
|
|
@@ -232,7 +285,14 @@ function parsePropertyRules(css) {
|
|
|
232
285
|
function normalizePatterns(patterns) {
|
|
233
286
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
234
287
|
}
|
|
235
|
-
|
|
288
|
+
function collectVarNames(scanned) {
|
|
289
|
+
const names = new Set(scanned.declarations.keys());
|
|
290
|
+
for (const values of scanned.themes.values()) {
|
|
291
|
+
for (const name of values.keys()) names.add(name);
|
|
292
|
+
}
|
|
293
|
+
return [...names].sort();
|
|
294
|
+
}
|
|
295
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
236
296
|
const normalized = normalizePatterns(patterns);
|
|
237
297
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
238
298
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -243,18 +303,23 @@ async function scanCss(patterns, exclude, selectors) {
|
|
|
243
303
|
css = await (0, import_promises.readFile)(file, "utf8");
|
|
244
304
|
} catch (err) {
|
|
245
305
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
246
|
-
return
|
|
306
|
+
return null;
|
|
247
307
|
}
|
|
248
|
-
return {
|
|
308
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
249
309
|
})
|
|
250
310
|
);
|
|
251
311
|
const declarations = /* @__PURE__ */ new Map();
|
|
252
312
|
const properties = /* @__PURE__ */ new Map();
|
|
313
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
253
314
|
for (const result of perFile) {
|
|
315
|
+
if (!result) continue;
|
|
254
316
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
255
317
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
318
|
+
for (const [theme, values] of result.themes) {
|
|
319
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
320
|
+
}
|
|
256
321
|
}
|
|
257
|
-
return { declarations, properties };
|
|
322
|
+
return { declarations, properties, themes: themeValues };
|
|
258
323
|
}
|
|
259
324
|
async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
260
325
|
return (await scanCss(patterns, exclude, selectors)).declarations;
|
|
@@ -263,35 +328,43 @@ async function scanVarNames(patterns, exclude, selectors) {
|
|
|
263
328
|
const declarations = await scanVarDeclarations(patterns, exclude, selectors);
|
|
264
329
|
return [...declarations.keys()].sort();
|
|
265
330
|
}
|
|
266
|
-
var
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
331
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
332
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
333
|
+
function readAccess(text, from) {
|
|
334
|
+
ACCESS_RE.lastIndex = from;
|
|
335
|
+
const match = ACCESS_RE.exec(text);
|
|
336
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
337
|
+
}
|
|
338
|
+
function extractUsage(text, into) {
|
|
339
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
340
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
341
|
+
if (!first) continue;
|
|
342
|
+
into.keys.add(first.key);
|
|
343
|
+
const second = readAccess(text, first.end);
|
|
344
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
345
|
+
else into.wholeKeys.add(first.key);
|
|
270
346
|
}
|
|
271
347
|
}
|
|
272
|
-
async function
|
|
348
|
+
async function scanUsage(patterns, exclude) {
|
|
273
349
|
const normalized = normalizePatterns(patterns);
|
|
274
350
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
275
351
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
276
|
-
const
|
|
352
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
353
|
+
const texts = await Promise.all(
|
|
277
354
|
files.map(async (file) => {
|
|
278
|
-
const used = /* @__PURE__ */ new Set();
|
|
279
|
-
let text;
|
|
280
355
|
try {
|
|
281
|
-
|
|
356
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
282
357
|
} catch (err) {
|
|
283
358
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
284
|
-
return
|
|
359
|
+
return "";
|
|
285
360
|
}
|
|
286
|
-
extractUsedKeys(text, used);
|
|
287
|
-
return used;
|
|
288
361
|
})
|
|
289
362
|
);
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
return
|
|
363
|
+
for (const text of texts) extractUsage(text, usage);
|
|
364
|
+
return usage;
|
|
365
|
+
}
|
|
366
|
+
async function scanUsedKeys(patterns, exclude) {
|
|
367
|
+
return (await scanUsage(patterns, exclude)).keys;
|
|
295
368
|
}
|
|
296
369
|
|
|
297
370
|
// src/generator.ts
|
|
@@ -354,6 +427,12 @@ function formatKey(key, naming = "camelCase") {
|
|
|
354
427
|
function computeKey(cssVarName, prefix, naming) {
|
|
355
428
|
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
356
429
|
}
|
|
430
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
431
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
432
|
+
const split = splitGroupKey(cssVarName);
|
|
433
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
434
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
435
|
+
}
|
|
357
436
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
358
437
|
const byKey = /* @__PURE__ */ new Map();
|
|
359
438
|
for (const name of varNames) {
|
|
@@ -372,23 +451,37 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
372
451
|
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
373
452
|
}
|
|
374
453
|
}
|
|
375
|
-
function
|
|
454
|
+
function entryMeta(name, options) {
|
|
455
|
+
const themes = [];
|
|
456
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
457
|
+
const value = values.get(name);
|
|
458
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
name,
|
|
462
|
+
value: options.declarations?.get(name),
|
|
463
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
464
|
+
...themes.length > 0 ? { themes } : {}
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
function buildEntries(varNames, options) {
|
|
468
|
+
const { prefix, naming } = options;
|
|
376
469
|
const byKey = /* @__PURE__ */ new Map();
|
|
377
470
|
for (const name of varNames) {
|
|
378
471
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
379
|
-
byKey.set(key,
|
|
472
|
+
byKey.set(key, entryMeta(name, options));
|
|
380
473
|
}
|
|
381
474
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
382
475
|
}
|
|
383
|
-
function buildGroupedEntries(varNames,
|
|
476
|
+
function buildGroupedEntries(varNames, options) {
|
|
477
|
+
const { naming } = options;
|
|
384
478
|
const groupMap = /* @__PURE__ */ new Map();
|
|
385
479
|
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
386
480
|
for (const name of varNames) {
|
|
387
|
-
const
|
|
388
|
-
const syntax = properties?.get(name)?.syntax;
|
|
481
|
+
const meta = entryMeta(name, options);
|
|
389
482
|
const split = splitGroupKey(name);
|
|
390
483
|
if (!split) {
|
|
391
|
-
ungroupedMap.set(formatKey(toKey(name, naming), naming),
|
|
484
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
392
485
|
continue;
|
|
393
486
|
}
|
|
394
487
|
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
@@ -398,7 +491,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
398
491
|
leafMap = /* @__PURE__ */ new Map();
|
|
399
492
|
groupMap.set(groupKey, leafMap);
|
|
400
493
|
}
|
|
401
|
-
leafMap.set(leafKey,
|
|
494
|
+
leafMap.set(leafKey, meta);
|
|
402
495
|
}
|
|
403
496
|
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
404
497
|
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
@@ -421,6 +514,9 @@ function unquoteCssString(value) {
|
|
|
421
514
|
function formatSyntaxComment(syntax, indent = " ") {
|
|
422
515
|
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
423
516
|
}
|
|
517
|
+
function formatThemeComment(theme, value, indent = " ") {
|
|
518
|
+
return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
|
|
519
|
+
}
|
|
424
520
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
425
521
|
function parseEnumSyntax(syntax) {
|
|
426
522
|
const unquoted = unquoteCssString(syntax).trim();
|
|
@@ -451,14 +547,15 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
451
547
|
return blocks;
|
|
452
548
|
}
|
|
453
549
|
function renderEntryLines(entries, indent, lineFor) {
|
|
454
|
-
return entries.flatMap(({ key, name, value, syntax }) => [
|
|
550
|
+
return entries.flatMap(({ key, name, value, syntax, themes }) => [
|
|
455
551
|
...value ? [formatDefaultComment(value, indent)] : [],
|
|
552
|
+
...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
|
|
456
553
|
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
457
554
|
`${indent}${lineFor(key, name)}`
|
|
458
555
|
]);
|
|
459
556
|
}
|
|
460
|
-
function renderGroupedBlock(varNames,
|
|
461
|
-
const { groups, ungrouped } = buildGroupedEntries(varNames,
|
|
557
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
558
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
462
559
|
const lines = [];
|
|
463
560
|
for (const group of groups) {
|
|
464
561
|
lines.push(`${indent}${group.key}: {`);
|
|
@@ -475,10 +572,52 @@ function assertGroupPrefixCompatible(prefix, group) {
|
|
|
475
572
|
}
|
|
476
573
|
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
477
574
|
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
478
|
-
function
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
const
|
|
575
|
+
function normalizeOptions(args) {
|
|
576
|
+
const [first] = args;
|
|
577
|
+
if (first !== null && typeof first === "object") return first;
|
|
578
|
+
const [prefix, naming, declarations, group, properties] = args;
|
|
579
|
+
return { prefix, naming, declarations, group, properties };
|
|
580
|
+
}
|
|
581
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
582
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
583
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
584
|
+
}
|
|
585
|
+
function emittedNames(varNames, options) {
|
|
586
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
587
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
588
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
589
|
+
}
|
|
590
|
+
function renderRefType(varNames, options) {
|
|
591
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
592
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
593
|
+
}
|
|
594
|
+
var HELPERS_TS = [
|
|
595
|
+
"export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
|
|
596
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
597
|
+
"}",
|
|
598
|
+
"",
|
|
599
|
+
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
600
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
601
|
+
"}"
|
|
602
|
+
];
|
|
603
|
+
var HELPERS_JS = [
|
|
604
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
605
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
606
|
+
"}",
|
|
607
|
+
"",
|
|
608
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
609
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
610
|
+
"}"
|
|
611
|
+
];
|
|
612
|
+
var HELPERS_DTS = [
|
|
613
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
614
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
615
|
+
];
|
|
616
|
+
function generateCode(varNames, ...args) {
|
|
617
|
+
const options = normalizeOptions(args);
|
|
618
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
619
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
620
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
|
|
482
621
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
483
622
|
return [
|
|
484
623
|
"// generated \u2014 do not edit",
|
|
@@ -489,21 +628,23 @@ function generateCode(varNames, prefix, naming, declarations, group, properties)
|
|
|
489
628
|
""
|
|
490
629
|
].join("\n");
|
|
491
630
|
}
|
|
492
|
-
function generateJs(varNames,
|
|
493
|
-
|
|
494
|
-
const entries =
|
|
631
|
+
function generateJs(varNames, ...args) {
|
|
632
|
+
const options = normalizeOptions(args);
|
|
633
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
495
634
|
return [
|
|
496
635
|
"// generated \u2014 do not edit",
|
|
497
636
|
"export const cssVars = {",
|
|
498
637
|
...entries,
|
|
499
638
|
"};",
|
|
639
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
500
640
|
""
|
|
501
641
|
].join("\n");
|
|
502
642
|
}
|
|
503
|
-
function generateDeclaration(varNames,
|
|
504
|
-
|
|
505
|
-
const entries =
|
|
506
|
-
const blocks = buildTailBlocks(varNames, group, properties);
|
|
643
|
+
function generateDeclaration(varNames, ...args) {
|
|
644
|
+
const options = normalizeOptions(args);
|
|
645
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
646
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
647
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
507
648
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
508
649
|
return [
|
|
509
650
|
"export declare const cssVars: {",
|
|
@@ -513,55 +654,115 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
|
|
|
513
654
|
""
|
|
514
655
|
].join("\n");
|
|
515
656
|
}
|
|
657
|
+
var TOKEN_TYPES = {
|
|
658
|
+
"<color>": "color",
|
|
659
|
+
"<length>": "dimension",
|
|
660
|
+
"<length-percentage>": "dimension",
|
|
661
|
+
"<number>": "number",
|
|
662
|
+
"<integer>": "number",
|
|
663
|
+
"<time>": "duration"
|
|
664
|
+
};
|
|
665
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
666
|
+
function generateTokens(varNames, options = {}) {
|
|
667
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
668
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
669
|
+
const meta = entryMeta(name, options);
|
|
670
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
671
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
672
|
+
});
|
|
673
|
+
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
674
|
+
const resolve2 = (value) => {
|
|
675
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
676
|
+
return target ? `{${target.join(".")}}` : value;
|
|
677
|
+
};
|
|
678
|
+
const root = {};
|
|
679
|
+
for (const { meta, value, path } of tokens) {
|
|
680
|
+
const token = { $value: resolve2(value) };
|
|
681
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
682
|
+
if (type) token.$type = type;
|
|
683
|
+
if (meta.themes) {
|
|
684
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
|
|
685
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
686
|
+
}
|
|
687
|
+
const [key, leaf] = path;
|
|
688
|
+
if (leaf === void 0) {
|
|
689
|
+
root[key] = token;
|
|
690
|
+
} else {
|
|
691
|
+
const group = root[key] ?? (root[key] = {});
|
|
692
|
+
group[leaf] = token;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
696
|
+
}
|
|
516
697
|
|
|
517
|
-
// src/
|
|
698
|
+
// src/prune.ts
|
|
518
699
|
function assertPruneCompatible(options) {
|
|
519
|
-
if (!options.
|
|
520
|
-
|
|
521
|
-
|
|
700
|
+
if (options.prune && !options.usage) {
|
|
701
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
function isUsed(name, usage, options) {
|
|
705
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
706
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
707
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
522
708
|
}
|
|
523
|
-
function partitionUnused(names,
|
|
709
|
+
function partitionUnused(names, usage, options) {
|
|
524
710
|
const used = [];
|
|
525
711
|
const unused = [];
|
|
526
712
|
for (const name of names) {
|
|
527
|
-
(
|
|
713
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
528
714
|
}
|
|
529
715
|
return { used, unused };
|
|
530
716
|
}
|
|
717
|
+
|
|
718
|
+
// src/index.ts
|
|
531
719
|
async function findUnusedVars(options) {
|
|
532
720
|
if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
|
|
533
|
-
const [
|
|
534
|
-
|
|
535
|
-
|
|
721
|
+
const [scanned, usage] = await Promise.all([
|
|
722
|
+
scanCss(options.input, options.exclude, options.selectors, options.themes),
|
|
723
|
+
scanUsage(options.usage, options.usageExclude)
|
|
536
724
|
]);
|
|
537
|
-
const names =
|
|
538
|
-
return partitionUnused(names,
|
|
725
|
+
const names = collectVarNames(scanned);
|
|
726
|
+
return partitionUnused(names, usage, options).unused;
|
|
539
727
|
}
|
|
540
728
|
async function computeOutputs(options) {
|
|
541
729
|
assertPruneCompatible(options);
|
|
542
|
-
const
|
|
543
|
-
|
|
730
|
+
const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
731
|
+
const { declarations, properties } = scanned;
|
|
732
|
+
let names = collectVarNames(scanned);
|
|
544
733
|
if (names.length === 0) {
|
|
545
734
|
console.warn("css-typed-vars: no CSS custom properties found.");
|
|
546
735
|
}
|
|
547
736
|
warnOnCollisions(names, options.prefix, options.naming);
|
|
548
737
|
if (options.prune) {
|
|
549
|
-
const
|
|
550
|
-
const { used, unused } = partitionUnused(names,
|
|
738
|
+
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
739
|
+
const { used, unused } = partitionUnused(names, usage, options);
|
|
551
740
|
if (unused.length > 0) {
|
|
552
741
|
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
553
742
|
}
|
|
554
743
|
names = used;
|
|
555
744
|
}
|
|
556
745
|
const outPath = (0, import_node_path.resolve)(options.output);
|
|
746
|
+
const generatorOptions = {
|
|
747
|
+
prefix: options.prefix,
|
|
748
|
+
naming: options.naming,
|
|
749
|
+
declarations,
|
|
750
|
+
group: options.group,
|
|
751
|
+
properties,
|
|
752
|
+
helpers: options.helpers,
|
|
753
|
+
themes: scanned.themes
|
|
754
|
+
};
|
|
755
|
+
if (/\.json$/i.test(options.output)) {
|
|
756
|
+
return { outPath, content: generateTokens(names, generatorOptions) };
|
|
757
|
+
}
|
|
557
758
|
const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
|
|
558
759
|
if (jsExtMatch) {
|
|
559
|
-
const content = generateJs(names,
|
|
760
|
+
const content = generateJs(names, generatorOptions);
|
|
560
761
|
const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
|
|
561
|
-
const dtsContent = generateDeclaration(names,
|
|
762
|
+
const dtsContent = generateDeclaration(names, generatorOptions);
|
|
562
763
|
return { outPath, content, dtsPath, dtsContent };
|
|
563
764
|
}
|
|
564
|
-
return { outPath, content: generateCode(names,
|
|
765
|
+
return { outPath, content: generateCode(names, generatorOptions) };
|
|
565
766
|
}
|
|
566
767
|
async function generate(options) {
|
|
567
768
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
@@ -589,7 +790,9 @@ async function checkGenerated(options) {
|
|
|
589
790
|
generateCode,
|
|
590
791
|
generateDeclaration,
|
|
591
792
|
generateJs,
|
|
793
|
+
generateTokens,
|
|
592
794
|
parsePropertyRules,
|
|
795
|
+
parseThemedDeclarations,
|
|
593
796
|
parseVarDeclarations,
|
|
594
797
|
parseVarNames,
|
|
595
798
|
scanCss,
|
package/dist/index.d.cts
CHANGED
|
@@ -1,30 +1,41 @@
|
|
|
1
|
-
import { P as PropertyRule, N as NamingConvention } from './generator-
|
|
2
|
-
export { g as generateCode, a as generateDeclaration, b as generateJs, p as parsePropertyRules,
|
|
1
|
+
import { P as PropertyRule, N as NamingConvention } from './generator-C1iVNsry.cjs';
|
|
2
|
+
export { G as GeneratorOptions, T as ThemedDeclarations, g as generateCode, a as generateDeclaration, b as generateJs, c as generateTokens, p as parsePropertyRules, d as parseThemedDeclarations, e as parseVarDeclarations, f as parseVarNames } from './generator-C1iVNsry.cjs';
|
|
3
3
|
|
|
4
4
|
interface ScannedCss {
|
|
5
5
|
declarations: Map<string, string>;
|
|
6
6
|
properties: Map<string, PropertyRule>;
|
|
7
|
+
/** Per theme name (from the `themes` option), the values declared for it. Empty without `themes`. */
|
|
8
|
+
themes: Map<string, Map<string, string>>;
|
|
7
9
|
}
|
|
8
|
-
declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<ScannedCss>;
|
|
10
|
+
declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[], themes?: Record<string, string>): Promise<ScannedCss>;
|
|
9
11
|
declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
|
|
10
12
|
declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
|
|
11
13
|
declare function scanUsedKeys(patterns: string | string[], exclude?: string | string[]): Promise<Set<string>>;
|
|
12
14
|
|
|
13
15
|
interface GenerateOptions {
|
|
14
16
|
input: string | string[];
|
|
17
|
+
/** `.ts`, `.js`/`.mjs`/`.cjs` (plus a `.d.ts`), or `.json` for a W3C design tokens (DTCG) file. */
|
|
15
18
|
output: string;
|
|
16
19
|
exclude?: string | string[];
|
|
17
20
|
prefix?: string;
|
|
18
21
|
naming?: NamingConvention;
|
|
19
22
|
selectors?: string[];
|
|
23
|
+
/**
|
|
24
|
+
* Theme name -> selector (`'[data-theme="dark"]'`) or `@media` prelude
|
|
25
|
+
* (`'@media (prefers-color-scheme: dark)'`). Each theme's values are emitted as
|
|
26
|
+
* `@theme <name> <value>` JSDoc tags, and kept out of the default value.
|
|
27
|
+
*/
|
|
28
|
+
themes?: Record<string, string>;
|
|
20
29
|
group?: boolean;
|
|
21
|
-
/** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage
|
|
30
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
22
31
|
prune?: boolean;
|
|
23
32
|
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true, or when calling `findUnusedVars`. */
|
|
24
33
|
usage?: string | string[];
|
|
25
34
|
usageExclude?: string | string[];
|
|
35
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
36
|
+
helpers?: boolean;
|
|
26
37
|
}
|
|
27
|
-
declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'prefix' | 'naming' | 'usage' | 'usageExclude'>): Promise<string[]>;
|
|
38
|
+
declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
|
|
28
39
|
declare function generate(options: GenerateOptions): Promise<void>;
|
|
29
40
|
declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
|
|
30
41
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,30 +1,41 @@
|
|
|
1
|
-
import { P as PropertyRule, N as NamingConvention } from './generator-
|
|
2
|
-
export { g as generateCode, a as generateDeclaration, b as generateJs, p as parsePropertyRules,
|
|
1
|
+
import { P as PropertyRule, N as NamingConvention } from './generator-C1iVNsry.js';
|
|
2
|
+
export { G as GeneratorOptions, T as ThemedDeclarations, g as generateCode, a as generateDeclaration, b as generateJs, c as generateTokens, p as parsePropertyRules, d as parseThemedDeclarations, e as parseVarDeclarations, f as parseVarNames } from './generator-C1iVNsry.js';
|
|
3
3
|
|
|
4
4
|
interface ScannedCss {
|
|
5
5
|
declarations: Map<string, string>;
|
|
6
6
|
properties: Map<string, PropertyRule>;
|
|
7
|
+
/** Per theme name (from the `themes` option), the values declared for it. Empty without `themes`. */
|
|
8
|
+
themes: Map<string, Map<string, string>>;
|
|
7
9
|
}
|
|
8
|
-
declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<ScannedCss>;
|
|
10
|
+
declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[], themes?: Record<string, string>): Promise<ScannedCss>;
|
|
9
11
|
declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
|
|
10
12
|
declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
|
|
11
13
|
declare function scanUsedKeys(patterns: string | string[], exclude?: string | string[]): Promise<Set<string>>;
|
|
12
14
|
|
|
13
15
|
interface GenerateOptions {
|
|
14
16
|
input: string | string[];
|
|
17
|
+
/** `.ts`, `.js`/`.mjs`/`.cjs` (plus a `.d.ts`), or `.json` for a W3C design tokens (DTCG) file. */
|
|
15
18
|
output: string;
|
|
16
19
|
exclude?: string | string[];
|
|
17
20
|
prefix?: string;
|
|
18
21
|
naming?: NamingConvention;
|
|
19
22
|
selectors?: string[];
|
|
23
|
+
/**
|
|
24
|
+
* Theme name -> selector (`'[data-theme="dark"]'`) or `@media` prelude
|
|
25
|
+
* (`'@media (prefers-color-scheme: dark)'`). Each theme's values are emitted as
|
|
26
|
+
* `@theme <name> <value>` JSDoc tags, and kept out of the default value.
|
|
27
|
+
*/
|
|
28
|
+
themes?: Record<string, string>;
|
|
20
29
|
group?: boolean;
|
|
21
|
-
/** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage
|
|
30
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
22
31
|
prune?: boolean;
|
|
23
32
|
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true, or when calling `findUnusedVars`. */
|
|
24
33
|
usage?: string | string[];
|
|
25
34
|
usageExclude?: string | string[];
|
|
35
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
36
|
+
helpers?: boolean;
|
|
26
37
|
}
|
|
27
|
-
declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'prefix' | 'naming' | 'usage' | 'usageExclude'>): Promise<string[]>;
|
|
38
|
+
declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
|
|
28
39
|
declare function generate(options: GenerateOptions): Promise<void>;
|
|
29
40
|
declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
|
|
30
41
|
|
package/dist/index.js
CHANGED
|
@@ -2,19 +2,21 @@ import {
|
|
|
2
2
|
checkGenerated,
|
|
3
3
|
findUnusedVars,
|
|
4
4
|
generate
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-PLO2JWR7.js";
|
|
6
6
|
import {
|
|
7
7
|
generateCode,
|
|
8
8
|
generateDeclaration,
|
|
9
9
|
generateJs,
|
|
10
|
+
generateTokens,
|
|
10
11
|
parsePropertyRules,
|
|
12
|
+
parseThemedDeclarations,
|
|
11
13
|
parseVarDeclarations,
|
|
12
14
|
parseVarNames,
|
|
13
15
|
scanCss,
|
|
14
16
|
scanUsedKeys,
|
|
15
17
|
scanVarDeclarations,
|
|
16
18
|
scanVarNames
|
|
17
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-6YWE4A6S.js";
|
|
18
20
|
export {
|
|
19
21
|
checkGenerated,
|
|
20
22
|
findUnusedVars,
|
|
@@ -22,7 +24,9 @@ export {
|
|
|
22
24
|
generateCode,
|
|
23
25
|
generateDeclaration,
|
|
24
26
|
generateJs,
|
|
27
|
+
generateTokens,
|
|
25
28
|
parsePropertyRules,
|
|
29
|
+
parseThemedDeclarations,
|
|
26
30
|
parseVarDeclarations,
|
|
27
31
|
parseVarNames,
|
|
28
32
|
scanCss,
|