css-typed-vars 0.4.14 → 0.4.16

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.
@@ -1,10 +1,10 @@
1
1
  import {
2
- findKeyCollisions,
3
2
  generateCode,
4
3
  generateDeclaration,
5
4
  generateJs,
6
- scanVarNames
7
- } from "./chunk-3UIYKYIL.js";
5
+ scanVarNames,
6
+ warnOnCollisions
7
+ } from "./chunk-NS2BULH3.js";
8
8
 
9
9
  // src/index.ts
10
10
  import { writeFile, mkdir } from "fs/promises";
@@ -14,9 +14,7 @@ async function generate(options) {
14
14
  if (names.length === 0) {
15
15
  console.warn("css-typed-vars: no CSS custom properties found.");
16
16
  }
17
- for (const [key, vars] of findKeyCollisions(names, options.prefix, options.naming)) {
18
- console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
19
- }
17
+ warnOnCollisions(names, options.prefix, options.naming);
20
18
  const outPath = resolve(options.output);
21
19
  await mkdir(dirname(outPath), { recursive: true });
22
20
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
@@ -6,6 +6,12 @@ var getDirname = () => path.dirname(getFilename());
6
6
  var __dirname = /* @__PURE__ */ getDirname();
7
7
 
8
8
  // src/parser.ts
9
+ function stepQuote(text, i, quote) {
10
+ const char = text[i];
11
+ if (char === "\\" && i + 1 < text.length) return { consumed: 2, closed: false };
12
+ if (char === quote) return { consumed: 1, closed: true };
13
+ return { consumed: 1, closed: false };
14
+ }
9
15
  function stripComments(text) {
10
16
  let result = "";
11
17
  let quote = null;
@@ -13,12 +19,10 @@ function stripComments(text) {
13
19
  for (let i = 0; i < text.length; i++) {
14
20
  const char = text[i];
15
21
  if (quote) {
16
- result += char;
17
- if (char === "\\" && i + 1 < text.length) {
18
- result += text[++i];
19
- } else if (char === quote) {
20
- quote = null;
21
- }
22
+ const step = stepQuote(text, i, quote);
23
+ result += text.slice(i, i + step.consumed);
24
+ if (step.closed) quote = null;
25
+ i += step.consumed - 1;
22
26
  continue;
23
27
  }
24
28
  if (char === '"' || char === "'") {
@@ -80,15 +84,14 @@ function maskQuotedContent(text) {
80
84
  for (let i = 0; i < text.length; i++) {
81
85
  const char = text[i];
82
86
  if (quote) {
83
- if (char === "\\" && i + 1 < text.length) {
84
- result += " ";
85
- i++;
86
- } else if (char === quote) {
87
- quote = null;
87
+ const step = stepQuote(text, i, quote);
88
+ if (step.closed) {
88
89
  result += char;
90
+ quote = null;
89
91
  } else {
90
- result += " ";
92
+ result += " ".repeat(step.consumed);
91
93
  }
94
+ i += step.consumed - 1;
92
95
  continue;
93
96
  }
94
97
  if (char === '"' || char === "'") {
@@ -149,7 +152,7 @@ async function scanVarNames(patterns, exclude, selectors) {
149
152
  var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
150
153
  function convertCase(value, naming) {
151
154
  if (!VALID_NAMINGS.includes(naming)) {
152
- throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: camelCase, snake, kebab`);
155
+ throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
153
156
  }
154
157
  if (naming === "kebab") return value;
155
158
  return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
@@ -158,11 +161,27 @@ function toKey(cssVarName, naming = "camelCase") {
158
161
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
159
162
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
160
163
  }
164
+ var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
165
+ var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
166
+ var SINGLE_QUOTE_ESCAPES = {};
167
+ SINGLE_QUOTE_ESCAPES["\\"] = "\\\\";
168
+ SINGLE_QUOTE_ESCAPES["'"] = "\\'";
169
+ SINGLE_QUOTE_ESCAPES["\n"] = "\\n";
170
+ SINGLE_QUOTE_ESCAPES["\r"] = "\\r";
171
+ SINGLE_QUOTE_ESCAPES[LINE_SEPARATOR_CHAR] = "\\u2028";
172
+ SINGLE_QUOTE_ESCAPES[PARAGRAPH_SEPARATOR_CHAR] = "\\u2029";
173
+ function escapeSingleQuoted(value) {
174
+ let result = "";
175
+ for (const char of value) {
176
+ result += SINGLE_QUOTE_ESCAPES[char] ?? char;
177
+ }
178
+ return result;
179
+ }
161
180
  function applyPrefix(key, prefix, naming = "camelCase") {
162
181
  if (!prefix) return key;
163
182
  let normalizedPrefix = convertCase(prefix, naming);
164
183
  if (naming === "kebab") {
165
- normalizedPrefix = normalizedPrefix.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
184
+ normalizedPrefix = escapeSingleQuoted(normalizedPrefix);
166
185
  return `${normalizedPrefix}-${key}`;
167
186
  }
168
187
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
@@ -187,11 +206,21 @@ function findKeyCollisions(varNames, prefix, naming) {
187
206
  }
188
207
  return byKey;
189
208
  }
190
- function generateCode(varNames, prefix, naming) {
191
- const entries = varNames.map((name) => {
209
+ function warnOnCollisions(varNames, prefix, naming) {
210
+ for (const [key, vars] of findKeyCollisions(varNames, prefix, naming)) {
211
+ 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
+ }
213
+ }
214
+ function buildEntries(varNames, prefix, naming) {
215
+ const byKey = /* @__PURE__ */ new Map();
216
+ for (const name of varNames) {
192
217
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
193
- return ` ${key}: 'var(${name})',`;
194
- });
218
+ byKey.set(key, name);
219
+ }
220
+ return [...byKey].map(([key, name]) => ({ key, name }));
221
+ }
222
+ function generateCode(varNames, prefix, naming) {
223
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
195
224
  return [
196
225
  "// generated \u2014 do not edit",
197
226
  "export const cssVars = {",
@@ -203,10 +232,7 @@ function generateCode(varNames, prefix, naming) {
203
232
  ].join("\n");
204
233
  }
205
234
  function generateJs(varNames, prefix, naming) {
206
- const entries = varNames.map((name) => {
207
- const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
208
- return ` ${key}: 'var(${name})',`;
209
- });
235
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
210
236
  return [
211
237
  "// generated \u2014 do not edit",
212
238
  "export const cssVars = {",
@@ -216,10 +242,7 @@ function generateJs(varNames, prefix, naming) {
216
242
  ].join("\n");
217
243
  }
218
244
  function generateDeclaration(varNames, prefix, naming) {
219
- const entries = varNames.map((name) => {
220
- const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
221
- return ` ${key}: 'var(${name})';`;
222
- });
245
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
223
246
  return [
224
247
  "export declare const cssVars: {",
225
248
  ...entries,
@@ -233,7 +256,8 @@ export {
233
256
  __dirname,
234
257
  parseVarNames,
235
258
  scanVarNames,
236
- findKeyCollisions,
259
+ VALID_NAMINGS,
260
+ warnOnCollisions,
237
261
  generateCode,
238
262
  generateJs,
239
263
  generateDeclaration
@@ -2,8 +2,9 @@ import {
2
2
  __dirname,
3
3
  generateDeclaration,
4
4
  generateJs,
5
- scanVarNames
6
- } from "./chunk-3UIYKYIL.js";
5
+ scanVarNames,
6
+ warnOnCollisions
7
+ } from "./chunk-NS2BULH3.js";
7
8
 
8
9
  // src/unplugin.ts
9
10
  import { createUnplugin } from "unplugin";
@@ -22,31 +23,51 @@ var unplugin_default = createUnplugin((options) => {
22
23
  vite: {
23
24
  enforce: "pre",
24
25
  configureServer(server) {
25
- const handle = async (file) => {
26
- if (!/\.(css|scss|less)$/i.test(file)) return;
27
- cachedNames = scanVarNames(options.input, options.exclude, options.selectors);
28
- const names = await cachedNames;
26
+ let generation = 0;
27
+ let debounceTimer = null;
28
+ let writeQueue = Promise.resolve();
29
+ const rescan = async () => {
30
+ const myGeneration = ++generation;
31
+ const namesPromise = scanVarNames(options.input, options.exclude, options.selectors);
32
+ cachedNames = namesPromise;
33
+ const names = await namesPromise;
34
+ if (myGeneration !== generation) return;
35
+ warnOnCollisions(names, options.prefix, options.naming);
29
36
  const dtsPath = getDtsPath(options);
30
37
  if (dtsPath) {
31
- await writeFile(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
38
+ const content = generateDeclaration(names, options.prefix, options.naming);
39
+ writeQueue = writeQueue.then(async () => {
40
+ if (myGeneration !== generation) return;
41
+ await writeFile(dtsPath, content, "utf8");
42
+ }).catch(console.error);
43
+ await writeQueue;
32
44
  }
45
+ if (myGeneration !== generation) return;
33
46
  const mod = server.moduleGraph.getModuleById(RESOLVED_ID);
34
47
  if (mod) {
35
48
  server.moduleGraph.invalidateModule(mod);
36
49
  server.ws.send({ type: "full-reload" });
37
50
  }
38
51
  };
39
- const safeHandle = (file) => handle(file).catch(console.error);
40
- server.watcher.on("change", safeHandle);
41
- server.watcher.on("add", safeHandle);
42
- server.watcher.on("unlink", safeHandle);
52
+ const handle = (file) => {
53
+ if (!/\.(css|scss|less)$/i.test(file)) return;
54
+ if (debounceTimer) clearTimeout(debounceTimer);
55
+ debounceTimer = setTimeout(() => {
56
+ debounceTimer = null;
57
+ rescan().catch(console.error);
58
+ }, 100);
59
+ };
60
+ server.watcher.on("change", handle);
61
+ server.watcher.on("add", handle);
62
+ server.watcher.on("unlink", handle);
43
63
  }
44
64
  },
45
65
  async buildStart() {
46
66
  cachedNames = scanVarNames(options.input, options.exclude, options.selectors);
67
+ const names = await cachedNames;
68
+ warnOnCollisions(names, options.prefix, options.naming);
47
69
  const dtsPath = getDtsPath(options);
48
70
  if (!dtsPath) return;
49
- const names = await cachedNames;
50
71
  await writeFile(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
51
72
  },
52
73
  resolveId(id) {
package/dist/cli.cjs CHANGED
@@ -42,6 +42,12 @@ var import_promises = require("fs/promises");
42
42
  var import_fast_glob = __toESM(require("fast-glob"), 1);
43
43
 
44
44
  // src/parser.ts
45
+ function stepQuote(text, i, quote) {
46
+ const char = text[i];
47
+ if (char === "\\" && i + 1 < text.length) return { consumed: 2, closed: false };
48
+ if (char === quote) return { consumed: 1, closed: true };
49
+ return { consumed: 1, closed: false };
50
+ }
45
51
  function stripComments(text) {
46
52
  let result = "";
47
53
  let quote = null;
@@ -49,12 +55,10 @@ function stripComments(text) {
49
55
  for (let i = 0; i < text.length; i++) {
50
56
  const char = text[i];
51
57
  if (quote) {
52
- result += char;
53
- if (char === "\\" && i + 1 < text.length) {
54
- result += text[++i];
55
- } else if (char === quote) {
56
- quote = null;
57
- }
58
+ const step = stepQuote(text, i, quote);
59
+ result += text.slice(i, i + step.consumed);
60
+ if (step.closed) quote = null;
61
+ i += step.consumed - 1;
58
62
  continue;
59
63
  }
60
64
  if (char === '"' || char === "'") {
@@ -116,15 +120,14 @@ function maskQuotedContent(text) {
116
120
  for (let i = 0; i < text.length; i++) {
117
121
  const char = text[i];
118
122
  if (quote) {
119
- if (char === "\\" && i + 1 < text.length) {
120
- result += " ";
121
- i++;
122
- } else if (char === quote) {
123
- quote = null;
123
+ const step = stepQuote(text, i, quote);
124
+ if (step.closed) {
124
125
  result += char;
126
+ quote = null;
125
127
  } else {
126
- result += " ";
128
+ result += " ".repeat(step.consumed);
127
129
  }
130
+ i += step.consumed - 1;
128
131
  continue;
129
132
  }
130
133
  if (char === '"' || char === "'") {
@@ -183,7 +186,7 @@ async function scanVarNames(patterns, exclude, selectors) {
183
186
  var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
184
187
  function convertCase(value, naming) {
185
188
  if (!VALID_NAMINGS.includes(naming)) {
186
- throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: camelCase, snake, kebab`);
189
+ throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
187
190
  }
188
191
  if (naming === "kebab") return value;
189
192
  return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
@@ -192,11 +195,27 @@ function toKey(cssVarName, naming = "camelCase") {
192
195
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
193
196
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
194
197
  }
198
+ var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
199
+ var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
200
+ var SINGLE_QUOTE_ESCAPES = {};
201
+ SINGLE_QUOTE_ESCAPES["\\"] = "\\\\";
202
+ SINGLE_QUOTE_ESCAPES["'"] = "\\'";
203
+ SINGLE_QUOTE_ESCAPES["\n"] = "\\n";
204
+ SINGLE_QUOTE_ESCAPES["\r"] = "\\r";
205
+ SINGLE_QUOTE_ESCAPES[LINE_SEPARATOR_CHAR] = "\\u2028";
206
+ SINGLE_QUOTE_ESCAPES[PARAGRAPH_SEPARATOR_CHAR] = "\\u2029";
207
+ function escapeSingleQuoted(value) {
208
+ let result = "";
209
+ for (const char of value) {
210
+ result += SINGLE_QUOTE_ESCAPES[char] ?? char;
211
+ }
212
+ return result;
213
+ }
195
214
  function applyPrefix(key, prefix, naming = "camelCase") {
196
215
  if (!prefix) return key;
197
216
  let normalizedPrefix = convertCase(prefix, naming);
198
217
  if (naming === "kebab") {
199
- normalizedPrefix = normalizedPrefix.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
218
+ normalizedPrefix = escapeSingleQuoted(normalizedPrefix);
200
219
  return `${normalizedPrefix}-${key}`;
201
220
  }
202
221
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
@@ -221,11 +240,21 @@ function findKeyCollisions(varNames, prefix, naming) {
221
240
  }
222
241
  return byKey;
223
242
  }
224
- function generateCode(varNames, prefix, naming) {
225
- const entries = varNames.map((name) => {
243
+ function warnOnCollisions(varNames, prefix, naming) {
244
+ for (const [key, vars] of findKeyCollisions(varNames, prefix, naming)) {
245
+ 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
+ }
247
+ }
248
+ function buildEntries(varNames, prefix, naming) {
249
+ const byKey = /* @__PURE__ */ new Map();
250
+ for (const name of varNames) {
226
251
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
227
- return ` ${key}: 'var(${name})',`;
228
- });
252
+ byKey.set(key, name);
253
+ }
254
+ return [...byKey].map(([key, name]) => ({ key, name }));
255
+ }
256
+ function generateCode(varNames, prefix, naming) {
257
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
229
258
  return [
230
259
  "// generated \u2014 do not edit",
231
260
  "export const cssVars = {",
@@ -237,10 +266,7 @@ function generateCode(varNames, prefix, naming) {
237
266
  ].join("\n");
238
267
  }
239
268
  function generateJs(varNames, prefix, naming) {
240
- const entries = varNames.map((name) => {
241
- const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
242
- return ` ${key}: 'var(${name})',`;
243
- });
269
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
244
270
  return [
245
271
  "// generated \u2014 do not edit",
246
272
  "export const cssVars = {",
@@ -250,10 +276,7 @@ function generateJs(varNames, prefix, naming) {
250
276
  ].join("\n");
251
277
  }
252
278
  function generateDeclaration(varNames, prefix, naming) {
253
- const entries = varNames.map((name) => {
254
- const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
255
- return ` ${key}: 'var(${name})';`;
256
- });
279
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
257
280
  return [
258
281
  "export declare const cssVars: {",
259
282
  ...entries,
@@ -269,9 +292,7 @@ async function generate(options) {
269
292
  if (names.length === 0) {
270
293
  console.warn("css-typed-vars: no CSS custom properties found.");
271
294
  }
272
- for (const [key, vars] of findKeyCollisions(names, options.prefix, options.naming)) {
273
- console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
274
- }
295
+ warnOnCollisions(names, options.prefix, options.naming);
275
296
  const outPath = (0, import_node_path.resolve)(options.output);
276
297
  await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
277
298
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
@@ -343,8 +364,8 @@ async function main() {
343
364
  const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
344
365
  const prefix = getArg("--prefix") ?? config.prefix;
345
366
  const namingRaw = getArg("--naming") ?? config.naming;
346
- if (namingRaw !== void 0 && !["camelCase", "snake", "kebab"].includes(namingRaw)) {
347
- console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: camelCase, snake, kebab`);
367
+ if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
368
+ console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
348
369
  process.exit(1);
349
370
  }
350
371
  const naming = namingRaw;
package/dist/cli.js CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  generate
4
- } from "./chunk-2JDQ2DY7.js";
5
- import "./chunk-3UIYKYIL.js";
4
+ } from "./chunk-ARQR224L.js";
5
+ import {
6
+ VALID_NAMINGS
7
+ } from "./chunk-NS2BULH3.js";
6
8
 
7
9
  // src/cli.ts
8
10
  import { readFile } from "fs/promises";
@@ -67,8 +69,8 @@ async function main() {
67
69
  const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
68
70
  const prefix = getArg("--prefix") ?? config.prefix;
69
71
  const namingRaw = getArg("--naming") ?? config.naming;
70
- if (namingRaw !== void 0 && !["camelCase", "snake", "kebab"].includes(namingRaw)) {
71
- console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: camelCase, snake, kebab`);
72
+ if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
73
+ console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
72
74
  process.exit(1);
73
75
  }
74
76
  const naming = namingRaw;
package/dist/esbuild.cjs CHANGED
@@ -44,6 +44,12 @@ var import_promises = require("fs/promises");
44
44
  var import_fast_glob = __toESM(require("fast-glob"), 1);
45
45
 
46
46
  // src/parser.ts
47
+ function stepQuote(text, i, quote) {
48
+ const char = text[i];
49
+ if (char === "\\" && i + 1 < text.length) return { consumed: 2, closed: false };
50
+ if (char === quote) return { consumed: 1, closed: true };
51
+ return { consumed: 1, closed: false };
52
+ }
47
53
  function stripComments(text) {
48
54
  let result = "";
49
55
  let quote = null;
@@ -51,12 +57,10 @@ function stripComments(text) {
51
57
  for (let i = 0; i < text.length; i++) {
52
58
  const char = text[i];
53
59
  if (quote) {
54
- result += char;
55
- if (char === "\\" && i + 1 < text.length) {
56
- result += text[++i];
57
- } else if (char === quote) {
58
- quote = null;
59
- }
60
+ const step = stepQuote(text, i, quote);
61
+ result += text.slice(i, i + step.consumed);
62
+ if (step.closed) quote = null;
63
+ i += step.consumed - 1;
60
64
  continue;
61
65
  }
62
66
  if (char === '"' || char === "'") {
@@ -118,15 +122,14 @@ function maskQuotedContent(text) {
118
122
  for (let i = 0; i < text.length; i++) {
119
123
  const char = text[i];
120
124
  if (quote) {
121
- if (char === "\\" && i + 1 < text.length) {
122
- result += " ";
123
- i++;
124
- } else if (char === quote) {
125
- quote = null;
125
+ const step = stepQuote(text, i, quote);
126
+ if (step.closed) {
126
127
  result += char;
128
+ quote = null;
127
129
  } else {
128
- result += " ";
130
+ result += " ".repeat(step.consumed);
129
131
  }
132
+ i += step.consumed - 1;
130
133
  continue;
131
134
  }
132
135
  if (char === '"' || char === "'") {
@@ -185,7 +188,7 @@ async function scanVarNames(patterns, exclude, selectors) {
185
188
  var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
186
189
  function convertCase(value, naming) {
187
190
  if (!VALID_NAMINGS.includes(naming)) {
188
- throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: camelCase, snake, kebab`);
191
+ throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
189
192
  }
190
193
  if (naming === "kebab") return value;
191
194
  return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
@@ -194,11 +197,27 @@ function toKey(cssVarName, naming = "camelCase") {
194
197
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
195
198
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
196
199
  }
200
+ var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
201
+ var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
202
+ var SINGLE_QUOTE_ESCAPES = {};
203
+ SINGLE_QUOTE_ESCAPES["\\"] = "\\\\";
204
+ SINGLE_QUOTE_ESCAPES["'"] = "\\'";
205
+ SINGLE_QUOTE_ESCAPES["\n"] = "\\n";
206
+ SINGLE_QUOTE_ESCAPES["\r"] = "\\r";
207
+ SINGLE_QUOTE_ESCAPES[LINE_SEPARATOR_CHAR] = "\\u2028";
208
+ SINGLE_QUOTE_ESCAPES[PARAGRAPH_SEPARATOR_CHAR] = "\\u2029";
209
+ function escapeSingleQuoted(value) {
210
+ let result = "";
211
+ for (const char of value) {
212
+ result += SINGLE_QUOTE_ESCAPES[char] ?? char;
213
+ }
214
+ return result;
215
+ }
197
216
  function applyPrefix(key, prefix, naming = "camelCase") {
198
217
  if (!prefix) return key;
199
218
  let normalizedPrefix = convertCase(prefix, naming);
200
219
  if (naming === "kebab") {
201
- normalizedPrefix = normalizedPrefix.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
220
+ normalizedPrefix = escapeSingleQuoted(normalizedPrefix);
202
221
  return `${normalizedPrefix}-${key}`;
203
222
  }
204
223
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
@@ -210,11 +229,34 @@ function formatKey(key, naming = "camelCase") {
210
229
  if (naming === "kebab") return `'${key}'`;
211
230
  return key;
212
231
  }
213
- function generateJs(varNames, prefix, naming) {
214
- const entries = varNames.map((name) => {
232
+ function findKeyCollisions(varNames, prefix, naming) {
233
+ const byKey = /* @__PURE__ */ new Map();
234
+ for (const name of varNames) {
235
+ const key = applyPrefix(toKey(name, naming), prefix, naming);
236
+ const existing = byKey.get(key);
237
+ if (existing) existing.push(name);
238
+ else byKey.set(key, [name]);
239
+ }
240
+ for (const [key, names] of byKey) {
241
+ if (names.length < 2) byKey.delete(key);
242
+ }
243
+ return byKey;
244
+ }
245
+ function warnOnCollisions(varNames, prefix, naming) {
246
+ for (const [key, vars] of findKeyCollisions(varNames, prefix, naming)) {
247
+ console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
248
+ }
249
+ }
250
+ function buildEntries(varNames, prefix, naming) {
251
+ const byKey = /* @__PURE__ */ new Map();
252
+ for (const name of varNames) {
215
253
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
216
- return ` ${key}: 'var(${name})',`;
217
- });
254
+ byKey.set(key, name);
255
+ }
256
+ return [...byKey].map(([key, name]) => ({ key, name }));
257
+ }
258
+ function generateJs(varNames, prefix, naming) {
259
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
218
260
  return [
219
261
  "// generated \u2014 do not edit",
220
262
  "export const cssVars = {",
@@ -224,10 +266,7 @@ function generateJs(varNames, prefix, naming) {
224
266
  ].join("\n");
225
267
  }
226
268
  function generateDeclaration(varNames, prefix, naming) {
227
- const entries = varNames.map((name) => {
228
- const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
229
- return ` ${key}: 'var(${name})';`;
230
- });
269
+ const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
231
270
  return [
232
271
  "export declare const cssVars: {",
233
272
  ...entries,
@@ -251,31 +290,51 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
251
290
  vite: {
252
291
  enforce: "pre",
253
292
  configureServer(server) {
254
- const handle = async (file) => {
255
- if (!/\.(css|scss|less)$/i.test(file)) return;
256
- cachedNames = scanVarNames(options.input, options.exclude, options.selectors);
257
- const names = await cachedNames;
293
+ let generation = 0;
294
+ let debounceTimer = null;
295
+ let writeQueue = Promise.resolve();
296
+ const rescan = async () => {
297
+ const myGeneration = ++generation;
298
+ const namesPromise = scanVarNames(options.input, options.exclude, options.selectors);
299
+ cachedNames = namesPromise;
300
+ const names = await namesPromise;
301
+ if (myGeneration !== generation) return;
302
+ warnOnCollisions(names, options.prefix, options.naming);
258
303
  const dtsPath = getDtsPath(options);
259
304
  if (dtsPath) {
260
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
305
+ const content = generateDeclaration(names, options.prefix, options.naming);
306
+ writeQueue = writeQueue.then(async () => {
307
+ if (myGeneration !== generation) return;
308
+ await (0, import_promises2.writeFile)(dtsPath, content, "utf8");
309
+ }).catch(console.error);
310
+ await writeQueue;
261
311
  }
312
+ if (myGeneration !== generation) return;
262
313
  const mod = server.moduleGraph.getModuleById(RESOLVED_ID);
263
314
  if (mod) {
264
315
  server.moduleGraph.invalidateModule(mod);
265
316
  server.ws.send({ type: "full-reload" });
266
317
  }
267
318
  };
268
- const safeHandle = (file) => handle(file).catch(console.error);
269
- server.watcher.on("change", safeHandle);
270
- server.watcher.on("add", safeHandle);
271
- server.watcher.on("unlink", safeHandle);
319
+ const handle = (file) => {
320
+ if (!/\.(css|scss|less)$/i.test(file)) return;
321
+ if (debounceTimer) clearTimeout(debounceTimer);
322
+ debounceTimer = setTimeout(() => {
323
+ debounceTimer = null;
324
+ rescan().catch(console.error);
325
+ }, 100);
326
+ };
327
+ server.watcher.on("change", handle);
328
+ server.watcher.on("add", handle);
329
+ server.watcher.on("unlink", handle);
272
330
  }
273
331
  },
274
332
  async buildStart() {
275
333
  cachedNames = scanVarNames(options.input, options.exclude, options.selectors);
334
+ const names = await cachedNames;
335
+ warnOnCollisions(names, options.prefix, options.naming);
276
336
  const dtsPath = getDtsPath(options);
277
337
  if (!dtsPath) return;
278
- const names = await cachedNames;
279
338
  await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
280
339
  },
281
340
  resolveId(id) {
package/dist/esbuild.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-HS4B2QT2.js";
4
- import "./chunk-3UIYKYIL.js";
3
+ } from "./chunk-YJPHNISO.js";
4
+ import "./chunk-NS2BULH3.js";
5
5
 
6
6
  // src/esbuild.ts
7
7
  var esbuild_default = unplugin_default.esbuild;