css-typed-vars 0.5.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 +152 -5
- package/dist/chunk-6YWE4A6S.js +691 -0
- package/dist/chunk-HBUSLYYB.js +127 -0
- package/dist/chunk-PLO2JWR7.js +88 -0
- package/dist/cli.cjs +480 -57
- package/dist/cli.js +51 -9
- package/dist/esbuild.cjs +433 -60
- 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 +452 -47
- package/dist/index.d.cts +27 -6
- package/dist/index.d.ts +27 -6
- package/dist/index.js +14 -2
- package/dist/rollup.cjs +433 -60
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +433 -60
- package/dist/unplugin.d.cts +17 -1
- package/dist/unplugin.d.ts +17 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +433 -60
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +433 -60
- package/dist/webpack.d.cts +1 -1
- package/dist/webpack.d.ts +1 -1
- package/dist/webpack.js +2 -2
- package/package.json +6 -2
- package/dist/chunk-H3T6RMQQ.js +0 -51
- package/dist/chunk-JDZAH2YQ.js +0 -320
- package/dist/chunk-YBZGHG2G.js +0 -91
- package/dist/generator-t6h8Ic7V.d.cts +0 -6
- package/dist/generator-t6h8Ic7V.d.ts +0 -6
package/dist/unplugin.cjs
CHANGED
|
@@ -157,37 +157,119 @@ function extractValue(text, start) {
|
|
|
157
157
|
}
|
|
158
158
|
return text.slice(start, i).trim();
|
|
159
159
|
}
|
|
160
|
-
function
|
|
161
|
-
const
|
|
162
|
-
const
|
|
163
|
-
|
|
160
|
+
function forEachProperty(block, onProperty) {
|
|
161
|
+
const masked = maskQuotedContent(block);
|
|
162
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
163
|
+
const name = prop[0];
|
|
164
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
165
|
+
onProperty(name, extractValue(block, colonIndex + 1));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
169
|
+
for (const sel of selectors) {
|
|
164
170
|
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
165
171
|
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
166
172
|
let match;
|
|
167
173
|
while (match = openRegex.exec(stripped)) {
|
|
168
174
|
const start = match.index + match[0].length;
|
|
169
175
|
const block = extractBlock(stripped, start);
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
174
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
175
|
-
}
|
|
176
|
-
openRegex.lastIndex = start + block.length + 1;
|
|
176
|
+
const end = start + block.length + 1;
|
|
177
|
+
onBlock(block, [start, end]);
|
|
178
|
+
openRegex.lastIndex = end;
|
|
177
179
|
}
|
|
178
180
|
}
|
|
179
181
|
}
|
|
180
|
-
|
|
182
|
+
var BASE_SELECTORS = [":root", "@theme"];
|
|
183
|
+
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
184
|
+
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
185
|
+
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
186
|
+
forEachProperty(block, onProperty);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
190
|
+
function forEachMediaBlock(stripped, media, onBlock) {
|
|
191
|
+
const wanted = normalizePrelude(media.replace(/^@media/i, ""));
|
|
192
|
+
const openRegex = /@media([^{;]*)\{/gi;
|
|
193
|
+
let match;
|
|
194
|
+
while (match = openRegex.exec(stripped)) {
|
|
195
|
+
const start = match.index + match[0].length;
|
|
196
|
+
const block = extractBlock(stripped, start);
|
|
197
|
+
const end = start + block.length + 1;
|
|
198
|
+
if (normalizePrelude(match[1]) === wanted) {
|
|
199
|
+
onBlock(block, [start, end]);
|
|
200
|
+
openRegex.lastIndex = end;
|
|
201
|
+
} else {
|
|
202
|
+
openRegex.lastIndex = start;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function parseThemedDeclarations(css, selectors, themes) {
|
|
207
|
+
const stripped = stripComments(css);
|
|
208
|
+
const themeValues = /* @__PURE__ */ new Map();
|
|
209
|
+
const skip = [];
|
|
210
|
+
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
211
|
+
const values = /* @__PURE__ */ new Map();
|
|
212
|
+
themeValues.set(themeName, values);
|
|
213
|
+
const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
|
|
214
|
+
const selector = themeSelector.trim();
|
|
215
|
+
if (/^@media\b/i.test(selector)) {
|
|
216
|
+
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
217
|
+
skip.push(range);
|
|
218
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
219
|
+
});
|
|
220
|
+
} else {
|
|
221
|
+
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
222
|
+
skip.push(range);
|
|
223
|
+
collect(block);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
181
227
|
const declarations = /* @__PURE__ */ new Map();
|
|
182
|
-
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
|
|
183
|
-
return declarations;
|
|
228
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
|
|
229
|
+
return { declarations, themes: themeValues };
|
|
230
|
+
}
|
|
231
|
+
var PROPERTY_DESCRIPTORS = [
|
|
232
|
+
["syntax", "syntax"],
|
|
233
|
+
["inherits", "inherits"],
|
|
234
|
+
["initial-value", "initialValue"]
|
|
235
|
+
];
|
|
236
|
+
function parsePropertyRules(css) {
|
|
237
|
+
const stripped = stripComments(css);
|
|
238
|
+
const rules = /* @__PURE__ */ new Map();
|
|
239
|
+
const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
|
|
240
|
+
let match;
|
|
241
|
+
while (match = openRegex.exec(stripped)) {
|
|
242
|
+
const name = match[1];
|
|
243
|
+
const start = match.index + match[0].length;
|
|
244
|
+
const block = extractBlock(stripped, start);
|
|
245
|
+
const masked = maskQuotedContent(block);
|
|
246
|
+
const rule = {};
|
|
247
|
+
for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
|
|
248
|
+
const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
|
|
249
|
+
const descMatch = descRegex.exec(masked);
|
|
250
|
+
if (!descMatch) continue;
|
|
251
|
+
const nameEnd = descMatch.index + descMatch[0].length;
|
|
252
|
+
const colonIndex = block.indexOf(":", nameEnd);
|
|
253
|
+
rule[key] = extractValue(block, colonIndex + 1);
|
|
254
|
+
}
|
|
255
|
+
if (Object.keys(rule).length > 0) rules.set(name, rule);
|
|
256
|
+
openRegex.lastIndex = start + block.length + 1;
|
|
257
|
+
}
|
|
258
|
+
return rules;
|
|
184
259
|
}
|
|
185
260
|
|
|
186
261
|
// src/scanner.ts
|
|
187
262
|
function normalizePatterns(patterns) {
|
|
188
263
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
189
264
|
}
|
|
190
|
-
|
|
265
|
+
function collectVarNames(scanned) {
|
|
266
|
+
const names = new Set(scanned.declarations.keys());
|
|
267
|
+
for (const values of scanned.themes.values()) {
|
|
268
|
+
for (const name of values.keys()) names.add(name);
|
|
269
|
+
}
|
|
270
|
+
return [...names].sort();
|
|
271
|
+
}
|
|
272
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
191
273
|
const normalized = normalizePatterns(patterns);
|
|
192
274
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
193
275
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -198,18 +280,58 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
|
198
280
|
css = await (0, import_promises.readFile)(file, "utf8");
|
|
199
281
|
} catch (err) {
|
|
200
282
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
201
|
-
return
|
|
283
|
+
return null;
|
|
202
284
|
}
|
|
203
|
-
return
|
|
285
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
204
286
|
})
|
|
205
287
|
);
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
288
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
289
|
+
const properties = /* @__PURE__ */ new Map();
|
|
290
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
291
|
+
for (const result of perFile) {
|
|
292
|
+
if (!result) continue;
|
|
293
|
+
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
294
|
+
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
295
|
+
for (const [theme, values] of result.themes) {
|
|
296
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
210
297
|
}
|
|
211
298
|
}
|
|
212
|
-
return
|
|
299
|
+
return { declarations, properties, themes: themeValues };
|
|
300
|
+
}
|
|
301
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
302
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
303
|
+
function readAccess(text, from) {
|
|
304
|
+
ACCESS_RE.lastIndex = from;
|
|
305
|
+
const match = ACCESS_RE.exec(text);
|
|
306
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
307
|
+
}
|
|
308
|
+
function extractUsage(text, into) {
|
|
309
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
310
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
311
|
+
if (!first) continue;
|
|
312
|
+
into.keys.add(first.key);
|
|
313
|
+
const second = readAccess(text, first.end);
|
|
314
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
315
|
+
else into.wholeKeys.add(first.key);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async function scanUsage(patterns, exclude) {
|
|
319
|
+
const normalized = normalizePatterns(patterns);
|
|
320
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
321
|
+
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
322
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
323
|
+
const texts = await Promise.all(
|
|
324
|
+
files.map(async (file) => {
|
|
325
|
+
try {
|
|
326
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
327
|
+
} catch (err) {
|
|
328
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
329
|
+
return "";
|
|
330
|
+
}
|
|
331
|
+
})
|
|
332
|
+
);
|
|
333
|
+
for (const text of texts) extractUsage(text, usage);
|
|
334
|
+
return usage;
|
|
213
335
|
}
|
|
214
336
|
|
|
215
337
|
// src/generator.ts
|
|
@@ -224,10 +346,19 @@ function convertCase(value, naming) {
|
|
|
224
346
|
if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
|
|
225
347
|
return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
|
|
226
348
|
}
|
|
227
|
-
function
|
|
228
|
-
const key = convertCase(
|
|
349
|
+
function toKeyFragment(fragment, naming = "camelCase") {
|
|
350
|
+
const key = convertCase(fragment, naming);
|
|
229
351
|
return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
|
|
230
352
|
}
|
|
353
|
+
function toKey(cssVarName, naming = "camelCase") {
|
|
354
|
+
return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
|
|
355
|
+
}
|
|
356
|
+
function splitGroupKey(cssVarName) {
|
|
357
|
+
const stripped = cssVarName.replace(/^--/, "");
|
|
358
|
+
const dashIndex = stripped.indexOf("-");
|
|
359
|
+
if (dashIndex === -1) return null;
|
|
360
|
+
return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
|
|
361
|
+
}
|
|
231
362
|
var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
|
|
232
363
|
var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
|
|
233
364
|
var SINGLE_QUOTE_ESCAPES = {};
|
|
@@ -260,6 +391,15 @@ function formatKey(key, naming = "camelCase") {
|
|
|
260
391
|
if (naming === "kebab") return `'${key}'`;
|
|
261
392
|
return key;
|
|
262
393
|
}
|
|
394
|
+
function computeKey(cssVarName, prefix, naming) {
|
|
395
|
+
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
396
|
+
}
|
|
397
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
398
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
399
|
+
const split = splitGroupKey(cssVarName);
|
|
400
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
401
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
402
|
+
}
|
|
263
403
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
264
404
|
const byKey = /* @__PURE__ */ new Map();
|
|
265
405
|
for (const name of varNames) {
|
|
@@ -278,43 +418,245 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
278
418
|
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
279
419
|
}
|
|
280
420
|
}
|
|
281
|
-
function
|
|
421
|
+
function entryMeta(name, options) {
|
|
422
|
+
const themes = [];
|
|
423
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
424
|
+
const value = values.get(name);
|
|
425
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
name,
|
|
429
|
+
value: options.declarations?.get(name),
|
|
430
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
431
|
+
...themes.length > 0 ? { themes } : {}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
function buildEntries(varNames, options) {
|
|
435
|
+
const { prefix, naming } = options;
|
|
282
436
|
const byKey = /* @__PURE__ */ new Map();
|
|
283
437
|
for (const name of varNames) {
|
|
284
438
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
285
|
-
byKey.set(key,
|
|
439
|
+
byKey.set(key, entryMeta(name, options));
|
|
286
440
|
}
|
|
287
441
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
288
442
|
}
|
|
289
|
-
function
|
|
290
|
-
|
|
443
|
+
function buildGroupedEntries(varNames, options) {
|
|
444
|
+
const { naming } = options;
|
|
445
|
+
const groupMap = /* @__PURE__ */ new Map();
|
|
446
|
+
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
447
|
+
for (const name of varNames) {
|
|
448
|
+
const meta = entryMeta(name, options);
|
|
449
|
+
const split = splitGroupKey(name);
|
|
450
|
+
if (!split) {
|
|
451
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
455
|
+
const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
|
|
456
|
+
let leafMap = groupMap.get(groupKey);
|
|
457
|
+
if (!leafMap) {
|
|
458
|
+
leafMap = /* @__PURE__ */ new Map();
|
|
459
|
+
groupMap.set(groupKey, leafMap);
|
|
460
|
+
}
|
|
461
|
+
leafMap.set(leafKey, meta);
|
|
462
|
+
}
|
|
463
|
+
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
464
|
+
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
465
|
+
key,
|
|
466
|
+
entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
|
|
467
|
+
}));
|
|
468
|
+
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
469
|
+
return { groups, ungrouped };
|
|
470
|
+
}
|
|
471
|
+
function formatDefaultComment(value, indent = " ") {
|
|
472
|
+
return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
|
|
473
|
+
}
|
|
474
|
+
function unquoteCssString(value) {
|
|
475
|
+
const quote = value[0];
|
|
476
|
+
if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
|
|
477
|
+
return value.slice(1, -1);
|
|
478
|
+
}
|
|
479
|
+
return value;
|
|
480
|
+
}
|
|
481
|
+
function formatSyntaxComment(syntax, indent = " ") {
|
|
482
|
+
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
483
|
+
}
|
|
484
|
+
function formatThemeComment(theme, value, indent = " ") {
|
|
485
|
+
return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
|
|
486
|
+
}
|
|
487
|
+
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
488
|
+
function parseEnumSyntax(syntax) {
|
|
489
|
+
const unquoted = unquoteCssString(syntax).trim();
|
|
490
|
+
if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
|
|
491
|
+
return unquoted.split("|").map((v) => v.trim());
|
|
492
|
+
}
|
|
493
|
+
function syntaxTypeName(cssVarName) {
|
|
494
|
+
const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
|
|
495
|
+
return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
|
|
496
|
+
}
|
|
497
|
+
function buildSyntaxTypes(varNames, properties) {
|
|
498
|
+
if (!properties) return [];
|
|
499
|
+
const byName = /* @__PURE__ */ new Map();
|
|
500
|
+
for (const name of varNames) {
|
|
501
|
+
const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
|
|
502
|
+
if (values) byName.set(syntaxTypeName(name), values);
|
|
503
|
+
}
|
|
504
|
+
return [...byName].map(([name, values]) => ({ name, values }));
|
|
505
|
+
}
|
|
506
|
+
function renderSyntaxTypeLines(types) {
|
|
507
|
+
return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
|
|
291
508
|
}
|
|
292
|
-
function
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
509
|
+
function buildTailBlocks(varNames, group, properties) {
|
|
510
|
+
const blocks = [];
|
|
511
|
+
if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
|
|
512
|
+
const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
|
|
513
|
+
if (syntaxLines.length > 0) blocks.push(syntaxLines);
|
|
514
|
+
return blocks;
|
|
515
|
+
}
|
|
516
|
+
function renderEntryLines(entries, indent, lineFor) {
|
|
517
|
+
return entries.flatMap(({ key, name, value, syntax, themes }) => [
|
|
518
|
+
...value ? [formatDefaultComment(value, indent)] : [],
|
|
519
|
+
...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
|
|
520
|
+
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
521
|
+
`${indent}${lineFor(key, name)}`
|
|
296
522
|
]);
|
|
523
|
+
}
|
|
524
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
525
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
526
|
+
const lines = [];
|
|
527
|
+
for (const group of groups) {
|
|
528
|
+
lines.push(`${indent}${group.key}: {`);
|
|
529
|
+
lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
|
|
530
|
+
lines.push(`${indent}}${closeSuffix}`);
|
|
531
|
+
}
|
|
532
|
+
lines.push(...renderEntryLines(ungrouped, indent, lineFor));
|
|
533
|
+
return lines;
|
|
534
|
+
}
|
|
535
|
+
function assertGroupPrefixCompatible(prefix, group) {
|
|
536
|
+
if (group && prefix) {
|
|
537
|
+
throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
541
|
+
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
542
|
+
function normalizeOptions(args) {
|
|
543
|
+
const [first] = args;
|
|
544
|
+
if (first !== null && typeof first === "object") return first;
|
|
545
|
+
const [prefix, naming, declarations, group, properties] = args;
|
|
546
|
+
return { prefix, naming, declarations, group, properties };
|
|
547
|
+
}
|
|
548
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
549
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
550
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
551
|
+
}
|
|
552
|
+
function emittedNames(varNames, options) {
|
|
553
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
554
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
555
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
556
|
+
}
|
|
557
|
+
function renderRefType(varNames, options) {
|
|
558
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
559
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
560
|
+
}
|
|
561
|
+
var HELPERS_JS = [
|
|
562
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
563
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
564
|
+
"}",
|
|
565
|
+
"",
|
|
566
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
567
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
568
|
+
"}"
|
|
569
|
+
];
|
|
570
|
+
var HELPERS_DTS = [
|
|
571
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
572
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
573
|
+
];
|
|
574
|
+
function generateJs(varNames, ...args) {
|
|
575
|
+
const options = normalizeOptions(args);
|
|
576
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
297
577
|
return [
|
|
298
578
|
"// generated \u2014 do not edit",
|
|
299
579
|
"export const cssVars = {",
|
|
300
580
|
...entries,
|
|
301
581
|
"};",
|
|
582
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
302
583
|
""
|
|
303
584
|
].join("\n");
|
|
304
585
|
}
|
|
305
|
-
function generateDeclaration(varNames,
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
]);
|
|
586
|
+
function generateDeclaration(varNames, ...args) {
|
|
587
|
+
const options = normalizeOptions(args);
|
|
588
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
589
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
590
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
591
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
310
592
|
return [
|
|
311
593
|
"export declare const cssVars: {",
|
|
312
594
|
...entries,
|
|
313
595
|
"};",
|
|
314
|
-
|
|
596
|
+
...tailBody,
|
|
315
597
|
""
|
|
316
598
|
].join("\n");
|
|
317
599
|
}
|
|
600
|
+
var TOKEN_TYPES = {
|
|
601
|
+
"<color>": "color",
|
|
602
|
+
"<length>": "dimension",
|
|
603
|
+
"<length-percentage>": "dimension",
|
|
604
|
+
"<number>": "number",
|
|
605
|
+
"<integer>": "number",
|
|
606
|
+
"<time>": "duration"
|
|
607
|
+
};
|
|
608
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
609
|
+
function generateTokens(varNames, options = {}) {
|
|
610
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
611
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
612
|
+
const meta = entryMeta(name, options);
|
|
613
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
614
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
615
|
+
});
|
|
616
|
+
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
617
|
+
const resolve2 = (value) => {
|
|
618
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
619
|
+
return target ? `{${target.join(".")}}` : value;
|
|
620
|
+
};
|
|
621
|
+
const root = {};
|
|
622
|
+
for (const { meta, value, path } of tokens) {
|
|
623
|
+
const token = { $value: resolve2(value) };
|
|
624
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
625
|
+
if (type) token.$type = type;
|
|
626
|
+
if (meta.themes) {
|
|
627
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
|
|
628
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
629
|
+
}
|
|
630
|
+
const [key, leaf] = path;
|
|
631
|
+
if (leaf === void 0) {
|
|
632
|
+
root[key] = token;
|
|
633
|
+
} else {
|
|
634
|
+
const group = root[key] ?? (root[key] = {});
|
|
635
|
+
group[leaf] = token;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// src/prune.ts
|
|
642
|
+
function assertPruneCompatible(options) {
|
|
643
|
+
if (options.prune && !options.usage) {
|
|
644
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
function isUsed(name, usage, options) {
|
|
648
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
649
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
650
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
651
|
+
}
|
|
652
|
+
function partitionUnused(names, usage, options) {
|
|
653
|
+
const used = [];
|
|
654
|
+
const unused = [];
|
|
655
|
+
for (const name of names) {
|
|
656
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
657
|
+
}
|
|
658
|
+
return { used, unused };
|
|
659
|
+
}
|
|
318
660
|
|
|
319
661
|
// src/unplugin.ts
|
|
320
662
|
var VIRTUAL_ID = "css-typed-vars/vars";
|
|
@@ -323,9 +665,40 @@ function getDtsPath(options) {
|
|
|
323
665
|
if (options.dts === false) return null;
|
|
324
666
|
return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
|
|
325
667
|
}
|
|
668
|
+
function outputFiles(options, names, generatorOptions) {
|
|
669
|
+
const files = [];
|
|
670
|
+
const dtsPath = getDtsPath(options);
|
|
671
|
+
if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
|
|
672
|
+
if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
|
|
673
|
+
return files;
|
|
674
|
+
}
|
|
326
675
|
var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
327
|
-
|
|
328
|
-
|
|
676
|
+
assertPruneCompatible(options);
|
|
677
|
+
let cachedScan = null;
|
|
678
|
+
const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
679
|
+
const applyPrune = async (names) => {
|
|
680
|
+
if (!options.prune) return names;
|
|
681
|
+
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
682
|
+
const { used, unused } = partitionUnused(names, usage, options);
|
|
683
|
+
if (unused.length > 0) {
|
|
684
|
+
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
685
|
+
}
|
|
686
|
+
return used;
|
|
687
|
+
};
|
|
688
|
+
const generatorOptions = ({ declarations, properties, themes }) => ({
|
|
689
|
+
prefix: options.prefix,
|
|
690
|
+
naming: options.naming,
|
|
691
|
+
declarations,
|
|
692
|
+
group: options.group,
|
|
693
|
+
properties,
|
|
694
|
+
helpers: options.helpers,
|
|
695
|
+
themes
|
|
696
|
+
});
|
|
697
|
+
const resolveNames = async (scanned) => {
|
|
698
|
+
const names = collectVarNames(scanned);
|
|
699
|
+
warnOnCollisions(names, options.prefix, options.naming);
|
|
700
|
+
return applyPrune(names);
|
|
701
|
+
};
|
|
329
702
|
return {
|
|
330
703
|
name: "css-typed-vars",
|
|
331
704
|
vite: {
|
|
@@ -336,18 +709,19 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
336
709
|
let writeQueue = Promise.resolve();
|
|
337
710
|
const rescan = async () => {
|
|
338
711
|
const myGeneration = ++generation;
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
const
|
|
712
|
+
const scanPromise = scan();
|
|
713
|
+
cachedScan = scanPromise;
|
|
714
|
+
const scanned = await scanPromise;
|
|
342
715
|
if (myGeneration !== generation) return;
|
|
343
|
-
const names =
|
|
344
|
-
|
|
345
|
-
const
|
|
346
|
-
if (
|
|
347
|
-
const content = generateDeclaration(names, options.prefix, options.naming, declarations);
|
|
716
|
+
const names = await resolveNames(scanned);
|
|
717
|
+
if (myGeneration !== generation) return;
|
|
718
|
+
const files = outputFiles(options, names, generatorOptions(scanned));
|
|
719
|
+
if (files.length > 0) {
|
|
348
720
|
writeQueue = writeQueue.then(async () => {
|
|
349
|
-
|
|
350
|
-
|
|
721
|
+
for (const [path, content] of files) {
|
|
722
|
+
if (myGeneration !== generation) return;
|
|
723
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
724
|
+
}
|
|
351
725
|
}).catch(console.error);
|
|
352
726
|
await writeQueue;
|
|
353
727
|
}
|
|
@@ -372,22 +746,21 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
372
746
|
}
|
|
373
747
|
},
|
|
374
748
|
async buildStart() {
|
|
375
|
-
|
|
376
|
-
const
|
|
377
|
-
const names =
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations), "utf8");
|
|
749
|
+
cachedScan = scan();
|
|
750
|
+
const scanned = await cachedScan;
|
|
751
|
+
const names = await resolveNames(scanned);
|
|
752
|
+
for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
|
|
753
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
754
|
+
}
|
|
382
755
|
},
|
|
383
756
|
resolveId(id) {
|
|
384
757
|
if (id === VIRTUAL_ID) return RESOLVED_ID;
|
|
385
758
|
},
|
|
386
759
|
async load(id) {
|
|
387
760
|
if (id === RESOLVED_ID) {
|
|
388
|
-
const
|
|
389
|
-
const names =
|
|
390
|
-
return generateJs(names,
|
|
761
|
+
const scanned = await (cachedScan ?? scan());
|
|
762
|
+
const names = await applyPrune(collectVarNames(scanned));
|
|
763
|
+
return generateJs(names, generatorOptions(scanned));
|
|
391
764
|
}
|
|
392
765
|
}
|
|
393
766
|
};
|
package/dist/unplugin.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as unplugin from 'unplugin';
|
|
2
|
-
import { N as NamingConvention } from './generator-
|
|
2
|
+
import { N as NamingConvention } from './generator-C1iVNsry.cjs';
|
|
3
3
|
|
|
4
4
|
interface Options {
|
|
5
5
|
input: string | string[];
|
|
@@ -10,10 +10,26 @@ interface Options {
|
|
|
10
10
|
* - `false`: skip writing
|
|
11
11
|
*/
|
|
12
12
|
dts?: string | false;
|
|
13
|
+
/** Also write a W3C design tokens (DTCG) JSON file to this path, relative to project root. */
|
|
14
|
+
tokens?: string;
|
|
13
15
|
exclude?: string | string[];
|
|
14
16
|
prefix?: string;
|
|
15
17
|
naming?: NamingConvention;
|
|
16
18
|
selectors?: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Theme name -> selector (`'[data-theme="dark"]'`) or `@media` prelude
|
|
21
|
+
* (`'@media (prefers-color-scheme: dark)'`). Each theme's values are emitted as
|
|
22
|
+
* `@theme <name> <value>` JSDoc tags, and kept out of the default value.
|
|
23
|
+
*/
|
|
24
|
+
themes?: Record<string, string>;
|
|
25
|
+
group?: boolean;
|
|
26
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
27
|
+
prune?: boolean;
|
|
28
|
+
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
|
|
29
|
+
usage?: string | string[];
|
|
30
|
+
usageExclude?: string | string[];
|
|
31
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
32
|
+
helpers?: boolean;
|
|
17
33
|
}
|
|
18
34
|
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
|
19
35
|
|
package/dist/unplugin.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as unplugin from 'unplugin';
|
|
2
|
-
import { N as NamingConvention } from './generator-
|
|
2
|
+
import { N as NamingConvention } from './generator-C1iVNsry.js';
|
|
3
3
|
|
|
4
4
|
interface Options {
|
|
5
5
|
input: string | string[];
|
|
@@ -10,10 +10,26 @@ interface Options {
|
|
|
10
10
|
* - `false`: skip writing
|
|
11
11
|
*/
|
|
12
12
|
dts?: string | false;
|
|
13
|
+
/** Also write a W3C design tokens (DTCG) JSON file to this path, relative to project root. */
|
|
14
|
+
tokens?: string;
|
|
13
15
|
exclude?: string | string[];
|
|
14
16
|
prefix?: string;
|
|
15
17
|
naming?: NamingConvention;
|
|
16
18
|
selectors?: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Theme name -> selector (`'[data-theme="dark"]'`) or `@media` prelude
|
|
21
|
+
* (`'@media (prefers-color-scheme: dark)'`). Each theme's values are emitted as
|
|
22
|
+
* `@theme <name> <value>` JSDoc tags, and kept out of the default value.
|
|
23
|
+
*/
|
|
24
|
+
themes?: Record<string, string>;
|
|
25
|
+
group?: boolean;
|
|
26
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
27
|
+
prune?: boolean;
|
|
28
|
+
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
|
|
29
|
+
usage?: string | string[];
|
|
30
|
+
usageExclude?: string | string[];
|
|
31
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
32
|
+
helpers?: boolean;
|
|
17
33
|
}
|
|
18
34
|
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
|
19
35
|
|