css-typed-vars 0.7.0 → 0.9.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/dist/cli.js CHANGED
@@ -1,16 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  checkGenerated,
4
+ findUndefinedRefs,
4
5
  findUnusedVars,
5
6
  generate
6
- } from "./chunk-PLO2JWR7.js";
7
+ } from "./chunk-TB5PSGEF.js";
7
8
  import {
8
9
  VALID_NAMINGS
9
- } from "./chunk-6YWE4A6S.js";
10
+ } from "./chunk-DHBPPGOE.js";
10
11
 
11
12
  // src/cli.ts
12
- import { readFile } from "fs/promises";
13
- import { resolve } from "path";
13
+ import { access, readFile } from "fs/promises";
14
+ import { relative, resolve } from "path";
14
15
  import { pathToFileURL } from "url";
15
16
  import { watch } from "chokidar";
16
17
  var args = process.argv.slice(2).flatMap((arg) => {
@@ -30,127 +31,317 @@ var getArgs = (flag) => {
30
31
  };
31
32
  var watchMode = args.includes("--watch");
32
33
  var checkMode = args.includes("--check");
33
- var groupFlag = args.includes("--group");
34
- var pruneFlag = args.includes("--prune");
35
34
  var pruneCheckMode = args.includes("--prune-check");
36
- var helpersFlag = args.includes("--helpers");
35
+ var lintRefsMode = args.includes("--lint-refs");
36
+ var OPTION_FLAGS = [
37
+ "--input",
38
+ "--output",
39
+ "--exclude",
40
+ "--prefix",
41
+ "--naming",
42
+ "--selector",
43
+ "--theme",
44
+ "--group",
45
+ "--prune",
46
+ "--usage",
47
+ "--usage-exclude",
48
+ "--helpers",
49
+ "--refs-ignore"
50
+ ];
51
+ var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
52
+ var VALUE_FLAGS = [
53
+ "--input",
54
+ "--output",
55
+ "--exclude",
56
+ "--prefix",
57
+ "--naming",
58
+ "--selector",
59
+ "--theme",
60
+ "--usage",
61
+ "--usage-exclude",
62
+ "--refs-ignore",
63
+ "--config"
64
+ ];
65
+ var BOOLEAN_FLAGS = [
66
+ "--group",
67
+ "--prune",
68
+ "--helpers",
69
+ "--watch",
70
+ "--check",
71
+ "--prune-check",
72
+ "--lint-refs",
73
+ "--version",
74
+ "-v",
75
+ "--help",
76
+ "-h"
77
+ ];
78
+ var HELP = `${USAGE}
79
+
80
+ Generates typed constants for the CSS custom properties found in <glob>.
81
+ Options can also be set in css-typed-vars.config.{js,mjs,cjs,ts,mts,json}; flags take precedence.
82
+
83
+ Options:
84
+ --config <file> Config file to use instead of looking one up
85
+ --input <glob> CSS files to scan (repeatable)
86
+ --output <file> .ts, .js/.mjs/.cjs (plus a .d.ts), or .json (design tokens)
87
+ --exclude <glob> Files to skip (repeatable)
88
+ --prefix <prefix> Prefix every generated key
89
+ --naming <convention> camelCase (default), snake, kebab, constant or pascal
90
+ --selector <selector> Also scan this selector's blocks, not just :root/@theme (repeatable)
91
+ --theme <name>=<sel> Theme block, emitted as @theme JSDoc tags (repeatable)
92
+ --group Nest keys by the first hyphen segment (cssVars.color.primary)
93
+ --helpers Also emit CssVarRef and getCssVar/setCssVar/withFallback
94
+ --prune Drop vars with no cssVars.<key> usage (needs --usage)
95
+ --usage <glob> Source files to scan for cssVars usage (repeatable)
96
+ --usage-exclude <glob> Source files to skip in the usage scan (repeatable)
97
+
98
+ Modes:
99
+ --watch Regenerate when input (or, with --prune, usage) files change
100
+ --check Exit 1 if the output is out of date, without writing
101
+ --prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
102
+ --lint-refs Exit 1 on var() references to undeclared variables
103
+ --refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
104
+ --version, -v Print the version
105
+ --help, -h Print this help
106
+
107
+ Docs: https://stanislavkozachenko.github.io/css-typed-vars/`;
108
+ function editDistance(a, b) {
109
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
110
+ for (let i = 1; i <= a.length; i++) {
111
+ const next = [i];
112
+ for (let j = 1; j <= b.length; j++) {
113
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
114
+ }
115
+ row = next;
116
+ }
117
+ return row[b.length];
118
+ }
119
+ function validateArgs() {
120
+ for (let i = 0; i < args.length; i++) {
121
+ const arg = args[i];
122
+ if (VALUE_FLAGS.includes(arg)) {
123
+ if (i + 1 >= args.length) throw new CliError(`css-typed-vars: ${arg} requires a value.`);
124
+ i++;
125
+ continue;
126
+ }
127
+ if (BOOLEAN_FLAGS.includes(arg)) continue;
128
+ if (arg.startsWith("-")) {
129
+ const known = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].filter((flag) => flag.startsWith("--"));
130
+ const closest = known.reduce((best, flag) => editDistance(arg, flag) < editDistance(arg, best) ? flag : best);
131
+ const hint = editDistance(arg, closest) <= 2 ? ` Did you mean ${closest}?` : "";
132
+ throw new CliError(`css-typed-vars: unknown option "${arg}".${hint} Run with --help to see all options.`);
133
+ }
134
+ throw new CliError(`css-typed-vars: unexpected argument "${arg}". If it's a glob, quote it so the shell doesn't expand it: --input "src/**/*.css".`);
135
+ }
136
+ }
137
+ var CliError = class extends Error {
138
+ };
139
+ var CONFIG_FILES = [
140
+ "css-typed-vars.config.js",
141
+ "css-typed-vars.config.mjs",
142
+ "css-typed-vars.config.cjs",
143
+ "css-typed-vars.config.ts",
144
+ "css-typed-vars.config.mts",
145
+ "css-typed-vars.config.json"
146
+ ];
147
+ async function importConfig(path) {
148
+ if (/\.json$/i.test(path)) return JSON.parse(await readFile(path, "utf8"));
149
+ const mod = await import(pathToFileURL(path).href);
150
+ return mod.default ?? {};
151
+ }
37
152
  async function loadConfig() {
38
- const candidates = [
39
- "css-typed-vars.config.js",
40
- "css-typed-vars.config.mjs",
41
- "css-typed-vars.config.json"
42
- ];
43
- for (const file of candidates) {
153
+ const explicit = getArg("--config");
154
+ if (explicit !== void 0) {
155
+ const path = resolve(process.cwd(), explicit);
156
+ if (!await exists(path)) throw new CliError(`css-typed-vars: config file "${explicit}" not found.`);
157
+ try {
158
+ return await importConfig(path);
159
+ } catch (err) {
160
+ throw new CliError(`css-typed-vars: failed to load config "${explicit}": ${err.message}`);
161
+ }
162
+ }
163
+ for (const file of CONFIG_FILES) {
44
164
  const path = resolve(process.cwd(), file);
165
+ if (!await exists(path)) continue;
45
166
  try {
46
- if (file.endsWith(".json")) {
47
- const content = await readFile(path, "utf8");
48
- return JSON.parse(content);
49
- } else {
50
- const mod = await import(pathToFileURL(path).href);
51
- return mod.default ?? {};
52
- }
167
+ return await importConfig(path);
53
168
  } catch (err) {
54
- const code = err.code;
55
- if (code === "ENOENT" || code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") continue;
56
169
  console.warn(`css-typed-vars: failed to load config "${file}": ${err.message}`);
57
170
  }
58
171
  }
59
172
  return {};
60
173
  }
61
- async function run(options) {
62
- await generate(options);
63
- console.log(`Generated \u2192 ${options.output}`);
64
- }
65
- async function main() {
66
- if (args.includes("--version") || args.includes("-v")) {
67
- const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
68
- console.log(pkg.version);
69
- process.exit(0);
70
- }
71
- const config = await loadConfig();
174
+ var exists = (path) => access(path).then(() => true, () => false);
175
+ function applyFlags(config) {
72
176
  const inputArgs = getArgs("--input");
73
- const input = inputArgs.length > 0 ? inputArgs : config.input;
74
- const output = getArg("--output") ?? config.output;
75
177
  const excludeArgs = getArgs("--exclude");
76
- const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
77
- const prefix = getArg("--prefix") ?? config.prefix;
78
- const namingRaw = getArg("--naming") ?? config.naming;
79
- if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
80
- console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
81
- process.exit(1);
82
- }
83
- const naming = namingRaw;
84
178
  const selectorArgs = getArgs("--selector");
85
- const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
86
179
  const themeArgs = getArgs("--theme");
87
180
  for (const arg of themeArgs) {
88
181
  if (!/^[^=]+=.+$/.test(arg)) {
89
- console.error(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
90
- process.exit(1);
182
+ throw new CliError(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
91
183
  }
92
184
  }
93
- const themes = themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes;
94
- const group = groupFlag || config.group;
95
- const prune = pruneFlag || config.prune;
96
185
  const usageArgs = getArgs("--usage");
97
- const usage = usageArgs.length > 0 ? usageArgs : config.usage;
98
186
  const usageExcludeArgs = getArgs("--usage-exclude");
99
- const usageExclude = usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude;
100
- const helpers = helpersFlag || config.helpers;
101
- if (!input || !output) {
102
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>]");
103
- console.error("Or add a css-typed-vars.config.js file with input and output fields.");
104
- process.exit(1);
187
+ const refsIgnoreArgs = getArgs("--refs-ignore");
188
+ return {
189
+ ...config,
190
+ input: inputArgs.length > 0 ? inputArgs : config.input,
191
+ output: getArg("--output") ?? config.output,
192
+ exclude: excludeArgs.length > 0 ? excludeArgs : config.exclude,
193
+ prefix: getArg("--prefix") ?? config.prefix,
194
+ naming: getArg("--naming") ?? config.naming,
195
+ selectors: selectorArgs.length > 0 ? selectorArgs : config.selectors,
196
+ themes: themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes,
197
+ group: args.includes("--group") || config.group,
198
+ prune: args.includes("--prune") || config.prune,
199
+ usage: usageArgs.length > 0 ? usageArgs : config.usage,
200
+ usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
201
+ helpers: args.includes("--helpers") || config.helpers,
202
+ refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
203
+ };
204
+ }
205
+ function loadTargets(config) {
206
+ if (!Array.isArray(config)) return [{ options: applyFlags(config), tag: "css-typed-vars" }];
207
+ if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
208
+ const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
209
+ if (used.length > 0) {
210
+ throw new CliError(`css-typed-vars: ${used.join(", ")} can't be used with an array config \u2014 set options per target in the config file instead.`);
105
211
  }
106
- if (checkMode && watchMode) {
107
- console.error("css-typed-vars: --check cannot be combined with --watch.");
108
- process.exit(1);
212
+ return config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
213
+ }
214
+ function validateModes() {
215
+ if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
216
+ throw new CliError("css-typed-vars: --lint-refs cannot be combined with --watch, --check or --prune-check.");
109
217
  }
218
+ if (checkMode && watchMode) throw new CliError("css-typed-vars: --check cannot be combined with --watch.");
110
219
  if (pruneCheckMode && (watchMode || checkMode)) {
111
- console.error("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
112
- process.exit(1);
220
+ throw new CliError("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
221
+ }
222
+ }
223
+ function validateTarget({ options, tag }, single) {
224
+ const { input, output, naming, group, prefix, prune, usage } = options;
225
+ if (naming !== void 0 && !VALID_NAMINGS.includes(naming)) {
226
+ throw new CliError(`${tag}: invalid --naming value "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
113
227
  }
114
- if (group && prefix) {
115
- console.error("css-typed-vars: --group cannot be combined with --prefix.");
116
- process.exit(1);
228
+ if (lintRefsMode) {
229
+ if (!input) throw new CliError(`${tag}: --lint-refs requires --input <glob> (or "input" in the config file).`);
230
+ return;
231
+ }
232
+ if (!input || !output) {
233
+ throw new CliError(single ? `${USAGE}
234
+ Or add a css-typed-vars.config.js file with input and output fields. Run with --help to see all options.` : `${tag}: every target needs "input" and "output".`);
117
235
  }
236
+ if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
118
237
  if ((prune || pruneCheckMode) && !usage) {
119
- console.error("css-typed-vars: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).");
120
- process.exit(1);
121
- }
122
- if (pruneCheckMode) {
123
- const unused = await findUnusedVars({ input, exclude, selectors, themes, prefix, naming, group, usage, usageExclude });
124
- if (unused.length > 0) {
125
- console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
126
- process.exit(1);
238
+ throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
239
+ }
240
+ }
241
+ async function lintRefs({ options, tag }) {
242
+ const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
243
+ const format = (ref) => ` ${relative(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
244
+ const errors = refs.filter((ref) => !ref.hasFallback);
245
+ const warnings = refs.filter((ref) => ref.hasFallback);
246
+ if (warnings.length > 0) {
247
+ console.warn(`${tag}: ${warnings.length} reference(s) to undeclared variables with a fallback:`);
248
+ for (const ref of warnings) console.warn(format(ref));
249
+ }
250
+ if (errors.length > 0) {
251
+ console.error(`${tag}: ${errors.length} reference(s) to undeclared variables:`);
252
+ for (const ref of errors) console.error(format(ref));
253
+ return false;
254
+ }
255
+ console.log(`${tag}: no references to undeclared variables.`);
256
+ return true;
257
+ }
258
+ async function pruneCheck({ options, tag }) {
259
+ const unused = await findUnusedVars({ ...options, input: options.input });
260
+ if (unused.length > 0) {
261
+ console.error(`${tag}: ${unused.length} unused variable(s): ${unused.join(", ")}`);
262
+ return false;
263
+ }
264
+ console.log(`${tag}: no unused variables.`);
265
+ return true;
266
+ }
267
+ async function check({ options, tag }) {
268
+ if (!await checkGenerated({ ...options, input: options.input, output: options.output })) {
269
+ console.error(`${tag}: "${options.output}" is out of date. Run without --check to regenerate.`);
270
+ return false;
271
+ }
272
+ console.log(`${tag}: "${options.output}" is up to date.`);
273
+ return true;
274
+ }
275
+ async function run({ options }) {
276
+ const written = await generate({ ...options, input: options.input, output: options.output });
277
+ console.log(`${written ? "Generated" : "Up to date"} \u2192 ${options.output}`);
278
+ }
279
+ var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
280
+ function watchTarget(target) {
281
+ const { input, exclude, output, prune, usage, usageExclude } = target.options;
282
+ const jsExt = /\.(m|c)?js$/i.exec(output);
283
+ const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => resolve(path)));
284
+ let timer = null;
285
+ let running = false;
286
+ let pending = false;
287
+ const regenerate = async () => {
288
+ if (running) {
289
+ pending = true;
290
+ return;
291
+ }
292
+ running = true;
293
+ await run(target).catch(console.error);
294
+ running = false;
295
+ if (pending) {
296
+ pending = false;
297
+ await regenerate();
127
298
  }
128
- console.log("css-typed-vars: no unused variables.");
299
+ };
300
+ const makeHandler = (label) => (file) => {
301
+ if (outputs.has(resolve(file))) return;
302
+ console.log(`${label}: ${file}`);
303
+ if (timer) clearTimeout(timer);
304
+ timer = setTimeout(() => {
305
+ timer = null;
306
+ void regenerate();
307
+ }, 100);
308
+ };
309
+ const subscribe = (patterns, ignored) => {
310
+ watch(patterns, { ignoreInitial: true, ...ignored.length > 0 ? { ignored } : {} }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
311
+ };
312
+ subscribe(toArray(input), toArray(exclude));
313
+ if (prune) subscribe(toArray(usage), toArray(usageExclude));
314
+ }
315
+ async function main() {
316
+ validateArgs();
317
+ if (args.includes("--help") || args.includes("-h")) {
318
+ console.log(HELP);
129
319
  return;
130
320
  }
131
- const runOptions = { input, output, exclude, prefix, naming, selectors, themes, group, prune, usage, usageExclude, helpers };
132
- if (checkMode) {
133
- const upToDate = await checkGenerated(runOptions);
134
- if (!upToDate) {
135
- console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
136
- process.exit(1);
321
+ if (args.includes("--version") || args.includes("-v")) {
322
+ const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
323
+ console.log(pkg.version);
324
+ process.exit(0);
325
+ }
326
+ const targets = loadTargets(await loadConfig());
327
+ validateModes();
328
+ for (const target of targets) validateTarget(target, targets.length === 1);
329
+ const mode = lintRefsMode ? lintRefs : pruneCheckMode ? pruneCheck : checkMode ? check : null;
330
+ if (mode) {
331
+ let ok = true;
332
+ for (const target of targets) {
333
+ if (!await mode(target)) ok = false;
137
334
  }
138
- console.log(`css-typed-vars: "${output}" is up to date.`);
335
+ if (!ok) process.exit(1);
139
336
  return;
140
337
  }
141
- await run(runOptions);
338
+ for (const target of targets) await run(target);
142
339
  if (watchMode) {
143
- const patterns = Array.isArray(input) ? input : [input];
144
- const makeHandler = (label) => (file) => {
145
- console.log(`${label}: ${file}`);
146
- run(runOptions).catch(console.error);
147
- };
148
- const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
149
- watch(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
340
+ for (const target of targets) watchTarget(target);
150
341
  console.log("Watching for changes...");
151
342
  }
152
343
  }
153
344
  main().catch((err) => {
154
- console.error(err);
345
+ console.error(err instanceof CliError ? err.message : err);
155
346
  process.exit(1);
156
347
  });