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
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
// node_modules/tsup/assets/esm_shims.js
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
var getFilename = () => fileURLToPath(import.meta.url);
|
|
5
|
+
var getDirname = () => path.dirname(getFilename());
|
|
6
|
+
var __dirname = /* @__PURE__ */ getDirname();
|
|
7
|
+
|
|
8
|
+
// src/parser.ts
|
|
9
|
+
function stepQuote(text, i, quote) {
|
|
10
|
+
const char = text[i];
|
|
11
|
+
if (char === "\\" && i + 1 < text.length) return { consumed: 2, closed: false };
|
|
12
|
+
if (char === quote) return { consumed: 1, closed: true };
|
|
13
|
+
return { consumed: 1, closed: false };
|
|
14
|
+
}
|
|
15
|
+
function stripComments(text) {
|
|
16
|
+
let result = "";
|
|
17
|
+
let quote = null;
|
|
18
|
+
let urlDepth = 0;
|
|
19
|
+
for (let i = 0; i < text.length; i++) {
|
|
20
|
+
const char = text[i];
|
|
21
|
+
if (quote) {
|
|
22
|
+
const step = stepQuote(text, i, quote);
|
|
23
|
+
result += text.slice(i, i + step.consumed);
|
|
24
|
+
if (step.closed) quote = null;
|
|
25
|
+
i += step.consumed - 1;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (char === '"' || char === "'") {
|
|
29
|
+
quote = char;
|
|
30
|
+
result += char;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (urlDepth > 0) {
|
|
34
|
+
if (char === "(") urlDepth++;
|
|
35
|
+
else if (char === ")") urlDepth--;
|
|
36
|
+
result += char;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (char === "(" && result.slice(-3).toLowerCase() === "url") {
|
|
40
|
+
urlDepth = 1;
|
|
41
|
+
result += char;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (char === "/" && text[i + 1] === "*") {
|
|
45
|
+
const end = text.indexOf("*/", i + 2);
|
|
46
|
+
if (end === -1) {
|
|
47
|
+
result += char;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
i = end + 1;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
|
|
54
|
+
const nl = text.indexOf("\n", i);
|
|
55
|
+
i = nl === -1 ? text.length - 1 : nl - 1;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
result += char;
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
function extractBlock(text, start) {
|
|
63
|
+
let depth = 1;
|
|
64
|
+
let quote = null;
|
|
65
|
+
let i = start;
|
|
66
|
+
for (; i < text.length && depth > 0; i++) {
|
|
67
|
+
const char = text[i];
|
|
68
|
+
if (quote) {
|
|
69
|
+
const step = stepQuote(text, i, quote);
|
|
70
|
+
if (step.closed) quote = null;
|
|
71
|
+
i += step.consumed - 1;
|
|
72
|
+
} else if (char === '"' || char === "'") {
|
|
73
|
+
quote = char;
|
|
74
|
+
} else if (char === "{") {
|
|
75
|
+
depth++;
|
|
76
|
+
} else if (char === "}") {
|
|
77
|
+
depth--;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return text.slice(start, depth === 0 ? i - 1 : i);
|
|
81
|
+
}
|
|
82
|
+
function maskQuotedContent(text) {
|
|
83
|
+
let result = "";
|
|
84
|
+
let quote = null;
|
|
85
|
+
for (let i = 0; i < text.length; i++) {
|
|
86
|
+
const char = text[i];
|
|
87
|
+
if (quote) {
|
|
88
|
+
const step = stepQuote(text, i, quote);
|
|
89
|
+
if (step.closed) {
|
|
90
|
+
result += char;
|
|
91
|
+
quote = null;
|
|
92
|
+
} else {
|
|
93
|
+
result += " ".repeat(step.consumed);
|
|
94
|
+
}
|
|
95
|
+
i += step.consumed - 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (char === '"' || char === "'") {
|
|
99
|
+
quote = char;
|
|
100
|
+
}
|
|
101
|
+
result += char;
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
function extractValue(text, start) {
|
|
106
|
+
let i = start;
|
|
107
|
+
let quote = null;
|
|
108
|
+
for (; i < text.length; i++) {
|
|
109
|
+
const char = text[i];
|
|
110
|
+
if (quote) {
|
|
111
|
+
const step = stepQuote(text, i, quote);
|
|
112
|
+
if (step.closed) quote = null;
|
|
113
|
+
i += step.consumed - 1;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (char === '"' || char === "'") {
|
|
117
|
+
quote = char;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (char === ";" || char === "}") break;
|
|
121
|
+
}
|
|
122
|
+
return text.slice(start, i).trim();
|
|
123
|
+
}
|
|
124
|
+
function forEachProperty(block, onProperty) {
|
|
125
|
+
const masked = maskQuotedContent(block);
|
|
126
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
127
|
+
const name = prop[0];
|
|
128
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
129
|
+
onProperty(name, extractValue(block, colonIndex + 1));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
133
|
+
for (const sel of selectors) {
|
|
134
|
+
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
135
|
+
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
136
|
+
let match;
|
|
137
|
+
while (match = openRegex.exec(stripped)) {
|
|
138
|
+
const start = match.index + match[0].length;
|
|
139
|
+
const block = extractBlock(stripped, start);
|
|
140
|
+
const end = start + block.length + 1;
|
|
141
|
+
onBlock(block, [start, end]);
|
|
142
|
+
openRegex.lastIndex = end;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
var BASE_SELECTORS = [":root", "@theme"];
|
|
147
|
+
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
148
|
+
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
149
|
+
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
150
|
+
forEachProperty(block, onProperty);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function parseVarNames(css, selectors) {
|
|
154
|
+
const names = /* @__PURE__ */ new Set();
|
|
155
|
+
scanDeclarations(css, selectors, (name) => names.add(name));
|
|
156
|
+
return [...names];
|
|
157
|
+
}
|
|
158
|
+
function parseVarDeclarations(css, selectors) {
|
|
159
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
160
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
|
|
161
|
+
return declarations;
|
|
162
|
+
}
|
|
163
|
+
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
164
|
+
function forEachMediaBlock(stripped, media, onBlock) {
|
|
165
|
+
const wanted = normalizePrelude(media.replace(/^@media/i, ""));
|
|
166
|
+
const openRegex = /@media([^{;]*)\{/gi;
|
|
167
|
+
let match;
|
|
168
|
+
while (match = openRegex.exec(stripped)) {
|
|
169
|
+
const start = match.index + match[0].length;
|
|
170
|
+
const block = extractBlock(stripped, start);
|
|
171
|
+
const end = start + block.length + 1;
|
|
172
|
+
if (normalizePrelude(match[1]) === wanted) {
|
|
173
|
+
onBlock(block, [start, end]);
|
|
174
|
+
openRegex.lastIndex = end;
|
|
175
|
+
} else {
|
|
176
|
+
openRegex.lastIndex = start;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function parseThemedDeclarations(css, selectors, themes) {
|
|
181
|
+
const stripped = stripComments(css);
|
|
182
|
+
const themeValues = /* @__PURE__ */ new Map();
|
|
183
|
+
const skip = [];
|
|
184
|
+
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
185
|
+
const values = /* @__PURE__ */ new Map();
|
|
186
|
+
themeValues.set(themeName, values);
|
|
187
|
+
const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
|
|
188
|
+
const selector = themeSelector.trim();
|
|
189
|
+
if (/^@media\b/i.test(selector)) {
|
|
190
|
+
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
191
|
+
skip.push(range);
|
|
192
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
193
|
+
});
|
|
194
|
+
} else {
|
|
195
|
+
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
196
|
+
skip.push(range);
|
|
197
|
+
collect(block);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
202
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
|
|
203
|
+
return { declarations, themes: themeValues };
|
|
204
|
+
}
|
|
205
|
+
var PROPERTY_DESCRIPTORS = [
|
|
206
|
+
["syntax", "syntax"],
|
|
207
|
+
["inherits", "inherits"],
|
|
208
|
+
["initial-value", "initialValue"]
|
|
209
|
+
];
|
|
210
|
+
function parsePropertyRules(css) {
|
|
211
|
+
const stripped = stripComments(css);
|
|
212
|
+
const rules = /* @__PURE__ */ new Map();
|
|
213
|
+
const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
|
|
214
|
+
let match;
|
|
215
|
+
while (match = openRegex.exec(stripped)) {
|
|
216
|
+
const name = match[1];
|
|
217
|
+
const start = match.index + match[0].length;
|
|
218
|
+
const block = extractBlock(stripped, start);
|
|
219
|
+
const masked = maskQuotedContent(block);
|
|
220
|
+
const rule = {};
|
|
221
|
+
for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
|
|
222
|
+
const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
|
|
223
|
+
const descMatch = descRegex.exec(masked);
|
|
224
|
+
if (!descMatch) continue;
|
|
225
|
+
const nameEnd = descMatch.index + descMatch[0].length;
|
|
226
|
+
const colonIndex = block.indexOf(":", nameEnd);
|
|
227
|
+
rule[key] = extractValue(block, colonIndex + 1);
|
|
228
|
+
}
|
|
229
|
+
if (Object.keys(rule).length > 0) rules.set(name, rule);
|
|
230
|
+
openRegex.lastIndex = start + block.length + 1;
|
|
231
|
+
}
|
|
232
|
+
return rules;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/scanner.ts
|
|
236
|
+
import { readFile } from "fs/promises";
|
|
237
|
+
import fg from "fast-glob";
|
|
238
|
+
function normalizePatterns(patterns) {
|
|
239
|
+
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
240
|
+
}
|
|
241
|
+
function collectVarNames(scanned) {
|
|
242
|
+
const names = new Set(scanned.declarations.keys());
|
|
243
|
+
for (const values of scanned.themes.values()) {
|
|
244
|
+
for (const name of values.keys()) names.add(name);
|
|
245
|
+
}
|
|
246
|
+
return [...names].sort();
|
|
247
|
+
}
|
|
248
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
249
|
+
const normalized = normalizePatterns(patterns);
|
|
250
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
251
|
+
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
252
|
+
const perFile = await Promise.all(
|
|
253
|
+
files.map(async (file) => {
|
|
254
|
+
let css;
|
|
255
|
+
try {
|
|
256
|
+
css = await readFile(file, "utf8");
|
|
257
|
+
} catch (err) {
|
|
258
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
262
|
+
})
|
|
263
|
+
);
|
|
264
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
265
|
+
const properties = /* @__PURE__ */ new Map();
|
|
266
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
267
|
+
for (const result of perFile) {
|
|
268
|
+
if (!result) continue;
|
|
269
|
+
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
270
|
+
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
271
|
+
for (const [theme, values] of result.themes) {
|
|
272
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return { declarations, properties, themes: themeValues };
|
|
276
|
+
}
|
|
277
|
+
async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
278
|
+
return (await scanCss(patterns, exclude, selectors)).declarations;
|
|
279
|
+
}
|
|
280
|
+
async function scanVarNames(patterns, exclude, selectors) {
|
|
281
|
+
const declarations = await scanVarDeclarations(patterns, exclude, selectors);
|
|
282
|
+
return [...declarations.keys()].sort();
|
|
283
|
+
}
|
|
284
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
285
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
286
|
+
function readAccess(text, from) {
|
|
287
|
+
ACCESS_RE.lastIndex = from;
|
|
288
|
+
const match = ACCESS_RE.exec(text);
|
|
289
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
290
|
+
}
|
|
291
|
+
function extractUsage(text, into) {
|
|
292
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
293
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
294
|
+
if (!first) continue;
|
|
295
|
+
into.keys.add(first.key);
|
|
296
|
+
const second = readAccess(text, first.end);
|
|
297
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
298
|
+
else into.wholeKeys.add(first.key);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async function scanUsage(patterns, exclude) {
|
|
302
|
+
const normalized = normalizePatterns(patterns);
|
|
303
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
304
|
+
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
305
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
306
|
+
const texts = await Promise.all(
|
|
307
|
+
files.map(async (file) => {
|
|
308
|
+
try {
|
|
309
|
+
return await readFile(file, "utf8");
|
|
310
|
+
} catch (err) {
|
|
311
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
312
|
+
return "";
|
|
313
|
+
}
|
|
314
|
+
})
|
|
315
|
+
);
|
|
316
|
+
for (const text of texts) extractUsage(text, usage);
|
|
317
|
+
return usage;
|
|
318
|
+
}
|
|
319
|
+
async function scanUsedKeys(patterns, exclude) {
|
|
320
|
+
return (await scanUsage(patterns, exclude)).keys;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/generator.ts
|
|
324
|
+
var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
|
|
325
|
+
function convertCase(value, naming) {
|
|
326
|
+
if (!VALID_NAMINGS.includes(naming)) {
|
|
327
|
+
throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
328
|
+
}
|
|
329
|
+
if (naming === "kebab") return value;
|
|
330
|
+
if (naming === "snake") return value.replace(/-+/g, "_");
|
|
331
|
+
if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
|
|
332
|
+
if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
|
|
333
|
+
return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
|
|
334
|
+
}
|
|
335
|
+
function toKeyFragment(fragment, naming = "camelCase") {
|
|
336
|
+
const key = convertCase(fragment, naming);
|
|
337
|
+
return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
|
|
338
|
+
}
|
|
339
|
+
function toKey(cssVarName, naming = "camelCase") {
|
|
340
|
+
return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
|
|
341
|
+
}
|
|
342
|
+
function splitGroupKey(cssVarName) {
|
|
343
|
+
const stripped = cssVarName.replace(/^--/, "");
|
|
344
|
+
const dashIndex = stripped.indexOf("-");
|
|
345
|
+
if (dashIndex === -1) return null;
|
|
346
|
+
return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
|
|
347
|
+
}
|
|
348
|
+
var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
|
|
349
|
+
var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
|
|
350
|
+
var SINGLE_QUOTE_ESCAPES = {};
|
|
351
|
+
SINGLE_QUOTE_ESCAPES["\\"] = "\\\\";
|
|
352
|
+
SINGLE_QUOTE_ESCAPES["'"] = "\\'";
|
|
353
|
+
SINGLE_QUOTE_ESCAPES["\n"] = "\\n";
|
|
354
|
+
SINGLE_QUOTE_ESCAPES["\r"] = "\\r";
|
|
355
|
+
SINGLE_QUOTE_ESCAPES[LINE_SEPARATOR_CHAR] = "\\u2028";
|
|
356
|
+
SINGLE_QUOTE_ESCAPES[PARAGRAPH_SEPARATOR_CHAR] = "\\u2029";
|
|
357
|
+
function escapeSingleQuoted(value) {
|
|
358
|
+
let result = "";
|
|
359
|
+
for (const char of value) {
|
|
360
|
+
result += SINGLE_QUOTE_ESCAPES[char] ?? char;
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
}
|
|
364
|
+
function applyPrefix(key, prefix, naming = "camelCase") {
|
|
365
|
+
if (!prefix) return key;
|
|
366
|
+
let normalizedPrefix = convertCase(prefix, naming);
|
|
367
|
+
if (naming === "kebab") {
|
|
368
|
+
normalizedPrefix = escapeSingleQuoted(normalizedPrefix);
|
|
369
|
+
return `${normalizedPrefix}-${key}`;
|
|
370
|
+
}
|
|
371
|
+
normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
|
|
372
|
+
if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
|
|
373
|
+
if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
|
|
374
|
+
return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
|
|
375
|
+
}
|
|
376
|
+
function formatKey(key, naming = "camelCase") {
|
|
377
|
+
if (naming === "kebab") return `'${key}'`;
|
|
378
|
+
return key;
|
|
379
|
+
}
|
|
380
|
+
function computeKey(cssVarName, prefix, naming) {
|
|
381
|
+
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
382
|
+
}
|
|
383
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
384
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
385
|
+
const split = splitGroupKey(cssVarName);
|
|
386
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
387
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
388
|
+
}
|
|
389
|
+
function findKeyCollisions(varNames, prefix, naming) {
|
|
390
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
391
|
+
for (const name of varNames) {
|
|
392
|
+
const key = applyPrefix(toKey(name, naming), prefix, naming);
|
|
393
|
+
const existing = byKey.get(key);
|
|
394
|
+
if (existing) existing.push(name);
|
|
395
|
+
else byKey.set(key, [name]);
|
|
396
|
+
}
|
|
397
|
+
for (const [key, names] of byKey) {
|
|
398
|
+
if (names.length < 2) byKey.delete(key);
|
|
399
|
+
}
|
|
400
|
+
return byKey;
|
|
401
|
+
}
|
|
402
|
+
function warnOnCollisions(varNames, prefix, naming) {
|
|
403
|
+
for (const [key, vars] of findKeyCollisions(varNames, prefix, naming)) {
|
|
404
|
+
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function entryMeta(name, options) {
|
|
408
|
+
const themes = [];
|
|
409
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
410
|
+
const value = values.get(name);
|
|
411
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
name,
|
|
415
|
+
value: options.declarations?.get(name),
|
|
416
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
417
|
+
...themes.length > 0 ? { themes } : {}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function buildEntries(varNames, options) {
|
|
421
|
+
const { prefix, naming } = options;
|
|
422
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
423
|
+
for (const name of varNames) {
|
|
424
|
+
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
425
|
+
byKey.set(key, entryMeta(name, options));
|
|
426
|
+
}
|
|
427
|
+
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
428
|
+
}
|
|
429
|
+
function buildGroupedEntries(varNames, options) {
|
|
430
|
+
const { naming } = options;
|
|
431
|
+
const groupMap = /* @__PURE__ */ new Map();
|
|
432
|
+
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
433
|
+
for (const name of varNames) {
|
|
434
|
+
const meta = entryMeta(name, options);
|
|
435
|
+
const split = splitGroupKey(name);
|
|
436
|
+
if (!split) {
|
|
437
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
441
|
+
const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
|
|
442
|
+
let leafMap = groupMap.get(groupKey);
|
|
443
|
+
if (!leafMap) {
|
|
444
|
+
leafMap = /* @__PURE__ */ new Map();
|
|
445
|
+
groupMap.set(groupKey, leafMap);
|
|
446
|
+
}
|
|
447
|
+
leafMap.set(leafKey, meta);
|
|
448
|
+
}
|
|
449
|
+
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
450
|
+
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
451
|
+
key,
|
|
452
|
+
entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
|
|
453
|
+
}));
|
|
454
|
+
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
455
|
+
return { groups, ungrouped };
|
|
456
|
+
}
|
|
457
|
+
function formatDefaultComment(value, indent = " ") {
|
|
458
|
+
return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
|
|
459
|
+
}
|
|
460
|
+
function unquoteCssString(value) {
|
|
461
|
+
const quote = value[0];
|
|
462
|
+
if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
|
|
463
|
+
return value.slice(1, -1);
|
|
464
|
+
}
|
|
465
|
+
return value;
|
|
466
|
+
}
|
|
467
|
+
function formatSyntaxComment(syntax, indent = " ") {
|
|
468
|
+
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
469
|
+
}
|
|
470
|
+
function formatThemeComment(theme, value, indent = " ") {
|
|
471
|
+
return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
|
|
472
|
+
}
|
|
473
|
+
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
474
|
+
function parseEnumSyntax(syntax) {
|
|
475
|
+
const unquoted = unquoteCssString(syntax).trim();
|
|
476
|
+
if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
|
|
477
|
+
return unquoted.split("|").map((v) => v.trim());
|
|
478
|
+
}
|
|
479
|
+
function syntaxTypeName(cssVarName) {
|
|
480
|
+
const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
|
|
481
|
+
return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
|
|
482
|
+
}
|
|
483
|
+
function buildSyntaxTypes(varNames, properties) {
|
|
484
|
+
if (!properties) return [];
|
|
485
|
+
const byName = /* @__PURE__ */ new Map();
|
|
486
|
+
for (const name of varNames) {
|
|
487
|
+
const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
|
|
488
|
+
if (values) byName.set(syntaxTypeName(name), values);
|
|
489
|
+
}
|
|
490
|
+
return [...byName].map(([name, values]) => ({ name, values }));
|
|
491
|
+
}
|
|
492
|
+
function renderSyntaxTypeLines(types) {
|
|
493
|
+
return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
|
|
494
|
+
}
|
|
495
|
+
function buildTailBlocks(varNames, group, properties) {
|
|
496
|
+
const blocks = [];
|
|
497
|
+
if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
|
|
498
|
+
const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
|
|
499
|
+
if (syntaxLines.length > 0) blocks.push(syntaxLines);
|
|
500
|
+
return blocks;
|
|
501
|
+
}
|
|
502
|
+
function renderEntryLines(entries, indent, lineFor) {
|
|
503
|
+
return entries.flatMap(({ key, name, value, syntax, themes }) => [
|
|
504
|
+
...value ? [formatDefaultComment(value, indent)] : [],
|
|
505
|
+
...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
|
|
506
|
+
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
507
|
+
`${indent}${lineFor(key, name)}`
|
|
508
|
+
]);
|
|
509
|
+
}
|
|
510
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
511
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
512
|
+
const lines = [];
|
|
513
|
+
for (const group of groups) {
|
|
514
|
+
lines.push(`${indent}${group.key}: {`);
|
|
515
|
+
lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
|
|
516
|
+
lines.push(`${indent}}${closeSuffix}`);
|
|
517
|
+
}
|
|
518
|
+
lines.push(...renderEntryLines(ungrouped, indent, lineFor));
|
|
519
|
+
return lines;
|
|
520
|
+
}
|
|
521
|
+
function assertGroupPrefixCompatible(prefix, group) {
|
|
522
|
+
if (group && prefix) {
|
|
523
|
+
throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
527
|
+
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
528
|
+
function normalizeOptions(args) {
|
|
529
|
+
const [first] = args;
|
|
530
|
+
if (first !== null && typeof first === "object") return first;
|
|
531
|
+
const [prefix, naming, declarations, group, properties] = args;
|
|
532
|
+
return { prefix, naming, declarations, group, properties };
|
|
533
|
+
}
|
|
534
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
535
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
536
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
537
|
+
}
|
|
538
|
+
function emittedNames(varNames, options) {
|
|
539
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
540
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
541
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
542
|
+
}
|
|
543
|
+
function renderRefType(varNames, options) {
|
|
544
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
545
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
546
|
+
}
|
|
547
|
+
var HELPERS_TS = [
|
|
548
|
+
"export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
|
|
549
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
550
|
+
"}",
|
|
551
|
+
"",
|
|
552
|
+
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
553
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
554
|
+
"}"
|
|
555
|
+
];
|
|
556
|
+
var HELPERS_JS = [
|
|
557
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
558
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
559
|
+
"}",
|
|
560
|
+
"",
|
|
561
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
562
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
563
|
+
"}"
|
|
564
|
+
];
|
|
565
|
+
var HELPERS_DTS = [
|
|
566
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
567
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
568
|
+
];
|
|
569
|
+
function generateCode(varNames, ...args) {
|
|
570
|
+
const options = normalizeOptions(args);
|
|
571
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
572
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
573
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
|
|
574
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
575
|
+
return [
|
|
576
|
+
"// generated \u2014 do not edit",
|
|
577
|
+
"export const cssVars = {",
|
|
578
|
+
...entries,
|
|
579
|
+
"} as const;",
|
|
580
|
+
...tailBody.length > 0 ? ["", ...tailBody] : [],
|
|
581
|
+
""
|
|
582
|
+
].join("\n");
|
|
583
|
+
}
|
|
584
|
+
function generateJs(varNames, ...args) {
|
|
585
|
+
const options = normalizeOptions(args);
|
|
586
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
587
|
+
return [
|
|
588
|
+
"// generated \u2014 do not edit",
|
|
589
|
+
"export const cssVars = {",
|
|
590
|
+
...entries,
|
|
591
|
+
"};",
|
|
592
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
593
|
+
""
|
|
594
|
+
].join("\n");
|
|
595
|
+
}
|
|
596
|
+
function generateDeclaration(varNames, ...args) {
|
|
597
|
+
const options = normalizeOptions(args);
|
|
598
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
599
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
600
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
601
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
602
|
+
return [
|
|
603
|
+
"export declare const cssVars: {",
|
|
604
|
+
...entries,
|
|
605
|
+
"};",
|
|
606
|
+
...tailBody,
|
|
607
|
+
""
|
|
608
|
+
].join("\n");
|
|
609
|
+
}
|
|
610
|
+
var TOKEN_TYPES = {
|
|
611
|
+
"<color>": "color",
|
|
612
|
+
"<length>": "dimension",
|
|
613
|
+
"<length-percentage>": "dimension",
|
|
614
|
+
"<number>": "number",
|
|
615
|
+
"<integer>": "number",
|
|
616
|
+
"<time>": "duration"
|
|
617
|
+
};
|
|
618
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
619
|
+
function generateTokens(varNames, options = {}) {
|
|
620
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
621
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
622
|
+
const meta = entryMeta(name, options);
|
|
623
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
624
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
625
|
+
});
|
|
626
|
+
const paths = new Map(tokens.map(({ meta, path: path2 }) => [meta.name, path2]));
|
|
627
|
+
const resolve = (value) => {
|
|
628
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
629
|
+
return target ? `{${target.join(".")}}` : value;
|
|
630
|
+
};
|
|
631
|
+
const root = {};
|
|
632
|
+
for (const { meta, value, path: path2 } of tokens) {
|
|
633
|
+
const token = { $value: resolve(value) };
|
|
634
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
635
|
+
if (type) token.$type = type;
|
|
636
|
+
if (meta.themes) {
|
|
637
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve(themeValue)]));
|
|
638
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
639
|
+
}
|
|
640
|
+
const [key, leaf] = path2;
|
|
641
|
+
if (leaf === void 0) {
|
|
642
|
+
root[key] = token;
|
|
643
|
+
} else {
|
|
644
|
+
const group = root[key] ?? (root[key] = {});
|
|
645
|
+
group[leaf] = token;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// src/prune.ts
|
|
652
|
+
function assertPruneCompatible(options) {
|
|
653
|
+
if (options.prune && !options.usage) {
|
|
654
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function isUsed(name, usage, options) {
|
|
658
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
659
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
660
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
661
|
+
}
|
|
662
|
+
function partitionUnused(names, usage, options) {
|
|
663
|
+
const used = [];
|
|
664
|
+
const unused = [];
|
|
665
|
+
for (const name of names) {
|
|
666
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
667
|
+
}
|
|
668
|
+
return { used, unused };
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
export {
|
|
672
|
+
__dirname,
|
|
673
|
+
parseVarNames,
|
|
674
|
+
parseVarDeclarations,
|
|
675
|
+
parseThemedDeclarations,
|
|
676
|
+
parsePropertyRules,
|
|
677
|
+
collectVarNames,
|
|
678
|
+
scanCss,
|
|
679
|
+
scanVarDeclarations,
|
|
680
|
+
scanVarNames,
|
|
681
|
+
scanUsage,
|
|
682
|
+
scanUsedKeys,
|
|
683
|
+
VALID_NAMINGS,
|
|
684
|
+
warnOnCollisions,
|
|
685
|
+
generateCode,
|
|
686
|
+
generateJs,
|
|
687
|
+
generateDeclaration,
|
|
688
|
+
generateTokens,
|
|
689
|
+
assertPruneCompatible,
|
|
690
|
+
partitionUnused
|
|
691
|
+
};
|