css-typed-vars 0.4.17 → 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
+ };
@@ -102,9 +102,27 @@ function maskQuotedContent(text) {
102
102
  }
103
103
  return result;
104
104
  }
105
- 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) {
106
125
  const stripped = stripComments(css);
107
- const names = /* @__PURE__ */ new Set();
108
126
  const allSelectors = [":root", ...selectors ?? []];
109
127
  for (const sel of allSelectors) {
110
128
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -113,50 +131,73 @@ function parseVarNames(css, selectors) {
113
131
  while (match = openRegex.exec(stripped)) {
114
132
  const start = match.index + match[0].length;
115
133
  const block = extractBlock(stripped, start);
116
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
117
- 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));
118
139
  }
119
140
  openRegex.lastIndex = start + block.length + 1;
120
141
  }
121
142
  }
143
+ }
144
+ function parseVarNames(css, selectors) {
145
+ const names = /* @__PURE__ */ new Set();
146
+ scanDeclarations(css, selectors, (name) => names.add(name));
122
147
  return [...names];
123
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
+ }
124
154
 
125
155
  // src/scanner.ts
126
156
  import { readFile } from "fs/promises";
127
157
  import fg from "fast-glob";
128
- async function scanVarNames(patterns, exclude, selectors) {
129
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
130
- (p) => p.replace(/\\/g, "/")
131
- );
132
- 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) : [];
133
164
  const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
134
- const all = /* @__PURE__ */ new Set();
135
- await Promise.all(
165
+ const perFile = await Promise.all(
136
166
  files.map(async (file) => {
137
167
  let css;
138
168
  try {
139
169
  css = await readFile(file, "utf8");
140
170
  } catch (err) {
141
171
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
142
- return;
143
- }
144
- for (const name of parseVarNames(css, selectors)) {
145
- all.add(name);
172
+ return /* @__PURE__ */ new Map();
146
173
  }
174
+ return parseVarDeclarations(css, selectors);
147
175
  })
148
176
  );
149
- 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();
150
188
  }
151
189
 
152
190
  // src/generator.ts
153
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
191
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
154
192
  function convertCase(value, naming) {
155
193
  if (!VALID_NAMINGS.includes(naming)) {
156
194
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
157
195
  }
158
196
  if (naming === "kebab") return value;
159
- 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, "");
160
201
  }
161
202
  function toKey(cssVarName, naming = "camelCase") {
162
203
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
@@ -187,7 +228,7 @@ function applyPrefix(key, prefix, naming = "camelCase") {
187
228
  }
188
229
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
189
230
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
190
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
231
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
191
232
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
192
233
  }
193
234
  function formatKey(key, naming = "camelCase") {
@@ -212,16 +253,22 @@ function warnOnCollisions(varNames, prefix, naming) {
212
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.`);
213
254
  }
214
255
  }
215
- function buildEntries(varNames, prefix, naming) {
256
+ function buildEntries(varNames, prefix, naming, declarations) {
216
257
  const byKey = /* @__PURE__ */ new Map();
217
258
  for (const name of varNames) {
218
259
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
219
- byKey.set(key, name);
260
+ byKey.set(key, { name, value: declarations?.get(name) });
220
261
  }
221
- 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, "*\\/")} */`;
222
266
  }
223
- function generateCode(varNames, prefix, naming) {
224
- 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
+ ]);
225
272
  return [
226
273
  "// generated \u2014 do not edit",
227
274
  "export const cssVars = {",
@@ -232,8 +279,11 @@ function generateCode(varNames, prefix, naming) {
232
279
  ""
233
280
  ].join("\n");
234
281
  }
235
- function generateJs(varNames, prefix, naming) {
236
- 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
+ ]);
237
287
  return [
238
288
  "// generated \u2014 do not edit",
239
289
  "export const cssVars = {",
@@ -242,8 +292,11 @@ function generateJs(varNames, prefix, naming) {
242
292
  ""
243
293
  ].join("\n");
244
294
  }
245
- function generateDeclaration(varNames, prefix, naming) {
246
- 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
+ ]);
247
300
  return [
248
301
  "export declare const cssVars: {",
249
302
  ...entries,
@@ -256,6 +309,8 @@ function generateDeclaration(varNames, prefix, naming) {
256
309
  export {
257
310
  __dirname,
258
311
  parseVarNames,
312
+ parseVarDeclarations,
313
+ scanVarDeclarations,
259
314
  scanVarNames,
260
315
  VALID_NAMINGS,
261
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-WYLYZXQJ.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
@@ -138,9 +138,27 @@ function maskQuotedContent(text) {
138
138
  }
139
139
  return result;
140
140
  }
141
- 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) {
142
161
  const stripped = stripComments(css);
143
- const names = /* @__PURE__ */ new Set();
144
162
  const allSelectors = [":root", ...selectors ?? []];
145
163
  for (const sel of allSelectors) {
146
164
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -149,48 +167,62 @@ function parseVarNames(css, selectors) {
149
167
  while (match = openRegex.exec(stripped)) {
150
168
  const start = match.index + match[0].length;
151
169
  const block = extractBlock(stripped, start);
152
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
153
- 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));
154
175
  }
155
176
  openRegex.lastIndex = start + block.length + 1;
156
177
  }
157
178
  }
158
- 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;
159
184
  }
160
185
 
161
186
  // src/scanner.ts
162
- async function scanVarNames(patterns, exclude, selectors) {
163
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
164
- (p) => p.replace(/\\/g, "/")
165
- );
166
- 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) : [];
167
193
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
168
- const all = /* @__PURE__ */ new Set();
169
- await Promise.all(
194
+ const perFile = await Promise.all(
170
195
  files.map(async (file) => {
171
196
  let css;
172
197
  try {
173
198
  css = await (0, import_promises.readFile)(file, "utf8");
174
199
  } catch (err) {
175
200
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
176
- return;
177
- }
178
- for (const name of parseVarNames(css, selectors)) {
179
- all.add(name);
201
+ return /* @__PURE__ */ new Map();
180
202
  }
203
+ return parseVarDeclarations(css, selectors);
181
204
  })
182
205
  );
183
- 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;
184
213
  }
185
214
 
186
215
  // src/generator.ts
187
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
216
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
188
217
  function convertCase(value, naming) {
189
218
  if (!VALID_NAMINGS.includes(naming)) {
190
219
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
191
220
  }
192
221
  if (naming === "kebab") return value;
193
- 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, "");
194
226
  }
195
227
  function toKey(cssVarName, naming = "camelCase") {
196
228
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
@@ -221,7 +253,7 @@ function applyPrefix(key, prefix, naming = "camelCase") {
221
253
  }
222
254
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
223
255
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
224
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
256
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
225
257
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
226
258
  }
227
259
  function formatKey(key, naming = "camelCase") {
@@ -246,16 +278,22 @@ function warnOnCollisions(varNames, prefix, naming) {
246
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.`);
247
279
  }
248
280
  }
249
- function buildEntries(varNames, prefix, naming) {
281
+ function buildEntries(varNames, prefix, naming, declarations) {
250
282
  const byKey = /* @__PURE__ */ new Map();
251
283
  for (const name of varNames) {
252
284
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
253
- byKey.set(key, name);
285
+ byKey.set(key, { name, value: declarations?.get(name) });
254
286
  }
255
- return [...byKey].map(([key, name]) => ({ key, name }));
287
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
288
+ }
289
+ function formatDefaultComment(value) {
290
+ return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
256
291
  }
257
- function generateCode(varNames, prefix, naming) {
258
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
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
+ ]);
259
297
  return [
260
298
  "// generated \u2014 do not edit",
261
299
  "export const cssVars = {",
@@ -266,8 +304,11 @@ function generateCode(varNames, prefix, naming) {
266
304
  ""
267
305
  ].join("\n");
268
306
  }
269
- function generateJs(varNames, prefix, naming) {
270
- 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
+ ]);
271
312
  return [
272
313
  "// generated \u2014 do not edit",
273
314
  "export const cssVars = {",
@@ -276,8 +317,11 @@ function generateJs(varNames, prefix, naming) {
276
317
  ""
277
318
  ].join("\n");
278
319
  }
279
- function generateDeclaration(varNames, prefix, naming) {
280
- 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
+ ]);
281
325
  return [
282
326
  "export declare const cssVars: {",
283
327
  ...entries,
@@ -288,22 +332,40 @@ function generateDeclaration(varNames, prefix, naming) {
288
332
  }
289
333
 
290
334
  // src/index.ts
291
- async function generate(options) {
292
- 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();
293
338
  if (names.length === 0) {
294
339
  console.warn("css-typed-vars: no CSS custom properties found.");
295
340
  }
296
341
  warnOnCollisions(names, options.prefix, options.naming);
297
342
  const outPath = (0, import_node_path.resolve)(options.output);
298
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
299
343
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
300
344
  if (jsExtMatch) {
301
- await (0, import_promises2.writeFile)(outPath, generateJs(names, options.prefix, options.naming), "utf8");
345
+ const content = generateJs(names, options.prefix, options.naming, declarations);
302
346
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
303
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
304
- } else {
305
- 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 };
306
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;
367
+ }
368
+ return true;
307
369
  }
308
370
 
309
371
  // src/cli.ts
@@ -323,6 +385,7 @@ var getArgs = (flag) => {
323
385
  return result;
324
386
  };
325
387
  var watchMode = args.includes("--watch");
388
+ var checkMode = args.includes("--check");
326
389
  async function loadConfig() {
327
390
  const candidates = [
328
391
  "css-typed-vars.config.js",
@@ -373,10 +436,23 @@ async function main() {
373
436
  const selectorArgs = getArgs("--selector");
374
437
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
375
438
  if (!input || !output) {
376
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch]");
439
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check]");
377
440
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
378
441
  process.exit(1);
379
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
+ }
380
456
  await run(input, output, exclude, prefix, naming, selectors);
381
457
  if (watchMode) {
382
458
  const patterns = Array.isArray(input) ? input : [input];