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/unplugin.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,27 @@ 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
|
+
}
|
|
214
319
|
|
|
215
320
|
// src/scanner.ts
|
|
216
321
|
function normalizePatterns(patterns) {
|
|
217
322
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
218
323
|
}
|
|
219
|
-
|
|
324
|
+
function collectVarNames(scanned) {
|
|
325
|
+
const names = new Set(scanned.declarations.keys());
|
|
326
|
+
for (const values of scanned.themes.values()) {
|
|
327
|
+
for (const name of values.keys()) names.add(name);
|
|
328
|
+
}
|
|
329
|
+
return [...names].sort();
|
|
330
|
+
}
|
|
331
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
220
332
|
const normalized = normalizePatterns(patterns);
|
|
221
333
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
222
334
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -227,48 +339,60 @@ async function scanCss(patterns, exclude, selectors) {
|
|
|
227
339
|
css = await (0, import_promises.readFile)(file, "utf8");
|
|
228
340
|
} catch (err) {
|
|
229
341
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
230
|
-
return
|
|
342
|
+
return null;
|
|
231
343
|
}
|
|
232
|
-
return {
|
|
344
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
233
345
|
})
|
|
234
346
|
);
|
|
235
347
|
const declarations = /* @__PURE__ */ new Map();
|
|
236
348
|
const properties = /* @__PURE__ */ new Map();
|
|
349
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
350
|
+
const docs = /* @__PURE__ */ new Map();
|
|
237
351
|
for (const result of perFile) {
|
|
352
|
+
if (!result) continue;
|
|
238
353
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
239
354
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
355
|
+
for (const [name, doc] of result.docs) docs.set(name, doc);
|
|
356
|
+
for (const [theme, values] of result.themes) {
|
|
357
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
358
|
+
}
|
|
240
359
|
}
|
|
241
|
-
return { declarations, properties };
|
|
242
|
-
}
|
|
243
|
-
var
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
360
|
+
return { declarations, properties, themes: themeValues, docs };
|
|
361
|
+
}
|
|
362
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
363
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
364
|
+
function readAccess(text, from) {
|
|
365
|
+
ACCESS_RE.lastIndex = from;
|
|
366
|
+
const match = ACCESS_RE.exec(text);
|
|
367
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
368
|
+
}
|
|
369
|
+
function extractUsage(text, into) {
|
|
370
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
371
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
372
|
+
if (!first) continue;
|
|
373
|
+
into.keys.add(first.key);
|
|
374
|
+
const second = readAccess(text, first.end);
|
|
375
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
376
|
+
else into.wholeKeys.add(first.key);
|
|
247
377
|
}
|
|
248
378
|
}
|
|
249
|
-
async function
|
|
379
|
+
async function scanUsage(patterns, exclude) {
|
|
250
380
|
const normalized = normalizePatterns(patterns);
|
|
251
381
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
252
382
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
253
|
-
const
|
|
383
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
384
|
+
const texts = await Promise.all(
|
|
254
385
|
files.map(async (file) => {
|
|
255
|
-
const used = /* @__PURE__ */ new Set();
|
|
256
|
-
let text;
|
|
257
386
|
try {
|
|
258
|
-
|
|
387
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
259
388
|
} catch (err) {
|
|
260
389
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
261
|
-
return
|
|
390
|
+
return "";
|
|
262
391
|
}
|
|
263
|
-
extractUsedKeys(text, used);
|
|
264
|
-
return used;
|
|
265
392
|
})
|
|
266
393
|
);
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
for (const key of used) all.add(key);
|
|
270
|
-
}
|
|
271
|
-
return all;
|
|
394
|
+
for (const text of texts) extractUsage(text, usage);
|
|
395
|
+
return usage;
|
|
272
396
|
}
|
|
273
397
|
|
|
274
398
|
// src/generator.ts
|
|
@@ -331,6 +455,12 @@ function formatKey(key, naming = "camelCase") {
|
|
|
331
455
|
function computeKey(cssVarName, prefix, naming) {
|
|
332
456
|
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
333
457
|
}
|
|
458
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
459
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
460
|
+
const split = splitGroupKey(cssVarName);
|
|
461
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
462
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
463
|
+
}
|
|
334
464
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
335
465
|
const byKey = /* @__PURE__ */ new Map();
|
|
336
466
|
for (const name of varNames) {
|
|
@@ -349,23 +479,38 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
349
479
|
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
350
480
|
}
|
|
351
481
|
}
|
|
352
|
-
function
|
|
482
|
+
function entryMeta(name, options) {
|
|
483
|
+
const themes = [];
|
|
484
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
485
|
+
const value = values.get(name);
|
|
486
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
487
|
+
}
|
|
488
|
+
return {
|
|
489
|
+
name,
|
|
490
|
+
value: options.declarations?.get(name),
|
|
491
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
492
|
+
...themes.length > 0 ? { themes } : {},
|
|
493
|
+
...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function buildEntries(varNames, options) {
|
|
497
|
+
const { prefix, naming } = options;
|
|
353
498
|
const byKey = /* @__PURE__ */ new Map();
|
|
354
499
|
for (const name of varNames) {
|
|
355
500
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
356
|
-
byKey.set(key,
|
|
501
|
+
byKey.set(key, entryMeta(name, options));
|
|
357
502
|
}
|
|
358
503
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
359
504
|
}
|
|
360
|
-
function buildGroupedEntries(varNames,
|
|
505
|
+
function buildGroupedEntries(varNames, options) {
|
|
506
|
+
const { naming } = options;
|
|
361
507
|
const groupMap = /* @__PURE__ */ new Map();
|
|
362
508
|
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
363
509
|
for (const name of varNames) {
|
|
364
|
-
const
|
|
365
|
-
const syntax = properties?.get(name)?.syntax;
|
|
510
|
+
const meta = entryMeta(name, options);
|
|
366
511
|
const split = splitGroupKey(name);
|
|
367
512
|
if (!split) {
|
|
368
|
-
ungroupedMap.set(formatKey(toKey(name, naming), naming),
|
|
513
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
369
514
|
continue;
|
|
370
515
|
}
|
|
371
516
|
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
@@ -375,7 +520,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
375
520
|
leafMap = /* @__PURE__ */ new Map();
|
|
376
521
|
groupMap.set(groupKey, leafMap);
|
|
377
522
|
}
|
|
378
|
-
leafMap.set(leafKey,
|
|
523
|
+
leafMap.set(leafKey, meta);
|
|
379
524
|
}
|
|
380
525
|
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
381
526
|
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
@@ -385,8 +530,12 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
385
530
|
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
386
531
|
return { groups, ungrouped };
|
|
387
532
|
}
|
|
388
|
-
|
|
389
|
-
|
|
533
|
+
var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
|
|
534
|
+
function renderJsDoc(tags, indent) {
|
|
535
|
+
if (tags.length === 0) return [];
|
|
536
|
+
if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
|
|
537
|
+
const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
|
|
538
|
+
return [`${indent}/**`, ...body, `${indent} */`];
|
|
390
539
|
}
|
|
391
540
|
function unquoteCssString(value) {
|
|
392
541
|
const quote = value[0];
|
|
@@ -395,8 +544,15 @@ function unquoteCssString(value) {
|
|
|
395
544
|
}
|
|
396
545
|
return value;
|
|
397
546
|
}
|
|
398
|
-
function
|
|
399
|
-
|
|
547
|
+
function entryTags({ value, syntax, themes, doc }) {
|
|
548
|
+
const deprecated = doc?.deprecated;
|
|
549
|
+
return [
|
|
550
|
+
...doc?.description ? [doc.description] : [],
|
|
551
|
+
...value ? [`@default ${value}`] : [],
|
|
552
|
+
...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
|
|
553
|
+
...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
|
|
554
|
+
...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
|
|
555
|
+
];
|
|
400
556
|
}
|
|
401
557
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
402
558
|
function parseEnumSyntax(syntax) {
|
|
@@ -428,14 +584,13 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
428
584
|
return blocks;
|
|
429
585
|
}
|
|
430
586
|
function renderEntryLines(entries, indent, lineFor) {
|
|
431
|
-
return entries.flatMap((
|
|
432
|
-
...
|
|
433
|
-
|
|
434
|
-
`${indent}${lineFor(key, name)}`
|
|
587
|
+
return entries.flatMap((entry) => [
|
|
588
|
+
...renderJsDoc(entryTags(entry), indent),
|
|
589
|
+
`${indent}${lineFor(entry.key, entry.name)}`
|
|
435
590
|
]);
|
|
436
591
|
}
|
|
437
|
-
function renderGroupedBlock(varNames,
|
|
438
|
-
const { groups, ungrouped } = buildGroupedEntries(varNames,
|
|
592
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
593
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
439
594
|
const lines = [];
|
|
440
595
|
for (const group of groups) {
|
|
441
596
|
lines.push(`${indent}${group.key}: {`);
|
|
@@ -452,21 +607,61 @@ function assertGroupPrefixCompatible(prefix, group) {
|
|
|
452
607
|
}
|
|
453
608
|
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
454
609
|
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
455
|
-
function
|
|
456
|
-
|
|
457
|
-
|
|
610
|
+
function normalizeOptions(args) {
|
|
611
|
+
const [first] = args;
|
|
612
|
+
if (first !== null && typeof first === "object") return first;
|
|
613
|
+
const [prefix, naming, declarations, group, properties] = args;
|
|
614
|
+
return { prefix, naming, declarations, group, properties };
|
|
615
|
+
}
|
|
616
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
617
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
618
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
619
|
+
}
|
|
620
|
+
function emittedNames(varNames, options) {
|
|
621
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
622
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
623
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
624
|
+
}
|
|
625
|
+
function renderRefType(varNames, options) {
|
|
626
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
627
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
628
|
+
}
|
|
629
|
+
var HELPERS_JS = [
|
|
630
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
631
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
632
|
+
"}",
|
|
633
|
+
"",
|
|
634
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
635
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
636
|
+
"}",
|
|
637
|
+
"",
|
|
638
|
+
"export function withFallback(ref, fallback) {",
|
|
639
|
+
" return `${ref.slice(0, -1)}, ${fallback})`;",
|
|
640
|
+
"}"
|
|
641
|
+
];
|
|
642
|
+
var HELPERS_DTS = [
|
|
643
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
644
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
|
|
645
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
646
|
+
"export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
|
|
647
|
+
];
|
|
648
|
+
function generateJs(varNames, ...args) {
|
|
649
|
+
const options = normalizeOptions(args);
|
|
650
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
458
651
|
return [
|
|
459
652
|
"// generated \u2014 do not edit",
|
|
460
653
|
"export const cssVars = {",
|
|
461
654
|
...entries,
|
|
462
655
|
"};",
|
|
656
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
463
657
|
""
|
|
464
658
|
].join("\n");
|
|
465
659
|
}
|
|
466
|
-
function generateDeclaration(varNames,
|
|
467
|
-
|
|
468
|
-
const entries =
|
|
469
|
-
const blocks = buildTailBlocks(varNames, group, properties);
|
|
660
|
+
function generateDeclaration(varNames, ...args) {
|
|
661
|
+
const options = normalizeOptions(args);
|
|
662
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
663
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
664
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
470
665
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
471
666
|
return [
|
|
472
667
|
"export declare const cssVars: {",
|
|
@@ -476,6 +671,68 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
|
|
|
476
671
|
""
|
|
477
672
|
].join("\n");
|
|
478
673
|
}
|
|
674
|
+
var TOKEN_TYPES = {
|
|
675
|
+
"<color>": "color",
|
|
676
|
+
"<length>": "dimension",
|
|
677
|
+
"<length-percentage>": "dimension",
|
|
678
|
+
"<number>": "number",
|
|
679
|
+
"<integer>": "number",
|
|
680
|
+
"<time>": "duration"
|
|
681
|
+
};
|
|
682
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
683
|
+
function generateTokens(varNames, options = {}) {
|
|
684
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
685
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
686
|
+
const meta = entryMeta(name, options);
|
|
687
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
688
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
689
|
+
});
|
|
690
|
+
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
691
|
+
const resolve2 = (value) => {
|
|
692
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
693
|
+
return target ? `{${target.join(".")}}` : value;
|
|
694
|
+
};
|
|
695
|
+
const root = {};
|
|
696
|
+
for (const { meta, value, path } of tokens) {
|
|
697
|
+
const token = { $value: resolve2(value) };
|
|
698
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
699
|
+
if (type) token.$type = type;
|
|
700
|
+
if (meta.doc?.description) token.$description = meta.doc.description;
|
|
701
|
+
if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
|
|
702
|
+
if (meta.themes) {
|
|
703
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
|
|
704
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
705
|
+
}
|
|
706
|
+
const [key, leaf] = path;
|
|
707
|
+
if (leaf === void 0) {
|
|
708
|
+
root[key] = token;
|
|
709
|
+
} else {
|
|
710
|
+
const group = root[key] ?? (root[key] = {});
|
|
711
|
+
group[leaf] = token;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// src/prune.ts
|
|
718
|
+
function assertPruneCompatible(options) {
|
|
719
|
+
if (options.prune && !options.usage) {
|
|
720
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
function isUsed(name, usage, options) {
|
|
724
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
725
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
726
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
727
|
+
}
|
|
728
|
+
function partitionUnused(names, usage, options) {
|
|
729
|
+
const used = [];
|
|
730
|
+
const unused = [];
|
|
731
|
+
for (const name of names) {
|
|
732
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
733
|
+
}
|
|
734
|
+
return { used, unused };
|
|
735
|
+
}
|
|
479
736
|
|
|
480
737
|
// src/unplugin.ts
|
|
481
738
|
var VIRTUAL_ID = "css-typed-vars/vars";
|
|
@@ -484,25 +741,38 @@ function getDtsPath(options) {
|
|
|
484
741
|
if (options.dts === false) return null;
|
|
485
742
|
return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
|
|
486
743
|
}
|
|
744
|
+
function outputFiles(options, names, generatorOptions) {
|
|
745
|
+
const files = [];
|
|
746
|
+
const dtsPath = getDtsPath(options);
|
|
747
|
+
if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
|
|
748
|
+
if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
|
|
749
|
+
return files;
|
|
750
|
+
}
|
|
487
751
|
var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
488
|
-
|
|
489
|
-
if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
|
|
490
|
-
if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
491
|
-
}
|
|
752
|
+
assertPruneCompatible(options);
|
|
492
753
|
let cachedScan = null;
|
|
493
|
-
const scan = () => scanCss(options.input, options.exclude, options.selectors);
|
|
754
|
+
const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
494
755
|
const applyPrune = async (names) => {
|
|
495
756
|
if (!options.prune) return names;
|
|
496
|
-
const
|
|
497
|
-
const
|
|
498
|
-
const unused = names.filter((name) => !isUsed(name));
|
|
757
|
+
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
758
|
+
const { used, unused } = partitionUnused(names, usage, options);
|
|
499
759
|
if (unused.length > 0) {
|
|
500
760
|
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
501
761
|
}
|
|
502
|
-
return
|
|
762
|
+
return used;
|
|
503
763
|
};
|
|
504
|
-
const
|
|
505
|
-
|
|
764
|
+
const generatorOptions = ({ declarations, properties, themes, docs }) => ({
|
|
765
|
+
prefix: options.prefix,
|
|
766
|
+
naming: options.naming,
|
|
767
|
+
declarations,
|
|
768
|
+
group: options.group,
|
|
769
|
+
properties,
|
|
770
|
+
helpers: options.helpers,
|
|
771
|
+
themes,
|
|
772
|
+
docs
|
|
773
|
+
});
|
|
774
|
+
const resolveNames = async (scanned) => {
|
|
775
|
+
const names = collectVarNames(scanned);
|
|
506
776
|
warnOnCollisions(names, options.prefix, options.naming);
|
|
507
777
|
return applyPrune(names);
|
|
508
778
|
};
|
|
@@ -518,16 +788,17 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
518
788
|
const myGeneration = ++generation;
|
|
519
789
|
const scanPromise = scan();
|
|
520
790
|
cachedScan = scanPromise;
|
|
521
|
-
const
|
|
791
|
+
const scanned = await scanPromise;
|
|
522
792
|
if (myGeneration !== generation) return;
|
|
523
|
-
const names = await resolveNames(
|
|
793
|
+
const names = await resolveNames(scanned);
|
|
524
794
|
if (myGeneration !== generation) return;
|
|
525
|
-
const
|
|
526
|
-
if (
|
|
527
|
-
const content = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
|
|
795
|
+
const files = outputFiles(options, names, generatorOptions(scanned));
|
|
796
|
+
if (files.length > 0) {
|
|
528
797
|
writeQueue = writeQueue.then(async () => {
|
|
529
|
-
|
|
530
|
-
|
|
798
|
+
for (const [path, content] of files) {
|
|
799
|
+
if (myGeneration !== generation) return;
|
|
800
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
801
|
+
}
|
|
531
802
|
}).catch(console.error);
|
|
532
803
|
await writeQueue;
|
|
533
804
|
}
|
|
@@ -553,20 +824,20 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
553
824
|
},
|
|
554
825
|
async buildStart() {
|
|
555
826
|
cachedScan = scan();
|
|
556
|
-
const
|
|
557
|
-
const names = await resolveNames(
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
|
|
827
|
+
const scanned = await cachedScan;
|
|
828
|
+
const names = await resolveNames(scanned);
|
|
829
|
+
for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
|
|
830
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
831
|
+
}
|
|
561
832
|
},
|
|
562
833
|
resolveId(id) {
|
|
563
834
|
if (id === VIRTUAL_ID) return RESOLVED_ID;
|
|
564
835
|
},
|
|
565
836
|
async load(id) {
|
|
566
837
|
if (id === RESOLVED_ID) {
|
|
567
|
-
const
|
|
568
|
-
const names = await applyPrune(
|
|
569
|
-
return generateJs(names,
|
|
838
|
+
const scanned = await (cachedScan ?? scan());
|
|
839
|
+
const names = await applyPrune(collectVarNames(scanned));
|
|
840
|
+
return generateJs(names, generatorOptions(scanned));
|
|
570
841
|
}
|
|
571
842
|
}
|
|
572
843
|
};
|
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-DJ9uOYBP.cjs';
|
|
3
3
|
|
|
4
4
|
interface Options {
|
|
5
5
|
input: string | string[];
|
|
@@ -10,16 +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>;
|
|
17
25
|
group?: boolean;
|
|
18
|
-
/** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage
|
|
26
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
19
27
|
prune?: boolean;
|
|
20
28
|
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
|
|
21
29
|
usage?: string | string[];
|
|
22
30
|
usageExclude?: string | string[];
|
|
31
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
32
|
+
helpers?: boolean;
|
|
23
33
|
}
|
|
24
34
|
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
|
25
35
|
|