css-typed-vars 0.4.16 → 0.5.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 CHANGED
@@ -35,6 +35,8 @@
35
35
 
36
36
  `css-typed-vars` scans your CSS files and gives you typed constants. Use `cssVars.colorPrimary` instead — TypeScript catches missing variables at compile time.
37
37
 
38
+ Each generated key also carries a `/** @default ... */` comment with the property's declared CSS value, so your editor shows it on hover and autocomplete.
39
+
38
40
  ## Installation
39
41
 
40
42
  ```sh
@@ -115,6 +117,7 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --exclude "**/
115
117
  npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prefix theme --naming snake
116
118
  npx css-typed-vars --input "src/**/*.css" --output src/cssVars.js # generates .js + .d.ts
117
119
  npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --selector ".dark" --selector "[data-theme='dark']"
120
+ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --check # for CI: exits 1 if out of date
118
121
  ```
119
122
 
120
123
  | Flag | Description |
@@ -123,9 +126,10 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --selector ".d
123
126
  | `--output` | Output file. `.ts` → TypeScript, `.js` → JavaScript + `.d.ts` alongside |
124
127
  | `--exclude` | Glob pattern for files to exclude (repeatable: `--exclude "**/a/**" --exclude "**/b/**"`) |
125
128
  | `--prefix` | Prefix for generated keys: `--prefix theme` → `themeColorPrimary` |
126
- | `--naming` | Key naming: `camelCase` (default), `snake`, `kebab` |
129
+ | `--naming` | Key naming: `camelCase` (default), `snake`, `kebab`, `constant`, `pascal` |
127
130
  | `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
128
131
  | `--watch` | Watch for file changes and regenerate |
132
+ | `--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
133
  | `--version`, `-v` | Print the version number and exit |
130
134
 
131
135
  CLI flags override values from the config file.
@@ -147,7 +151,7 @@ export default {
147
151
  output: 'src/cssVars.ts',
148
152
  exclude: ['**/vendor/**', '**/node_modules/**'],
149
153
  prefix: 'theme',
150
- naming: 'snake', // 'camelCase' | 'snake' | 'kebab'
154
+ naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
151
155
  selectors: ['.dark', '[data-theme="dark"]'],
152
156
  };
153
157
  ```
@@ -245,7 +249,7 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
245
249
  | `input` | `string \| string[]` | — | Glob pattern for CSS/SCSS/Less files |
246
250
  | `exclude` | `string \| string[]` | — | Glob pattern(s) for files to exclude |
247
251
  | `prefix` | `string` | — | Prefix for generated keys: `'theme'` → `themeColorPrimary` |
248
- | `naming` | `'camelCase' \| 'snake' \| 'kebab'` | `'camelCase'` | Key naming convention |
252
+ | `naming` | `'camelCase' \| 'snake' \| 'kebab' \| 'constant' \| 'pascal'` | `'camelCase'` | Key naming convention |
249
253
  | `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
250
254
  | `dts` | `string \| false` | inside `node_modules` | Path to write type declarations. `false` to skip |
251
255
 
@@ -302,15 +306,17 @@ await generate({
302
306
  output: 'src/cssVars.ts', // or 'src/cssVars.js' → generates .js + .d.ts
303
307
  exclude: ['**/vendor/**'],
304
308
  prefix: 'theme',
305
- naming: 'snake', // 'camelCase' | 'snake' | 'kebab'
309
+ naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
306
310
  selectors: ['.dark', '[data-theme="dark"]'],
307
311
  });
308
312
  ```
309
313
 
314
+ `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.
315
+
310
316
  Lower-level exports:
311
317
 
312
318
  ```ts
313
- import { parseVarNames, generateCode, scanVarNames } from 'css-typed-vars';
319
+ import { parseVarNames, parseVarDeclarations, generateCode, scanVarNames, scanVarDeclarations } from 'css-typed-vars';
314
320
  ```
315
321
 
316
322
  ## Supported formats
@@ -0,0 +1,51 @@
1
+ import {
2
+ generateCode,
3
+ generateDeclaration,
4
+ generateJs,
5
+ scanVarDeclarations,
6
+ warnOnCollisions
7
+ } from "./chunk-JDZAH2YQ.js";
8
+
9
+ // src/index.ts
10
+ import { writeFile, mkdir, readFile } from "fs/promises";
11
+ import { dirname, resolve } from "path";
12
+ async function computeOutputs(options) {
13
+ const declarations = await scanVarDeclarations(options.input, options.exclude, options.selectors);
14
+ const names = [...declarations.keys()].sort();
15
+ if (names.length === 0) {
16
+ console.warn("css-typed-vars: no CSS custom properties found.");
17
+ }
18
+ warnOnCollisions(names, options.prefix, options.naming);
19
+ const outPath = resolve(options.output);
20
+ const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
21
+ if (jsExtMatch) {
22
+ const content = generateJs(names, options.prefix, options.naming, declarations);
23
+ const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
24
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations);
25
+ return { outPath, content, dtsPath, dtsContent };
26
+ }
27
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations) };
28
+ }
29
+ async function generate(options) {
30
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
31
+ await mkdir(dirname(outPath), { recursive: true });
32
+ await writeFile(outPath, content, "utf8");
33
+ if (dtsPath && dtsContent !== void 0) {
34
+ await writeFile(dtsPath, dtsContent, "utf8");
35
+ }
36
+ }
37
+ async function checkGenerated(options) {
38
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
39
+ const current = await readFile(outPath, "utf8").catch(() => null);
40
+ if (current !== content) return false;
41
+ if (dtsPath && dtsContent !== void 0) {
42
+ const currentDts = await readFile(dtsPath, "utf8").catch(() => null);
43
+ if (currentDts !== dtsContent) return false;
44
+ }
45
+ return true;
46
+ }
47
+
48
+ export {
49
+ generate,
50
+ checkGenerated
51
+ };
@@ -66,8 +66,9 @@ function extractBlock(text, start) {
66
66
  for (; i < text.length && depth > 0; i++) {
67
67
  const char = text[i];
68
68
  if (quote) {
69
- if (char === "\\") i++;
70
- else if (char === quote) quote = null;
69
+ const step = stepQuote(text, i, quote);
70
+ if (step.closed) quote = null;
71
+ i += step.consumed - 1;
71
72
  } else if (char === '"' || char === "'") {
72
73
  quote = char;
73
74
  } else if (char === "{") {
@@ -101,9 +102,27 @@ function maskQuotedContent(text) {
101
102
  }
102
103
  return result;
103
104
  }
104
- function parseVarNames(css, selectors) {
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) {
105
125
  const stripped = stripComments(css);
106
- const names = /* @__PURE__ */ new Set();
107
126
  const allSelectors = [":root", ...selectors ?? []];
108
127
  for (const sel of allSelectors) {
109
128
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -112,50 +131,73 @@ function parseVarNames(css, selectors) {
112
131
  while (match = openRegex.exec(stripped)) {
113
132
  const start = match.index + match[0].length;
114
133
  const block = extractBlock(stripped, start);
115
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
116
- names.add(prop[0]);
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));
117
139
  }
118
140
  openRegex.lastIndex = start + block.length + 1;
119
141
  }
120
142
  }
143
+ }
144
+ function parseVarNames(css, selectors) {
145
+ const names = /* @__PURE__ */ new Set();
146
+ scanDeclarations(css, selectors, (name) => names.add(name));
121
147
  return [...names];
122
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
+ }
123
154
 
124
155
  // src/scanner.ts
125
156
  import { readFile } from "fs/promises";
126
157
  import fg from "fast-glob";
127
- async function scanVarNames(patterns, exclude, selectors) {
128
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
129
- (p) => p.replace(/\\/g, "/")
130
- );
131
- const normalizedExclude = exclude ? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => p.replace(/\\/g, "/")) : [];
158
+ function normalizePatterns(patterns) {
159
+ return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
160
+ }
161
+ async function scanVarDeclarations(patterns, exclude, selectors) {
162
+ const normalized = normalizePatterns(patterns);
163
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
132
164
  const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
133
- const all = /* @__PURE__ */ new Set();
134
- await Promise.all(
165
+ const perFile = await Promise.all(
135
166
  files.map(async (file) => {
136
167
  let css;
137
168
  try {
138
169
  css = await readFile(file, "utf8");
139
170
  } catch (err) {
140
171
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
141
- return;
142
- }
143
- for (const name of parseVarNames(css, selectors)) {
144
- all.add(name);
172
+ return /* @__PURE__ */ new Map();
145
173
  }
174
+ return parseVarDeclarations(css, selectors);
146
175
  })
147
176
  );
148
- return [...all].sort();
177
+ const all = /* @__PURE__ */ new Map();
178
+ for (const declarations of perFile) {
179
+ for (const [name, value] of declarations) {
180
+ all.set(name, value);
181
+ }
182
+ }
183
+ return all;
184
+ }
185
+ async function scanVarNames(patterns, exclude, selectors) {
186
+ const declarations = await scanVarDeclarations(patterns, exclude, selectors);
187
+ return [...declarations.keys()].sort();
149
188
  }
150
189
 
151
190
  // src/generator.ts
152
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
191
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
153
192
  function convertCase(value, naming) {
154
193
  if (!VALID_NAMINGS.includes(naming)) {
155
194
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
156
195
  }
157
196
  if (naming === "kebab") return value;
158
- return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
197
+ if (naming === "snake") return value.replace(/-+/g, "_");
198
+ if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
199
+ if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
200
+ return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
159
201
  }
160
202
  function toKey(cssVarName, naming = "camelCase") {
161
203
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
@@ -186,7 +228,7 @@ function applyPrefix(key, prefix, naming = "camelCase") {
186
228
  }
187
229
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
188
230
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
189
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
231
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
190
232
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
191
233
  }
192
234
  function formatKey(key, naming = "camelCase") {
@@ -211,16 +253,22 @@ function warnOnCollisions(varNames, prefix, naming) {
211
253
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
212
254
  }
213
255
  }
214
- function buildEntries(varNames, prefix, naming) {
256
+ function buildEntries(varNames, prefix, naming, declarations) {
215
257
  const byKey = /* @__PURE__ */ new Map();
216
258
  for (const name of varNames) {
217
259
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
218
- byKey.set(key, name);
260
+ byKey.set(key, { name, value: declarations?.get(name) });
219
261
  }
220
- return [...byKey].map(([key, name]) => ({ key, name }));
262
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
263
+ }
264
+ function formatDefaultComment(value) {
265
+ return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
221
266
  }
222
- function generateCode(varNames, prefix, naming) {
223
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
267
+ function generateCode(varNames, prefix, naming, declarations) {
268
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
269
+ ...value ? [formatDefaultComment(value)] : [],
270
+ ` ${key}: 'var(${name})',`
271
+ ]);
224
272
  return [
225
273
  "// generated \u2014 do not edit",
226
274
  "export const cssVars = {",
@@ -231,8 +279,11 @@ function generateCode(varNames, prefix, naming) {
231
279
  ""
232
280
  ].join("\n");
233
281
  }
234
- function generateJs(varNames, prefix, naming) {
235
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
282
+ function generateJs(varNames, prefix, naming, declarations) {
283
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
284
+ ...value ? [formatDefaultComment(value)] : [],
285
+ ` ${key}: 'var(${name})',`
286
+ ]);
236
287
  return [
237
288
  "// generated \u2014 do not edit",
238
289
  "export const cssVars = {",
@@ -241,8 +292,11 @@ function generateJs(varNames, prefix, naming) {
241
292
  ""
242
293
  ].join("\n");
243
294
  }
244
- function generateDeclaration(varNames, prefix, naming) {
245
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
295
+ function generateDeclaration(varNames, prefix, naming, declarations) {
296
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
297
+ ...value ? [formatDefaultComment(value)] : [],
298
+ ` ${key}: 'var(${name})';`
299
+ ]);
246
300
  return [
247
301
  "export declare const cssVars: {",
248
302
  ...entries,
@@ -255,6 +309,8 @@ function generateDeclaration(varNames, prefix, naming) {
255
309
  export {
256
310
  __dirname,
257
311
  parseVarNames,
312
+ parseVarDeclarations,
313
+ scanVarDeclarations,
258
314
  scanVarNames,
259
315
  VALID_NAMINGS,
260
316
  warnOnCollisions,
@@ -2,9 +2,9 @@ import {
2
2
  __dirname,
3
3
  generateDeclaration,
4
4
  generateJs,
5
- scanVarNames,
5
+ scanVarDeclarations,
6
6
  warnOnCollisions
7
- } from "./chunk-NS2BULH3.js";
7
+ } from "./chunk-JDZAH2YQ.js";
8
8
 
9
9
  // src/unplugin.ts
10
10
  import { createUnplugin } from "unplugin";
@@ -17,7 +17,8 @@ function getDtsPath(options) {
17
17
  return options.dts ? resolve(process.cwd(), options.dts) : join(__dirname, "generated.d.ts");
18
18
  }
19
19
  var unplugin_default = createUnplugin((options) => {
20
- let cachedNames = null;
20
+ let cachedDeclarations = null;
21
+ const scan = () => scanVarDeclarations(options.input, options.exclude, options.selectors);
21
22
  return {
22
23
  name: "css-typed-vars",
23
24
  vite: {
@@ -28,14 +29,15 @@ var unplugin_default = createUnplugin((options) => {
28
29
  let writeQueue = Promise.resolve();
29
30
  const rescan = async () => {
30
31
  const myGeneration = ++generation;
31
- const namesPromise = scanVarNames(options.input, options.exclude, options.selectors);
32
- cachedNames = namesPromise;
33
- const names = await namesPromise;
32
+ const declarationsPromise = scan();
33
+ cachedDeclarations = declarationsPromise;
34
+ const declarations = await declarationsPromise;
34
35
  if (myGeneration !== generation) return;
36
+ const names = [...declarations.keys()].sort();
35
37
  warnOnCollisions(names, options.prefix, options.naming);
36
38
  const dtsPath = getDtsPath(options);
37
39
  if (dtsPath) {
38
- const content = generateDeclaration(names, options.prefix, options.naming);
40
+ const content = generateDeclaration(names, options.prefix, options.naming, declarations);
39
41
  writeQueue = writeQueue.then(async () => {
40
42
  if (myGeneration !== generation) return;
41
43
  await writeFile(dtsPath, content, "utf8");
@@ -63,20 +65,22 @@ var unplugin_default = createUnplugin((options) => {
63
65
  }
64
66
  },
65
67
  async buildStart() {
66
- cachedNames = scanVarNames(options.input, options.exclude, options.selectors);
67
- const names = await cachedNames;
68
+ cachedDeclarations = scan();
69
+ const declarations = await cachedDeclarations;
70
+ const names = [...declarations.keys()].sort();
68
71
  warnOnCollisions(names, options.prefix, options.naming);
69
72
  const dtsPath = getDtsPath(options);
70
73
  if (!dtsPath) return;
71
- await writeFile(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
74
+ await writeFile(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations), "utf8");
72
75
  },
73
76
  resolveId(id) {
74
77
  if (id === VIRTUAL_ID) return RESOLVED_ID;
75
78
  },
76
79
  async load(id) {
77
80
  if (id === RESOLVED_ID) {
78
- const names = await (cachedNames ?? scanVarNames(options.input, options.exclude, options.selectors));
79
- return generateJs(names, options.prefix, options.naming);
81
+ const declarations = await (cachedDeclarations ?? scan());
82
+ const names = [...declarations.keys()].sort();
83
+ return generateJs(names, options.prefix, options.naming, declarations);
80
84
  }
81
85
  }
82
86
  };
package/dist/cli.cjs CHANGED
@@ -102,8 +102,9 @@ function extractBlock(text, start) {
102
102
  for (; i < text.length && depth > 0; i++) {
103
103
  const char = text[i];
104
104
  if (quote) {
105
- if (char === "\\") i++;
106
- else if (char === quote) quote = null;
105
+ const step = stepQuote(text, i, quote);
106
+ if (step.closed) quote = null;
107
+ i += step.consumed - 1;
107
108
  } else if (char === '"' || char === "'") {
108
109
  quote = char;
109
110
  } else if (char === "{") {
@@ -137,9 +138,27 @@ function maskQuotedContent(text) {
137
138
  }
138
139
  return result;
139
140
  }
140
- function parseVarNames(css, selectors) {
141
+ function extractValue(text, start) {
142
+ let i = start;
143
+ let quote = null;
144
+ for (; i < text.length; i++) {
145
+ const char = text[i];
146
+ if (quote) {
147
+ const step = stepQuote(text, i, quote);
148
+ if (step.closed) quote = null;
149
+ i += step.consumed - 1;
150
+ continue;
151
+ }
152
+ if (char === '"' || char === "'") {
153
+ quote = char;
154
+ continue;
155
+ }
156
+ if (char === ";" || char === "}") break;
157
+ }
158
+ return text.slice(start, i).trim();
159
+ }
160
+ function scanDeclarations(css, selectors, onProperty) {
141
161
  const stripped = stripComments(css);
142
- const names = /* @__PURE__ */ new Set();
143
162
  const allSelectors = [":root", ...selectors ?? []];
144
163
  for (const sel of allSelectors) {
145
164
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -148,48 +167,62 @@ function parseVarNames(css, selectors) {
148
167
  while (match = openRegex.exec(stripped)) {
149
168
  const start = match.index + match[0].length;
150
169
  const block = extractBlock(stripped, start);
151
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
152
- names.add(prop[0]);
170
+ const masked = maskQuotedContent(block);
171
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
172
+ const name = prop[0];
173
+ const colonIndex = block.indexOf(":", prop.index + name.length);
174
+ onProperty(name, extractValue(block, colonIndex + 1));
153
175
  }
154
176
  openRegex.lastIndex = start + block.length + 1;
155
177
  }
156
178
  }
157
- return [...names];
179
+ }
180
+ function parseVarDeclarations(css, selectors) {
181
+ const declarations = /* @__PURE__ */ new Map();
182
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
183
+ return declarations;
158
184
  }
159
185
 
160
186
  // src/scanner.ts
161
- async function scanVarNames(patterns, exclude, selectors) {
162
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
163
- (p) => p.replace(/\\/g, "/")
164
- );
165
- const normalizedExclude = exclude ? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => p.replace(/\\/g, "/")) : [];
187
+ function normalizePatterns(patterns) {
188
+ return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
189
+ }
190
+ async function scanVarDeclarations(patterns, exclude, selectors) {
191
+ const normalized = normalizePatterns(patterns);
192
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
166
193
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
167
- const all = /* @__PURE__ */ new Set();
168
- await Promise.all(
194
+ const perFile = await Promise.all(
169
195
  files.map(async (file) => {
170
196
  let css;
171
197
  try {
172
198
  css = await (0, import_promises.readFile)(file, "utf8");
173
199
  } catch (err) {
174
200
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
175
- return;
176
- }
177
- for (const name of parseVarNames(css, selectors)) {
178
- all.add(name);
201
+ return /* @__PURE__ */ new Map();
179
202
  }
203
+ return parseVarDeclarations(css, selectors);
180
204
  })
181
205
  );
182
- return [...all].sort();
206
+ const all = /* @__PURE__ */ new Map();
207
+ for (const declarations of perFile) {
208
+ for (const [name, value] of declarations) {
209
+ all.set(name, value);
210
+ }
211
+ }
212
+ return all;
183
213
  }
184
214
 
185
215
  // src/generator.ts
186
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
216
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
187
217
  function convertCase(value, naming) {
188
218
  if (!VALID_NAMINGS.includes(naming)) {
189
219
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
190
220
  }
191
221
  if (naming === "kebab") return value;
192
- return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
222
+ if (naming === "snake") return value.replace(/-+/g, "_");
223
+ if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
224
+ if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
225
+ return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
193
226
  }
194
227
  function toKey(cssVarName, naming = "camelCase") {
195
228
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
@@ -220,7 +253,7 @@ function applyPrefix(key, prefix, naming = "camelCase") {
220
253
  }
221
254
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
222
255
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
223
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
256
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
224
257
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
225
258
  }
226
259
  function formatKey(key, naming = "camelCase") {
@@ -245,16 +278,22 @@ function warnOnCollisions(varNames, prefix, naming) {
245
278
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
246
279
  }
247
280
  }
248
- function buildEntries(varNames, prefix, naming) {
281
+ function buildEntries(varNames, prefix, naming, declarations) {
249
282
  const byKey = /* @__PURE__ */ new Map();
250
283
  for (const name of varNames) {
251
284
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
252
- byKey.set(key, name);
285
+ byKey.set(key, { name, value: declarations?.get(name) });
253
286
  }
254
- return [...byKey].map(([key, name]) => ({ key, name }));
287
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
255
288
  }
256
- function generateCode(varNames, prefix, naming) {
257
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
289
+ function formatDefaultComment(value) {
290
+ return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
291
+ }
292
+ function generateCode(varNames, prefix, naming, declarations) {
293
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
294
+ ...value ? [formatDefaultComment(value)] : [],
295
+ ` ${key}: 'var(${name})',`
296
+ ]);
258
297
  return [
259
298
  "// generated \u2014 do not edit",
260
299
  "export const cssVars = {",
@@ -265,8 +304,11 @@ function generateCode(varNames, prefix, naming) {
265
304
  ""
266
305
  ].join("\n");
267
306
  }
268
- function generateJs(varNames, prefix, naming) {
269
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
307
+ function generateJs(varNames, prefix, naming, declarations) {
308
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
309
+ ...value ? [formatDefaultComment(value)] : [],
310
+ ` ${key}: 'var(${name})',`
311
+ ]);
270
312
  return [
271
313
  "// generated \u2014 do not edit",
272
314
  "export const cssVars = {",
@@ -275,8 +317,11 @@ function generateJs(varNames, prefix, naming) {
275
317
  ""
276
318
  ].join("\n");
277
319
  }
278
- function generateDeclaration(varNames, prefix, naming) {
279
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
320
+ function generateDeclaration(varNames, prefix, naming, declarations) {
321
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
322
+ ...value ? [formatDefaultComment(value)] : [],
323
+ ` ${key}: 'var(${name})';`
324
+ ]);
280
325
  return [
281
326
  "export declare const cssVars: {",
282
327
  ...entries,
@@ -287,22 +332,40 @@ function generateDeclaration(varNames, prefix, naming) {
287
332
  }
288
333
 
289
334
  // src/index.ts
290
- async function generate(options) {
291
- const names = await scanVarNames(options.input, options.exclude, options.selectors);
335
+ async function computeOutputs(options) {
336
+ const declarations = await scanVarDeclarations(options.input, options.exclude, options.selectors);
337
+ const names = [...declarations.keys()].sort();
292
338
  if (names.length === 0) {
293
339
  console.warn("css-typed-vars: no CSS custom properties found.");
294
340
  }
295
341
  warnOnCollisions(names, options.prefix, options.naming);
296
342
  const outPath = (0, import_node_path.resolve)(options.output);
297
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
298
343
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
299
344
  if (jsExtMatch) {
300
- await (0, import_promises2.writeFile)(outPath, generateJs(names, options.prefix, options.naming), "utf8");
345
+ const content = generateJs(names, options.prefix, options.naming, declarations);
301
346
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
302
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
303
- } else {
304
- await (0, import_promises2.writeFile)(outPath, generateCode(names, options.prefix, options.naming), "utf8");
347
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations);
348
+ return { outPath, content, dtsPath, dtsContent };
349
+ }
350
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations) };
351
+ }
352
+ async function generate(options) {
353
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
354
+ await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
355
+ await (0, import_promises2.writeFile)(outPath, content, "utf8");
356
+ if (dtsPath && dtsContent !== void 0) {
357
+ await (0, import_promises2.writeFile)(dtsPath, dtsContent, "utf8");
358
+ }
359
+ }
360
+ async function checkGenerated(options) {
361
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
362
+ const current = await (0, import_promises2.readFile)(outPath, "utf8").catch(() => null);
363
+ if (current !== content) return false;
364
+ if (dtsPath && dtsContent !== void 0) {
365
+ const currentDts = await (0, import_promises2.readFile)(dtsPath, "utf8").catch(() => null);
366
+ if (currentDts !== dtsContent) return false;
305
367
  }
368
+ return true;
306
369
  }
307
370
 
308
371
  // src/cli.ts
@@ -322,6 +385,7 @@ var getArgs = (flag) => {
322
385
  return result;
323
386
  };
324
387
  var watchMode = args.includes("--watch");
388
+ var checkMode = args.includes("--check");
325
389
  async function loadConfig() {
326
390
  const candidates = [
327
391
  "css-typed-vars.config.js",
@@ -372,10 +436,23 @@ async function main() {
372
436
  const selectorArgs = getArgs("--selector");
373
437
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
374
438
  if (!input || !output) {
375
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch]");
439
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check]");
376
440
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
377
441
  process.exit(1);
378
442
  }
443
+ if (checkMode && watchMode) {
444
+ console.error("css-typed-vars: --check cannot be combined with --watch.");
445
+ process.exit(1);
446
+ }
447
+ if (checkMode) {
448
+ const upToDate = await checkGenerated({ input, output, exclude, prefix, naming, selectors });
449
+ if (!upToDate) {
450
+ console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
451
+ process.exit(1);
452
+ }
453
+ console.log(`css-typed-vars: "${output}" is up to date.`);
454
+ return;
455
+ }
379
456
  await run(input, output, exclude, prefix, naming, selectors);
380
457
  if (watchMode) {
381
458
  const patterns = Array.isArray(input) ? input : [input];