css-typed-vars 0.10.0 → 0.11.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 +15 -1
- package/dist/{chunk-NZUQZYNM.js → chunk-CBN3J54B.js} +17 -7
- package/dist/{chunk-O7MEOCHS.js → chunk-P3HJQZ6Y.js} +1 -1
- package/dist/{chunk-XCAFJREQ.js → chunk-TR53YUPE.js} +16 -7
- package/dist/cli.cjs +98 -34
- package/dist/cli.js +61 -16
- package/dist/esbuild.cjs +31 -13
- package/dist/esbuild.js +2 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -2
- package/dist/rollup.cjs +31 -13
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +31 -13
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +31 -13
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +31 -13
- package/dist/webpack.js +2 -2
- package/package.json +6 -4
- package/schema.json +84 -0
package/README.md
CHANGED
|
@@ -141,7 +141,7 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
|
|
|
141
141
|
| `--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`. |
|
|
142
142
|
| `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)`/`withFallback(ref, fallback)` helpers — see [Usage](#usage). |
|
|
143
143
|
| `--prune` | Drop generated vars with no detected `cssVars.<key>` usage. Requires `--usage <glob>` (repeatable). With `--group`, matches `cssVars.<group>.<key>` and keeps a whole group referenced as `cssVars.<group>`. |
|
|
144
|
-
| `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Useful in CI. |
|
|
144
|
+
| `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Doesn't need `--output`. Useful in CI. |
|
|
145
145
|
| `--lint-refs` | Report `var(--name)` references to variables not declared anywhere in the input; exits 1 if any (without a fallback) are found — see [Linting var() references](#linting-var-references) |
|
|
146
146
|
| `--refs-ignore` | Name or `--prefix-*` pattern for `--lint-refs` to skip (repeatable) |
|
|
147
147
|
| `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
|
|
@@ -217,6 +217,18 @@ export default defineConfig({
|
|
|
217
217
|
});
|
|
218
218
|
```
|
|
219
219
|
|
|
220
|
+
For a JSON config, point `$schema` at the bundled JSON Schema to get the same autocompletion and validation in your editor:
|
|
221
|
+
|
|
222
|
+
```json
|
|
223
|
+
{
|
|
224
|
+
"$schema": "./node_modules/css-typed-vars/schema.json",
|
|
225
|
+
"input": "src/styles/**/*.css",
|
|
226
|
+
"output": "src/cssVars.ts"
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
An unknown key in any config file (a typo like `"ouput"`) is reported as a warning, with the closest option suggested.
|
|
231
|
+
|
|
220
232
|
#### Multiple targets
|
|
221
233
|
|
|
222
234
|
Export an array to generate several files in one run — e.g. one per package in a monorepo, or a TypeScript file plus a design tokens file:
|
|
@@ -242,6 +254,8 @@ No file is generated — CSS variables are served as a virtual module directly b
|
|
|
242
254
|
|
|
243
255
|
TypeScript types are written to `node_modules/css-typed-vars/dist/generated.d.ts` automatically on each build or dev server start.
|
|
244
256
|
|
|
257
|
+
In watch builds (`vite build --watch`, `rollup --watch`, `webpack --watch`, esbuild's `context.watch()`), editing a scanned CSS file triggers a rebuild.
|
|
258
|
+
|
|
245
259
|
### Vite
|
|
246
260
|
|
|
247
261
|
```ts
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
scanUsage,
|
|
13
13
|
warnOnCollisions,
|
|
14
14
|
writeOutput
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-TR53YUPE.js";
|
|
16
16
|
|
|
17
17
|
// src/unplugin.ts
|
|
18
18
|
import { createUnplugin } from "unplugin";
|
|
@@ -31,18 +31,23 @@ function outputFiles(options, names, generatorOptions) {
|
|
|
31
31
|
if (options.tokens) files.push([resolve(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
|
|
32
32
|
return files;
|
|
33
33
|
}
|
|
34
|
-
var unplugin_default = createUnplugin((options) => {
|
|
34
|
+
var unplugin_default = createUnplugin((options, meta) => {
|
|
35
35
|
assertPruneCompatible(options);
|
|
36
36
|
let cachedScan = null;
|
|
37
|
+
let devServer = false;
|
|
37
38
|
const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
38
39
|
const applyPrune = async (names) => {
|
|
39
|
-
if (!options.prune) return names;
|
|
40
|
+
if (!options.prune) return { names, usageFiles: [] };
|
|
40
41
|
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
41
42
|
const { used, unused } = partitionUnused(names, usage, options);
|
|
42
43
|
if (unused.length > 0) {
|
|
43
44
|
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
44
45
|
}
|
|
45
|
-
return used;
|
|
46
|
+
return { names: used, usageFiles: usage.files };
|
|
47
|
+
};
|
|
48
|
+
const watchFiles = (context, scanned, usageFiles) => {
|
|
49
|
+
if (devServer) return;
|
|
50
|
+
for (const file of [...scanned.files, ...usageFiles]) context.addWatchFile(resolve(file));
|
|
46
51
|
};
|
|
47
52
|
const generatorOptions = ({ declarations, properties, themes, docs }) => ({
|
|
48
53
|
prefix: options.prefix,
|
|
@@ -63,6 +68,9 @@ var unplugin_default = createUnplugin((options) => {
|
|
|
63
68
|
name: "css-typed-vars",
|
|
64
69
|
vite: {
|
|
65
70
|
enforce: "pre",
|
|
71
|
+
configResolved(config) {
|
|
72
|
+
devServer = config.command === "serve";
|
|
73
|
+
},
|
|
66
74
|
configureServer(server) {
|
|
67
75
|
let generation = 0;
|
|
68
76
|
let debounceTimer = null;
|
|
@@ -73,7 +81,7 @@ var unplugin_default = createUnplugin((options) => {
|
|
|
73
81
|
cachedScan = scanPromise;
|
|
74
82
|
const scanned = await scanPromise;
|
|
75
83
|
if (myGeneration !== generation) return;
|
|
76
|
-
const names = await resolveNames(scanned);
|
|
84
|
+
const { names } = await resolveNames(scanned);
|
|
77
85
|
if (myGeneration !== generation) return;
|
|
78
86
|
const files = outputFiles(options, names, generatorOptions(scanned));
|
|
79
87
|
if (files.length > 0) {
|
|
@@ -113,7 +121,8 @@ var unplugin_default = createUnplugin((options) => {
|
|
|
113
121
|
async buildStart() {
|
|
114
122
|
cachedScan = scan();
|
|
115
123
|
const scanned = await cachedScan;
|
|
116
|
-
const names = await resolveNames(scanned);
|
|
124
|
+
const { names, usageFiles } = await resolveNames(scanned);
|
|
125
|
+
if (meta.framework !== "esbuild") watchFiles(this, scanned, usageFiles);
|
|
117
126
|
for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
|
|
118
127
|
await writeOutput(path, content);
|
|
119
128
|
}
|
|
@@ -124,7 +133,8 @@ var unplugin_default = createUnplugin((options) => {
|
|
|
124
133
|
async load(id) {
|
|
125
134
|
if (id === RESOLVED_ID) {
|
|
126
135
|
const scanned = await (cachedScan ?? scan());
|
|
127
|
-
const names = await applyPrune(collectVarNames(scanned));
|
|
136
|
+
const { names, usageFiles } = await applyPrune(collectVarNames(scanned));
|
|
137
|
+
watchFiles(this, scanned, usageFiles);
|
|
128
138
|
return generateJs(names, generatorOptions(scanned));
|
|
129
139
|
}
|
|
130
140
|
}
|
|
@@ -342,12 +342,20 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
|
|
|
342
342
|
return matches(include) && !matches(ignore);
|
|
343
343
|
};
|
|
344
344
|
}
|
|
345
|
+
function globWatchRoots(patterns, cwd = process.cwd()) {
|
|
346
|
+
const roots = /* @__PURE__ */ new Map();
|
|
347
|
+
for (const pattern of normalizePatterns(patterns)) {
|
|
348
|
+
const { base, glob, isGlob } = picomatch.scan(pattern);
|
|
349
|
+
const dir = resolve(cwd, isGlob ? base || "." : dirname2(pattern));
|
|
350
|
+
const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob) ? void 0 : glob.split("/").length - 1;
|
|
351
|
+
const previous = roots.get(dir);
|
|
352
|
+
const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
|
|
353
|
+
roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
|
|
354
|
+
}
|
|
355
|
+
return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
|
|
356
|
+
}
|
|
345
357
|
function globBaseDirs(patterns, cwd = process.cwd()) {
|
|
346
|
-
|
|
347
|
-
const { base, isGlob } = picomatch.scan(pattern);
|
|
348
|
-
return resolve(cwd, isGlob ? base || "." : dirname2(pattern));
|
|
349
|
-
});
|
|
350
|
-
return [...new Set(dirs)];
|
|
358
|
+
return globWatchRoots(patterns, cwd).map((root) => root.dir);
|
|
351
359
|
}
|
|
352
360
|
function collectVarNames(scanned) {
|
|
353
361
|
const names = new Set(scanned.declarations.keys());
|
|
@@ -385,7 +393,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
385
393
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
386
394
|
}
|
|
387
395
|
}
|
|
388
|
-
return { declarations, properties, themes: themeValues, docs };
|
|
396
|
+
return { declarations, properties, themes: themeValues, docs, files };
|
|
389
397
|
}
|
|
390
398
|
async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
391
399
|
return (await scanCss(patterns, exclude, selectors)).declarations;
|
|
@@ -426,7 +434,7 @@ async function scanUsage(patterns, exclude) {
|
|
|
426
434
|
const normalized = normalizePatterns(patterns);
|
|
427
435
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
428
436
|
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
429
|
-
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
437
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
|
|
430
438
|
const texts = await Promise.all(
|
|
431
439
|
files.map(async (file) => {
|
|
432
440
|
try {
|
|
@@ -846,6 +854,7 @@ export {
|
|
|
846
854
|
parseVarReferences,
|
|
847
855
|
parseDeclaredNames,
|
|
848
856
|
createFileMatcher,
|
|
857
|
+
globWatchRoots,
|
|
849
858
|
globBaseDirs,
|
|
850
859
|
collectVarNames,
|
|
851
860
|
scanCss,
|
package/dist/cli.cjs
CHANGED
|
@@ -33,24 +33,9 @@ var import_node_path4 = require("path");
|
|
|
33
33
|
var import_node_url = require("url");
|
|
34
34
|
var import_chokidar = require("chokidar");
|
|
35
35
|
|
|
36
|
-
// src/
|
|
37
|
-
var import_promises3 = require("fs/promises");
|
|
38
|
-
var import_node_path3 = require("path");
|
|
39
|
-
|
|
40
|
-
// src/write.ts
|
|
36
|
+
// src/scanner.ts
|
|
41
37
|
var import_promises = require("fs/promises");
|
|
42
38
|
var import_node_path = require("path");
|
|
43
|
-
async function writeOutput(path, content) {
|
|
44
|
-
const current = await (0, import_promises.readFile)(path, "utf8").catch(() => null);
|
|
45
|
-
if (current === content) return false;
|
|
46
|
-
await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
|
|
47
|
-
await (0, import_promises.writeFile)(path, content, "utf8");
|
|
48
|
-
return true;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// src/scanner.ts
|
|
52
|
-
var import_promises2 = require("fs/promises");
|
|
53
|
-
var import_node_path2 = require("path");
|
|
54
39
|
var import_fast_glob = __toESM(require("fast-glob"), 1);
|
|
55
40
|
var import_picomatch = __toESM(require("picomatch"), 1);
|
|
56
41
|
|
|
@@ -355,6 +340,29 @@ function parseDeclaredNames(css) {
|
|
|
355
340
|
function normalizePatterns(patterns) {
|
|
356
341
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
357
342
|
}
|
|
343
|
+
function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
|
|
344
|
+
const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
|
|
345
|
+
const include = compile(patterns);
|
|
346
|
+
const ignore = exclude ? compile(exclude) : () => false;
|
|
347
|
+
return (file) => {
|
|
348
|
+
const absolute = (0, import_node_path.resolve)(cwd, file).replace(/\\/g, "/");
|
|
349
|
+
const fromCwd = (0, import_node_path.relative)(cwd, absolute).replace(/\\/g, "/");
|
|
350
|
+
const matches = (test) => test(fromCwd) || test(absolute);
|
|
351
|
+
return matches(include) && !matches(ignore);
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
function globWatchRoots(patterns, cwd = process.cwd()) {
|
|
355
|
+
const roots = /* @__PURE__ */ new Map();
|
|
356
|
+
for (const pattern of normalizePatterns(patterns)) {
|
|
357
|
+
const { base, glob, isGlob } = import_picomatch.default.scan(pattern);
|
|
358
|
+
const dir = (0, import_node_path.resolve)(cwd, isGlob ? base || "." : (0, import_node_path.dirname)(pattern));
|
|
359
|
+
const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob) ? void 0 : glob.split("/").length - 1;
|
|
360
|
+
const previous = roots.get(dir);
|
|
361
|
+
const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
|
|
362
|
+
roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
|
|
363
|
+
}
|
|
364
|
+
return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
|
|
365
|
+
}
|
|
358
366
|
function collectVarNames(scanned) {
|
|
359
367
|
const names = new Set(scanned.declarations.keys());
|
|
360
368
|
for (const values of scanned.themes.values()) {
|
|
@@ -370,7 +378,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
370
378
|
files.map(async (file) => {
|
|
371
379
|
let css;
|
|
372
380
|
try {
|
|
373
|
-
css = await (0,
|
|
381
|
+
css = await (0, import_promises.readFile)(file, "utf8");
|
|
374
382
|
} catch (err) {
|
|
375
383
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
376
384
|
return null;
|
|
@@ -391,7 +399,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
391
399
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
392
400
|
}
|
|
393
401
|
}
|
|
394
|
-
return { declarations, properties, themes: themeValues, docs };
|
|
402
|
+
return { declarations, properties, themes: themeValues, docs, files };
|
|
395
403
|
}
|
|
396
404
|
var ROOT_RE = /\bcssVars\b/g;
|
|
397
405
|
var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
|
|
@@ -425,11 +433,11 @@ async function scanUsage(patterns, exclude) {
|
|
|
425
433
|
const normalized = normalizePatterns(patterns);
|
|
426
434
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
427
435
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
428
|
-
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
436
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
|
|
429
437
|
const texts = await Promise.all(
|
|
430
438
|
files.map(async (file) => {
|
|
431
439
|
try {
|
|
432
|
-
return await (0,
|
|
440
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
433
441
|
} catch (err) {
|
|
434
442
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
435
443
|
return "";
|
|
@@ -446,7 +454,7 @@ async function scanReferences(patterns, exclude) {
|
|
|
446
454
|
const perFile = await Promise.all(
|
|
447
455
|
files.map(async (file) => {
|
|
448
456
|
try {
|
|
449
|
-
return { file, css: await (0,
|
|
457
|
+
return { file, css: await (0, import_promises.readFile)(file, "utf8") };
|
|
450
458
|
} catch (err) {
|
|
451
459
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
452
460
|
return null;
|
|
@@ -463,6 +471,21 @@ async function scanReferences(patterns, exclude) {
|
|
|
463
471
|
return { references, declared };
|
|
464
472
|
}
|
|
465
473
|
|
|
474
|
+
// src/index.ts
|
|
475
|
+
var import_promises3 = require("fs/promises");
|
|
476
|
+
var import_node_path3 = require("path");
|
|
477
|
+
|
|
478
|
+
// src/write.ts
|
|
479
|
+
var import_promises2 = require("fs/promises");
|
|
480
|
+
var import_node_path2 = require("path");
|
|
481
|
+
async function writeOutput(path, content) {
|
|
482
|
+
const current = await (0, import_promises2.readFile)(path, "utf8").catch(() => null);
|
|
483
|
+
if (current === content) return false;
|
|
484
|
+
await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(path), { recursive: true });
|
|
485
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
486
|
+
return true;
|
|
487
|
+
}
|
|
488
|
+
|
|
466
489
|
// src/generator.ts
|
|
467
490
|
var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
|
|
468
491
|
function convertCase(value, naming) {
|
|
@@ -909,6 +932,23 @@ async function checkGenerated(options) {
|
|
|
909
932
|
return true;
|
|
910
933
|
}
|
|
911
934
|
|
|
935
|
+
// src/config.ts
|
|
936
|
+
var CONFIG_KEYS = [
|
|
937
|
+
"input",
|
|
938
|
+
"output",
|
|
939
|
+
"exclude",
|
|
940
|
+
"prefix",
|
|
941
|
+
"naming",
|
|
942
|
+
"selectors",
|
|
943
|
+
"themes",
|
|
944
|
+
"group",
|
|
945
|
+
"prune",
|
|
946
|
+
"usage",
|
|
947
|
+
"usageExclude",
|
|
948
|
+
"helpers",
|
|
949
|
+
"refsIgnore"
|
|
950
|
+
];
|
|
951
|
+
|
|
912
952
|
// src/cli.ts
|
|
913
953
|
var args = process.argv.slice(2).flatMap((arg) => {
|
|
914
954
|
const match = /^(--[\w-]+)=(.*)$/.exec(arg);
|
|
@@ -1012,6 +1052,10 @@ function editDistance(a, b) {
|
|
|
1012
1052
|
}
|
|
1013
1053
|
return row[b.length];
|
|
1014
1054
|
}
|
|
1055
|
+
function suggest(value, candidates) {
|
|
1056
|
+
const closest = candidates.reduce((best, candidate) => editDistance(value, candidate) < editDistance(value, best) ? candidate : best);
|
|
1057
|
+
return editDistance(value, closest) <= 2 ? ` Did you mean ${closest}?` : "";
|
|
1058
|
+
}
|
|
1015
1059
|
function validateArgs() {
|
|
1016
1060
|
for (let i = 0; i < args.length; i++) {
|
|
1017
1061
|
const arg = args[i];
|
|
@@ -1023,9 +1067,7 @@ function validateArgs() {
|
|
|
1023
1067
|
if (BOOLEAN_FLAGS.includes(arg)) continue;
|
|
1024
1068
|
if (arg.startsWith("-")) {
|
|
1025
1069
|
const known = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].filter((flag) => flag.startsWith("--"));
|
|
1026
|
-
|
|
1027
|
-
const hint = editDistance(arg, closest) <= 2 ? ` Did you mean ${closest}?` : "";
|
|
1028
|
-
throw new CliError(`css-typed-vars: unknown option "${arg}".${hint} Run with --help to see all options.`);
|
|
1070
|
+
throw new CliError(`css-typed-vars: unknown option "${arg}".${suggest(arg, known)} Run with --help to see all options.`);
|
|
1029
1071
|
}
|
|
1030
1072
|
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".`);
|
|
1031
1073
|
}
|
|
@@ -1068,6 +1110,13 @@ async function loadConfig() {
|
|
|
1068
1110
|
return {};
|
|
1069
1111
|
}
|
|
1070
1112
|
var exists = (path) => (0, import_promises4.access)(path).then(() => true, () => false);
|
|
1113
|
+
function warnUnknownKeys(config, tag) {
|
|
1114
|
+
if (typeof config !== "object" || config === null) return;
|
|
1115
|
+
for (const key of Object.keys(config)) {
|
|
1116
|
+
if (key === "$schema" || CONFIG_KEYS.includes(key)) continue;
|
|
1117
|
+
console.warn(`${tag}: unknown option "${key}" in the config file.${suggest(key, CONFIG_KEYS)}`);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1071
1120
|
function applyFlags(config) {
|
|
1072
1121
|
const inputArgs = getArgs("--input");
|
|
1073
1122
|
const excludeArgs = getArgs("--exclude");
|
|
@@ -1099,13 +1148,18 @@ function applyFlags(config) {
|
|
|
1099
1148
|
};
|
|
1100
1149
|
}
|
|
1101
1150
|
function loadTargets(config) {
|
|
1102
|
-
if (!Array.isArray(config))
|
|
1151
|
+
if (!Array.isArray(config)) {
|
|
1152
|
+
warnUnknownKeys(config, "css-typed-vars");
|
|
1153
|
+
return [{ options: applyFlags(config), tag: "css-typed-vars" }];
|
|
1154
|
+
}
|
|
1103
1155
|
if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
|
|
1104
1156
|
const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
|
|
1105
1157
|
if (used.length > 0) {
|
|
1106
1158
|
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.`);
|
|
1107
1159
|
}
|
|
1108
|
-
|
|
1160
|
+
const targets = config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
|
|
1161
|
+
for (const { options, tag } of targets) warnUnknownKeys(options, tag);
|
|
1162
|
+
return targets;
|
|
1109
1163
|
}
|
|
1110
1164
|
function validateModes() {
|
|
1111
1165
|
if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
|
|
@@ -1125,7 +1179,10 @@ function validateTarget({ options, tag }, single) {
|
|
|
1125
1179
|
if (!input) throw new CliError(`${tag}: --lint-refs requires --input <glob> (or "input" in the config file).`);
|
|
1126
1180
|
return;
|
|
1127
1181
|
}
|
|
1128
|
-
if (
|
|
1182
|
+
if (pruneCheckMode && !input) {
|
|
1183
|
+
throw new CliError(`${tag}: --prune-check requires --input <glob> (or "input" in the config file).`);
|
|
1184
|
+
}
|
|
1185
|
+
if (!input || !output && !pruneCheckMode) {
|
|
1129
1186
|
throw new CliError(single ? `${USAGE}
|
|
1130
1187
|
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".`);
|
|
1131
1188
|
}
|
|
@@ -1193,20 +1250,27 @@ function watchTarget(target) {
|
|
|
1193
1250
|
await regenerate();
|
|
1194
1251
|
}
|
|
1195
1252
|
};
|
|
1253
|
+
const isInput = createFileMatcher(input, exclude);
|
|
1254
|
+
const isUsage = prune ? createFileMatcher(usage, usageExclude) : () => false;
|
|
1255
|
+
const isWatched = (file) => !outputs.has((0, import_node_path4.resolve)(file)) && (isInput(file) || isUsage(file));
|
|
1196
1256
|
const makeHandler = (label) => (file) => {
|
|
1197
|
-
if (
|
|
1198
|
-
console.log(`${label}: ${file}`);
|
|
1257
|
+
if (!isWatched(file)) return;
|
|
1258
|
+
console.log(`${label}: ${(0, import_node_path4.relative)(process.cwd(), file).replace(/\\/g, "/")}`);
|
|
1199
1259
|
if (timer) clearTimeout(timer);
|
|
1200
1260
|
timer = setTimeout(() => {
|
|
1201
1261
|
timer = null;
|
|
1202
1262
|
void regenerate();
|
|
1203
1263
|
}, 100);
|
|
1204
1264
|
};
|
|
1205
|
-
const
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1265
|
+
const roots = globWatchRoots([...toArray(input), ...prune ? toArray(usage) : []]);
|
|
1266
|
+
for (const { dir, depth } of roots) {
|
|
1267
|
+
(0, import_chokidar.watch)(dir, {
|
|
1268
|
+
ignoreInitial: true,
|
|
1269
|
+
depth,
|
|
1270
|
+
// No need to watch a file that can't match; directories are still traversed.
|
|
1271
|
+
ignored: (path, stats) => stats?.isFile() === true && !isWatched(path)
|
|
1272
|
+
}).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
1273
|
+
}
|
|
1210
1274
|
}
|
|
1211
1275
|
async function main() {
|
|
1212
1276
|
validateArgs();
|
package/dist/cli.js
CHANGED
|
@@ -4,16 +4,37 @@ import {
|
|
|
4
4
|
findUndefinedRefs,
|
|
5
5
|
findUnusedVars,
|
|
6
6
|
generate
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-P3HJQZ6Y.js";
|
|
8
8
|
import {
|
|
9
|
-
VALID_NAMINGS
|
|
10
|
-
|
|
9
|
+
VALID_NAMINGS,
|
|
10
|
+
createFileMatcher,
|
|
11
|
+
globWatchRoots
|
|
12
|
+
} from "./chunk-TR53YUPE.js";
|
|
11
13
|
|
|
12
14
|
// src/cli.ts
|
|
13
15
|
import { access, readFile } from "fs/promises";
|
|
14
16
|
import { relative, resolve } from "path";
|
|
15
17
|
import { pathToFileURL } from "url";
|
|
16
18
|
import { watch } from "chokidar";
|
|
19
|
+
|
|
20
|
+
// src/config.ts
|
|
21
|
+
var CONFIG_KEYS = [
|
|
22
|
+
"input",
|
|
23
|
+
"output",
|
|
24
|
+
"exclude",
|
|
25
|
+
"prefix",
|
|
26
|
+
"naming",
|
|
27
|
+
"selectors",
|
|
28
|
+
"themes",
|
|
29
|
+
"group",
|
|
30
|
+
"prune",
|
|
31
|
+
"usage",
|
|
32
|
+
"usageExclude",
|
|
33
|
+
"helpers",
|
|
34
|
+
"refsIgnore"
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
// src/cli.ts
|
|
17
38
|
var args = process.argv.slice(2).flatMap((arg) => {
|
|
18
39
|
const match = /^(--[\w-]+)=(.*)$/.exec(arg);
|
|
19
40
|
return match ? [match[1], match[2]] : [arg];
|
|
@@ -116,6 +137,10 @@ function editDistance(a, b) {
|
|
|
116
137
|
}
|
|
117
138
|
return row[b.length];
|
|
118
139
|
}
|
|
140
|
+
function suggest(value, candidates) {
|
|
141
|
+
const closest = candidates.reduce((best, candidate) => editDistance(value, candidate) < editDistance(value, best) ? candidate : best);
|
|
142
|
+
return editDistance(value, closest) <= 2 ? ` Did you mean ${closest}?` : "";
|
|
143
|
+
}
|
|
119
144
|
function validateArgs() {
|
|
120
145
|
for (let i = 0; i < args.length; i++) {
|
|
121
146
|
const arg = args[i];
|
|
@@ -127,9 +152,7 @@ function validateArgs() {
|
|
|
127
152
|
if (BOOLEAN_FLAGS.includes(arg)) continue;
|
|
128
153
|
if (arg.startsWith("-")) {
|
|
129
154
|
const known = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].filter((flag) => flag.startsWith("--"));
|
|
130
|
-
|
|
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.`);
|
|
155
|
+
throw new CliError(`css-typed-vars: unknown option "${arg}".${suggest(arg, known)} Run with --help to see all options.`);
|
|
133
156
|
}
|
|
134
157
|
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
158
|
}
|
|
@@ -172,6 +195,13 @@ async function loadConfig() {
|
|
|
172
195
|
return {};
|
|
173
196
|
}
|
|
174
197
|
var exists = (path) => access(path).then(() => true, () => false);
|
|
198
|
+
function warnUnknownKeys(config, tag) {
|
|
199
|
+
if (typeof config !== "object" || config === null) return;
|
|
200
|
+
for (const key of Object.keys(config)) {
|
|
201
|
+
if (key === "$schema" || CONFIG_KEYS.includes(key)) continue;
|
|
202
|
+
console.warn(`${tag}: unknown option "${key}" in the config file.${suggest(key, CONFIG_KEYS)}`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
175
205
|
function applyFlags(config) {
|
|
176
206
|
const inputArgs = getArgs("--input");
|
|
177
207
|
const excludeArgs = getArgs("--exclude");
|
|
@@ -203,13 +233,18 @@ function applyFlags(config) {
|
|
|
203
233
|
};
|
|
204
234
|
}
|
|
205
235
|
function loadTargets(config) {
|
|
206
|
-
if (!Array.isArray(config))
|
|
236
|
+
if (!Array.isArray(config)) {
|
|
237
|
+
warnUnknownKeys(config, "css-typed-vars");
|
|
238
|
+
return [{ options: applyFlags(config), tag: "css-typed-vars" }];
|
|
239
|
+
}
|
|
207
240
|
if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
|
|
208
241
|
const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
|
|
209
242
|
if (used.length > 0) {
|
|
210
243
|
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.`);
|
|
211
244
|
}
|
|
212
|
-
|
|
245
|
+
const targets = config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
|
|
246
|
+
for (const { options, tag } of targets) warnUnknownKeys(options, tag);
|
|
247
|
+
return targets;
|
|
213
248
|
}
|
|
214
249
|
function validateModes() {
|
|
215
250
|
if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
|
|
@@ -229,7 +264,10 @@ function validateTarget({ options, tag }, single) {
|
|
|
229
264
|
if (!input) throw new CliError(`${tag}: --lint-refs requires --input <glob> (or "input" in the config file).`);
|
|
230
265
|
return;
|
|
231
266
|
}
|
|
232
|
-
if (
|
|
267
|
+
if (pruneCheckMode && !input) {
|
|
268
|
+
throw new CliError(`${tag}: --prune-check requires --input <glob> (or "input" in the config file).`);
|
|
269
|
+
}
|
|
270
|
+
if (!input || !output && !pruneCheckMode) {
|
|
233
271
|
throw new CliError(single ? `${USAGE}
|
|
234
272
|
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".`);
|
|
235
273
|
}
|
|
@@ -297,20 +335,27 @@ function watchTarget(target) {
|
|
|
297
335
|
await regenerate();
|
|
298
336
|
}
|
|
299
337
|
};
|
|
338
|
+
const isInput = createFileMatcher(input, exclude);
|
|
339
|
+
const isUsage = prune ? createFileMatcher(usage, usageExclude) : () => false;
|
|
340
|
+
const isWatched = (file) => !outputs.has(resolve(file)) && (isInput(file) || isUsage(file));
|
|
300
341
|
const makeHandler = (label) => (file) => {
|
|
301
|
-
if (
|
|
302
|
-
console.log(`${label}: ${file}`);
|
|
342
|
+
if (!isWatched(file)) return;
|
|
343
|
+
console.log(`${label}: ${relative(process.cwd(), file).replace(/\\/g, "/")}`);
|
|
303
344
|
if (timer) clearTimeout(timer);
|
|
304
345
|
timer = setTimeout(() => {
|
|
305
346
|
timer = null;
|
|
306
347
|
void regenerate();
|
|
307
348
|
}, 100);
|
|
308
349
|
};
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
350
|
+
const roots = globWatchRoots([...toArray(input), ...prune ? toArray(usage) : []]);
|
|
351
|
+
for (const { dir, depth } of roots) {
|
|
352
|
+
watch(dir, {
|
|
353
|
+
ignoreInitial: true,
|
|
354
|
+
depth,
|
|
355
|
+
// No need to watch a file that can't match; directories are still traversed.
|
|
356
|
+
ignored: (path, stats) => stats?.isFile() === true && !isWatched(path)
|
|
357
|
+
}).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
358
|
+
}
|
|
314
359
|
}
|
|
315
360
|
async function main() {
|
|
316
361
|
validateArgs();
|
package/dist/esbuild.cjs
CHANGED
|
@@ -348,12 +348,20 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
|
|
|
348
348
|
return matches(include) && !matches(ignore);
|
|
349
349
|
};
|
|
350
350
|
}
|
|
351
|
+
function globWatchRoots(patterns, cwd = process.cwd()) {
|
|
352
|
+
const roots = /* @__PURE__ */ new Map();
|
|
353
|
+
for (const pattern of normalizePatterns(patterns)) {
|
|
354
|
+
const { base, glob, isGlob } = import_picomatch.default.scan(pattern);
|
|
355
|
+
const dir = (0, import_node_path2.resolve)(cwd, isGlob ? base || "." : (0, import_node_path2.dirname)(pattern));
|
|
356
|
+
const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob) ? void 0 : glob.split("/").length - 1;
|
|
357
|
+
const previous = roots.get(dir);
|
|
358
|
+
const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
|
|
359
|
+
roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
|
|
360
|
+
}
|
|
361
|
+
return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
|
|
362
|
+
}
|
|
351
363
|
function globBaseDirs(patterns, cwd = process.cwd()) {
|
|
352
|
-
|
|
353
|
-
const { base, isGlob } = import_picomatch.default.scan(pattern);
|
|
354
|
-
return (0, import_node_path2.resolve)(cwd, isGlob ? base || "." : (0, import_node_path2.dirname)(pattern));
|
|
355
|
-
});
|
|
356
|
-
return [...new Set(dirs)];
|
|
364
|
+
return globWatchRoots(patterns, cwd).map((root) => root.dir);
|
|
357
365
|
}
|
|
358
366
|
function collectVarNames(scanned) {
|
|
359
367
|
const names = new Set(scanned.declarations.keys());
|
|
@@ -391,7 +399,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
391
399
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
392
400
|
}
|
|
393
401
|
}
|
|
394
|
-
return { declarations, properties, themes: themeValues, docs };
|
|
402
|
+
return { declarations, properties, themes: themeValues, docs, files };
|
|
395
403
|
}
|
|
396
404
|
var ROOT_RE = /\bcssVars\b/g;
|
|
397
405
|
var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
|
|
@@ -425,7 +433,7 @@ async function scanUsage(patterns, exclude) {
|
|
|
425
433
|
const normalized = normalizePatterns(patterns);
|
|
426
434
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
427
435
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
428
|
-
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
436
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
|
|
429
437
|
const texts = await Promise.all(
|
|
430
438
|
files.map(async (file) => {
|
|
431
439
|
try {
|
|
@@ -794,18 +802,23 @@ function outputFiles(options, names, generatorOptions) {
|
|
|
794
802
|
if (options.tokens) files.push([(0, import_node_path3.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
|
|
795
803
|
return files;
|
|
796
804
|
}
|
|
797
|
-
var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
805
|
+
var unplugin_default = (0, import_unplugin.createUnplugin)((options, meta) => {
|
|
798
806
|
assertPruneCompatible(options);
|
|
799
807
|
let cachedScan = null;
|
|
808
|
+
let devServer = false;
|
|
800
809
|
const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
801
810
|
const applyPrune = async (names) => {
|
|
802
|
-
if (!options.prune) return names;
|
|
811
|
+
if (!options.prune) return { names, usageFiles: [] };
|
|
803
812
|
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
804
813
|
const { used, unused } = partitionUnused(names, usage, options);
|
|
805
814
|
if (unused.length > 0) {
|
|
806
815
|
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
807
816
|
}
|
|
808
|
-
return used;
|
|
817
|
+
return { names: used, usageFiles: usage.files };
|
|
818
|
+
};
|
|
819
|
+
const watchFiles = (context, scanned, usageFiles) => {
|
|
820
|
+
if (devServer) return;
|
|
821
|
+
for (const file of [...scanned.files, ...usageFiles]) context.addWatchFile((0, import_node_path3.resolve)(file));
|
|
809
822
|
};
|
|
810
823
|
const generatorOptions = ({ declarations, properties, themes, docs }) => ({
|
|
811
824
|
prefix: options.prefix,
|
|
@@ -826,6 +839,9 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
826
839
|
name: "css-typed-vars",
|
|
827
840
|
vite: {
|
|
828
841
|
enforce: "pre",
|
|
842
|
+
configResolved(config) {
|
|
843
|
+
devServer = config.command === "serve";
|
|
844
|
+
},
|
|
829
845
|
configureServer(server) {
|
|
830
846
|
let generation = 0;
|
|
831
847
|
let debounceTimer = null;
|
|
@@ -836,7 +852,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
836
852
|
cachedScan = scanPromise;
|
|
837
853
|
const scanned = await scanPromise;
|
|
838
854
|
if (myGeneration !== generation) return;
|
|
839
|
-
const names = await resolveNames(scanned);
|
|
855
|
+
const { names } = await resolveNames(scanned);
|
|
840
856
|
if (myGeneration !== generation) return;
|
|
841
857
|
const files = outputFiles(options, names, generatorOptions(scanned));
|
|
842
858
|
if (files.length > 0) {
|
|
@@ -876,7 +892,8 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
876
892
|
async buildStart() {
|
|
877
893
|
cachedScan = scan();
|
|
878
894
|
const scanned = await cachedScan;
|
|
879
|
-
const names = await resolveNames(scanned);
|
|
895
|
+
const { names, usageFiles } = await resolveNames(scanned);
|
|
896
|
+
if (meta.framework !== "esbuild") watchFiles(this, scanned, usageFiles);
|
|
880
897
|
for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
|
|
881
898
|
await writeOutput(path, content);
|
|
882
899
|
}
|
|
@@ -887,7 +904,8 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
887
904
|
async load(id) {
|
|
888
905
|
if (id === RESOLVED_ID) {
|
|
889
906
|
const scanned = await (cachedScan ?? scan());
|
|
890
|
-
const names = await applyPrune(collectVarNames(scanned));
|
|
907
|
+
const { names, usageFiles } = await applyPrune(collectVarNames(scanned));
|
|
908
|
+
watchFiles(this, scanned, usageFiles);
|
|
891
909
|
return generateJs(names, generatorOptions(scanned));
|
|
892
910
|
}
|
|
893
911
|
}
|