css-typed-vars 0.4.17 → 0.6.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 +74 -6
- package/dist/chunk-LH53WYFF.js +487 -0
- package/dist/{chunk-DOOYTSTY.js → chunk-TD7SYMDA.js} +38 -14
- package/dist/chunk-VZ2BHHXD.js +86 -0
- package/dist/cli.cjs +352 -47
- package/dist/cli.js +59 -8
- package/dist/esbuild.cjs +266 -42
- package/dist/esbuild.d.cts +1 -1
- package/dist/esbuild.d.ts +1 -1
- package/dist/esbuild.js +2 -2
- package/dist/generator-C2AppeJL.d.cts +15 -0
- package/dist/generator-C2AppeJL.d.ts +15 -0
- package/dist/index.cjs +319 -40
- package/dist/index.d.cts +18 -5
- package/dist/index.d.ts +18 -5
- package/dist/index.js +16 -2
- package/dist/rollup.cjs +266 -42
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +266 -42
- package/dist/unplugin.d.cts +7 -1
- package/dist/unplugin.d.ts +7 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +266 -42
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +266 -42
- 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-EHRNYU34.js +0 -32
- package/dist/chunk-WYLYZXQJ.js +0 -265
- package/dist/generator-Ba8XeISD.d.cts +0 -6
- package/dist/generator-Ba8XeISD.d.ts +0 -6
package/README.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<h1>css-typed-vars</h1>
|
|
4
4
|
<p>Generate TypeScript typed constants from CSS custom properties</p>
|
|
5
|
+
<p><a href="https://stanislavkozachenko.github.io/css-typed-vars/">📖 Full documentation</a></p>
|
|
5
6
|
|
|
6
7
|
<p>
|
|
7
8
|
<a href="https://github.com/StanislavKozachenko/css-typed-vars/actions"><img src="https://github.com/StanislavKozachenko/css-typed-vars/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
|
@@ -27,6 +28,7 @@
|
|
|
27
28
|
- [Usage](#usage)
|
|
28
29
|
- [Programmatic API](#programmatic-api)
|
|
29
30
|
- [Supported formats](#supported-formats)
|
|
31
|
+
- [@property syntax typing](#property-syntax-typing)
|
|
30
32
|
- [Contributing](#contributing)
|
|
31
33
|
|
|
32
34
|
---
|
|
@@ -35,6 +37,8 @@
|
|
|
35
37
|
|
|
36
38
|
`css-typed-vars` scans your CSS files and gives you typed constants. Use `cssVars.colorPrimary` instead — TypeScript catches missing variables at compile time.
|
|
37
39
|
|
|
40
|
+
Each generated key also carries a `/** @default ... */` comment with the property's declared CSS value, so your editor shows it on hover and autocomplete. If the variable is registered with [`@property`](#property-syntax-typing), its `syntax` descriptor shows up too, and an enum-like syntax (e.g. `"light | dark | system"`) gets its own exported TS union type.
|
|
41
|
+
|
|
38
42
|
## Installation
|
|
39
43
|
|
|
40
44
|
```sh
|
|
@@ -115,6 +119,10 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --exclude "**/
|
|
|
115
119
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prefix theme --naming snake
|
|
116
120
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.js # generates .js + .d.ts
|
|
117
121
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --selector ".dark" --selector "[data-theme='dark']"
|
|
122
|
+
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --check # for CI: exits 1 if out of date
|
|
123
|
+
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --group # nest keys by first name segment
|
|
124
|
+
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune --usage "src/**/*.{ts,tsx}" # drop unused vars from the output
|
|
125
|
+
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check --usage "src/**/*.{ts,tsx}" # for CI: exits 1 if any var is unused
|
|
118
126
|
```
|
|
119
127
|
|
|
120
128
|
| Flag | Description |
|
|
@@ -123,11 +131,26 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --selector ".d
|
|
|
123
131
|
| `--output` | Output file. `.ts` → TypeScript, `.js` → JavaScript + `.d.ts` alongside |
|
|
124
132
|
| `--exclude` | Glob pattern for files to exclude (repeatable: `--exclude "**/a/**" --exclude "**/b/**"`) |
|
|
125
133
|
| `--prefix` | Prefix for generated keys: `--prefix theme` → `themeColorPrimary` |
|
|
126
|
-
| `--naming` | Key naming: `camelCase` (default), `snake`, `kebab` |
|
|
134
|
+
| `--naming` | Key naming: `camelCase` (default), `snake`, `kebab`, `constant`, `pascal` |
|
|
127
135
|
| `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
|
|
136
|
+
| `--group` | Nest keys under an object named after each variable's first hyphen segment: `--color-primary`/`--color-secondary` → `cssVars.color.primary`/`cssVars.color.secondary`. A variable with no hyphen stays top-level. Can't be combined with `--prefix`. |
|
|
137
|
+
| `--prune` | Drop generated vars with no detected `cssVars.<key>` usage. Requires `--usage <glob>` (repeatable). Can't be combined with `--group`. |
|
|
138
|
+
| `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Useful in CI. |
|
|
139
|
+
| `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
|
|
140
|
+
| `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
|
|
128
141
|
| `--watch` | Watch for file changes and regenerate |
|
|
142
|
+
| `--check` | Check whether the output is up to date without writing; exits 1 if it would differ. Useful in CI. Can't be combined with `--watch`. |
|
|
129
143
|
| `--version`, `-v` | Print the version number and exit |
|
|
130
144
|
|
|
145
|
+
### Pruning unused variables
|
|
146
|
+
|
|
147
|
+
`--prune`/`--prune-check` scan your source files for `cssVars.<key>` (dot access) or `cssVars['<key>']`/`cssVars["<key>"]` (bracket access) usage and compare that against the generated keys. This is a textual scan, not a full parser, so it has two limitations worth knowing:
|
|
148
|
+
|
|
149
|
+
- It won't see through a renamed import (`import { cssVars as vars } from './cssVars'` — usages via `vars.foo` aren't detected).
|
|
150
|
+
- A match inside a comment or string still counts as "used".
|
|
151
|
+
|
|
152
|
+
When in doubt, use `--prune-check` in CI to review what it would remove before turning on `--prune` for real.
|
|
153
|
+
|
|
131
154
|
CLI flags override values from the config file.
|
|
132
155
|
|
|
133
156
|
### Config file
|
|
@@ -147,8 +170,11 @@ export default {
|
|
|
147
170
|
output: 'src/cssVars.ts',
|
|
148
171
|
exclude: ['**/vendor/**', '**/node_modules/**'],
|
|
149
172
|
prefix: 'theme',
|
|
150
|
-
naming: 'snake', // 'camelCase' | 'snake' | 'kebab'
|
|
173
|
+
naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
|
|
151
174
|
selectors: ['.dark', '[data-theme="dark"]'],
|
|
175
|
+
group: false,
|
|
176
|
+
prune: false,
|
|
177
|
+
usage: 'src/**/*.{ts,tsx}',
|
|
152
178
|
};
|
|
153
179
|
```
|
|
154
180
|
|
|
@@ -245,8 +271,12 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
|
|
|
245
271
|
| `input` | `string \| string[]` | — | Glob pattern for CSS/SCSS/Less files |
|
|
246
272
|
| `exclude` | `string \| string[]` | — | Glob pattern(s) for files to exclude |
|
|
247
273
|
| `prefix` | `string` | — | Prefix for generated keys: `'theme'` → `themeColorPrimary` |
|
|
248
|
-
| `naming` | `'camelCase' \| 'snake' \| 'kebab'` | `'camelCase'` | Key naming convention |
|
|
274
|
+
| `naming` | `'camelCase' \| 'snake' \| 'kebab' \| 'constant' \| 'pascal'` | `'camelCase'` | Key naming convention |
|
|
249
275
|
| `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
|
|
276
|
+
| `group` | `boolean` | `false` | Nest keys by each variable's first hyphen segment, e.g. `cssVars.color.primary`. Can't be combined with `prefix` |
|
|
277
|
+
| `prune` | `boolean` | `false` | Drop vars with no detected `cssVars.<key>` usage. Requires `usage`. Can't be combined with `group` |
|
|
278
|
+
| `usage` | `string \| string[]` | — | Glob(s) of source files to scan for `cssVars` usage, for `prune` |
|
|
279
|
+
| `usageExclude` | `string \| string[]` | — | Glob(s) of source files to exclude from the usage scan |
|
|
250
280
|
| `dts` | `string \| false` | inside `node_modules` | Path to write type declarations. `false` to skip |
|
|
251
281
|
|
|
252
282
|
---
|
|
@@ -302,15 +332,22 @@ await generate({
|
|
|
302
332
|
output: 'src/cssVars.ts', // or 'src/cssVars.js' → generates .js + .d.ts
|
|
303
333
|
exclude: ['**/vendor/**'],
|
|
304
334
|
prefix: 'theme',
|
|
305
|
-
naming: 'snake', // 'camelCase' | 'snake' | 'kebab'
|
|
335
|
+
naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
|
|
306
336
|
selectors: ['.dark', '[data-theme="dark"]'],
|
|
337
|
+
group: false, // nest keys by first hyphen segment, e.g. cssVars.color.primary
|
|
338
|
+
prune: false, // drop vars with no detected cssVars.<key> usage (requires `usage`)
|
|
339
|
+
usage: 'src/**/*.{ts,tsx}',
|
|
307
340
|
});
|
|
308
341
|
```
|
|
309
342
|
|
|
343
|
+
`checkGenerated(options)` takes the same options and returns `Promise<boolean>` — `true` if the existing output already matches what would be generated, without writing anything. Same thing `--check` does on the CLI.
|
|
344
|
+
|
|
345
|
+
`findUnusedVars(options)` takes `input`/`exclude`/`selectors`/`prefix`/`naming`/`usage`/`usageExclude` and returns `Promise<string[]>` — the CSS variable names with no detected `cssVars.<key>` usage, without writing or pruning anything. Same thing `--prune-check` does on the CLI.
|
|
346
|
+
|
|
310
347
|
Lower-level exports:
|
|
311
348
|
|
|
312
349
|
```ts
|
|
313
|
-
import { parseVarNames, generateCode, scanVarNames } from 'css-typed-vars';
|
|
350
|
+
import { parseVarNames, parseVarDeclarations, parsePropertyRules, generateCode, scanVarNames, scanVarDeclarations, scanCss, scanUsedKeys } from 'css-typed-vars';
|
|
314
351
|
```
|
|
315
352
|
|
|
316
353
|
## Supported formats
|
|
@@ -321,7 +358,38 @@ import { parseVarNames, generateCode, scanVarNames } from 'css-typed-vars';
|
|
|
321
358
|
| SCSS | `.scss` |
|
|
322
359
|
| Less | `.less` |
|
|
323
360
|
|
|
324
|
-
By default, variables are scanned from `:root {}` blocks (including attribute selectors like `:root[data-theme="dark"]`). Use the `selectors` option to also pick up variables from other selectors such as `.dark` or `[data-theme="dark"]`.
|
|
361
|
+
By default, variables are scanned from `:root {}` blocks (including attribute selectors like `:root[data-theme="dark"]`) and Tailwind CSS v4's `@theme {}` blocks. Use the `selectors` option to also pick up variables from other selectors such as `.dark` or `[data-theme="dark"]`.
|
|
362
|
+
|
|
363
|
+
## @property syntax typing
|
|
364
|
+
|
|
365
|
+
If a variable is registered via the [CSS Properties and Values API](https://developer.mozilla.org/en-US/docs/Web/CSS/@property), its `syntax` descriptor is picked up automatically — no config needed:
|
|
366
|
+
|
|
367
|
+
```css
|
|
368
|
+
@property --theme-mode {
|
|
369
|
+
syntax: "light | dark | system";
|
|
370
|
+
inherits: true;
|
|
371
|
+
initial-value: light;
|
|
372
|
+
}
|
|
373
|
+
:root {
|
|
374
|
+
--theme-mode: light;
|
|
375
|
+
}
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
export const cssVars = {
|
|
380
|
+
/** @default light */
|
|
381
|
+
/** @syntax light | dark | system */
|
|
382
|
+
themeMode: 'var(--theme-mode)',
|
|
383
|
+
} as const;
|
|
384
|
+
|
|
385
|
+
export type CssVarName = keyof typeof cssVars;
|
|
386
|
+
|
|
387
|
+
export type ThemeModeSyntax = 'light' | 'dark' | 'system';
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Every `syntax` shows up as a `@syntax` JSDoc comment. When it's a pipe-separated list of custom idents (an enum, like above) — as opposed to a generic data type like `<color>` or `<length>` — it also gets its own exported union type, named `<PascalCaseVarName>Syntax`. Useful when setting the property from JS: `el.style.setProperty('--theme-mode', mode satisfies ThemeModeSyntax)`.
|
|
391
|
+
|
|
392
|
+
Note this doesn't change the type of `cssVars.themeMode` itself — that's always the literal string `'var(--theme-mode)'`, regardless of `@property`, since that's what you actually get at runtime. The union type is a separate, additional export for validating what you *assign* to the variable.
|
|
325
393
|
|
|
326
394
|
## Contributing
|
|
327
395
|
|
|
@@ -0,0 +1,487 @@
|
|
|
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 scanDeclarations(css, selectors, onProperty) {
|
|
125
|
+
const stripped = stripComments(css);
|
|
126
|
+
const allSelectors = [":root", "@theme", ...selectors ?? []];
|
|
127
|
+
for (const sel of allSelectors) {
|
|
128
|
+
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
129
|
+
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
130
|
+
let match;
|
|
131
|
+
while (match = openRegex.exec(stripped)) {
|
|
132
|
+
const start = match.index + match[0].length;
|
|
133
|
+
const block = extractBlock(stripped, start);
|
|
134
|
+
const masked = maskQuotedContent(block);
|
|
135
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
136
|
+
const name = prop[0];
|
|
137
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
138
|
+
onProperty(name, extractValue(block, colonIndex + 1));
|
|
139
|
+
}
|
|
140
|
+
openRegex.lastIndex = start + block.length + 1;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function parseVarNames(css, selectors) {
|
|
145
|
+
const names = /* @__PURE__ */ new Set();
|
|
146
|
+
scanDeclarations(css, selectors, (name) => names.add(name));
|
|
147
|
+
return [...names];
|
|
148
|
+
}
|
|
149
|
+
function parseVarDeclarations(css, selectors) {
|
|
150
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
151
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
|
|
152
|
+
return declarations;
|
|
153
|
+
}
|
|
154
|
+
var PROPERTY_DESCRIPTORS = [
|
|
155
|
+
["syntax", "syntax"],
|
|
156
|
+
["inherits", "inherits"],
|
|
157
|
+
["initial-value", "initialValue"]
|
|
158
|
+
];
|
|
159
|
+
function parsePropertyRules(css) {
|
|
160
|
+
const stripped = stripComments(css);
|
|
161
|
+
const rules = /* @__PURE__ */ new Map();
|
|
162
|
+
const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
|
|
163
|
+
let match;
|
|
164
|
+
while (match = openRegex.exec(stripped)) {
|
|
165
|
+
const name = match[1];
|
|
166
|
+
const start = match.index + match[0].length;
|
|
167
|
+
const block = extractBlock(stripped, start);
|
|
168
|
+
const masked = maskQuotedContent(block);
|
|
169
|
+
const rule = {};
|
|
170
|
+
for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
|
|
171
|
+
const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
|
|
172
|
+
const descMatch = descRegex.exec(masked);
|
|
173
|
+
if (!descMatch) continue;
|
|
174
|
+
const nameEnd = descMatch.index + descMatch[0].length;
|
|
175
|
+
const colonIndex = block.indexOf(":", nameEnd);
|
|
176
|
+
rule[key] = extractValue(block, colonIndex + 1);
|
|
177
|
+
}
|
|
178
|
+
if (Object.keys(rule).length > 0) rules.set(name, rule);
|
|
179
|
+
openRegex.lastIndex = start + block.length + 1;
|
|
180
|
+
}
|
|
181
|
+
return rules;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/scanner.ts
|
|
185
|
+
import { readFile } from "fs/promises";
|
|
186
|
+
import fg from "fast-glob";
|
|
187
|
+
function normalizePatterns(patterns) {
|
|
188
|
+
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
189
|
+
}
|
|
190
|
+
async function scanCss(patterns, exclude, selectors) {
|
|
191
|
+
const normalized = normalizePatterns(patterns);
|
|
192
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
193
|
+
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
194
|
+
const perFile = await Promise.all(
|
|
195
|
+
files.map(async (file) => {
|
|
196
|
+
let css;
|
|
197
|
+
try {
|
|
198
|
+
css = await readFile(file, "utf8");
|
|
199
|
+
} catch (err) {
|
|
200
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
201
|
+
return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
|
|
202
|
+
}
|
|
203
|
+
return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
|
|
204
|
+
})
|
|
205
|
+
);
|
|
206
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
207
|
+
const properties = /* @__PURE__ */ new Map();
|
|
208
|
+
for (const result of perFile) {
|
|
209
|
+
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
210
|
+
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
211
|
+
}
|
|
212
|
+
return { declarations, properties };
|
|
213
|
+
}
|
|
214
|
+
async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
215
|
+
return (await scanCss(patterns, exclude, selectors)).declarations;
|
|
216
|
+
}
|
|
217
|
+
async function scanVarNames(patterns, exclude, selectors) {
|
|
218
|
+
const declarations = await scanVarDeclarations(patterns, exclude, selectors);
|
|
219
|
+
return [...declarations.keys()].sort();
|
|
220
|
+
}
|
|
221
|
+
var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
|
|
222
|
+
function extractUsedKeys(text, into) {
|
|
223
|
+
for (const match of text.matchAll(USAGE_RE)) {
|
|
224
|
+
into.add(match[1] ?? match[3]);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async function scanUsedKeys(patterns, exclude) {
|
|
228
|
+
const normalized = normalizePatterns(patterns);
|
|
229
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
230
|
+
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
231
|
+
const perFile = await Promise.all(
|
|
232
|
+
files.map(async (file) => {
|
|
233
|
+
const used = /* @__PURE__ */ new Set();
|
|
234
|
+
let text;
|
|
235
|
+
try {
|
|
236
|
+
text = await readFile(file, "utf8");
|
|
237
|
+
} catch (err) {
|
|
238
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
239
|
+
return used;
|
|
240
|
+
}
|
|
241
|
+
extractUsedKeys(text, used);
|
|
242
|
+
return used;
|
|
243
|
+
})
|
|
244
|
+
);
|
|
245
|
+
const all = /* @__PURE__ */ new Set();
|
|
246
|
+
for (const used of perFile) {
|
|
247
|
+
for (const key of used) all.add(key);
|
|
248
|
+
}
|
|
249
|
+
return all;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/generator.ts
|
|
253
|
+
var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
|
|
254
|
+
function convertCase(value, naming) {
|
|
255
|
+
if (!VALID_NAMINGS.includes(naming)) {
|
|
256
|
+
throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
257
|
+
}
|
|
258
|
+
if (naming === "kebab") return value;
|
|
259
|
+
if (naming === "snake") return value.replace(/-+/g, "_");
|
|
260
|
+
if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
|
|
261
|
+
if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
|
|
262
|
+
return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
|
|
263
|
+
}
|
|
264
|
+
function toKeyFragment(fragment, naming = "camelCase") {
|
|
265
|
+
const key = convertCase(fragment, naming);
|
|
266
|
+
return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
|
|
267
|
+
}
|
|
268
|
+
function toKey(cssVarName, naming = "camelCase") {
|
|
269
|
+
return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
|
|
270
|
+
}
|
|
271
|
+
function splitGroupKey(cssVarName) {
|
|
272
|
+
const stripped = cssVarName.replace(/^--/, "");
|
|
273
|
+
const dashIndex = stripped.indexOf("-");
|
|
274
|
+
if (dashIndex === -1) return null;
|
|
275
|
+
return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
|
|
276
|
+
}
|
|
277
|
+
var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
|
|
278
|
+
var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
|
|
279
|
+
var SINGLE_QUOTE_ESCAPES = {};
|
|
280
|
+
SINGLE_QUOTE_ESCAPES["\\"] = "\\\\";
|
|
281
|
+
SINGLE_QUOTE_ESCAPES["'"] = "\\'";
|
|
282
|
+
SINGLE_QUOTE_ESCAPES["\n"] = "\\n";
|
|
283
|
+
SINGLE_QUOTE_ESCAPES["\r"] = "\\r";
|
|
284
|
+
SINGLE_QUOTE_ESCAPES[LINE_SEPARATOR_CHAR] = "\\u2028";
|
|
285
|
+
SINGLE_QUOTE_ESCAPES[PARAGRAPH_SEPARATOR_CHAR] = "\\u2029";
|
|
286
|
+
function escapeSingleQuoted(value) {
|
|
287
|
+
let result = "";
|
|
288
|
+
for (const char of value) {
|
|
289
|
+
result += SINGLE_QUOTE_ESCAPES[char] ?? char;
|
|
290
|
+
}
|
|
291
|
+
return result;
|
|
292
|
+
}
|
|
293
|
+
function applyPrefix(key, prefix, naming = "camelCase") {
|
|
294
|
+
if (!prefix) return key;
|
|
295
|
+
let normalizedPrefix = convertCase(prefix, naming);
|
|
296
|
+
if (naming === "kebab") {
|
|
297
|
+
normalizedPrefix = escapeSingleQuoted(normalizedPrefix);
|
|
298
|
+
return `${normalizedPrefix}-${key}`;
|
|
299
|
+
}
|
|
300
|
+
normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
|
|
301
|
+
if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
|
|
302
|
+
if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
|
|
303
|
+
return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
|
|
304
|
+
}
|
|
305
|
+
function formatKey(key, naming = "camelCase") {
|
|
306
|
+
if (naming === "kebab") return `'${key}'`;
|
|
307
|
+
return key;
|
|
308
|
+
}
|
|
309
|
+
function computeKey(cssVarName, prefix, naming) {
|
|
310
|
+
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
311
|
+
}
|
|
312
|
+
function findKeyCollisions(varNames, prefix, naming) {
|
|
313
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
314
|
+
for (const name of varNames) {
|
|
315
|
+
const key = applyPrefix(toKey(name, naming), prefix, naming);
|
|
316
|
+
const existing = byKey.get(key);
|
|
317
|
+
if (existing) existing.push(name);
|
|
318
|
+
else byKey.set(key, [name]);
|
|
319
|
+
}
|
|
320
|
+
for (const [key, names] of byKey) {
|
|
321
|
+
if (names.length < 2) byKey.delete(key);
|
|
322
|
+
}
|
|
323
|
+
return byKey;
|
|
324
|
+
}
|
|
325
|
+
function warnOnCollisions(varNames, prefix, naming) {
|
|
326
|
+
for (const [key, vars] of findKeyCollisions(varNames, prefix, naming)) {
|
|
327
|
+
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function buildEntries(varNames, prefix, naming, declarations, properties) {
|
|
331
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
332
|
+
for (const name of varNames) {
|
|
333
|
+
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
334
|
+
byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
|
|
335
|
+
}
|
|
336
|
+
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
337
|
+
}
|
|
338
|
+
function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
339
|
+
const groupMap = /* @__PURE__ */ new Map();
|
|
340
|
+
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
341
|
+
for (const name of varNames) {
|
|
342
|
+
const value = declarations?.get(name);
|
|
343
|
+
const syntax = properties?.get(name)?.syntax;
|
|
344
|
+
const split = splitGroupKey(name);
|
|
345
|
+
if (!split) {
|
|
346
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
350
|
+
const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
|
|
351
|
+
let leafMap = groupMap.get(groupKey);
|
|
352
|
+
if (!leafMap) {
|
|
353
|
+
leafMap = /* @__PURE__ */ new Map();
|
|
354
|
+
groupMap.set(groupKey, leafMap);
|
|
355
|
+
}
|
|
356
|
+
leafMap.set(leafKey, { name, value, syntax });
|
|
357
|
+
}
|
|
358
|
+
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
359
|
+
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
360
|
+
key,
|
|
361
|
+
entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
|
|
362
|
+
}));
|
|
363
|
+
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
364
|
+
return { groups, ungrouped };
|
|
365
|
+
}
|
|
366
|
+
function formatDefaultComment(value, indent = " ") {
|
|
367
|
+
return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
|
|
368
|
+
}
|
|
369
|
+
function unquoteCssString(value) {
|
|
370
|
+
const quote = value[0];
|
|
371
|
+
if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
|
|
372
|
+
return value.slice(1, -1);
|
|
373
|
+
}
|
|
374
|
+
return value;
|
|
375
|
+
}
|
|
376
|
+
function formatSyntaxComment(syntax, indent = " ") {
|
|
377
|
+
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
378
|
+
}
|
|
379
|
+
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
380
|
+
function parseEnumSyntax(syntax) {
|
|
381
|
+
const unquoted = unquoteCssString(syntax).trim();
|
|
382
|
+
if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
|
|
383
|
+
return unquoted.split("|").map((v) => v.trim());
|
|
384
|
+
}
|
|
385
|
+
function syntaxTypeName(cssVarName) {
|
|
386
|
+
const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
|
|
387
|
+
return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
|
|
388
|
+
}
|
|
389
|
+
function buildSyntaxTypes(varNames, properties) {
|
|
390
|
+
if (!properties) return [];
|
|
391
|
+
const byName = /* @__PURE__ */ new Map();
|
|
392
|
+
for (const name of varNames) {
|
|
393
|
+
const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
|
|
394
|
+
if (values) byName.set(syntaxTypeName(name), values);
|
|
395
|
+
}
|
|
396
|
+
return [...byName].map(([name, values]) => ({ name, values }));
|
|
397
|
+
}
|
|
398
|
+
function renderSyntaxTypeLines(types) {
|
|
399
|
+
return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
|
|
400
|
+
}
|
|
401
|
+
function buildTailBlocks(varNames, group, properties) {
|
|
402
|
+
const blocks = [];
|
|
403
|
+
if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
|
|
404
|
+
const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
|
|
405
|
+
if (syntaxLines.length > 0) blocks.push(syntaxLines);
|
|
406
|
+
return blocks;
|
|
407
|
+
}
|
|
408
|
+
function renderEntryLines(entries, indent, lineFor) {
|
|
409
|
+
return entries.flatMap(({ key, name, value, syntax }) => [
|
|
410
|
+
...value ? [formatDefaultComment(value, indent)] : [],
|
|
411
|
+
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
412
|
+
`${indent}${lineFor(key, name)}`
|
|
413
|
+
]);
|
|
414
|
+
}
|
|
415
|
+
function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
|
|
416
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
|
|
417
|
+
const lines = [];
|
|
418
|
+
for (const group of groups) {
|
|
419
|
+
lines.push(`${indent}${group.key}: {`);
|
|
420
|
+
lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
|
|
421
|
+
lines.push(`${indent}}${closeSuffix}`);
|
|
422
|
+
}
|
|
423
|
+
lines.push(...renderEntryLines(ungrouped, indent, lineFor));
|
|
424
|
+
return lines;
|
|
425
|
+
}
|
|
426
|
+
function assertGroupPrefixCompatible(prefix, group) {
|
|
427
|
+
if (group && prefix) {
|
|
428
|
+
throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
432
|
+
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
433
|
+
function generateCode(varNames, prefix, naming, declarations, group, properties) {
|
|
434
|
+
assertGroupPrefixCompatible(prefix, group);
|
|
435
|
+
const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
|
|
436
|
+
const blocks = buildTailBlocks(varNames, group, properties);
|
|
437
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
438
|
+
return [
|
|
439
|
+
"// generated \u2014 do not edit",
|
|
440
|
+
"export const cssVars = {",
|
|
441
|
+
...entries,
|
|
442
|
+
"} as const;",
|
|
443
|
+
...tailBody.length > 0 ? ["", ...tailBody] : [],
|
|
444
|
+
""
|
|
445
|
+
].join("\n");
|
|
446
|
+
}
|
|
447
|
+
function generateJs(varNames, prefix, naming, declarations, group, properties) {
|
|
448
|
+
assertGroupPrefixCompatible(prefix, group);
|
|
449
|
+
const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
|
|
450
|
+
return [
|
|
451
|
+
"// generated \u2014 do not edit",
|
|
452
|
+
"export const cssVars = {",
|
|
453
|
+
...entries,
|
|
454
|
+
"};",
|
|
455
|
+
""
|
|
456
|
+
].join("\n");
|
|
457
|
+
}
|
|
458
|
+
function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
|
|
459
|
+
assertGroupPrefixCompatible(prefix, group);
|
|
460
|
+
const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
|
|
461
|
+
const blocks = buildTailBlocks(varNames, group, properties);
|
|
462
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
463
|
+
return [
|
|
464
|
+
"export declare const cssVars: {",
|
|
465
|
+
...entries,
|
|
466
|
+
"};",
|
|
467
|
+
...tailBody,
|
|
468
|
+
""
|
|
469
|
+
].join("\n");
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export {
|
|
473
|
+
__dirname,
|
|
474
|
+
parseVarNames,
|
|
475
|
+
parseVarDeclarations,
|
|
476
|
+
parsePropertyRules,
|
|
477
|
+
scanCss,
|
|
478
|
+
scanVarDeclarations,
|
|
479
|
+
scanVarNames,
|
|
480
|
+
scanUsedKeys,
|
|
481
|
+
VALID_NAMINGS,
|
|
482
|
+
computeKey,
|
|
483
|
+
warnOnCollisions,
|
|
484
|
+
generateCode,
|
|
485
|
+
generateJs,
|
|
486
|
+
generateDeclaration
|
|
487
|
+
};
|