@csszyx/unplugin 0.8.0 → 0.9.1

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.
Files changed (48) hide show
  1. package/README.md +16 -7
  2. package/dist/css-mangler.cjs +4 -4
  3. package/dist/css-mangler.mjs +4 -4
  4. package/dist/index.cjs +23 -1
  5. package/dist/index.d.cts +100 -5
  6. package/dist/index.d.mts +99 -3
  7. package/dist/index.mjs +7 -1
  8. package/dist/next-prebuild.cjs +148 -0
  9. package/dist/next-prebuild.d.cts +66 -0
  10. package/dist/next-prebuild.d.mts +66 -0
  11. package/dist/next-prebuild.mjs +131 -0
  12. package/dist/next-turbo-loader.cjs +210 -0
  13. package/dist/next-turbo-loader.d.cts +68 -0
  14. package/dist/next-turbo-loader.d.mts +66 -0
  15. package/dist/next-turbo-loader.mjs +190 -0
  16. package/dist/next-watcher.cjs +237 -0
  17. package/dist/next-watcher.d.cts +106 -0
  18. package/dist/next-watcher.d.mts +106 -0
  19. package/dist/next-watcher.mjs +219 -0
  20. package/dist/shared/unplugin.8er8o6rn.mjs +276 -0
  21. package/dist/shared/unplugin.B_U4rZvG.cjs +281 -0
  22. package/dist/shared/unplugin.BbtspS8t.mjs +3271 -0
  23. package/dist/shared/unplugin.BceVw1eW.mjs +184 -0
  24. package/dist/shared/unplugin.BtQzlC2C.mjs +567 -0
  25. package/dist/shared/unplugin.CFp386gH.cjs +3321 -0
  26. package/dist/shared/unplugin.CPEWNSA0.d.cts +77 -0
  27. package/dist/shared/unplugin.CPEWNSA0.d.mts +77 -0
  28. package/dist/shared/unplugin.CScQRdTp.d.cts +15 -0
  29. package/dist/shared/unplugin.CScQRdTp.d.mts +15 -0
  30. package/dist/shared/unplugin.CdZxp0x-.d.mts +16 -0
  31. package/dist/shared/unplugin.DLrBgECN.d.cts +282 -0
  32. package/dist/shared/unplugin.DLrBgECN.d.mts +282 -0
  33. package/dist/shared/unplugin.DUxdYaSG.cjs +205 -0
  34. package/dist/shared/unplugin.s62yJbu1.cjs +591 -0
  35. package/dist/shared/unplugin.xeED_qwh.d.cts +16 -0
  36. package/dist/vite.cjs +7 -1
  37. package/dist/vite.d.cts +2 -1
  38. package/dist/vite.d.mts +2 -1
  39. package/dist/vite.mjs +7 -1
  40. package/dist/webpack.cjs +7 -1
  41. package/dist/webpack.d.cts +2 -1
  42. package/dist/webpack.d.mts +2 -1
  43. package/dist/webpack.mjs +7 -1
  44. package/package.json +41 -8
  45. package/dist/shared/unplugin.BNsv2szs.cjs +0 -1753
  46. package/dist/shared/unplugin.DCv0RtVZ.mjs +0 -1722
  47. package/dist/shared/unplugin.DUbr5w-N.d.cts +0 -49
  48. package/dist/shared/unplugin.DUbr5w-N.d.mts +0 -49
@@ -0,0 +1,3321 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const node_module = require('node:module');
5
+ const path = require('node:path');
6
+ const node_perf_hooks = require('node:perf_hooks');
7
+ const node_url = require('node:url');
8
+ const compiler = require('@csszyx/compiler');
9
+ const core = require('@csszyx/core');
10
+ const svelteAdapter = require('@csszyx/svelte-adapter');
11
+ const types = require('@csszyx/types');
12
+ const vueAdapter = require('@csszyx/vue-adapter');
13
+ const unplugin$1 = require('unplugin');
14
+ const cssMangler = require('../css-mangler.cjs');
15
+ const node_crypto = require('node:crypto');
16
+ const transformCache = require('./unplugin.DUxdYaSG.cjs');
17
+ const postcss = require('postcss');
18
+ const valueParser = require('postcss-value-parser');
19
+
20
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
22
+
23
+ function _interopNamespaceCompat(e) {
24
+ if (e && typeof e === 'object' && 'default' in e) return e;
25
+ const n = Object.create(null);
26
+ if (e) {
27
+ for (const k in e) {
28
+ n[k] = e[k];
29
+ }
30
+ }
31
+ n.default = e;
32
+ return n;
33
+ }
34
+
35
+ const fs__namespace = /*#__PURE__*/_interopNamespaceCompat(fs);
36
+ const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
37
+ const postcss__default = /*#__PURE__*/_interopDefaultCompat(postcss);
38
+ const valueParser__default = /*#__PURE__*/_interopDefaultCompat(valueParser);
39
+
40
+ function resolveGlobalVarScanCacheDir(cacheDir) {
41
+ return path__namespace.join(cacheDir, "global-vars");
42
+ }
43
+ function createGlobalVarScanCacheKey(input) {
44
+ const hash = node_crypto.createHash("sha256");
45
+ hash.update(input.filePath);
46
+ hash.update("\0");
47
+ hash.update(String(input.mtimeMs));
48
+ hash.update("\0");
49
+ hash.update(node_crypto.createHash("sha256").update(input.css).digest("hex"));
50
+ return hash.digest("hex");
51
+ }
52
+ function readGlobalVarScanCache(cacheDir, key) {
53
+ try {
54
+ const raw = fs__namespace.readFileSync(globalVarScanCacheFile(cacheDir, key), "utf8");
55
+ const entry = JSON.parse(raw);
56
+ if (entry.key !== key || !entry.result) {
57
+ return null;
58
+ }
59
+ return entry.result;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+ function writeGlobalVarScanCache(cacheDir, key, result) {
65
+ try {
66
+ fs__namespace.mkdirSync(cacheDir, { recursive: true });
67
+ fs__namespace.writeFileSync(
68
+ globalVarScanCacheFile(cacheDir, key),
69
+ JSON.stringify({ key, result }),
70
+ "utf8"
71
+ );
72
+ } catch {
73
+ }
74
+ }
75
+ function globalVarScanCacheFile(cacheDir, key) {
76
+ return path__namespace.join(cacheDir, `${key}.json`);
77
+ }
78
+
79
+ const DEFAULT_SCOPE_ID = "<root>";
80
+ function isInsideThemeAtRule(node) {
81
+ let current = node.parent;
82
+ while (current && current.type !== "root") {
83
+ if (current.type === "atrule" && current.name === "theme") {
84
+ return true;
85
+ }
86
+ current = current.parent;
87
+ }
88
+ return false;
89
+ }
90
+ function hasSiblingDeclaration(decl, prop) {
91
+ const parent = decl.parent;
92
+ if (!parent || !("nodes" in parent)) {
93
+ return false;
94
+ }
95
+ return parent.nodes.some((node) => node.type === "decl" && node.prop === prop);
96
+ }
97
+ function nodeLocation(node, filePath) {
98
+ return {
99
+ filePath,
100
+ line: node.source?.start?.line ?? 1,
101
+ column: node.source?.start?.column ?? 1
102
+ };
103
+ }
104
+ function buildScopeId(node) {
105
+ const parts = [];
106
+ let current = node.parent;
107
+ while (current && current.type !== "root") {
108
+ if (current.type === "rule") {
109
+ parts.push(`rule:${current.selector}`);
110
+ } else if (current.type === "atrule") {
111
+ const atRule = current;
112
+ parts.push(`@${atRule.name} ${atRule.params}`.trim());
113
+ }
114
+ current = current.parent;
115
+ }
116
+ return parts.reverse().join(" > ") || DEFAULT_SCOPE_ID;
117
+ }
118
+
119
+ const VAR_REFERENCE_RE = /var\(\s*(--[\w-]+)/g;
120
+ function scanGlobalVarCss(css, options = {}) {
121
+ const filePath = options.filePath ?? "<inline>";
122
+ const root = postcss__default.parse(css, { from: filePath });
123
+ const registered = collectRegisteredProperties(root);
124
+ const definitions = [];
125
+ const references = [];
126
+ root.walkDecls((decl) => {
127
+ const scopeId = buildScopeId(decl);
128
+ const tailwindOwned = isInsideThemeAtRule(decl);
129
+ if (decl.prop.startsWith("--")) {
130
+ definitions.push({
131
+ name: decl.prop,
132
+ scopeId,
133
+ tailwindOwned,
134
+ registered: registered.has(decl.prop),
135
+ ...nodeLocation(decl, filePath)
136
+ });
137
+ }
138
+ for (const name of extractVarReferences(decl.value)) {
139
+ references.push({
140
+ name,
141
+ scopeId,
142
+ owner: decl.prop,
143
+ tailwindOwned,
144
+ ...nodeLocation(decl, filePath)
145
+ });
146
+ }
147
+ });
148
+ root.walkAtRules((atRule) => {
149
+ if (atRule.name === "property") {
150
+ return;
151
+ }
152
+ for (const name of extractVarReferences(atRule.params)) {
153
+ references.push({
154
+ name,
155
+ scopeId: buildScopeId(atRule),
156
+ owner: `@${atRule.name}`,
157
+ tailwindOwned: isInsideThemeAtRule(atRule),
158
+ ...nodeLocation(atRule, filePath)
159
+ });
160
+ }
161
+ });
162
+ return {
163
+ filePath,
164
+ definitions,
165
+ references,
166
+ registered: [...registered].sort(),
167
+ thirdParty: isThirdPartyCssPath(filePath)
168
+ };
169
+ }
170
+ function collectRegisteredProperties(root) {
171
+ const registered = /* @__PURE__ */ new Set();
172
+ root.walkAtRules("property", (atRule) => {
173
+ const name = atRule.params.trim();
174
+ if (name.startsWith("--")) {
175
+ registered.add(name);
176
+ }
177
+ });
178
+ return registered;
179
+ }
180
+ function extractVarReferences(value) {
181
+ const references = /* @__PURE__ */ new Set();
182
+ for (const match of value.matchAll(VAR_REFERENCE_RE)) {
183
+ references.add(match[1]);
184
+ }
185
+ return [...references].sort();
186
+ }
187
+ function isThirdPartyCssPath(filePath) {
188
+ return filePath.split(/[\\/]/).includes("node_modules");
189
+ }
190
+
191
+ function planGlobalVarAliases(input) {
192
+ const definitions = flattenDefinitions(input.scans);
193
+ const candidates = collectCandidates(input, definitions);
194
+ const aliasPrefix = input.aliasPrefix ?? types.CSSZYX_GLOBAL_ALIAS_PREFIX;
195
+ const diagnostics = validateCandidates(
196
+ candidates,
197
+ definitions,
198
+ input.reserved ?? [],
199
+ aliasPrefix
200
+ );
201
+ if (diagnostics.length > 0) {
202
+ return { entries: [], aliases: /* @__PURE__ */ new Map(), diagnostics };
203
+ }
204
+ const definitionNames = new Set(definitions.keys());
205
+ const entries = [];
206
+ for (const [index, original] of candidates.entries()) {
207
+ const alias = `${aliasPrefix}${core.encode(index)}`;
208
+ if (definitionNames.has(alias)) {
209
+ return {
210
+ entries: [],
211
+ aliases: /* @__PURE__ */ new Map(),
212
+ diagnostics: [
213
+ {
214
+ code: "alias-collision",
215
+ severity: "error",
216
+ name: alias,
217
+ message: `Generated alias ${alias} collides with an existing CSS custom property.`,
218
+ location: definitions.get(alias)?.[0]
219
+ }
220
+ ]
221
+ };
222
+ }
223
+ entries.push({
224
+ original,
225
+ alias,
226
+ scopes: [
227
+ ...new Set((definitions.get(original) ?? []).map((definition) => definition.scopeId))
228
+ ].sort()
229
+ });
230
+ }
231
+ return {
232
+ entries,
233
+ aliases: new Map(entries.map((entry) => [entry.original, entry.alias])),
234
+ diagnostics: []
235
+ };
236
+ }
237
+ function isTailwindReservedGlobalVar(name) {
238
+ return types.isTailwindReservedCustomProperty(name);
239
+ }
240
+ function flattenDefinitions(scans) {
241
+ const definitions = /* @__PURE__ */ new Map();
242
+ for (const scan of scans) {
243
+ for (const definition of scan.definitions) {
244
+ const existing = definitions.get(definition.name) ?? [];
245
+ existing.push(definition);
246
+ definitions.set(definition.name, existing);
247
+ }
248
+ }
249
+ return definitions;
250
+ }
251
+ function collectCandidates(input, definitions) {
252
+ const candidates = new Set(input.tokens ?? []);
253
+ const autoPrefix = input.autoPrefix ?? "";
254
+ if (autoPrefix !== "") {
255
+ for (const name of definitions.keys()) {
256
+ if (name.startsWith(autoPrefix)) {
257
+ candidates.add(name);
258
+ }
259
+ }
260
+ }
261
+ return [...candidates].sort();
262
+ }
263
+ function validateCandidates(candidates, definitions, reserved, aliasPrefix) {
264
+ const diagnostics = [];
265
+ for (const name of candidates) {
266
+ const tokenDefinitions = definitions.get(name) ?? [];
267
+ if (tokenDefinitions.length === 0) {
268
+ diagnostics.push({
269
+ code: "missing-definition",
270
+ severity: "error",
271
+ name,
272
+ message: `Global variable token ${name} is not defined in scanned CSS.`
273
+ });
274
+ continue;
275
+ }
276
+ if (isTailwindReservedGlobalVar(name) || matchesUserReserved(name, reserved)) {
277
+ diagnostics.push({
278
+ code: "tailwind-reserved",
279
+ severity: "error",
280
+ name,
281
+ message: `Global variable token ${name} is reserved and cannot be aliased.`,
282
+ location: tokenDefinitions[0]
283
+ });
284
+ }
285
+ if (types.isCsszyxGlobalAliasCustomProperty(name, aliasPrefix)) {
286
+ diagnostics.push({
287
+ code: "tailwind-reserved",
288
+ severity: "error",
289
+ name,
290
+ message: `Global variable token ${name} uses csszyx reserved namespace ${aliasPrefix}* and cannot be aliased.`,
291
+ location: tokenDefinitions[0]
292
+ });
293
+ }
294
+ const tailwindDefinition = tokenDefinitions.find((definition) => definition.tailwindOwned);
295
+ if (tailwindDefinition) {
296
+ diagnostics.push({
297
+ code: "tailwind-owned",
298
+ severity: "error",
299
+ name,
300
+ message: `Global variable token ${name} is declared inside @theme and cannot be aliased.`,
301
+ location: tailwindDefinition
302
+ });
303
+ }
304
+ const registeredDefinition = tokenDefinitions.find((definition) => definition.registered);
305
+ if (registeredDefinition) {
306
+ diagnostics.push({
307
+ code: "registered-property",
308
+ severity: "error",
309
+ name,
310
+ message: `Registered custom property ${name} is not aliasable in Phase H v1.`,
311
+ location: registeredDefinition
312
+ });
313
+ }
314
+ }
315
+ return diagnostics;
316
+ }
317
+ function matchesUserReserved(name, reserved) {
318
+ return reserved.some((pattern) => {
319
+ if (pattern.endsWith("*")) {
320
+ return name.startsWith(pattern.slice(0, -1));
321
+ }
322
+ return name === pattern;
323
+ });
324
+ }
325
+
326
+ function rewriteGlobalVarCssAliases(options) {
327
+ if (options.plan.diagnostics.length > 0 || options.plan.entries.length === 0) {
328
+ return {
329
+ css: options.css,
330
+ aliasDeclarations: 0,
331
+ rewrittenReferences: 0,
332
+ diagnostics: options.plan.diagnostics
333
+ };
334
+ }
335
+ const root = postcss__default.parse(options.css, { from: options.filePath });
336
+ const aliasNames = new Set(options.plan.entries.map((entry) => entry.alias));
337
+ const referenceAliases = new Map(
338
+ options.plan.entries.filter((entry) => canRewriteGlobalVarReferences(entry)).map((entry) => [entry.original, entry.alias])
339
+ );
340
+ let aliasDeclarations = 0;
341
+ let rewrittenReferences = 0;
342
+ root.walkDecls((decl) => {
343
+ if (isInsideThemeAtRule(decl)) {
344
+ return;
345
+ }
346
+ const alias = options.plan.aliases.get(decl.prop);
347
+ if (alias && !hasSiblingDeclaration(decl, alias)) {
348
+ decl.cloneAfter({ prop: alias, value: `var(${decl.prop})` });
349
+ aliasDeclarations++;
350
+ }
351
+ if (options.plan.aliases.has(decl.prop) || aliasNames.has(decl.prop)) {
352
+ return;
353
+ }
354
+ const rewrite = rewriteGlobalVarValue(decl.value, referenceAliases);
355
+ if (rewrite.count > 0) {
356
+ decl.value = rewrite.value;
357
+ rewrittenReferences += rewrite.count;
358
+ }
359
+ });
360
+ return {
361
+ css: root.toString(),
362
+ aliasDeclarations,
363
+ rewrittenReferences,
364
+ diagnostics: []
365
+ };
366
+ }
367
+ function canRewriteGlobalVarReferences(entry) {
368
+ return entry.scopes.some(isInheritedGlobalAliasScope);
369
+ }
370
+ function isInheritedGlobalAliasScope(scope) {
371
+ const leaf = scope.split(" > ").at(-1);
372
+ if (!leaf?.startsWith("rule:")) {
373
+ return false;
374
+ }
375
+ const selector = leaf.slice("rule:".length);
376
+ return selector.split(",").some((part) => {
377
+ const normalized = part.trim();
378
+ return normalized === ":root" || normalized === "html" || normalized === "body";
379
+ });
380
+ }
381
+ function rewriteGlobalVarValue(value, aliases) {
382
+ const parsed = valueParser__default(value);
383
+ let count = 0;
384
+ parsed.walk((node) => {
385
+ if (node.type !== "function" || node.value.toLowerCase() !== "var") {
386
+ return;
387
+ }
388
+ const firstArgument = node.nodes.find((child) => child.type !== "space");
389
+ if (!firstArgument || firstArgument.type !== "word") {
390
+ return;
391
+ }
392
+ const alias = aliases.get(firstArgument.value);
393
+ if (!alias) {
394
+ return;
395
+ }
396
+ firstArgument.value = alias;
397
+ count++;
398
+ });
399
+ return { value: count > 0 ? valueParser__default.stringify(parsed.nodes) : value, count };
400
+ }
401
+
402
+ function validateGlobalVarAliasInputs(options) {
403
+ const scans = options.cssFiles.map(
404
+ (file) => scanCssSourceWithOptionalCache(file, options.cacheDir)
405
+ );
406
+ const plan = planGlobalVarAliases({
407
+ scans,
408
+ tokens: options.tokens,
409
+ autoPrefix: options.autoPrefix,
410
+ aliasPrefix: options.aliasPrefix,
411
+ reserved: options.reserved
412
+ });
413
+ if (plan.diagnostics.length > 0 || plan.entries.length === 0) {
414
+ return { scans, plan, usageDiagnostics: [] };
415
+ }
416
+ const candidateTokens = plan.entries.map((entry) => entry.original);
417
+ const usageDiagnostics = (options.sourceFiles ?? []).flatMap(
418
+ (file) => compiler.scanGlobalVarUsages(file.code, file.filePath, { tokens: candidateTokens })
419
+ );
420
+ return { scans, plan, usageDiagnostics };
421
+ }
422
+ function createGlobalVarAliasValidationOptions(input) {
423
+ return {
424
+ cssFiles: input.cssAssets.filter((asset) => /\.css(?:$|\?)/.test(asset.fileName)).map((asset) => ({
425
+ filePath: normalizeBuildAssetPath(input.rootDir, asset.fileName),
426
+ css: cssAssetSourceToString(asset.source),
427
+ mtimeMs: asset.mtimeMs
428
+ })),
429
+ sourceFiles: input.sourceFiles ?? [],
430
+ tokens: input.tokens,
431
+ autoPrefix: input.autoPrefix,
432
+ aliasPrefix: input.aliasPrefix,
433
+ reserved: input.reserved,
434
+ cacheDir: input.cacheDir
435
+ };
436
+ }
437
+ function scanCssSourceWithOptionalCache(file, cacheDir) {
438
+ if (cacheDir === void 0 || file.mtimeMs === void 0) {
439
+ return scanGlobalVarCss(file.css, { filePath: file.filePath });
440
+ }
441
+ const key = createGlobalVarScanCacheKey({
442
+ filePath: file.filePath,
443
+ css: file.css,
444
+ mtimeMs: file.mtimeMs
445
+ });
446
+ const cached = readGlobalVarScanCache(cacheDir, key);
447
+ if (cached) {
448
+ return cached;
449
+ }
450
+ const result = scanGlobalVarCss(file.css, { filePath: file.filePath });
451
+ writeGlobalVarScanCache(cacheDir, key, result);
452
+ return result;
453
+ }
454
+ function normalizeBuildAssetPath(rootDir, fileName) {
455
+ return (path__namespace.isAbsolute(fileName) ? fileName : path__namespace.join(rootDir, fileName)).replace(
456
+ /\\/g,
457
+ "/"
458
+ );
459
+ }
460
+ function cssAssetSourceToString(source) {
461
+ return typeof source === "string" ? source : Buffer.from(source).toString("utf8");
462
+ }
463
+
464
+ const SERVER_DIRECTIVE_RE = /^['"]use server['"];?$/;
465
+ const CLIENT_DIRECTIVE_RE = /^['"]use client['"];?$/;
466
+ const RUNTIME_HELPER_MODULES = /* @__PURE__ */ new Set([
467
+ "@csszyx/runtime",
468
+ "@csszyx/runtime/lite",
469
+ "csszyx",
470
+ "csszyx/lite"
471
+ ]);
472
+ const CLIENT_RUNTIME_MODULES = /* @__PURE__ */ new Set(["csszyx/browser"]);
473
+ const CLIENT_RUNTIME_MODULE_ROOTS = ["@csszyx/dynamic", "csszyx/dynamic"];
474
+ const normalizedModuleIdCache = /* @__PURE__ */ new Map();
475
+ const resolvedLocalModuleCache = /* @__PURE__ */ new Map();
476
+ const FORBIDDEN_SYMBOLS = /* @__PURE__ */ new Set([
477
+ "_sz",
478
+ "_sz2",
479
+ "_sz3",
480
+ "_szIf",
481
+ "_szMerge",
482
+ "_szSwitch",
483
+ "__csszyx_runtime__"
484
+ ]);
485
+ function hasUseServerDirective(code) {
486
+ for (const statement of readDirectivePrologue(code)) {
487
+ if (SERVER_DIRECTIVE_RE.test(statement)) {
488
+ return true;
489
+ }
490
+ if (CLIENT_DIRECTIVE_RE.test(statement)) {
491
+ return false;
492
+ }
493
+ }
494
+ return false;
495
+ }
496
+ function hasUseClientDirective(code) {
497
+ for (const statement of readDirectivePrologue(code)) {
498
+ if (CLIENT_DIRECTIVE_RE.test(statement)) {
499
+ return true;
500
+ }
501
+ if (SERVER_DIRECTIVE_RE.test(statement)) {
502
+ return false;
503
+ }
504
+ }
505
+ return false;
506
+ }
507
+ function isRSCServerModule(code, id) {
508
+ if (hasUseServerDirective(code)) {
509
+ return true;
510
+ }
511
+ if (hasUseClientDirective(code)) {
512
+ return false;
513
+ }
514
+ return isNextAppRouterEntry(id);
515
+ }
516
+ function findRSCBoundaryViolation(code, id) {
517
+ if (!isRSCServerModule(code, id)) {
518
+ return null;
519
+ }
520
+ for (const imported of findRuntimeImports(code)) {
521
+ for (const symbol of imported.symbols) {
522
+ if (FORBIDDEN_SYMBOLS.has(symbol)) {
523
+ return {
524
+ symbol,
525
+ path: id,
526
+ importChain: [id, imported.source]
527
+ };
528
+ }
529
+ }
530
+ }
531
+ return null;
532
+ }
533
+ function createRSCModuleRecord(code, id) {
534
+ const normalized = normalizeModuleId(id);
535
+ return {
536
+ id: normalized,
537
+ isServer: isRSCServerModule(code, normalized),
538
+ isClient: hasUseClientDirective(code),
539
+ imports: findLocalImportSources(code).map((source) => resolveLocalModule(normalized, source)).filter((resolved) => resolved !== null),
540
+ runtimeImports: findRuntimeImports(code).filter(
541
+ (imported) => imported.symbols.some((symbol) => FORBIDDEN_SYMBOLS.has(symbol))
542
+ )
543
+ };
544
+ }
545
+ function deleteRSCModuleRecord(records, id) {
546
+ const normalized = normalizeModuleId(id);
547
+ const clean = id.split("?")[0]?.replace(/\\/g, "/") ?? id;
548
+ const resolved = path__namespace.resolve(clean).replace(/\\/g, "/");
549
+ pruneRSCModulePathCaches(/* @__PURE__ */ new Set([normalized, resolved, clean]));
550
+ let deleted = records.delete(normalized);
551
+ if (resolved !== normalized) {
552
+ deleted = records.delete(resolved) || deleted;
553
+ }
554
+ if (clean !== normalized && clean !== resolved) {
555
+ deleted = records.delete(clean) || deleted;
556
+ }
557
+ return deleted;
558
+ }
559
+ function findRSCGraphViolation(records) {
560
+ for (const root of records.values()) {
561
+ if (!root.isServer) {
562
+ continue;
563
+ }
564
+ const violation = walkRSCGraph(root, records, [root.id], /* @__PURE__ */ new Set([root.id]));
565
+ if (violation) {
566
+ return {
567
+ symbol: violation.symbol,
568
+ path: root.id,
569
+ importChain: violation.importChain
570
+ };
571
+ }
572
+ }
573
+ return null;
574
+ }
575
+ function assertNoRSCGraphViolation(records) {
576
+ const violation = findRSCGraphViolation(records);
577
+ if (!violation) {
578
+ return;
579
+ }
580
+ throw new Error(formatRSCViolation(violation));
581
+ }
582
+ const APP_ROUTER_ENTRIES = /* @__PURE__ */ new Set([
583
+ "page",
584
+ "layout",
585
+ "template",
586
+ "loading",
587
+ "error",
588
+ "not-found",
589
+ "global-error",
590
+ "default",
591
+ "route"
592
+ ]);
593
+ function isNextAppRouterEntry(id) {
594
+ const clean = id.split("?")[0]?.replace(/\\/g, "/") ?? id;
595
+ if (!clean.includes("/app/") && !clean.startsWith("app/")) return false;
596
+ const basename = clean.split("/").pop() ?? "";
597
+ const dotIdx = basename.indexOf(".");
598
+ if (dotIdx === -1) return false;
599
+ const stem = basename.slice(0, dotIdx);
600
+ const ext = basename.slice(dotIdx + 1);
601
+ return APP_ROUTER_ENTRIES.has(stem) && /^[cm]?[tj]sx?$/.test(ext);
602
+ }
603
+ function assertNoRSCBoundaryViolation(code, id) {
604
+ const violation = findRSCBoundaryViolation(code, id);
605
+ if (!violation) {
606
+ return;
607
+ }
608
+ throw new Error(formatRSCViolation(violation));
609
+ }
610
+ function formatRSCViolation(violation) {
611
+ return `csszyxRSCViolation: ${violation.symbol} imported in Server Component ${violation.path}
612
+ Import chain: ${violation.importChain.join(" -> ")}`;
613
+ }
614
+ function walkRSCGraph(current, records, chain, seen) {
615
+ if (current.isClient) {
616
+ return null;
617
+ }
618
+ const runtime = current.runtimeImports[0];
619
+ const symbol = runtime?.symbols.find((s) => FORBIDDEN_SYMBOLS.has(s));
620
+ if (runtime && symbol) {
621
+ return {
622
+ symbol,
623
+ path: chain[0] ?? current.id,
624
+ importChain: [...chain, runtime.source]
625
+ };
626
+ }
627
+ for (const importedId of current.imports) {
628
+ if (seen.has(importedId)) {
629
+ continue;
630
+ }
631
+ const next = records.get(importedId);
632
+ if (!next) {
633
+ continue;
634
+ }
635
+ seen.add(importedId);
636
+ const violation = walkRSCGraph(next, records, [...chain, importedId], seen);
637
+ if (violation) {
638
+ return violation;
639
+ }
640
+ }
641
+ return null;
642
+ }
643
+ function readDirectivePrologue(code) {
644
+ const out = [];
645
+ let i = code.charCodeAt(0) === 65279 ? 1 : 0;
646
+ while (i < code.length) {
647
+ i = skipWhitespaceAndComments(code, i);
648
+ const quote = code[i];
649
+ if (quote !== '"' && quote !== "'") {
650
+ break;
651
+ }
652
+ let j = i + 1;
653
+ let escaped = false;
654
+ while (j < code.length) {
655
+ const ch = code[j];
656
+ if (escaped) {
657
+ escaped = false;
658
+ } else if (ch === "\\") {
659
+ escaped = true;
660
+ } else if (ch === quote) {
661
+ break;
662
+ }
663
+ j++;
664
+ }
665
+ if (j >= code.length) {
666
+ break;
667
+ }
668
+ let end = j + 1;
669
+ while (end < code.length && /[ \t\r\n]/.test(code[end])) {
670
+ end++;
671
+ }
672
+ if (code[end] === ";") {
673
+ end++;
674
+ }
675
+ out.push(code.slice(i, end).trim());
676
+ i = end;
677
+ }
678
+ return out;
679
+ }
680
+ function skipWhitespaceAndComments(code, start) {
681
+ let i = start;
682
+ while (i < code.length) {
683
+ while (i < code.length && /\s/.test(code[i])) {
684
+ i++;
685
+ }
686
+ if (code.startsWith("//", i)) {
687
+ const next = code.indexOf("\n", i + 2);
688
+ i = next === -1 ? code.length : next + 1;
689
+ continue;
690
+ }
691
+ if (code.startsWith("/*", i)) {
692
+ const next = code.indexOf("*/", i + 2);
693
+ i = next === -1 ? code.length : next + 2;
694
+ continue;
695
+ }
696
+ break;
697
+ }
698
+ return i;
699
+ }
700
+ function findRuntimeImports(code) {
701
+ const imports = [];
702
+ const scanCode = stripCommentsForImportScan(code);
703
+ const dynamicImportRe = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
704
+ for (const { clause, source } of findStaticImports(scanCode)) {
705
+ if (!isRuntimeImportSource(source)) {
706
+ continue;
707
+ }
708
+ if (clause === null) {
709
+ imports.push({
710
+ source,
711
+ symbols: isWholeRuntimeModuleForbidden(source) ? Array.from(FORBIDDEN_SYMBOLS) : []
712
+ });
713
+ } else {
714
+ imports.push({ source, symbols: readRuntimeImportSymbols(source, clause) });
715
+ }
716
+ }
717
+ for (const match of scanCode.matchAll(dynamicImportRe)) {
718
+ const source = match[1];
719
+ if (isRuntimeImportSource(source)) {
720
+ imports.push({ source, symbols: Array.from(FORBIDDEN_SYMBOLS) });
721
+ }
722
+ }
723
+ return imports;
724
+ }
725
+ function findStaticImports(code) {
726
+ const imports = [];
727
+ let cursor = 0;
728
+ while (cursor < code.length) {
729
+ const importStart = code.indexOf("import", cursor);
730
+ if (importStart === -1) {
731
+ break;
732
+ }
733
+ cursor = importStart + 6;
734
+ if (importStart > 0 && isIdentifierPart(code.charCodeAt(importStart - 1)) || isIdentifierPart(code.charCodeAt(cursor))) {
735
+ continue;
736
+ }
737
+ let position = skipAsciiWhitespace(code, cursor);
738
+ const opener = code.charAt(position);
739
+ if (opener === "(") {
740
+ continue;
741
+ }
742
+ if (opener === '"' || opener === "'") {
743
+ const literal2 = readQuotedString(code, position);
744
+ if (literal2) {
745
+ imports.push({ clause: null, source: literal2.value });
746
+ cursor = literal2.end;
747
+ }
748
+ continue;
749
+ }
750
+ const clauseStart = position;
751
+ let fromStart = -1;
752
+ while (position < code.length) {
753
+ if (code.startsWith("from", position) && (position === clauseStart || !isIdentifierPart(code.charCodeAt(position - 1))) && !isIdentifierPart(code.charCodeAt(position + 4))) {
754
+ fromStart = position;
755
+ break;
756
+ }
757
+ if (code.charAt(position) === ";") {
758
+ break;
759
+ }
760
+ position += 1;
761
+ }
762
+ if (fromStart === -1) {
763
+ continue;
764
+ }
765
+ const clause = code.slice(clauseStart, fromStart).trim();
766
+ if (splitAsciiWhitespace(clause)[0] === "type") {
767
+ cursor = fromStart + 4;
768
+ continue;
769
+ }
770
+ position = skipAsciiWhitespace(code, fromStart + 4);
771
+ const literal = readQuotedString(code, position);
772
+ if (literal) {
773
+ imports.push({ clause, source: literal.value });
774
+ cursor = literal.end;
775
+ }
776
+ }
777
+ return imports;
778
+ }
779
+ function readQuotedString(code, start) {
780
+ const quote = code.charAt(start);
781
+ if (quote !== '"' && quote !== "'") {
782
+ return null;
783
+ }
784
+ let value = "";
785
+ for (let index = start + 1; index < code.length; index += 1) {
786
+ const char = code.charAt(index);
787
+ if (char === "\\") {
788
+ if (index + 1 >= code.length) {
789
+ return null;
790
+ }
791
+ value += code.charAt(index + 1);
792
+ index += 1;
793
+ } else if (char === quote) {
794
+ return { end: index + 1, value };
795
+ } else if (char === "\n" || char === "\r") {
796
+ return null;
797
+ } else {
798
+ value += char;
799
+ }
800
+ }
801
+ return null;
802
+ }
803
+ function skipAsciiWhitespace(code, start) {
804
+ let index = start;
805
+ while (index < code.length) {
806
+ const charCode = code.charCodeAt(index);
807
+ if (charCode !== 9 && charCode !== 10 && charCode !== 13 && charCode !== 32) {
808
+ break;
809
+ }
810
+ index += 1;
811
+ }
812
+ return index;
813
+ }
814
+ function isIdentifierPart(code) {
815
+ return isIdentifierStart(code) || code >= 48 && code <= 57;
816
+ }
817
+ function isRuntimeImportSource(source) {
818
+ return RUNTIME_HELPER_MODULES.has(source) || source.startsWith("@csszyx/runtime/") || CLIENT_RUNTIME_MODULES.has(source) || CLIENT_RUNTIME_MODULE_ROOTS.some((root) => source === root || source.startsWith(`${root}/`));
819
+ }
820
+ function isWholeRuntimeModuleForbidden(source) {
821
+ return source.startsWith("@csszyx/runtime/") || CLIENT_RUNTIME_MODULES.has(source) || CLIENT_RUNTIME_MODULE_ROOTS.some((root) => source === root || source.startsWith(`${root}/`));
822
+ }
823
+ function readRuntimeImportSymbols(source, clause) {
824
+ if (isWholeRuntimeModuleForbidden(source)) {
825
+ return Array.from(FORBIDDEN_SYMBOLS);
826
+ }
827
+ return readImportedSymbols(clause);
828
+ }
829
+ function findLocalImportSources(code) {
830
+ const out = [];
831
+ const staticImportRe = /import\s+(?!type\b)(?:\S(?:.*\S)?\s+from\s+)?['"]([^'"]+)['"]/g;
832
+ const exportFromRe = /export\s+(?!type\b)\S(?:.*\S)?\s+from\s+['"]([^'"]+)['"]/g;
833
+ const dynamicImportRe = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
834
+ for (const re of [staticImportRe, exportFromRe, dynamicImportRe]) {
835
+ for (const match of code.matchAll(re)) {
836
+ const source = match[1];
837
+ if (source.startsWith(".") || source.startsWith("/")) {
838
+ out.push(source);
839
+ }
840
+ }
841
+ }
842
+ return out;
843
+ }
844
+ function normalizeModuleId(id) {
845
+ const clean = id.split("?")[0] ?? id;
846
+ const cached = normalizedModuleIdCache.get(clean);
847
+ if (cached) {
848
+ return cached;
849
+ }
850
+ let normalized;
851
+ try {
852
+ normalized = fs__namespace.realpathSync.native(clean).replace(/\\/g, "/");
853
+ } catch {
854
+ normalized = path__namespace.resolve(clean).replace(/\\/g, "/");
855
+ }
856
+ normalizedModuleIdCache.set(clean, normalized);
857
+ return normalized;
858
+ }
859
+ function resolveLocalModule(importer, source) {
860
+ const cacheKey = `${importer}\0${source}`;
861
+ const cached = resolvedLocalModuleCache.get(cacheKey);
862
+ if (cached) {
863
+ return cached;
864
+ }
865
+ const base = source.startsWith("/") ? source : path__namespace.resolve(path__namespace.dirname(importer), source);
866
+ const candidates = [
867
+ base,
868
+ `${base}.tsx`,
869
+ `${base}.ts`,
870
+ `${base}.jsx`,
871
+ `${base}.js`,
872
+ `${base}.mjs`,
873
+ `${base}.cjs`,
874
+ path__namespace.join(base, "index.tsx"),
875
+ path__namespace.join(base, "index.ts"),
876
+ path__namespace.join(base, "index.jsx"),
877
+ path__namespace.join(base, "index.js")
878
+ ];
879
+ for (const candidate of candidates) {
880
+ try {
881
+ if (!fs__namespace.statSync(candidate).isFile()) {
882
+ continue;
883
+ }
884
+ const resolved = normalizeModuleId(candidate);
885
+ resolvedLocalModuleCache.set(cacheKey, resolved);
886
+ return resolved;
887
+ } catch (error) {
888
+ if (error.code !== "ENOENT") {
889
+ throw error;
890
+ }
891
+ }
892
+ }
893
+ return null;
894
+ }
895
+ function pruneRSCModulePathCaches(moduleIds) {
896
+ for (const [key, value] of normalizedModuleIdCache) {
897
+ const normalizedKey = key.replace(/\\/g, "/");
898
+ if (moduleIds.has(value) || moduleIds.has(normalizedKey)) {
899
+ normalizedModuleIdCache.delete(key);
900
+ }
901
+ }
902
+ for (const [key, value] of resolvedLocalModuleCache) {
903
+ if (moduleIds.has(value)) {
904
+ resolvedLocalModuleCache.delete(key);
905
+ }
906
+ }
907
+ }
908
+ function readImportedSymbols(clause) {
909
+ const symbols = [];
910
+ const openBrace = clause.indexOf("{");
911
+ const closeBrace = openBrace === -1 ? -1 : clause.indexOf("}", openBrace);
912
+ if (openBrace !== -1 && closeBrace !== -1) {
913
+ const namedPart = clause.slice(openBrace + 1, closeBrace);
914
+ for (const part of namedPart.split(",")) {
915
+ const trimmed = part.trim();
916
+ if (!trimmed || trimmed.startsWith("type ")) {
917
+ continue;
918
+ }
919
+ const sourceName = trimmed.replace(/^type[ \t]+/, "").split(/[ \t]+as[ \t]+/)[0]?.trim();
920
+ if (sourceName) {
921
+ symbols.push(sourceName);
922
+ }
923
+ }
924
+ }
925
+ const namespaceParts = splitAsciiWhitespace(clause);
926
+ if (namespaceParts.length >= 3 && namespaceParts[0] === "*" && namespaceParts[1] === "as" && isIdentifier(namespaceParts[2] ?? "")) {
927
+ symbols.push(...FORBIDDEN_SYMBOLS);
928
+ }
929
+ const braceStart = clause.indexOf("{");
930
+ const braceEnd = clause.indexOf("}", braceStart);
931
+ const stripped = braceStart !== -1 && braceEnd !== -1 ? clause.slice(0, braceStart) + clause.slice(braceEnd + 1) : clause;
932
+ const defaultCandidate = stripped.trimStart().split(",", 1)[0]?.trim() ?? "";
933
+ const defaultSymbol = isIdentifier(defaultCandidate) ? defaultCandidate : void 0;
934
+ if (defaultSymbol && FORBIDDEN_SYMBOLS.has(defaultSymbol)) {
935
+ symbols.push(defaultSymbol);
936
+ }
937
+ return symbols;
938
+ }
939
+ function isIdentifier(value) {
940
+ if (value.length === 0 || !isIdentifierStart(value.charCodeAt(0))) {
941
+ return false;
942
+ }
943
+ for (let index = 1; index < value.length; index += 1) {
944
+ const code = value.charCodeAt(index);
945
+ if (!isIdentifierStart(code) && (code < 48 || code > 57)) {
946
+ return false;
947
+ }
948
+ }
949
+ return true;
950
+ }
951
+ function isIdentifierStart(code) {
952
+ return code === 36 || code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
953
+ }
954
+ function splitAsciiWhitespace(value) {
955
+ const parts = [];
956
+ let start = -1;
957
+ for (let index = 0; index <= value.length; index += 1) {
958
+ const code = index < value.length ? value.charCodeAt(index) : 32;
959
+ const whitespace = code === 9 || code === 10 || code === 13 || code === 32;
960
+ if (whitespace) {
961
+ if (start !== -1) {
962
+ parts.push(value.slice(start, index));
963
+ start = -1;
964
+ }
965
+ } else if (start === -1) {
966
+ start = index;
967
+ }
968
+ }
969
+ return parts;
970
+ }
971
+ function stripCommentsForImportScan(code) {
972
+ let out = "";
973
+ let i = 0;
974
+ let quote = null;
975
+ let escaped = false;
976
+ while (i < code.length) {
977
+ const ch = code[i];
978
+ const next = code[i + 1];
979
+ if (quote) {
980
+ out += ch;
981
+ if (escaped) {
982
+ escaped = false;
983
+ } else if (ch === "\\") {
984
+ escaped = true;
985
+ } else if (ch === quote) {
986
+ quote = null;
987
+ }
988
+ i++;
989
+ continue;
990
+ }
991
+ if (ch === '"' || ch === "'" || ch === "`") {
992
+ quote = ch;
993
+ out += ch;
994
+ i++;
995
+ continue;
996
+ }
997
+ if (ch === "/" && next === "/") {
998
+ out += " ";
999
+ i += 2;
1000
+ while (i < code.length && code[i] !== "\n") {
1001
+ out += " ";
1002
+ i++;
1003
+ }
1004
+ continue;
1005
+ }
1006
+ if (ch === "/" && next === "*") {
1007
+ out += " ";
1008
+ i += 2;
1009
+ while (i < code.length) {
1010
+ const blockCh = code[i];
1011
+ const blockNext = code[i + 1];
1012
+ if (blockCh === "*" && blockNext === "/") {
1013
+ out += " ";
1014
+ i += 2;
1015
+ break;
1016
+ }
1017
+ out += blockCh === "\n" ? "\n" : " ";
1018
+ i++;
1019
+ }
1020
+ continue;
1021
+ }
1022
+ out += ch;
1023
+ i++;
1024
+ }
1025
+ return out;
1026
+ }
1027
+
1028
+ const EMPTY_THEME = { colors: [], spacings: [], fonts: [], radii: [], shadows: [] };
1029
+ function stripLayerWrappers(css) {
1030
+ let result = "";
1031
+ let i = 0;
1032
+ while (i < css.length) {
1033
+ const layerIdx = css.indexOf("@layer", i);
1034
+ if (layerIdx === -1) {
1035
+ result += css.slice(i);
1036
+ break;
1037
+ }
1038
+ result += css.slice(i, layerIdx);
1039
+ const openBrace = css.indexOf("{", layerIdx);
1040
+ if (openBrace === -1) {
1041
+ result += css.slice(layerIdx);
1042
+ break;
1043
+ }
1044
+ let depth = 0;
1045
+ let j = openBrace;
1046
+ while (j < css.length) {
1047
+ if (css[j] === "{") {
1048
+ depth++;
1049
+ }
1050
+ if (css[j] === "}") {
1051
+ depth--;
1052
+ if (depth === 0) {
1053
+ result += css.slice(openBrace + 1, j);
1054
+ i = j + 1;
1055
+ break;
1056
+ }
1057
+ }
1058
+ j++;
1059
+ }
1060
+ if (depth !== 0) {
1061
+ result += css.slice(openBrace);
1062
+ break;
1063
+ }
1064
+ }
1065
+ return result;
1066
+ }
1067
+ function extractThemeBlocks(css) {
1068
+ const blocks = [];
1069
+ const themeStart = /@theme\s+(?:inline\s+)?\{|@theme\{/g;
1070
+ for (const match of css.matchAll(themeStart)) {
1071
+ const openPos = css.indexOf("{", match.index);
1072
+ let depth = 0;
1073
+ let j = openPos;
1074
+ while (j < css.length) {
1075
+ if (css[j] === "{") {
1076
+ depth++;
1077
+ }
1078
+ if (css[j] === "}") {
1079
+ depth--;
1080
+ if (depth === 0) {
1081
+ blocks.push(css.slice(openPos + 1, j));
1082
+ break;
1083
+ }
1084
+ }
1085
+ j++;
1086
+ }
1087
+ }
1088
+ return blocks;
1089
+ }
1090
+ function categorizeProperty(prop) {
1091
+ const categoryMap = [
1092
+ ["color-", "colors"],
1093
+ ["spacing-", "spacings"],
1094
+ ["font-", "fonts"],
1095
+ ["radius-", "radii"],
1096
+ ["shadow-", "shadows"]
1097
+ ];
1098
+ for (const [prefix, category] of categoryMap) {
1099
+ if (prop.startsWith(prefix)) {
1100
+ let token = prop.slice(prefix.length);
1101
+ token = token.replace(/-\d+$/, "");
1102
+ if (token) {
1103
+ return { category, token };
1104
+ }
1105
+ }
1106
+ }
1107
+ return null;
1108
+ }
1109
+ function parseThemeBlocks(cssContent) {
1110
+ const result = {
1111
+ colors: /* @__PURE__ */ new Set(),
1112
+ spacings: /* @__PURE__ */ new Set(),
1113
+ fonts: /* @__PURE__ */ new Set(),
1114
+ radii: /* @__PURE__ */ new Set(),
1115
+ shadows: /* @__PURE__ */ new Set()
1116
+ };
1117
+ const stripped = stripLayerWrappers(cssContent);
1118
+ const blocks = extractThemeBlocks(stripped);
1119
+ const propPattern = /--([a-z][a-z0-9-]*)(?:\s*:[^;]+)?;/g;
1120
+ for (const block of blocks) {
1121
+ for (const match of block.matchAll(propPattern)) {
1122
+ const categorized = categorizeProperty(match[1]);
1123
+ if (categorized) {
1124
+ result[categorized.category].add(categorized.token);
1125
+ }
1126
+ }
1127
+ }
1128
+ return {
1129
+ colors: [...result.colors].sort(),
1130
+ spacings: [...result.spacings].sort(),
1131
+ fonts: [...result.fonts].sort(),
1132
+ radii: [...result.radii].sort(),
1133
+ shadows: [...result.shadows].sort()
1134
+ };
1135
+ }
1136
+ function mergeThemes(themes) {
1137
+ if (themes.length === 0) {
1138
+ return { ...EMPTY_THEME };
1139
+ }
1140
+ const merged = {
1141
+ colors: /* @__PURE__ */ new Set(),
1142
+ spacings: /* @__PURE__ */ new Set(),
1143
+ fonts: /* @__PURE__ */ new Set(),
1144
+ radii: /* @__PURE__ */ new Set(),
1145
+ shadows: /* @__PURE__ */ new Set()
1146
+ };
1147
+ for (const theme of themes) {
1148
+ for (const cat of Object.keys(merged)) {
1149
+ for (const token of theme[cat]) {
1150
+ merged[cat].add(token);
1151
+ }
1152
+ }
1153
+ }
1154
+ return {
1155
+ colors: [...merged.colors].sort(),
1156
+ spacings: [...merged.spacings].sort(),
1157
+ fonts: [...merged.fonts].sort(),
1158
+ radii: [...merged.radii].sort(),
1159
+ shadows: [...merged.shadows].sort()
1160
+ };
1161
+ }
1162
+ function hasTokens(theme) {
1163
+ return Object.values(theme).some((arr) => arr.length > 0);
1164
+ }
1165
+
1166
+ const GLOB_MAGIC_RE = /[*?[\]{}]/;
1167
+ const DEFAULT_IGNORED_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", ".turbo", "dist", "build"]);
1168
+ function normalizeFileId(id) {
1169
+ return id.split(/[?#]/, 1)[0].replace(/\\/g, "/");
1170
+ }
1171
+ function normalizeRoot(rootDir) {
1172
+ return path__namespace.resolve(rootDir).replace(/\\/g, "/");
1173
+ }
1174
+ function hasGlobMagic(pattern) {
1175
+ return GLOB_MAGIC_RE.test(pattern);
1176
+ }
1177
+ function escapeRegExp(ch) {
1178
+ return /[|\\{}()[\]^$+?.]/.test(ch) ? `\\${ch}` : ch;
1179
+ }
1180
+ function globToRegExp(pattern) {
1181
+ const normalized = pattern.replace(/\\/g, "/");
1182
+ let out = "^";
1183
+ for (let i = 0; i < normalized.length; i++) {
1184
+ const ch = normalized[i];
1185
+ if (ch === "*") {
1186
+ if (normalized[i + 1] === "*") {
1187
+ out += ".*";
1188
+ i++;
1189
+ } else {
1190
+ out += "[^/]*";
1191
+ }
1192
+ } else if (ch === "?") {
1193
+ out += "[^/]";
1194
+ } else {
1195
+ out += escapeRegExp(ch);
1196
+ }
1197
+ }
1198
+ out += "$";
1199
+ return new RegExp(out);
1200
+ }
1201
+ function relativeToRoot(file, rootDir) {
1202
+ const root = normalizeRoot(rootDir);
1203
+ const normalizedFile = normalizeFileId(file);
1204
+ return path__namespace.posix.relative(root, normalizedFile).replace(/\\/g, "/");
1205
+ }
1206
+ function matchesPattern(id, pattern, rootDir) {
1207
+ const file = normalizeFileId(id);
1208
+ const relative = relativeToRoot(file, rootDir);
1209
+ if (pattern instanceof RegExp) {
1210
+ pattern.lastIndex = 0;
1211
+ return pattern.test(file) || pattern.test(relative);
1212
+ }
1213
+ const normalizedPattern = pattern.replace(/\\/g, "/");
1214
+ if (hasGlobMagic(normalizedPattern)) {
1215
+ const re = globToRegExp(normalizedPattern);
1216
+ return re.test(file) || re.test(relative);
1217
+ }
1218
+ const absolutePattern = path__namespace.isAbsolute(normalizedPattern) ? normalizeFileId(normalizedPattern) : normalizeFileId(path__namespace.join(rootDir, normalizedPattern));
1219
+ return file === absolutePattern || relative === normalizedPattern;
1220
+ }
1221
+ function matchesAnyPattern(id, patterns, rootDir) {
1222
+ if (!patterns) {
1223
+ return false;
1224
+ }
1225
+ const list = Array.isArray(patterns) ? patterns : [patterns];
1226
+ return list.some((pattern) => matchesPattern(id, pattern, rootDir));
1227
+ }
1228
+ function expandFilePatterns(rootDir, patterns) {
1229
+ const list = Array.isArray(patterns) ? patterns : [patterns];
1230
+ const files = /* @__PURE__ */ new Set();
1231
+ const walk = (dir) => {
1232
+ let entries;
1233
+ try {
1234
+ entries = fs__namespace.readdirSync(dir, { withFileTypes: true });
1235
+ } catch {
1236
+ return;
1237
+ }
1238
+ for (const entry of entries) {
1239
+ const full = path__namespace.join(dir, entry.name);
1240
+ if (entry.isDirectory()) {
1241
+ if (!DEFAULT_IGNORED_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
1242
+ walk(full);
1243
+ }
1244
+ } else {
1245
+ files.add(path__namespace.resolve(full));
1246
+ }
1247
+ }
1248
+ };
1249
+ let needsWalk = false;
1250
+ for (const pattern of list) {
1251
+ const resolved = path__namespace.isAbsolute(pattern) ? pattern : path__namespace.join(rootDir, pattern);
1252
+ if (hasGlobMagic(pattern)) {
1253
+ needsWalk = true;
1254
+ continue;
1255
+ }
1256
+ if (fs__namespace.existsSync(resolved)) {
1257
+ files.add(path__namespace.resolve(resolved));
1258
+ }
1259
+ }
1260
+ if (needsWalk) {
1261
+ walk(rootDir);
1262
+ for (const file of Array.from(files)) {
1263
+ if (!list.some(
1264
+ (pattern) => hasGlobMagic(pattern) && matchesPattern(file, pattern, rootDir)
1265
+ )) {
1266
+ const isLiteralMatch = list.some((pattern) => {
1267
+ if (hasGlobMagic(pattern)) {
1268
+ return false;
1269
+ }
1270
+ const resolved = path__namespace.isAbsolute(pattern) ? pattern : path__namespace.join(rootDir, pattern);
1271
+ return normalizeFileId(path__namespace.resolve(resolved)) === normalizeFileId(file);
1272
+ });
1273
+ if (!isLiteralMatch) {
1274
+ files.delete(file);
1275
+ }
1276
+ }
1277
+ }
1278
+ }
1279
+ return Array.from(files).sort();
1280
+ }
1281
+
1282
+ function safeJsonForScriptTag(value, prettyPrint = false) {
1283
+ const json = prettyPrint ? JSON.stringify(value, null, 2) : JSON.stringify(value);
1284
+ return json.replace(/</g, "\\u003C").replace(/>/g, "\\u003E").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1285
+ }
1286
+ function injectChecksum(html, checksum, minify = false) {
1287
+ const attrName = minify ? "data-sz-cs" : "data-sz-checksum";
1288
+ const htmlTagPattern = /<html([^>]*)>/i;
1289
+ const match = html.match(htmlTagPattern);
1290
+ if (!match) {
1291
+ return html;
1292
+ }
1293
+ const existingAttrs = match[1];
1294
+ const checksumAttr = ` ${attrName}="${checksum}"`;
1295
+ return html.replace(htmlTagPattern, `<html${checksumAttr}${existingAttrs}>`);
1296
+ }
1297
+ function injectMangleMapScript(html, mangleMap, options = {}) {
1298
+ const {
1299
+ prettyPrint = false,
1300
+ varMangleMap = {},
1301
+ globalVarAliasPrefix = types.CSSZYX_GLOBAL_ALIAS_PREFIX
1302
+ } = options;
1303
+ const checksumMap = createHydrationMangleMap(mangleMap, varMangleMap);
1304
+ const jsonContent = safeJsonForScriptTag(checksumMap, prettyPrint);
1305
+ const classMapContent = safeJsonForScriptTag(mangleMap);
1306
+ const varMapContent = safeJsonForScriptTag(varMangleMap);
1307
+ const scriptTag = `<script id="__CSSZYX_MANGLE_MAP__" type="application/json">${jsonContent}<\/script>`;
1308
+ const prefixContent = safeJsonForScriptTag(globalVarAliasPrefix);
1309
+ const debugScript = `<script>(function(){var m=${classMapContent};var vm=${varMapContent};var gp=${prefixContent};var r={};var vr={};for(var k in m)r[m[k]]=k;for(var vk in vm){var vv=vm[vk];var vs=Array.isArray(vv)?vv:[vv];for(var vi=0;vi<vs.length;vi++)(vr[vs[vi]]||(vr[vs[vi]]=[])).push(vk)}var cs=document.documentElement.getAttribute("data-sz-checksum")||"";window.__csszyx={mangleMap:m,varMangleMap:vm,checksum:cs,decode:function(c){return r[c]},encode:function(c){return m[c]},decodeVar:function(v){return vr[v]||[]},encodeVar:function(v){return vm[v]},decodeGlobalVar:function(v){var a=vr[v]||[];return v.indexOf(gp)===0?a[0]:void 0},decodeAll:function(el){return(el.className||"").split(" ").map(function(c){return r[c]||c})}}})()<\/script>`;
1310
+ const combined = `${scriptTag}
1311
+ ${debugScript}`;
1312
+ if (html.includes("</head>")) {
1313
+ return html.replace("</head>", `${combined}
1314
+ </head>`);
1315
+ } else if (html.includes("</html>")) {
1316
+ return html.replace("</html>", `${combined}
1317
+ </html>`);
1318
+ }
1319
+ return html + combined;
1320
+ }
1321
+ function injectMangleMapAttribute(html, mangleMap, minify = false, varMangleMap = {}) {
1322
+ const attrName = minify ? "data-sz-m" : "data-sz-map";
1323
+ const jsonContent = JSON.stringify(createHydrationMangleMap(mangleMap, varMangleMap));
1324
+ const htmlTagPattern = /<html([^>]*)>/i;
1325
+ const match = html.match(htmlTagPattern);
1326
+ if (!match) {
1327
+ return html;
1328
+ }
1329
+ const existingAttrs = match[1];
1330
+ const mapAttr = ` ${attrName}='${jsonContent}'`;
1331
+ return html.replace(htmlTagPattern, `<html${mapAttr}${existingAttrs}>`);
1332
+ }
1333
+ function injectHydrationData(html, mangleMap, checksum, options = {}) {
1334
+ const { mode = "script", minify = false } = options;
1335
+ let result = html;
1336
+ result = injectChecksum(result, checksum, minify);
1337
+ if (mode === "inline") {
1338
+ result = injectMangleMapAttribute(result, mangleMap, minify, options.varMangleMap);
1339
+ } else if (mode === "script") {
1340
+ result = injectMangleMapScript(result, mangleMap, options);
1341
+ } else if (mode === "both") {
1342
+ result = injectMangleMapAttribute(result, mangleMap, minify, options.varMangleMap);
1343
+ result = injectMangleMapScript(result, mangleMap, options);
1344
+ }
1345
+ return result;
1346
+ }
1347
+ function transformIndexHtml(html, mangleMap, checksum, options = {}) {
1348
+ return injectHydrationData(html, mangleMap, checksum, options);
1349
+ }
1350
+ function createHydrationMangleMap(classMap, varMap = {}) {
1351
+ if (Object.keys(varMap).length === 0) {
1352
+ return classMap;
1353
+ }
1354
+ const payload = {};
1355
+ for (const [key, value] of Object.entries(classMap)) {
1356
+ payload[`class:${key}`] = value;
1357
+ }
1358
+ for (const [key, value] of Object.entries(varMap)) {
1359
+ if (Array.isArray(value)) {
1360
+ for (const mangled of value) {
1361
+ payload[`var:${key}:${mangled}`] = mangled;
1362
+ }
1363
+ } else {
1364
+ payload[`var:${key}`] = value;
1365
+ }
1366
+ }
1367
+ return payload;
1368
+ }
1369
+ function buildRecoveryManifest(tokens, options) {
1370
+ const stripped = options.production === true;
1371
+ const strippedDevOnlyPaths = [];
1372
+ const sorted = {};
1373
+ const sortedKeys = [...tokens.keys()].sort();
1374
+ for (const key of sortedKeys) {
1375
+ const data = tokens.get(key);
1376
+ if (!data) {
1377
+ continue;
1378
+ }
1379
+ if (stripped && data.mode === "dev-only") {
1380
+ strippedDevOnlyPaths.push(data.path);
1381
+ continue;
1382
+ }
1383
+ sorted[key] = stripped ? { mode: data.mode, component: data.component, path: "" } : data;
1384
+ }
1385
+ const serialised = JSON.stringify(sorted);
1386
+ const fullChecksum = node_crypto.createHash("sha256").update(serialised).digest("hex");
1387
+ const checksum = fullChecksum.substring(0, 16);
1388
+ const buildId = `${Date.now().toString(36)}-${fullChecksum.substring(0, 6)}`;
1389
+ return {
1390
+ manifest: { buildId, checksum, mangleChecksum: options.mangleChecksum, tokens: sorted },
1391
+ strippedDevOnlyPaths
1392
+ };
1393
+ }
1394
+ function injectRecoveryManifest(html, manifest) {
1395
+ if (Object.keys(manifest.tokens).length === 0) {
1396
+ return html;
1397
+ }
1398
+ const json = JSON.stringify(manifest);
1399
+ const scriptTag = `<script id="__SZ_RECOVERY_MANIFEST__" type="application/json">${json}<\/script>`;
1400
+ if (html.includes("</head>")) {
1401
+ return html.replace("</head>", `${scriptTag}
1402
+ </head>`);
1403
+ } else if (html.includes("</html>")) {
1404
+ return html.replace("</html>", `${scriptTag}
1405
+ </html>`);
1406
+ }
1407
+ return html + scriptTag;
1408
+ }
1409
+
1410
+ const DEFAULT_MAX_ATTEMPTS = 3;
1411
+ const NODE_FS = {
1412
+ openSync: fs__namespace.openSync,
1413
+ fstatSync: (fd, options) => fs__namespace.fstatSync(fd, options),
1414
+ readFileSync: (fd, encoding) => fs__namespace.readFileSync(fd, encoding),
1415
+ closeSync: fs__namespace.closeSync
1416
+ };
1417
+ function readStableTextFileSnapshotSync(file, maxAttempts = DEFAULT_MAX_ATTEMPTS, fsApi = NODE_FS) {
1418
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
1419
+ throw new RangeError("maxAttempts must be a positive integer.");
1420
+ }
1421
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
1422
+ const fd = fsApi.openSync(file, "r");
1423
+ try {
1424
+ const before = fsApi.fstatSync(fd, { bigint: true });
1425
+ const source = fsApi.readFileSync(fd, "utf8");
1426
+ const after = fsApi.fstatSync(fd, { bigint: true });
1427
+ if (isSameFileVersion(before, after)) {
1428
+ return { source, mtimeMs: Number(after.mtimeMs) };
1429
+ }
1430
+ } finally {
1431
+ fsApi.closeSync(fd);
1432
+ }
1433
+ }
1434
+ throw new Error(`CSS source changed while being read: ${file}`);
1435
+ }
1436
+ function isSameFileVersion(before, after) {
1437
+ return before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeNs === after.mtimeNs && before.ctimeNs === after.ctimeNs;
1438
+ }
1439
+
1440
+ function generateThemeDts(opts) {
1441
+ const { theme, sourceFiles } = opts;
1442
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1443
+ const sources = sourceFiles.join(", ");
1444
+ const toUnion = (tokens) => tokens.map((t) => `'${t}'`).join(" | ");
1445
+ const entries = [];
1446
+ if (theme.colors.length > 0) {
1447
+ entries.push(` colors: ${toUnion(theme.colors)};`);
1448
+ }
1449
+ if (theme.spacings.length > 0) {
1450
+ entries.push(` spacings: ${toUnion(theme.spacings)};`);
1451
+ }
1452
+ if (theme.fonts.length > 0) {
1453
+ entries.push(` fonts: ${toUnion(theme.fonts)};`);
1454
+ }
1455
+ if (theme.radii.length > 0) {
1456
+ entries.push(` radii: ${toUnion(theme.radii)};`);
1457
+ }
1458
+ if (theme.shadows.length > 0) {
1459
+ entries.push(` shadows: ${toUnion(theme.shadows)};`);
1460
+ }
1461
+ return [
1462
+ "// Auto-generated by csszyx theme-scanner \u2014 DO NOT EDIT",
1463
+ `// Source: ${sources}`,
1464
+ `// Updated: ${timestamp}`,
1465
+ "",
1466
+ "declare module '@csszyx/compiler' {",
1467
+ " /**",
1468
+ " * Custom design tokens extracted from @theme blocks.",
1469
+ " * These tokens are surfaced in sz prop IntelliSense.",
1470
+ " */",
1471
+ " interface CustomTheme {",
1472
+ ...entries,
1473
+ " }",
1474
+ "}",
1475
+ "",
1476
+ "export {};",
1477
+ ""
1478
+ ].join("\n");
1479
+ }
1480
+ function writeThemeDts(opts) {
1481
+ const content = generateThemeDts(opts);
1482
+ fs.mkdirSync(path.dirname(opts.outputPath), { recursive: true });
1483
+ fs.writeFileSync(opts.outputPath, content, "utf-8");
1484
+ }
1485
+
1486
+ const VIRTUAL_MODULE_ID = "virtual:csszyx/mangle-map";
1487
+ const RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
1488
+ const VIRTUAL_CHECKSUM_ID = "virtual:csszyx/checksum";
1489
+ const RESOLVED_VIRTUAL_CHECKSUM_ID = `\0${VIRTUAL_CHECKSUM_ID}`;
1490
+ function createMangleMapModule(mangleMap, checksum, varMangleMap = {}, cssVarMetrics = null) {
1491
+ return `/**
1492
+ * Auto-generated mangle map for csszyx.
1493
+ * This module is generated at build time and contains the mapping
1494
+ * from original class names and CSS variable names to mangled names.
1495
+ *
1496
+ * @generated
1497
+ */
1498
+
1499
+ export const mangleMap = ${JSON.stringify(mangleMap, null, 2)};
1500
+
1501
+ export const varMangleMap = ${JSON.stringify(varMangleMap, null, 2)};
1502
+
1503
+ export const cssVarMetrics = ${JSON.stringify(cssVarMetrics, null, 2)};
1504
+
1505
+ export const checksum = ${JSON.stringify(checksum)};
1506
+
1507
+ export default {
1508
+ mangleMap,
1509
+ varMangleMap,
1510
+ cssVarMetrics,
1511
+ checksum,
1512
+ };
1513
+ `;
1514
+ }
1515
+ function createChecksumModule(checksum) {
1516
+ return `/**
1517
+ * Auto-generated checksum for csszyx mangle map.
1518
+ *
1519
+ * @generated
1520
+ */
1521
+
1522
+ export const checksum = ${JSON.stringify(checksum)};
1523
+
1524
+ export default checksum;
1525
+ `;
1526
+ }
1527
+ function isVirtualModule(id) {
1528
+ return id === VIRTUAL_MODULE_ID || id === VIRTUAL_CHECKSUM_ID;
1529
+ }
1530
+ function resolveVirtualModule(id) {
1531
+ if (id === VIRTUAL_MODULE_ID) {
1532
+ return RESOLVED_VIRTUAL_MODULE_ID;
1533
+ }
1534
+ if (id === VIRTUAL_CHECKSUM_ID) {
1535
+ return RESOLVED_VIRTUAL_CHECKSUM_ID;
1536
+ }
1537
+ return void 0;
1538
+ }
1539
+
1540
+ const CHECKSUM_PLACEHOLDER = "___CSSZYX_CHECKSUM___";
1541
+ const MANGLE_MAP_PLACEHOLDER = "___CSSZYX_MANGLE_MAP___";
1542
+ const VAR_MANGLE_MAP_PLACEHOLDER = "___CSSZYX_VAR_MANGLE_MAP___";
1543
+ const UNKNOWN_PACKAGE_VERSION = "0.0.0";
1544
+ const TRANSFORM_CACHE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1e3;
1545
+ const TRANSFORM_CACHE_MAX_ENTRIES = 1e4;
1546
+ const TRANSFORM_MEMORY_CACHE_MAX_ENTRIES = 1e3;
1547
+ const DEFAULT_VAR_MANGLE_MAP_MAX_BYTES = 100 * 1024;
1548
+ const GLOBAL_VAR_ALIAS_MAP_OWNER = "\0csszyx:global-var-aliases";
1549
+ const DIRECTIVE_PROLOGUE_PREFIX_RE = /^((?:\s|\/\/[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*)(['"]use (?:client|server)['"];?\s*)/;
1550
+ const RUNTIME_HELPER_IMPORT_RE = {
1551
+ _sz: /\{[^}]*\b_sz\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/,
1552
+ _szMerge: /\{[^}]*\b_szMerge\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/,
1553
+ __szColorVar: /\{[^}]*\b__szColorVar\b[^}]*\}\s*from\s*['"]@csszyx\/runtime['"]/
1554
+ };
1555
+ let _hasWarnedTsConfig = false;
1556
+ let _hasWarnedTransformCacheVersion = false;
1557
+ const requireFromHere = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/unplugin.CFp386gH.cjs', document.baseURI).href)));
1558
+ const PLUGIN_VERSION = findPackageVersionFromFile(
1559
+ node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/unplugin.CFp386gH.cjs', document.baseURI).href))),
1560
+ UNKNOWN_PACKAGE_VERSION
1561
+ );
1562
+ const COMPILER_VERSION = findPackageVersionFromModule("@csszyx/compiler", UNKNOWN_PACKAGE_VERSION);
1563
+ const BENCH_TRACE_ENABLED = process.env.CSSZYX_BENCH_TRACE === "1";
1564
+ const BENCH_TRACE_FILE = process.env.CSSZYX_BENCH_TRACE_FILE;
1565
+ function cssVariableEntries(result) {
1566
+ const entries = [];
1567
+ for (const [original, value] of result.cssVariableMap ?? []) {
1568
+ if (Array.isArray(value)) {
1569
+ for (const mangled of value) {
1570
+ entries.push([original, mangled]);
1571
+ }
1572
+ } else {
1573
+ entries.push([original, value]);
1574
+ }
1575
+ }
1576
+ return entries;
1577
+ }
1578
+ function recordFileVarMangleEntries(state, filename, entries) {
1579
+ const normalizedFilename = normalizeSourceFilename(filename);
1580
+ if (entries.length === 0) {
1581
+ state.varMangleEntriesByFile.delete(normalizedFilename);
1582
+ } else {
1583
+ state.varMangleEntriesByFile.set(normalizedFilename, entries);
1584
+ }
1585
+ state.varMangleMap = buildVarMangleMap(state.varMangleEntriesByFile);
1586
+ }
1587
+ function recordGlobalVarSourceFile(state, filename, code) {
1588
+ const normalizedFilename = normalizeSourceFilename(filename);
1589
+ if (!/\.[tj]sx?(?:\?.*)?$/.test(normalizedFilename)) {
1590
+ return;
1591
+ }
1592
+ if (code === null) {
1593
+ state.globalVarSourceFilesByFile.delete(normalizedFilename);
1594
+ } else {
1595
+ state.globalVarSourceFilesByFile.set(normalizedFilename, code);
1596
+ }
1597
+ }
1598
+ function buildGlobalVarSourceFiles(state) {
1599
+ return [...state.globalVarSourceFilesByFile.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([filePath, code]) => ({ filePath, code }));
1600
+ }
1601
+ function collectRollupGlobalVarCssAssets(bundle) {
1602
+ return Object.values(bundle).filter(
1603
+ (chunk) => chunk.type === "asset" && typeof chunk.fileName === "string" && /\.css(?:$|\?)/.test(chunk.fileName) && (typeof chunk.source === "string" || chunk.source instanceof Uint8Array)
1604
+ ).sort((left, right) => left.fileName.localeCompare(right.fileName)).map((asset) => ({
1605
+ fileName: asset.fileName,
1606
+ source: asset.source
1607
+ }));
1608
+ }
1609
+ function collectConfiguredGlobalVarCssSources(rootDir, scanCss) {
1610
+ if (!scanCss) {
1611
+ return [];
1612
+ }
1613
+ return expandFilePatterns(rootDir, scanCss).filter((file) => file.endsWith(".css")).sort((left, right) => left.localeCompare(right)).flatMap((file) => {
1614
+ try {
1615
+ const snapshot = readStableTextFileSnapshotSync(file);
1616
+ return [
1617
+ {
1618
+ fileName: file,
1619
+ source: snapshot.source,
1620
+ mtimeMs: snapshot.mtimeMs
1621
+ }
1622
+ ];
1623
+ } catch {
1624
+ return [];
1625
+ }
1626
+ });
1627
+ }
1628
+ function collectWebpackGlobalVarCssAssets(assets) {
1629
+ return Object.entries(assets).flatMap(([fileName, asset]) => {
1630
+ if (!/\.css(?:$|\?)/.test(fileName)) {
1631
+ return [];
1632
+ }
1633
+ const source = asset.source();
1634
+ if (typeof source !== "string" && !(source instanceof Uint8Array)) {
1635
+ return [];
1636
+ }
1637
+ return [{ fileName, source }];
1638
+ }).sort((left, right) => left.fileName.localeCompare(right.fileName)).map(({ fileName, source }) => ({ fileName, source }));
1639
+ }
1640
+ function assertNoGlobalVarAliasValidationErrors(result) {
1641
+ const messages = [
1642
+ ...result.plan.diagnostics.map((diagnostic) => {
1643
+ const location = diagnostic.location ? ` (${diagnostic.location.filePath}:${diagnostic.location.line}:${diagnostic.location.column})` : "";
1644
+ return `[${diagnostic.code}] ${diagnostic.name}${location}: ${diagnostic.message}`;
1645
+ }),
1646
+ ...result.usageDiagnostics.map((diagnostic) => {
1647
+ const location = diagnostic.location;
1648
+ return `[${diagnostic.kind}] ${diagnostic.name} (${location.filePath}:${location.line}:${location.column}): ${diagnostic.message}`;
1649
+ })
1650
+ ];
1651
+ if (messages.length > 0) {
1652
+ throw new Error(
1653
+ `[csszyx] production.mangleGlobalVars validation failed:
1654
+ ${messages.join("\n")}`
1655
+ );
1656
+ }
1657
+ }
1658
+ function rewriteCssWithValidatedGlobalVarPlan(css, filePath, result) {
1659
+ if (result === null || result.plan.entries.length === 0) {
1660
+ return css;
1661
+ }
1662
+ const rewrite = rewriteGlobalVarCssAliases({
1663
+ css,
1664
+ plan: result.plan,
1665
+ filePath
1666
+ });
1667
+ assertNoGlobalVarAliasValidationErrors({
1668
+ scans: result.scans,
1669
+ plan: {
1670
+ ...result.plan,
1671
+ diagnostics: rewrite.diagnostics
1672
+ },
1673
+ usageDiagnostics: []
1674
+ });
1675
+ return rewrite.css;
1676
+ }
1677
+ function assertGlobalVarPlanMatchesEarlyAliases(result, expectedEntries) {
1678
+ const actualEntries = [...result.plan.aliases.entries()].sort(
1679
+ ([left], [right]) => left.localeCompare(right)
1680
+ );
1681
+ const expected = expectedEntries.map(([original, alias]) => [original, alias]).sort(([left], [right]) => left.localeCompare(right));
1682
+ const expectedJson = JSON.stringify(expected);
1683
+ const actualJson = JSON.stringify(actualEntries);
1684
+ if (expectedJson !== actualJson) {
1685
+ throw new Error(
1686
+ `[csszyx] production.mangleGlobalVars validation failed:
1687
+ CSS alias plan ${actualJson} does not match source-transform alias table ${expectedJson}.`
1688
+ );
1689
+ }
1690
+ }
1691
+ function buildVarMangleMap(entriesByFile) {
1692
+ const next = {};
1693
+ const files = [...entriesByFile.keys()].sort();
1694
+ for (const file of files) {
1695
+ for (const [original, mangled] of entriesByFile.get(file) ?? []) {
1696
+ addVarMangleMapping(next, original, mangled);
1697
+ }
1698
+ }
1699
+ return next;
1700
+ }
1701
+ function extractGlobalVarAliasesForManifest(varMangleMap, aliasPrefix = types.CSSZYX_GLOBAL_ALIAS_PREFIX, validationResult = null) {
1702
+ const aliases = {};
1703
+ for (const [original, value] of Object.entries(varMangleMap).sort(
1704
+ ([left], [right]) => left.localeCompare(right)
1705
+ )) {
1706
+ const values = Array.isArray(value) ? value : [value];
1707
+ const alias = values.find((candidate) => candidate.startsWith(aliasPrefix));
1708
+ if (alias) {
1709
+ aliases[original] = alias;
1710
+ }
1711
+ }
1712
+ for (const entry of validationResult?.plan.entries ?? []) {
1713
+ if (entry.alias.startsWith(aliasPrefix)) {
1714
+ aliases[entry.original] = entry.alias;
1715
+ }
1716
+ }
1717
+ return Object.fromEntries(
1718
+ Object.entries(aliases).sort(([left], [right]) => left.localeCompare(right))
1719
+ );
1720
+ }
1721
+ function createGlobalVarMapAssetSource(varMangleMap, aliasPrefix = types.CSSZYX_GLOBAL_ALIAS_PREFIX, validationResult = null) {
1722
+ const aliases = extractGlobalVarAliasesForManifest(varMangleMap, aliasPrefix, validationResult);
1723
+ return Object.keys(aliases).length > 0 ? JSON.stringify(aliases) : null;
1724
+ }
1725
+ function normalizeGlobalVarAliasesForCache(aliases) {
1726
+ if (!aliases) {
1727
+ return [];
1728
+ }
1729
+ const entries = aliases instanceof Map ? aliases.entries() : Array.isArray(aliases) ? aliases : Object.entries(aliases);
1730
+ const normalized = /* @__PURE__ */ new Map();
1731
+ for (const [original, alias] of entries) {
1732
+ if (original.startsWith("--") && alias.startsWith("--")) {
1733
+ normalized.set(original, alias);
1734
+ }
1735
+ }
1736
+ return [...normalized].sort(([left], [right]) => left.localeCompare(right));
1737
+ }
1738
+ function createEarlyGlobalVarAliasEntries(config, aliasPrefix) {
1739
+ if (config?.enabled !== true || !config.tokens || config.tokens.length === 0) {
1740
+ return [];
1741
+ }
1742
+ const tokens = [...new Set(config.tokens)].sort();
1743
+ return tokens.map((original, index) => [original, `${aliasPrefix}${core.encode(index)}`]);
1744
+ }
1745
+ function shouldEmitGlobalVarMapAsset(config) {
1746
+ return config?.emitMap !== false;
1747
+ }
1748
+ function assertVarMangleMapSize(varMangleMap, maxBytes) {
1749
+ const size = Buffer.byteLength(JSON.stringify(varMangleMap), "utf8");
1750
+ if (size <= maxBytes) {
1751
+ return;
1752
+ }
1753
+ throw new Error(
1754
+ `[csszyx] CSS variable mangle map is ${size} bytes, which exceeds the ${maxBytes} byte safety cap. Reduce production.mangleVars usage, split the bundle, or raise CSSZYX_VAR_MANGLE_MAP_MAX_BYTES if this payload size is intentional.`
1755
+ );
1756
+ }
1757
+ function resolveVarMangleMapMaxBytes() {
1758
+ const raw = process.env.CSSZYX_VAR_MANGLE_MAP_MAX_BYTES;
1759
+ if (!raw) {
1760
+ return DEFAULT_VAR_MANGLE_MAP_MAX_BYTES;
1761
+ }
1762
+ const value = Number.parseInt(raw, 10);
1763
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_VAR_MANGLE_MAP_MAX_BYTES;
1764
+ }
1765
+ function addVarMangleMapping(map, original, mangled) {
1766
+ const existing = map[original];
1767
+ if (!existing) {
1768
+ map[original] = mangled;
1769
+ return;
1770
+ }
1771
+ const values = Array.isArray(existing) ? existing : [existing];
1772
+ if (!values.includes(mangled)) {
1773
+ map[original] = [...values, mangled];
1774
+ }
1775
+ }
1776
+ function emptyCSSVariableMetrics() {
1777
+ return {
1778
+ componentClassUses: 0,
1779
+ componentStyleDeclarations: 0,
1780
+ estimatedHoistedDeclarationsSaved: 0,
1781
+ scopedClassUses: 0,
1782
+ scopedStyleDeclarations: 0
1783
+ };
1784
+ }
1785
+ function recordFileCSSVariableMetrics(state, filename, code) {
1786
+ const normalizedFilename = normalizeSourceFilename(filename);
1787
+ if (!code) {
1788
+ state.cssVarMetricsByFile.delete(normalizedFilename);
1789
+ } else {
1790
+ const metrics = collectCSSVariableMetrics(code);
1791
+ if (hasCSSVariableMetrics(metrics)) {
1792
+ state.cssVarMetricsByFile.set(normalizedFilename, metrics);
1793
+ } else {
1794
+ state.cssVarMetricsByFile.delete(normalizedFilename);
1795
+ }
1796
+ }
1797
+ state.cssVarMetrics = buildCSSVariableMetrics(state.cssVarMetricsByFile);
1798
+ }
1799
+ function collectCSSVariableMetrics(code) {
1800
+ const componentUses = /* @__PURE__ */ new Map();
1801
+ const componentDeclarations = /* @__PURE__ */ new Map();
1802
+ const metrics = emptyCSSVariableMetrics();
1803
+ for (const match of code.matchAll(/\(--([cs][A-Za-z0-9]+)\)/g)) {
1804
+ const name = `--${match[1]}`;
1805
+ if (name.startsWith("--c")) {
1806
+ metrics.componentClassUses++;
1807
+ incrementCount(componentUses, name);
1808
+ } else {
1809
+ metrics.scopedClassUses++;
1810
+ }
1811
+ }
1812
+ for (const match of code.matchAll(/["'](--([cs][A-Za-z0-9]+))["']\s*:/g)) {
1813
+ const name = match[1];
1814
+ if (name.startsWith("--c")) {
1815
+ metrics.componentStyleDeclarations++;
1816
+ incrementCount(componentDeclarations, name);
1817
+ } else {
1818
+ metrics.scopedStyleDeclarations++;
1819
+ }
1820
+ }
1821
+ for (const [name, uses] of componentUses) {
1822
+ const declarations = componentDeclarations.get(name) ?? 0;
1823
+ metrics.estimatedHoistedDeclarationsSaved += Math.max(0, uses - declarations);
1824
+ }
1825
+ return metrics;
1826
+ }
1827
+ function buildCSSVariableMetrics(metricsByFile) {
1828
+ const total = emptyCSSVariableMetrics();
1829
+ for (const file of [...metricsByFile.keys()].sort()) {
1830
+ const metrics = metricsByFile.get(file);
1831
+ if (!metrics) {
1832
+ continue;
1833
+ }
1834
+ total.componentClassUses += metrics.componentClassUses;
1835
+ total.componentStyleDeclarations += metrics.componentStyleDeclarations;
1836
+ total.estimatedHoistedDeclarationsSaved += metrics.estimatedHoistedDeclarationsSaved;
1837
+ total.scopedClassUses += metrics.scopedClassUses;
1838
+ total.scopedStyleDeclarations += metrics.scopedStyleDeclarations;
1839
+ }
1840
+ return total;
1841
+ }
1842
+ function hasCSSVariableMetrics(metrics) {
1843
+ return Object.values(metrics).some((value) => value > 0);
1844
+ }
1845
+ function incrementCount(map, key) {
1846
+ map.set(key, (map.get(key) ?? 0) + 1);
1847
+ }
1848
+ function traceBenchTiming(label, filename, elapsedMs) {
1849
+ if (!BENCH_TRACE_ENABLED) {
1850
+ return;
1851
+ }
1852
+ if (BENCH_TRACE_FILE && !filename.includes(BENCH_TRACE_FILE)) {
1853
+ return;
1854
+ }
1855
+ console.log(
1856
+ `[csszyx:bench] ${label} ${elapsedMs.toFixed(3)}ms ${normalizeSourceFilename(filename)}`
1857
+ );
1858
+ }
1859
+ function runThemeScan(rootDir, scanCss) {
1860
+ if (!scanCss) {
1861
+ return;
1862
+ }
1863
+ const sourceFiles = expandFilePatterns(rootDir, scanCss).filter((file) => file.endsWith(".css"));
1864
+ if (sourceFiles.length === 0) {
1865
+ return;
1866
+ }
1867
+ const themes = sourceFiles.map((f) => {
1868
+ try {
1869
+ return parseThemeBlocks(readStableTextFileSnapshotSync(f).source);
1870
+ } catch {
1871
+ return null;
1872
+ }
1873
+ }).filter((t) => t !== null);
1874
+ const merged = mergeThemes(themes);
1875
+ const outputPath = path__namespace.join(rootDir, ".csszyx", "theme.d.ts");
1876
+ writeThemeDts({ outputPath, theme: merged, sourceFiles });
1877
+ if (!_hasWarnedTsConfig) {
1878
+ _hasWarnedTsConfig = true;
1879
+ try {
1880
+ const checkFile = (cfgPath) => {
1881
+ let content;
1882
+ try {
1883
+ content = fs__namespace.readFileSync(cfgPath, "utf-8");
1884
+ } catch (err) {
1885
+ if (err?.code === "ENOENT") {
1886
+ return false;
1887
+ }
1888
+ throw err;
1889
+ }
1890
+ if (!content.includes(".csszyx")) {
1891
+ console.warn(
1892
+ `
1893
+ \x1B[33m\u26A0\uFE0F CSSzyx: Theme Auto-Scan enabled, but TypeScript isn't configured. Run "npx @csszyx/cli init" to fix.\x1B[0m
1894
+ `
1895
+ );
1896
+ }
1897
+ return true;
1898
+ };
1899
+ if (!checkFile(path__namespace.join(rootDir, "tsconfig.json"))) {
1900
+ checkFile(path__namespace.join(rootDir, "tsconfig.app.json"));
1901
+ }
1902
+ } catch {
1903
+ }
1904
+ }
1905
+ }
1906
+ function findPackageVersionFromModule(specifier, fallback) {
1907
+ try {
1908
+ return findPackageVersionFromFile(requireFromHere.resolve(specifier), fallback);
1909
+ } catch {
1910
+ return fallback;
1911
+ }
1912
+ }
1913
+ function findPackageVersionFromFile(file, fallback) {
1914
+ let dir = path__namespace.dirname(file);
1915
+ while (true) {
1916
+ const packageJson = path__namespace.join(dir, "package.json");
1917
+ try {
1918
+ const parsed = JSON.parse(fs__namespace.readFileSync(packageJson, "utf8"));
1919
+ if (typeof parsed.version === "string") {
1920
+ return parsed.version;
1921
+ }
1922
+ return fallback;
1923
+ } catch {
1924
+ }
1925
+ const parent = path__namespace.dirname(dir);
1926
+ if (parent === dir) {
1927
+ return fallback;
1928
+ }
1929
+ dir = parent;
1930
+ }
1931
+ }
1932
+ function normalizeSourceFilename(filename) {
1933
+ return filename.replace(/\\/g, "/");
1934
+ }
1935
+ function insertRuntimeImport(code, importStmt) {
1936
+ const directiveMatch = code.match(DIRECTIVE_PROLOGUE_PREFIX_RE);
1937
+ if (!directiveMatch) {
1938
+ return `${importStmt}${code}`;
1939
+ }
1940
+ return code.replace(directiveMatch[0], `${directiveMatch[1]}${directiveMatch[2]}${importStmt}`);
1941
+ }
1942
+ function mangleCodeClassesSync(code, mangleMap) {
1943
+ function mangleClassString(classString) {
1944
+ return classString.split(/\s+/).filter(Boolean).map((cls) => {
1945
+ return mangleMap[cls.replace(/\\(.)/g, "$1")] || cls;
1946
+ }).join(" ");
1947
+ }
1948
+ let result = code.replace(/(?:class(?:Name)?|sz)[:=]\s*"((?:[^"\\]|\\.)*)"/g, (match, classes) => {
1949
+ const mangled = mangleClassString(classes);
1950
+ if (mangled === classes) {
1951
+ return match;
1952
+ }
1953
+ return match.replace(classes, mangled);
1954
+ }).replace(/(?:class(?:Name)?|sz)[:=]\s*'((?:[^'\\]|\\.)*)'/g, (match, classes) => {
1955
+ const mangled = mangleClassString(classes);
1956
+ if (mangled === classes) {
1957
+ return match;
1958
+ }
1959
+ return match.replace(classes, mangled);
1960
+ });
1961
+ result = result.replace(/className:\s*`([^`]+)`/g, (fullMatch, tplContent) => {
1962
+ let changed = false;
1963
+ let out = "";
1964
+ let i = 0;
1965
+ while (i < tplContent.length) {
1966
+ const interStart = tplContent.indexOf("${", i);
1967
+ if (interStart === -1) {
1968
+ const quasi2 = tplContent.slice(i);
1969
+ const trimmed2 = quasi2.trim();
1970
+ if (trimmed2) {
1971
+ const m = mangleClassString(trimmed2);
1972
+ if (m !== trimmed2) {
1973
+ changed = true;
1974
+ out += quasi2.replace(trimmed2, m);
1975
+ } else {
1976
+ out += quasi2;
1977
+ }
1978
+ } else {
1979
+ out += quasi2;
1980
+ }
1981
+ break;
1982
+ }
1983
+ const quasi = tplContent.slice(i, interStart);
1984
+ const trimmed = quasi.trim();
1985
+ if (trimmed) {
1986
+ const m = mangleClassString(trimmed);
1987
+ if (m !== trimmed) {
1988
+ changed = true;
1989
+ out += quasi.replace(trimmed, m);
1990
+ } else {
1991
+ out += quasi;
1992
+ }
1993
+ } else {
1994
+ out += quasi;
1995
+ }
1996
+ let j = interStart + 2;
1997
+ let depth = 0;
1998
+ while (j < tplContent.length) {
1999
+ if (tplContent[j] === "{") {
2000
+ depth++;
2001
+ } else if (tplContent[j] === "}") {
2002
+ if (depth === 0) {
2003
+ j++;
2004
+ break;
2005
+ }
2006
+ depth--;
2007
+ }
2008
+ j++;
2009
+ }
2010
+ const interInner = tplContent.slice(interStart + 2, j - 1);
2011
+ const mangledInner = interInner.replace(/"([^"]*)"/g, (qm, inner) => {
2012
+ const parts = inner.split(/\s+/).filter(Boolean);
2013
+ if (parts.length === 0) {
2014
+ return qm;
2015
+ }
2016
+ const m = parts.map((p) => mangleMap[p] || p).join(" ");
2017
+ if (m === inner) {
2018
+ return qm;
2019
+ }
2020
+ changed = true;
2021
+ return `"${m}"`;
2022
+ });
2023
+ out += `\${${mangledInner}}`;
2024
+ i = j;
2025
+ }
2026
+ return changed ? `className:\`${out}\`` : fullMatch;
2027
+ });
2028
+ {
2029
+ const marker = "className:";
2030
+ let searchFrom = 0;
2031
+ let out = "";
2032
+ while (searchFrom < result.length) {
2033
+ const idx = result.indexOf(marker, searchFrom);
2034
+ if (idx === -1) {
2035
+ out += result.slice(searchFrom);
2036
+ break;
2037
+ }
2038
+ out += result.slice(searchFrom, idx + marker.length);
2039
+ const afterColon = idx + marker.length;
2040
+ let exprStart = afterColon;
2041
+ while (exprStart < result.length && result[exprStart] === " ") {
2042
+ exprStart++;
2043
+ }
2044
+ const firstChar = result[exprStart];
2045
+ if (firstChar === '"' || firstChar === "'" || firstChar === "`") {
2046
+ searchFrom = afterColon;
2047
+ continue;
2048
+ }
2049
+ let depth = 0;
2050
+ let j = afterColon;
2051
+ while (j < result.length) {
2052
+ const ch = result[j];
2053
+ if (ch === "(" || ch === "[") {
2054
+ depth++;
2055
+ } else if (ch === ")" || ch === "]") {
2056
+ if (depth === 0) {
2057
+ break;
2058
+ }
2059
+ depth--;
2060
+ } else if (depth === 0 && (ch === "," || ch === ";" || ch === "\n" || ch === "}")) {
2061
+ break;
2062
+ }
2063
+ j++;
2064
+ }
2065
+ const expr = result.slice(afterColon, j);
2066
+ const qIdx = expr.indexOf("?");
2067
+ if (qIdx === -1 || !expr.slice(qIdx).includes(":")) {
2068
+ out += expr;
2069
+ searchFrom = j;
2070
+ continue;
2071
+ }
2072
+ let changed = false;
2073
+ const mangled = expr.replace(/"([^"]*)"/g, (qm, inner) => {
2074
+ const parts = inner.split(/\s+/).filter(Boolean);
2075
+ if (parts.length === 0) {
2076
+ return qm;
2077
+ }
2078
+ const mangledStr = parts.map((p) => mangleMap[p] || p).join(" ");
2079
+ if (mangledStr !== inner) {
2080
+ changed = true;
2081
+ return `"${mangledStr}"`;
2082
+ }
2083
+ return qm;
2084
+ });
2085
+ out += changed ? mangled : expr;
2086
+ searchFrom = j;
2087
+ }
2088
+ result = out;
2089
+ }
2090
+ result = result.replace(/(?<=(?:[,(]|&&)\s*)"([^"]+)"/g, (match, inner) => {
2091
+ const tokens = inner.split(/\s+/).filter(Boolean);
2092
+ if (tokens.length === 0) {
2093
+ return match;
2094
+ }
2095
+ let changed = false;
2096
+ const mangled = [];
2097
+ for (const t of tokens) {
2098
+ const m = mangleMap[t];
2099
+ if (m === void 0) {
2100
+ return match;
2101
+ }
2102
+ if (m !== t) {
2103
+ changed = true;
2104
+ }
2105
+ mangled.push(m);
2106
+ }
2107
+ if (!changed) {
2108
+ return match;
2109
+ }
2110
+ return `"${mangled.join(" ")}"`;
2111
+ });
2112
+ return result;
2113
+ }
2114
+ function assertGlobalVarMangleConfig(options) {
2115
+ const config = options.production?.mangleGlobalVars;
2116
+ const errors = types.validateGlobalVarMangleConfig(config);
2117
+ if (errors.length > 0) {
2118
+ throw new Error(
2119
+ `[csszyx] Invalid production.mangleGlobalVars config:
2120
+ ${errors.join("\n")}`
2121
+ );
2122
+ }
2123
+ if (config?.enabled === true) {
2124
+ if (!config.tokens || config.tokens.length === 0) {
2125
+ throw new Error(
2126
+ "[csszyx] production.mangleGlobalVars.enabled requires explicit tokens in Phase H v1."
2127
+ );
2128
+ }
2129
+ if (config.autoPrefix !== void 0 && config.autoPrefix !== "") {
2130
+ throw new Error(
2131
+ "[csszyx] production.mangleGlobalVars.autoPrefix requires CSS pre-scan support and is not enabled in Phase H v1."
2132
+ );
2133
+ }
2134
+ }
2135
+ }
2136
+ function createCsszyxPlugins(options = {}) {
2137
+ assertGlobalVarMangleConfig(options);
2138
+ const manglingEnabled = options.production?.mangle !== false;
2139
+ const astBudgetOverride = options.build?.astBudgetLimit;
2140
+ const cacheRequested = (options.build?.cache ?? types.DEFAULT_BUILD_CONFIG.cache) !== false;
2141
+ const cacheVersionsKnown = PLUGIN_VERSION !== UNKNOWN_PACKAGE_VERSION && COMPILER_VERSION !== UNKNOWN_PACKAGE_VERSION;
2142
+ const cacheEnabled = cacheRequested && cacheVersionsKnown;
2143
+ const varMangleMapMaxBytes = resolveVarMangleMapMaxBytes();
2144
+ const globalVarMangleConfig = options.production?.mangleGlobalVars;
2145
+ const globalVarAliasPrefix = globalVarMangleConfig?.aliasPrefix ?? types.CSSZYX_GLOBAL_ALIAS_PREFIX;
2146
+ const encodedGlobalVarAliasPrefix = encodeURIComponent(globalVarAliasPrefix);
2147
+ const earlyGlobalVarAliasEntries = createEarlyGlobalVarAliasEntries(
2148
+ globalVarMangleConfig,
2149
+ globalVarAliasPrefix
2150
+ );
2151
+ if (cacheRequested && !cacheVersionsKnown && !_hasWarnedTransformCacheVersion) {
2152
+ _hasWarnedTransformCacheVersion = true;
2153
+ console.warn(
2154
+ "[csszyx] Transform cache disabled because package versions could not be resolved."
2155
+ );
2156
+ }
2157
+ const parserOverride = process.env.CSSZYX_PARSER;
2158
+ const defaultParser = types.DEFAULT_BUILD_CONFIG.parser ?? "rust";
2159
+ const parserMode = parserOverride === "babel" || parserOverride === "oxc" || parserOverride === "rust" ? parserOverride : options.build?.parser ?? defaultParser;
2160
+ let evictedCacheRoot = null;
2161
+ const transformMemoryCache = /* @__PURE__ */ new Map();
2162
+ const state = {
2163
+ classes: /* @__PURE__ */ new Set(),
2164
+ mangleMap: {},
2165
+ varMangleEntriesByFile: /* @__PURE__ */ new Map(),
2166
+ varMangleMap: Object.fromEntries(earlyGlobalVarAliasEntries),
2167
+ cssVarMetricsByFile: /* @__PURE__ */ new Map(),
2168
+ cssVarMetrics: emptyCSSVariableMetrics(),
2169
+ checksum: "",
2170
+ finalized: false,
2171
+ rootDir: process.cwd(),
2172
+ recoveryTokens: /* @__PURE__ */ new Map(),
2173
+ rscModules: /* @__PURE__ */ new Map(),
2174
+ globalVarSourceFilesByFile: /* @__PURE__ */ new Map(),
2175
+ globalVarValidationResult: null
2176
+ };
2177
+ if (earlyGlobalVarAliasEntries.length > 0) {
2178
+ state.varMangleEntriesByFile.set(GLOBAL_VAR_ALIAS_MAP_OWNER, earlyGlobalVarAliasEntries);
2179
+ }
2180
+ const SAFELIST_FILENAME = "csszyx-classes.html";
2181
+ const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([".tsx", ".jsx", ".ts", ".js"]);
2182
+ const IGNORE_DIRS = /* @__PURE__ */ new Set(["node_modules", ".next", ".git", "dist", "build", ".turbo"]);
2183
+ function isUserExcluded(id) {
2184
+ return matchesAnyPattern(id, options.exclude, state.rootDir);
2185
+ }
2186
+ function isUserIncluded(id) {
2187
+ return !options.include || matchesAnyPattern(id, options.include, state.rootDir);
2188
+ }
2189
+ function resolveGlobalVarValidationCacheDir() {
2190
+ if (!cacheEnabled) {
2191
+ return void 0;
2192
+ }
2193
+ const cacheRoot = path__namespace.resolve(
2194
+ state.rootDir,
2195
+ options.build?.cacheDir ?? types.DEFAULT_BUILD_CONFIG.cacheDir ?? ".csszyx/cache"
2196
+ );
2197
+ return resolveGlobalVarScanCacheDir(cacheRoot);
2198
+ }
2199
+ function validateGlobalVarBundleInputs(cssAssets) {
2200
+ if (globalVarMangleConfig?.enabled !== true) {
2201
+ return null;
2202
+ }
2203
+ const configuredCssAssets = collectConfiguredGlobalVarCssSources(
2204
+ state.rootDir,
2205
+ options.build?.scanCss
2206
+ );
2207
+ const result = validateGlobalVarAliasInputs(
2208
+ createGlobalVarAliasValidationOptions({
2209
+ rootDir: state.rootDir,
2210
+ cssAssets: [...configuredCssAssets, ...cssAssets],
2211
+ sourceFiles: buildGlobalVarSourceFiles(state),
2212
+ tokens: globalVarMangleConfig.tokens,
2213
+ autoPrefix: globalVarMangleConfig.autoPrefix,
2214
+ aliasPrefix: globalVarAliasPrefix,
2215
+ reserved: globalVarMangleConfig.reserved,
2216
+ cacheDir: resolveGlobalVarValidationCacheDir()
2217
+ })
2218
+ );
2219
+ assertNoGlobalVarAliasValidationErrors(result);
2220
+ assertGlobalVarPlanMatchesEarlyAliases(result, earlyGlobalVarAliasEntries);
2221
+ return result;
2222
+ }
2223
+ function isHardIgnored(id) {
2224
+ return id.includes("node_modules") || id.includes("/packages/") || id.includes(".next") && !id.includes("static");
2225
+ }
2226
+ function shouldProcessSource(id) {
2227
+ return !isHardIgnored(id) && !isUserExcluded(id) && isUserIncluded(id) && (/\.[tj]sx?(\?.*)?$/.test(id) || id.endsWith(".vue") || id.endsWith(".svelte"));
2228
+ }
2229
+ function shouldProcessCss(id) {
2230
+ return !isHardIgnored(id) && !isUserExcluded(id) && /\.css(\?.*)?$/.test(id);
2231
+ }
2232
+ function transformConfiguredSource(source, filename) {
2233
+ const compilerOptions = createCompilerOptions();
2234
+ const effectiveFilename = normalizeSourceFilename(filename);
2235
+ const cacheRoot = transformCache.resolveTransformCacheDir(state.rootDir, options.build?.cacheDir);
2236
+ if (cacheEnabled) {
2237
+ evictTransformCacheOnce();
2238
+ }
2239
+ const cacheInput = createConfiguredTransformCacheInput(
2240
+ source,
2241
+ effectiveFilename,
2242
+ compilerOptions
2243
+ );
2244
+ if (parserMode === "rust") {
2245
+ compiler.ensureRustTransformAvailable();
2246
+ }
2247
+ const cacheKey = cacheEnabled ? transformCache.createTransformCacheKey(cacheInput) : null;
2248
+ if (cacheEnabled && cacheKey) {
2249
+ const memoryCached = transformMemoryCache.get(cacheKey.key);
2250
+ if (memoryCached) {
2251
+ transformMemoryCache.delete(cacheKey.key);
2252
+ transformMemoryCache.set(cacheKey.key, memoryCached);
2253
+ return memoryCached;
2254
+ }
2255
+ const cached = transformCache.readTransformCache(cacheRoot, cacheInput, cacheKey);
2256
+ if (cached) {
2257
+ rememberTransformCacheEntry(cacheKey.key, cached);
2258
+ return cached;
2259
+ }
2260
+ }
2261
+ let result;
2262
+ if (parserMode === "babel") {
2263
+ result = compiler.transformSourceCode(source, effectiveFilename, compilerOptions);
2264
+ } else if (parserMode === "rust") {
2265
+ result = compiler.transformRust(source, effectiveFilename, compilerOptions);
2266
+ } else {
2267
+ try {
2268
+ result = compiler.transformOxc(source, effectiveFilename, compilerOptions);
2269
+ } catch (err) {
2270
+ result = compiler.transformSourceCode(source, effectiveFilename, compilerOptions);
2271
+ const reason = err instanceof Error ? err.message : String(err);
2272
+ result.diagnostics.push(
2273
+ `[csszyx] oxc parser fell back to Babel for ${effectiveFilename}: ${reason}`
2274
+ );
2275
+ return result;
2276
+ }
2277
+ }
2278
+ if (cacheEnabled && cacheKey) {
2279
+ transformCache.writeTransformCache(cacheRoot, cacheInput, result, cacheKey);
2280
+ rememberTransformCacheEntry(cacheKey.key, result);
2281
+ }
2282
+ return result;
2283
+ }
2284
+ function createCompilerOptions() {
2285
+ return {
2286
+ astBudget: astBudgetOverride,
2287
+ mangleVars: options.production?.mangleVars === true,
2288
+ mangleVarHoistMaxDepth: options.production?.mangleVarHoistMaxDepth,
2289
+ globalVarAliases: earlyGlobalVarAliasEntries.length > 0 ? earlyGlobalVarAliasEntries : void 0
2290
+ };
2291
+ }
2292
+ function createConfiguredTransformCacheInput(source, effectiveFilename, compilerOptions) {
2293
+ return {
2294
+ pluginVersion: PLUGIN_VERSION,
2295
+ compilerVersion: COMPILER_VERSION,
2296
+ parserMode,
2297
+ producer: parserMode,
2298
+ astBudget: astBudgetOverride,
2299
+ mangleVars: compilerOptions.mangleVars,
2300
+ mangleVarHoistMaxDepth: compilerOptions.mangleVarHoistMaxDepth,
2301
+ globalVarAliases: normalizeGlobalVarAliasesForCache(compilerOptions.globalVarAliases),
2302
+ filename: effectiveFilename,
2303
+ source
2304
+ };
2305
+ }
2306
+ function transformPrescanSources(files) {
2307
+ if (parserMode !== "rust" || files.length <= 1) {
2308
+ return transformPrescanSourcesIndividually(files);
2309
+ }
2310
+ const compilerOptions = createCompilerOptions();
2311
+ const cacheRoot = transformCache.resolveTransformCacheDir(state.rootDir, options.build?.cacheDir);
2312
+ const results = /* @__PURE__ */ new Map();
2313
+ const misses = [];
2314
+ if (cacheEnabled) {
2315
+ evictTransformCacheOnce();
2316
+ }
2317
+ compiler.ensureRustTransformAvailable();
2318
+ for (const file of files) {
2319
+ const effectiveFilename = normalizeSourceFilename(file.filePath);
2320
+ const cacheInput = createConfiguredTransformCacheInput(
2321
+ file.content,
2322
+ effectiveFilename,
2323
+ compilerOptions
2324
+ );
2325
+ const cacheKey = cacheEnabled ? transformCache.createTransformCacheKey(cacheInput) : null;
2326
+ if (cacheEnabled && cacheKey) {
2327
+ const memoryCached = transformMemoryCache.get(cacheKey.key);
2328
+ if (memoryCached) {
2329
+ transformMemoryCache.delete(cacheKey.key);
2330
+ transformMemoryCache.set(cacheKey.key, memoryCached);
2331
+ results.set(file.filePath, memoryCached);
2332
+ continue;
2333
+ }
2334
+ const cached = transformCache.readTransformCache(cacheRoot, cacheInput, cacheKey);
2335
+ if (cached) {
2336
+ rememberTransformCacheEntry(cacheKey.key, cached);
2337
+ results.set(file.filePath, cached);
2338
+ continue;
2339
+ }
2340
+ }
2341
+ misses.push({
2342
+ filePath: file.filePath,
2343
+ effectiveFilename,
2344
+ content: file.content,
2345
+ cacheInput,
2346
+ cacheKey
2347
+ });
2348
+ }
2349
+ if (misses.length === 0) {
2350
+ return files.map((file) => {
2351
+ const result = results.get(file.filePath);
2352
+ return result ? { filePath: file.filePath, result } : null;
2353
+ }).filter((entry) => entry !== null);
2354
+ }
2355
+ try {
2356
+ const batchResults = compiler.transformRustBatch(
2357
+ misses.map((file) => ({
2358
+ filename: file.effectiveFilename,
2359
+ source: file.content
2360
+ })),
2361
+ compilerOptions
2362
+ );
2363
+ for (let index = 0; index < misses.length; index++) {
2364
+ const miss = misses[index];
2365
+ const result = batchResults[index];
2366
+ if (!miss || !result) {
2367
+ continue;
2368
+ }
2369
+ if (cacheEnabled && miss.cacheKey) {
2370
+ transformCache.writeTransformCache(cacheRoot, miss.cacheInput, result, miss.cacheKey);
2371
+ rememberTransformCacheEntry(miss.cacheKey.key, result);
2372
+ }
2373
+ results.set(miss.filePath, result);
2374
+ }
2375
+ } catch {
2376
+ for (const miss of misses) {
2377
+ try {
2378
+ results.set(
2379
+ miss.filePath,
2380
+ transformConfiguredSource(miss.content, miss.effectiveFilename)
2381
+ );
2382
+ } catch {
2383
+ }
2384
+ }
2385
+ }
2386
+ return files.map((file) => {
2387
+ const result = results.get(file.filePath);
2388
+ return result ? { filePath: file.filePath, result } : null;
2389
+ }).filter((entry) => entry !== null);
2390
+ }
2391
+ function transformPrescanSourcesIndividually(files) {
2392
+ const results = [];
2393
+ for (const file of files) {
2394
+ try {
2395
+ results.push({
2396
+ filePath: file.filePath,
2397
+ result: transformConfiguredSource(file.content, file.filePath)
2398
+ });
2399
+ } catch {
2400
+ }
2401
+ }
2402
+ return results;
2403
+ }
2404
+ function rememberTransformCacheEntry(key, result) {
2405
+ transformMemoryCache.delete(key);
2406
+ transformMemoryCache.set(key, result);
2407
+ if (transformMemoryCache.size <= TRANSFORM_MEMORY_CACHE_MAX_ENTRIES) {
2408
+ return;
2409
+ }
2410
+ const oldest = transformMemoryCache.keys().next().value;
2411
+ if (oldest) {
2412
+ transformMemoryCache.delete(oldest);
2413
+ }
2414
+ }
2415
+ function evictTransformCacheOnce() {
2416
+ if (!cacheEnabled) {
2417
+ return;
2418
+ }
2419
+ const cacheRoot = transformCache.resolveTransformCacheDir(state.rootDir, options.build?.cacheDir);
2420
+ if (evictedCacheRoot === cacheRoot) {
2421
+ return;
2422
+ }
2423
+ evictedCacheRoot = cacheRoot;
2424
+ transformCache.evictOldTransformCacheEntries(cacheRoot, {
2425
+ maxAgeMs: TRANSFORM_CACHE_MAX_AGE_MS,
2426
+ maxEntries: TRANSFORM_CACHE_MAX_ENTRIES
2427
+ });
2428
+ }
2429
+ function writeSafelistFile(classes) {
2430
+ if (classes.size === 0) {
2431
+ return;
2432
+ }
2433
+ const safelistPath = path__namespace.join(state.rootDir, SAFELIST_FILENAME);
2434
+ const classList = Array.from(classes).join(" ");
2435
+ const content = `<!-- Auto-generated by csszyx \u2014 DO NOT EDIT -->
2436
+ <!-- Tailwind CSS scans this file for class name detection -->
2437
+ <div class="${classList}"><div class="${classList}">x</div><div class="${classList}">x</div></div>
2438
+ `;
2439
+ try {
2440
+ let existing = "";
2441
+ try {
2442
+ existing = fs__namespace.readFileSync(safelistPath, "utf-8");
2443
+ } catch (err) {
2444
+ if (err?.code !== "ENOENT") {
2445
+ throw err;
2446
+ }
2447
+ }
2448
+ if (existing !== content) {
2449
+ fs__namespace.writeFileSync(safelistPath, content);
2450
+ }
2451
+ } catch {
2452
+ }
2453
+ }
2454
+ function prescanAndWriteClasses() {
2455
+ const prescanStarted = node_perf_hooks.performance.now();
2456
+ const discoveredClasses = /* @__PURE__ */ new Set();
2457
+ const rawDiscoveredClasses = /* @__PURE__ */ new Set();
2458
+ const prescanSources = [];
2459
+ function scanDir(dir) {
2460
+ let entries;
2461
+ try {
2462
+ entries = fs__namespace.readdirSync(dir, { withFileTypes: true });
2463
+ } catch {
2464
+ return;
2465
+ }
2466
+ for (const entry of entries) {
2467
+ if (entry.isDirectory()) {
2468
+ if (!IGNORE_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
2469
+ scanDir(path__namespace.join(dir, entry.name));
2470
+ }
2471
+ } else if (SOURCE_EXTENSIONS.has(path__namespace.extname(entry.name))) {
2472
+ const filePath = path__namespace.join(dir, entry.name);
2473
+ if (!shouldProcessSource(filePath)) {
2474
+ continue;
2475
+ }
2476
+ let content;
2477
+ try {
2478
+ content = fs__namespace.readFileSync(filePath, "utf-8");
2479
+ } catch {
2480
+ continue;
2481
+ }
2482
+ if (!content.includes("sz=") && !content.includes("sz:")) {
2483
+ continue;
2484
+ }
2485
+ prescanSources.push({ filePath, content });
2486
+ }
2487
+ }
2488
+ }
2489
+ scanDir(state.rootDir);
2490
+ for (const { filePath, result } of transformPrescanSources(prescanSources)) {
2491
+ if (!result.transformed) {
2492
+ continue;
2493
+ }
2494
+ collectPrescanResult(result, filePath, discoveredClasses, rawDiscoveredClasses);
2495
+ }
2496
+ for (const cls of discoveredClasses) {
2497
+ state.classes.add(cls);
2498
+ }
2499
+ const safelistClasses = /* @__PURE__ */ new Set([...discoveredClasses, ...rawDiscoveredClasses]);
2500
+ writeSafelistFile(safelistClasses);
2501
+ traceBenchTiming("prescan", state.rootDir, node_perf_hooks.performance.now() - prescanStarted);
2502
+ }
2503
+ function collectPrescanResult(result, filePath, discoveredClasses, rawDiscoveredClasses) {
2504
+ for (const cls of result.classes) {
2505
+ discoveredClasses.add(cls);
2506
+ }
2507
+ for (const cls of result.rawClassNames) {
2508
+ rawDiscoveredClasses.add(cls);
2509
+ }
2510
+ for (const [token, data] of result.recoveryTokens) {
2511
+ state.recoveryTokens.set(token, data);
2512
+ }
2513
+ recordFileVarMangleEntries(state, filePath, cssVariableEntries(result));
2514
+ recordFileCSSVariableMetrics(state, filePath, result.code);
2515
+ collectRuntimeStaticClasses(result, discoveredClasses);
2516
+ }
2517
+ function collectRuntimeStaticClasses(result, discoveredClasses) {
2518
+ if (!result.usesRuntime) {
2519
+ return;
2520
+ }
2521
+ const szCallRe = /_sz\(\s*\{/g;
2522
+ for (const szMatch of result.code.matchAll(szCallRe)) {
2523
+ let depth = 1;
2524
+ let idx = (szMatch.index ?? 0) + szMatch[0].length;
2525
+ while (idx < result.code.length && depth > 0) {
2526
+ if (result.code[idx] === "{") {
2527
+ depth++;
2528
+ } else if (result.code[idx] === "}") {
2529
+ depth--;
2530
+ }
2531
+ idx++;
2532
+ }
2533
+ const objStr = result.code.slice((szMatch.index ?? 0) + szMatch[0].length, idx - 1);
2534
+ collectRuntimeStringClasses(objStr, discoveredClasses);
2535
+ collectRuntimeNumberClasses(objStr, discoveredClasses);
2536
+ collectRuntimeBooleanClasses(objStr, discoveredClasses);
2537
+ }
2538
+ }
2539
+ function collectRuntimeStringClasses(objStr, discoveredClasses) {
2540
+ const strKv = /(\w+)\s*:\s*(?:"([^"]*)"|'([^']*)')/g;
2541
+ for (const kv of objStr.matchAll(strKv)) {
2542
+ try {
2543
+ const val = kv[2] ?? kv[3];
2544
+ collectTransformClasses(compiler.transform({ [kv[1]]: val }), discoveredClasses);
2545
+ } catch {
2546
+ }
2547
+ }
2548
+ }
2549
+ function collectRuntimeNumberClasses(objStr, discoveredClasses) {
2550
+ const numKv = /(\w+)\s*:\s*(-?\d+(?:\.\d+)?)\s*(?=[,}\n])/g;
2551
+ for (const kv of objStr.matchAll(numKv)) {
2552
+ try {
2553
+ collectTransformClasses(
2554
+ compiler.transform({ [kv[1]]: parseFloat(kv[2]) }),
2555
+ discoveredClasses
2556
+ );
2557
+ } catch {
2558
+ }
2559
+ }
2560
+ }
2561
+ function collectRuntimeBooleanClasses(objStr, discoveredClasses) {
2562
+ const boolKv = /(\w+)\s*:\s*(true|false)\s*(?=[,}\n])/g;
2563
+ for (const kv of objStr.matchAll(boolKv)) {
2564
+ try {
2565
+ collectTransformClasses(
2566
+ compiler.transform({ [kv[1]]: kv[2] === "true" }),
2567
+ discoveredClasses
2568
+ );
2569
+ } catch {
2570
+ }
2571
+ }
2572
+ }
2573
+ function collectTransformClasses(result, discoveredClasses) {
2574
+ for (const cls of result.className.split(/\s+/).filter(Boolean)) {
2575
+ discoveredClasses.add(cls);
2576
+ }
2577
+ }
2578
+ function extractClasses(code) {
2579
+ const dqPattern = /(?:class(?:Name)?|sz)[:=]\s*"([^"]*)"/g;
2580
+ const sqPattern = /(?:class(?:Name)?|sz)[:=]\s*'([^']*)'/g;
2581
+ for (const classPattern of [dqPattern, sqPattern]) {
2582
+ for (const match of code.matchAll(classPattern)) {
2583
+ const classes = match[1].split(/\s+/).filter(Boolean);
2584
+ for (const cls of classes) {
2585
+ state.classes.add(cls);
2586
+ }
2587
+ }
2588
+ }
2589
+ const exprStart = /className=\{/g;
2590
+ for (const match of code.matchAll(exprStart)) {
2591
+ let depth = 1;
2592
+ let i = (match.index ?? 0) + match[0].length;
2593
+ while (i < code.length && depth > 0) {
2594
+ if (code[i] === "{") {
2595
+ depth++;
2596
+ } else if (code[i] === "}") {
2597
+ depth--;
2598
+ }
2599
+ i++;
2600
+ }
2601
+ const expr = code.slice((match.index ?? 0) + match[0].length, i - 1);
2602
+ const strPattern = /"([^"]+)"|'([^']+)'/g;
2603
+ for (const strMatch of expr.matchAll(strPattern)) {
2604
+ const str = strMatch[1] || strMatch[2];
2605
+ const classes = str.split(/\s+/).filter(Boolean);
2606
+ for (const cls of classes) {
2607
+ state.classes.add(cls);
2608
+ }
2609
+ }
2610
+ }
2611
+ }
2612
+ function finalizeMangleMap() {
2613
+ const sortedClasses = Array.from(state.classes);
2614
+ const newMap = {};
2615
+ for (let i = 0; i < sortedClasses.length; i++) {
2616
+ newMap[sortedClasses[i]] = core.encode(i);
2617
+ }
2618
+ state.mangleMap = newMap;
2619
+ assertVarMangleMapSize(state.varMangleMap, varMangleMapMaxBytes);
2620
+ state.checksum = core.compute_mangle_checksum(
2621
+ createHydrationMangleMap(state.mangleMap, state.varMangleMap)
2622
+ );
2623
+ state.finalized = true;
2624
+ }
2625
+ function mangleCodeClasses(code) {
2626
+ return mangleCodeClassesSync(code, state.mangleMap);
2627
+ }
2628
+ function replacePlaceholders(code) {
2629
+ let result = code;
2630
+ if (result.includes(CHECKSUM_PLACEHOLDER)) {
2631
+ result = result.split(CHECKSUM_PLACEHOLDER).join(state.checksum);
2632
+ }
2633
+ if (result.includes(MANGLE_MAP_PLACEHOLDER)) {
2634
+ const jsonMap = JSON.stringify(state.mangleMap);
2635
+ const escapedMap = result.includes("eval(") ? jsonMap.replace(/"/g, '\\"') : jsonMap;
2636
+ result = result.split(MANGLE_MAP_PLACEHOLDER).join(escapedMap);
2637
+ }
2638
+ if (result.includes(VAR_MANGLE_MAP_PLACEHOLDER)) {
2639
+ const jsonMap = JSON.stringify(state.varMangleMap);
2640
+ const escapedMap = result.includes("eval(") ? jsonMap.replace(/"/g, '\\"') : jsonMap;
2641
+ result = result.split(VAR_MANGLE_MAP_PLACEHOLDER).join(escapedMap);
2642
+ }
2643
+ return result;
2644
+ }
2645
+ const prePlugin = unplugin$1.createUnplugin(
2646
+ (_pluginOptions) => ({
2647
+ name: "csszyx:pre",
2648
+ enforce: "pre",
2649
+ /**
2650
+ * Resolves virtual module IDs for csszyx mangle-map and checksum modules.
2651
+ * @param id - the module ID to resolve
2652
+ * @returns resolved ID if virtual, null otherwise
2653
+ */
2654
+ resolveId(id) {
2655
+ if (isVirtualModule(id)) {
2656
+ return resolveVirtualModule(id);
2657
+ }
2658
+ return null;
2659
+ },
2660
+ /**
2661
+ * Loads virtual module content — generates mangle map or checksum module code.
2662
+ * @param id - the resolved module ID to load
2663
+ * @returns generated module source if virtual, null otherwise
2664
+ */
2665
+ load(id) {
2666
+ if (id === RESOLVED_VIRTUAL_MODULE_ID) {
2667
+ finalizeMangleMap();
2668
+ return createMangleMapModule(
2669
+ state.mangleMap,
2670
+ state.checksum,
2671
+ state.varMangleMap,
2672
+ state.cssVarMetrics
2673
+ );
2674
+ }
2675
+ if (id === RESOLVED_VIRTUAL_CHECKSUM_ID) {
2676
+ finalizeMangleMap();
2677
+ return createChecksumModule(state.checksum);
2678
+ }
2679
+ return null;
2680
+ },
2681
+ /**
2682
+ * Filters files for the pre-transform phase — source files plus CSS files.
2683
+ * CSS files need special handling to inject @source inline() for Tailwind class discovery.
2684
+ * @param id - the file path to check for inclusion
2685
+ * @returns true if the file should be transformed, false otherwise
2686
+ */
2687
+ transformInclude(id) {
2688
+ if (shouldProcessCss(id)) {
2689
+ return true;
2690
+ }
2691
+ return shouldProcessSource(id);
2692
+ },
2693
+ /**
2694
+ * Core transform: detects sz prop, compiles to className, injects runtime, collects classes.
2695
+ * For CSS files: injects @source inline() so Tailwind generates CSS for sz-derived classes.
2696
+ * @param code - the source code to transform
2697
+ * @param id - the file path of the module being transformed
2698
+ * @returns transformed code with source map, or null if no changes were made
2699
+ */
2700
+ transform(code, id) {
2701
+ if (!shouldProcessCss(id) && !shouldProcessSource(id)) {
2702
+ return null;
2703
+ }
2704
+ if (shouldProcessSource(id)) {
2705
+ recordGlobalVarSourceFile(state, id, code);
2706
+ }
2707
+ if (/\.[tj]sx?(\?.*)?$/.test(id)) {
2708
+ assertNoRSCBoundaryViolation(code, id);
2709
+ }
2710
+ if (/\.css(\?.*)?$/.test(id)) {
2711
+ const hasTailwindImport = code.includes('@import "tailwindcss') || code.includes("@import 'tailwindcss");
2712
+ if (hasTailwindImport && state.classes.size > 0) {
2713
+ const candidates = Array.from(state.classes).filter((c) => c.length >= 2 && /^[a-z]/.test(c)).join(" ");
2714
+ if (candidates) {
2715
+ const safelistPath = path__namespace.join(state.rootDir, SAFELIST_FILENAME).replace(/\\/g, "/");
2716
+ const cssDir = path__namespace.dirname(id).replace(/\\/g, "/");
2717
+ let relPath = path__namespace.posix.relative(cssDir, safelistPath);
2718
+ if (!relPath.startsWith(".")) {
2719
+ relPath = `./${relPath}`;
2720
+ }
2721
+ const sourceDirective = `@source "${relPath}";
2722
+ `;
2723
+ const transformed2 = code.replace(
2724
+ /(@import\s+["']tailwindcss[^"']*["'];)/,
2725
+ `$1
2726
+ ${sourceDirective}`
2727
+ );
2728
+ if (transformed2 !== code) {
2729
+ return { code: transformed2, map: null };
2730
+ }
2731
+ }
2732
+ }
2733
+ return null;
2734
+ }
2735
+ let transformedCode = code;
2736
+ let usesRuntime = false;
2737
+ let usesMerge = false;
2738
+ let usesColorVar = false;
2739
+ let transformed = false;
2740
+ let szClasses;
2741
+ const hasSzProp = code.includes("sz=") || /\bsz\s*:\s*["'{]/.test(code) || code.includes('sz: "');
2742
+ if (hasSzProp) {
2743
+ if (id.endsWith(".vue")) {
2744
+ const result = vueAdapter.preprocess(code, options);
2745
+ if (result.transformed) {
2746
+ transformedCode = result.code;
2747
+ transformed = true;
2748
+ }
2749
+ } else if (id.endsWith(".svelte")) {
2750
+ const result = svelteAdapter.preprocess(code, options);
2751
+ if (result) {
2752
+ transformedCode = result.code;
2753
+ transformed = true;
2754
+ }
2755
+ } else {
2756
+ const transformStarted = node_perf_hooks.performance.now();
2757
+ const result = transformConfiguredSource(code, id);
2758
+ traceBenchTiming(
2759
+ "transform-hook",
2760
+ id,
2761
+ node_perf_hooks.performance.now() - transformStarted
2762
+ );
2763
+ transformedCode = result.code;
2764
+ usesRuntime = result.usesRuntime;
2765
+ usesMerge = result.usesMerge;
2766
+ usesColorVar = result.usesColorVar;
2767
+ transformed = result.transformed;
2768
+ szClasses = result.classes;
2769
+ recordFileVarMangleEntries(state, id, cssVariableEntries(result));
2770
+ recordFileCSSVariableMetrics(state, id, result.code);
2771
+ if (result.diagnostics.length > 0 && process.env.NODE_ENV !== "production") {
2772
+ for (const msg of result.diagnostics) {
2773
+ this.warn(`[csszyx] ${id}
2774
+ ${msg}`);
2775
+ }
2776
+ }
2777
+ for (const [token, data] of result.recoveryTokens) {
2778
+ state.recoveryTokens.set(token, data);
2779
+ }
2780
+ }
2781
+ } else if (shouldProcessSource(id)) {
2782
+ recordFileVarMangleEntries(state, id, []);
2783
+ recordFileCSSVariableMetrics(state, id, null);
2784
+ }
2785
+ if (transformedCode.includes("<html") && /(?:layout|Root|Document|app)\.tsx?$/i.test(id)) {
2786
+ const attrName = options.production?.minify ? "data-sz-cs" : "data-sz-checksum";
2787
+ transformedCode = transformedCode.replace(
2788
+ /<html([^>]*)>/i,
2789
+ `<html$1 ${attrName}="${CHECKSUM_PLACEHOLDER}">`
2790
+ );
2791
+ const debugScript = `<script dangerouslySetInnerHTML={{__html: \`(function(){var m=${MANGLE_MAP_PLACEHOLDER};var vm=${VAR_MANGLE_MAP_PLACEHOLDER};var gp=decodeURIComponent(${JSON.stringify(encodedGlobalVarAliasPrefix)});var r={};var vr={};for(var k in m)r[m[k]]=k;for(var vk in vm){var vv=vm[vk];var vs=Array.isArray(vv)?vv:[vv];for(var vi=0;vi<vs.length;vi++)(vr[vs[vi]]||(vr[vs[vi]]=[])).push(vk)}window.__csszyx={mangleMap:m,varMangleMap:vm,checksum:"${CHECKSUM_PLACEHOLDER}",decode:function(c){return r[c]},encode:function(c){return m[c]},decodeVar:function(v){return vr[v]||[]},encodeVar:function(v){return vm[v]},decodeGlobalVar:function(v){var a=vr[v]||[];return v.indexOf(gp)===0?a[0]:void 0},decodeAll:function(el){return(el.className||"").split(" ").map(function(c){return r[c]||c})}}})()\`}} />`;
2792
+ if (transformedCode.includes("<body")) {
2793
+ transformedCode = transformedCode.replace(
2794
+ /(<body[^>]*>)/i,
2795
+ `$1${debugScript}`
2796
+ );
2797
+ }
2798
+ transformed = true;
2799
+ }
2800
+ {
2801
+ const imports = [];
2802
+ if (usesRuntime) {
2803
+ imports.push("_sz");
2804
+ }
2805
+ if (usesMerge) {
2806
+ imports.push("_szMerge");
2807
+ }
2808
+ if (usesColorVar) {
2809
+ imports.push("__szColorVar");
2810
+ }
2811
+ const hasRuntimeImport = imports.length > 0 && transformedCode.includes("@csszyx/runtime");
2812
+ const needed = hasRuntimeImport ? imports.filter(
2813
+ (name) => !RUNTIME_HELPER_IMPORT_RE[name]?.test(transformedCode)
2814
+ ) : imports;
2815
+ if (needed.length > 0) {
2816
+ const existingImport = transformedCode.match(
2817
+ /^(import\s*\{[^}]*)\}\s*from\s*'@csszyx\/runtime'/m
2818
+ );
2819
+ if (existingImport) {
2820
+ transformedCode = transformedCode.replace(
2821
+ existingImport[0],
2822
+ `${existingImport[1]}, ${needed.join(", ")} } from '@csszyx/runtime'`
2823
+ );
2824
+ } else {
2825
+ const importStmt = `import { ${needed.join(", ")} } from '@csszyx/runtime';
2826
+ `;
2827
+ transformedCode = insertRuntimeImport(transformedCode, importStmt);
2828
+ }
2829
+ transformed = true;
2830
+ }
2831
+ }
2832
+ if (/\.[tj]sx?(\?.*)?$/.test(id)) {
2833
+ assertNoRSCBoundaryViolation(transformedCode, id);
2834
+ const record = createRSCModuleRecord(transformedCode, id);
2835
+ state.rscModules.set(record.id, record);
2836
+ }
2837
+ if (transformed || transformedCode.includes("class=") || transformedCode.includes("className=")) {
2838
+ if (szClasses !== void 0) {
2839
+ for (const cls of szClasses) {
2840
+ state.classes.add(cls);
2841
+ }
2842
+ } else {
2843
+ extractClasses(transformedCode);
2844
+ }
2845
+ return { code: transformedCode, map: null };
2846
+ }
2847
+ return null;
2848
+ },
2849
+ /** Finalizes the mangle map after all source modules have been processed. */
2850
+ buildEnd() {
2851
+ finalizeMangleMap();
2852
+ assertNoRSCGraphViolation(state.rscModules);
2853
+ if (manglingEnabled && Object.keys(state.mangleMap).length > 0) {
2854
+ globalThis.__csszyx_ssr_mangle_map = state.mangleMap;
2855
+ }
2856
+ },
2857
+ watchChange(id, change) {
2858
+ if (change.event === "delete") {
2859
+ deleteRSCModuleRecord(state.rscModules, id);
2860
+ recordGlobalVarSourceFile(state, id, null);
2861
+ recordFileVarMangleEntries(state, id, []);
2862
+ recordFileCSSVariableMetrics(state, id, null);
2863
+ }
2864
+ },
2865
+ /**
2866
+ * Webpack hook: pre-scans source files before compilation for Tailwind class discovery.
2867
+ * @param compiler - the Webpack compiler instance
2868
+ */
2869
+ webpack(compiler) {
2870
+ compiler.hooks.beforeCompile.tap("csszyx:prescan", () => {
2871
+ const root = compiler.context || process.cwd();
2872
+ state.rootDir = root;
2873
+ evictTransformCacheOnce();
2874
+ if (state.classes.size === 0) {
2875
+ prescanAndWriteClasses();
2876
+ }
2877
+ runThemeScan(root, options.build?.scanCss);
2878
+ });
2879
+ if (options.build?.scanCss) {
2880
+ compiler.hooks.thisCompilation.tap("csszyx:theme-deps", (compilation) => {
2881
+ const root = compiler.context || process.cwd();
2882
+ for (const file of expandFilePatterns(root, options.build?.scanCss ?? [])) {
2883
+ compilation.fileDependencies.add(file);
2884
+ }
2885
+ });
2886
+ }
2887
+ },
2888
+ vite: {
2889
+ /**
2890
+ * Vite hook: pre-scans source files when config is resolved.
2891
+ * Also runs theme scan to generate .csszyx/theme.d.ts if scanCss is configured.
2892
+ * @param config - the resolved Vite configuration object
2893
+ */
2894
+ configResolved(config) {
2895
+ const root = config.root || process.cwd();
2896
+ state.rootDir = root;
2897
+ evictTransformCacheOnce();
2898
+ prescanAndWriteClasses();
2899
+ runThemeScan(root, options.build?.scanCss);
2900
+ },
2901
+ /**
2902
+ * Vite HMR hook: re-runs theme scan when a watched CSS file changes,
2903
+ * and incrementally updates csszyx-classes.html when a source file gains new sz classes.
2904
+ * @param ctx - HMR context containing the changed file
2905
+ */
2906
+ handleHotUpdate(ctx) {
2907
+ const scanCss = options.build?.scanCss;
2908
+ if (scanCss) {
2909
+ const root = ctx.server.config.root || process.cwd();
2910
+ if (matchesAnyPattern(ctx.file, scanCss, root)) {
2911
+ runThemeScan(root, scanCss);
2912
+ }
2913
+ }
2914
+ if (!shouldProcessSource(ctx.file)) {
2915
+ return;
2916
+ }
2917
+ let fileContent, result;
2918
+ try {
2919
+ fileContent = fs__namespace.readFileSync(ctx.file, "utf-8");
2920
+ } catch {
2921
+ return;
2922
+ }
2923
+ if (!fileContent.includes("sz=") && !/\bsz\s*:\s*["'{]/.test(fileContent)) {
2924
+ recordGlobalVarSourceFile(state, ctx.file, fileContent);
2925
+ recordFileVarMangleEntries(state, ctx.file, []);
2926
+ recordFileCSSVariableMetrics(state, ctx.file, null);
2927
+ return;
2928
+ }
2929
+ try {
2930
+ const hmrTransformStarted = node_perf_hooks.performance.now();
2931
+ result = transformConfiguredSource(fileContent, ctx.file);
2932
+ traceBenchTiming(
2933
+ "handle-hot-update",
2934
+ ctx.file,
2935
+ node_perf_hooks.performance.now() - hmrTransformStarted
2936
+ );
2937
+ } catch {
2938
+ recordGlobalVarSourceFile(state, ctx.file, fileContent);
2939
+ recordFileVarMangleEntries(state, ctx.file, []);
2940
+ recordFileCSSVariableMetrics(state, ctx.file, null);
2941
+ return;
2942
+ }
2943
+ if (!result.transformed) {
2944
+ recordGlobalVarSourceFile(state, ctx.file, fileContent);
2945
+ recordFileVarMangleEntries(state, ctx.file, []);
2946
+ recordFileCSSVariableMetrics(state, ctx.file, null);
2947
+ return;
2948
+ }
2949
+ const sizeBefore = state.classes.size;
2950
+ recordGlobalVarSourceFile(state, ctx.file, fileContent);
2951
+ for (const cls of result.classes) {
2952
+ state.classes.add(cls);
2953
+ }
2954
+ recordFileVarMangleEntries(state, ctx.file, cssVariableEntries(result));
2955
+ recordFileCSSVariableMetrics(state, ctx.file, result.code);
2956
+ for (const [token, data] of result.recoveryTokens) {
2957
+ state.recoveryTokens.set(token, data);
2958
+ }
2959
+ if (state.classes.size > sizeBefore) {
2960
+ writeSafelistFile(state.classes);
2961
+ const safelistPath = path__namespace.join(state.rootDir, SAFELIST_FILENAME);
2962
+ ctx.server.watcher.emit("change", safelistPath);
2963
+ }
2964
+ },
2965
+ transformIndexHtml: {
2966
+ order: "pre",
2967
+ /**
2968
+ * Injects hydration data (mangle map + checksum) into the HTML document.
2969
+ * Also mangles class attributes in SSR-rendered HTML so they match mangled CSS selectors.
2970
+ * @param html - the raw HTML string to transform
2971
+ * @returns transformed HTML with injected hydration data
2972
+ */
2973
+ handler(html) {
2974
+ finalizeMangleMap();
2975
+ let result = transformIndexHtml(html, state.mangleMap, state.checksum, {
2976
+ mode: options.production?.injectChecksum === false ? "script" : "script",
2977
+ minify: process.env.NODE_ENV === "production",
2978
+ varMangleMap: state.varMangleMap,
2979
+ globalVarAliasPrefix
2980
+ });
2981
+ if (state.recoveryTokens.size > 0) {
2982
+ const isProduction = process.env.NODE_ENV === "production";
2983
+ const { manifest, strippedDevOnlyPaths } = buildRecoveryManifest(
2984
+ state.recoveryTokens,
2985
+ {
2986
+ production: isProduction,
2987
+ mangleChecksum: state.checksum
2988
+ }
2989
+ );
2990
+ if (strippedDevOnlyPaths.length > 0) {
2991
+ console.warn(
2992
+ `[csszyx] Stripped ${strippedDevOnlyPaths.length} szRecover="dev-only" token(s) from the production manifest. Recovery for these elements is disabled in production by design. Sites: ${strippedDevOnlyPaths.join(", ")}`
2993
+ );
2994
+ }
2995
+ result = injectRecoveryManifest(result, manifest);
2996
+ }
2997
+ return result;
2998
+ }
2999
+ }
3000
+ }
3001
+ })
3002
+ );
3003
+ const postPlugin = unplugin$1.createUnplugin(() => ({
3004
+ name: "csszyx:post",
3005
+ enforce: "post",
3006
+ // No transform hook — all mangling is deferred to asset processing
3007
+ // where the complete mangle map is available.
3008
+ /**
3009
+ * Webpack hook: mangles CSS/JS class names in processAssets after compilation.
3010
+ * @param compiler - the Webpack compiler instance
3011
+ */
3012
+ webpack(compiler) {
3013
+ compiler.hooks.compilation.tap("csszyx:post", (compilation) => {
3014
+ const stage = compiler.webpack?.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE || compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE;
3015
+ compilation.hooks.processAssets.tap(
3016
+ {
3017
+ name: "csszyx:post",
3018
+ stage: stage || 400
3019
+ // Fallback integer
3020
+ },
3021
+ (assets) => {
3022
+ finalizeMangleMap();
3023
+ state.globalVarValidationResult = validateGlobalVarBundleInputs(
3024
+ collectWebpackGlobalVarCssAssets(assets)
3025
+ );
3026
+ const isWebpackDevMode = compiler.options.mode === "development";
3027
+ const manifestData = {
3028
+ version: "0.4.0",
3029
+ buildId: state.checksum,
3030
+ classes: Object.keys(state.mangleMap)
3031
+ };
3032
+ if (manglingEnabled && !isWebpackDevMode && Object.keys(state.mangleMap).length > 0) {
3033
+ manifestData.mangleMap = state.mangleMap;
3034
+ }
3035
+ if (Object.keys(state.varMangleMap).length > 0) {
3036
+ manifestData.varMangleMap = state.varMangleMap;
3037
+ }
3038
+ const globalVarAliases = extractGlobalVarAliasesForManifest(
3039
+ state.varMangleMap,
3040
+ globalVarAliasPrefix,
3041
+ state.globalVarValidationResult
3042
+ );
3043
+ if (Object.keys(globalVarAliases).length > 0) {
3044
+ manifestData.globalVarAliases = globalVarAliases;
3045
+ }
3046
+ if (hasCSSVariableMetrics(state.cssVarMetrics)) {
3047
+ manifestData.cssVarMetrics = state.cssVarMetrics;
3048
+ }
3049
+ compilation.emitAsset(
3050
+ "csszyx-manifest.json",
3051
+ new compiler.webpack.sources.RawSource(JSON.stringify(manifestData))
3052
+ );
3053
+ if (shouldEmitGlobalVarMapAsset(globalVarMangleConfig)) {
3054
+ const globalVarMapAsset = createGlobalVarMapAssetSource(
3055
+ state.varMangleMap,
3056
+ globalVarAliasPrefix,
3057
+ state.globalVarValidationResult
3058
+ );
3059
+ if (globalVarMapAsset) {
3060
+ compilation.emitAsset(
3061
+ ".csszyx/global-var-map.json",
3062
+ new compiler.webpack.sources.RawSource(globalVarMapAsset)
3063
+ );
3064
+ }
3065
+ }
3066
+ for (const file in assets) {
3067
+ const asset = assets[file];
3068
+ const source = asset.source().toString();
3069
+ if (file.endsWith(".css")) {
3070
+ let css = rewriteCssWithValidatedGlobalVarPlan(
3071
+ source,
3072
+ file,
3073
+ state.globalVarValidationResult
3074
+ );
3075
+ if (manglingEnabled && !isWebpackDevMode && Object.keys(state.mangleMap).length > 0) {
3076
+ try {
3077
+ const result = cssMangler.mangleCSSSync(css, state.mangleMap, {
3078
+ debug: options.development?.debug,
3079
+ from: file
3080
+ });
3081
+ if (result.transformedCount > 0) {
3082
+ css = result.css;
3083
+ }
3084
+ } catch (e) {
3085
+ if (e && typeof e === "object" && "name" in e && e.name === "CssSyntaxError") ; else {
3086
+ throw e;
3087
+ }
3088
+ }
3089
+ }
3090
+ if (css !== source) {
3091
+ compilation.updateAsset(
3092
+ file,
3093
+ new compiler.webpack.sources.RawSource(css)
3094
+ );
3095
+ }
3096
+ continue;
3097
+ }
3098
+ if (manglingEnabled && !isWebpackDevMode && Object.keys(state.mangleMap).length > 0) {
3099
+ if (file.endsWith(".html")) {
3100
+ const mangledHtml = source.replace(
3101
+ /\bclass="([^"]*)"/g,
3102
+ (_m, cls) => {
3103
+ const out = cls.split(/\s+/).filter(Boolean).map((c) => state.mangleMap[c] || c).join(" ");
3104
+ return out !== cls ? `class="${out}"` : _m;
3105
+ }
3106
+ ).replace(
3107
+ /\bclass='([^']*)'/g,
3108
+ (_m, cls) => {
3109
+ const out = cls.split(/\s+/).filter(Boolean).map((c) => state.mangleMap[c] || c).join(" ");
3110
+ return out !== cls ? `class='${out}'` : _m;
3111
+ }
3112
+ );
3113
+ if (mangledHtml !== source) {
3114
+ compilation.updateAsset(
3115
+ file,
3116
+ new compiler.webpack.sources.RawSource(mangledHtml)
3117
+ );
3118
+ continue;
3119
+ }
3120
+ } else if (file.endsWith(".js")) {
3121
+ let mangled = mangleCodeClasses(source);
3122
+ mangled = replacePlaceholders(mangled);
3123
+ if (mangled !== source) {
3124
+ compilation.updateAsset(
3125
+ file,
3126
+ new compiler.webpack.sources.RawSource(mangled)
3127
+ );
3128
+ continue;
3129
+ }
3130
+ }
3131
+ }
3132
+ if (file.endsWith(".js") && (source.includes(CHECKSUM_PLACEHOLDER) || source.includes(MANGLE_MAP_PLACEHOLDER))) {
3133
+ const replaced = replacePlaceholders(source);
3134
+ if (replaced !== source) {
3135
+ compilation.updateAsset(
3136
+ file,
3137
+ new compiler.webpack.sources.RawSource(replaced)
3138
+ );
3139
+ }
3140
+ }
3141
+ }
3142
+ }
3143
+ );
3144
+ });
3145
+ },
3146
+ vite: {
3147
+ /**
3148
+ * Vite hook: mangles CSS selectors and JS class strings in the final bundle.
3149
+ * @param _options - the output options (unused)
3150
+ * @param bundle - the output bundle containing chunks and assets to process
3151
+ */
3152
+ generateBundle(_options, bundle) {
3153
+ finalizeMangleMap();
3154
+ state.globalVarValidationResult = validateGlobalVarBundleInputs(
3155
+ collectRollupGlobalVarCssAssets(bundle)
3156
+ );
3157
+ const manifestData = {
3158
+ version: "0.4.0",
3159
+ buildId: state.checksum,
3160
+ classes: Object.keys(state.mangleMap)
3161
+ };
3162
+ if (manglingEnabled && Object.keys(state.mangleMap).length > 0) {
3163
+ manifestData.mangleMap = state.mangleMap;
3164
+ }
3165
+ if (Object.keys(state.varMangleMap).length > 0) {
3166
+ manifestData.varMangleMap = state.varMangleMap;
3167
+ }
3168
+ const globalVarAliases = extractGlobalVarAliasesForManifest(
3169
+ state.varMangleMap,
3170
+ globalVarAliasPrefix,
3171
+ state.globalVarValidationResult
3172
+ );
3173
+ if (Object.keys(globalVarAliases).length > 0) {
3174
+ manifestData.globalVarAliases = globalVarAliases;
3175
+ }
3176
+ if (hasCSSVariableMetrics(state.cssVarMetrics)) {
3177
+ manifestData.cssVarMetrics = state.cssVarMetrics;
3178
+ }
3179
+ this.emitFile({
3180
+ type: "asset",
3181
+ fileName: "csszyx-manifest.json",
3182
+ source: JSON.stringify(manifestData)
3183
+ });
3184
+ if (shouldEmitGlobalVarMapAsset(globalVarMangleConfig)) {
3185
+ const globalVarMapAsset = createGlobalVarMapAssetSource(
3186
+ state.varMangleMap,
3187
+ globalVarAliasPrefix,
3188
+ state.globalVarValidationResult
3189
+ );
3190
+ if (globalVarMapAsset) {
3191
+ this.emitFile({
3192
+ type: "asset",
3193
+ fileName: ".csszyx/global-var-map.json",
3194
+ source: globalVarMapAsset
3195
+ });
3196
+ }
3197
+ }
3198
+ for (const file in bundle) {
3199
+ const chunk = bundle[file];
3200
+ if (chunk.type === "asset" && chunk.fileName.endsWith(".css")) {
3201
+ const originalCss = chunk.source.toString();
3202
+ let css = rewriteCssWithValidatedGlobalVarPlan(
3203
+ originalCss,
3204
+ file,
3205
+ state.globalVarValidationResult
3206
+ );
3207
+ if (manglingEnabled && Object.keys(state.mangleMap).length > 0) {
3208
+ try {
3209
+ const result = cssMangler.mangleCSSSync(css, state.mangleMap, {
3210
+ debug: options.development?.debug,
3211
+ from: file
3212
+ });
3213
+ if (result.transformedCount > 0) {
3214
+ css = result.css;
3215
+ }
3216
+ } catch (e) {
3217
+ if (e && typeof e === "object" && "name" in e && e.name === "CssSyntaxError") ; else {
3218
+ throw e;
3219
+ }
3220
+ }
3221
+ }
3222
+ if (css !== originalCss) {
3223
+ chunk.source = css;
3224
+ }
3225
+ continue;
3226
+ }
3227
+ if (manglingEnabled && Object.keys(state.mangleMap).length > 0) {
3228
+ if (chunk.type === "chunk") {
3229
+ let mangledCode = mangleCodeClasses(chunk.code);
3230
+ mangledCode = replacePlaceholders(mangledCode);
3231
+ if (mangledCode !== chunk.code) {
3232
+ chunk.code = mangledCode;
3233
+ }
3234
+ continue;
3235
+ }
3236
+ }
3237
+ if (chunk.type === "chunk" && (chunk.code.includes(CHECKSUM_PLACEHOLDER) || chunk.code.includes(MANGLE_MAP_PLACEHOLDER))) {
3238
+ const replaced = replacePlaceholders(chunk.code);
3239
+ if (replaced !== chunk.code) {
3240
+ chunk.code = replaced;
3241
+ }
3242
+ }
3243
+ }
3244
+ }
3245
+ }
3246
+ }));
3247
+ return { prePlugin, postPlugin };
3248
+ }
3249
+ const defaultInstance = createCsszyxPlugins();
3250
+ const unplugin = defaultInstance.prePlugin;
3251
+ const vitePlugin = (options = {}) => {
3252
+ const { prePlugin, postPlugin } = createCsszyxPlugins(options);
3253
+ return [prePlugin.vite(options), postPlugin.vite(options)];
3254
+ };
3255
+ const webpackPlugin = (options = {}) => {
3256
+ const { prePlugin, postPlugin } = createCsszyxPlugins(options);
3257
+ return {
3258
+ /**
3259
+ * Applies both pre and post plugins to the Webpack compiler.
3260
+ * @param compiler - the Webpack compiler instance to apply plugins to
3261
+ */
3262
+ apply(compiler) {
3263
+ prePlugin.webpack(options).apply(compiler);
3264
+ postPlugin.webpack(options).apply(compiler);
3265
+ }
3266
+ };
3267
+ };
3268
+ const rollupPlugin = (options = {}) => {
3269
+ const { prePlugin, postPlugin } = createCsszyxPlugins(options);
3270
+ return [
3271
+ prePlugin.rollup(options),
3272
+ postPlugin.rollup(options)
3273
+ ];
3274
+ };
3275
+ const esbuildPlugin = (options = {}) => {
3276
+ const { prePlugin, postPlugin } = createCsszyxPlugins(options);
3277
+ return {
3278
+ name: "csszyx",
3279
+ /**
3280
+ * Registers both pre and post plugin setup hooks with the esbuild build.
3281
+ * @param build - the esbuild plugin build context
3282
+ */
3283
+ setup(build) {
3284
+ const b = build;
3285
+ prePlugin.esbuild(options).setup(b);
3286
+ postPlugin.esbuild(options).setup(b);
3287
+ }
3288
+ };
3289
+ };
3290
+
3291
+ exports.assertNoRSCBoundaryViolation = assertNoRSCBoundaryViolation;
3292
+ exports.assertNoRSCGraphViolation = assertNoRSCGraphViolation;
3293
+ exports.createGlobalVarAliasValidationOptions = createGlobalVarAliasValidationOptions;
3294
+ exports.createGlobalVarMapAssetSource = createGlobalVarMapAssetSource;
3295
+ exports.createGlobalVarScanCacheKey = createGlobalVarScanCacheKey;
3296
+ exports.createRSCModuleRecord = createRSCModuleRecord;
3297
+ exports.deleteRSCModuleRecord = deleteRSCModuleRecord;
3298
+ exports.esbuildPlugin = esbuildPlugin;
3299
+ exports.extractGlobalVarAliasesForManifest = extractGlobalVarAliasesForManifest;
3300
+ exports.findRSCBoundaryViolation = findRSCBoundaryViolation;
3301
+ exports.findRSCGraphViolation = findRSCGraphViolation;
3302
+ exports.hasTokens = hasTokens;
3303
+ exports.hasUseClientDirective = hasUseClientDirective;
3304
+ exports.hasUseServerDirective = hasUseServerDirective;
3305
+ exports.isRSCServerModule = isRSCServerModule;
3306
+ exports.isTailwindReservedGlobalVar = isTailwindReservedGlobalVar;
3307
+ exports.mangleCodeClassesSync = mangleCodeClassesSync;
3308
+ exports.mergeThemes = mergeThemes;
3309
+ exports.normalizeGlobalVarAliasesForCache = normalizeGlobalVarAliasesForCache;
3310
+ exports.parseThemeBlocks = parseThemeBlocks;
3311
+ exports.planGlobalVarAliases = planGlobalVarAliases;
3312
+ exports.readGlobalVarScanCache = readGlobalVarScanCache;
3313
+ exports.resolveGlobalVarScanCacheDir = resolveGlobalVarScanCacheDir;
3314
+ exports.rewriteGlobalVarCssAliases = rewriteGlobalVarCssAliases;
3315
+ exports.rollupPlugin = rollupPlugin;
3316
+ exports.scanGlobalVarCss = scanGlobalVarCss;
3317
+ exports.unplugin = unplugin;
3318
+ exports.validateGlobalVarAliasInputs = validateGlobalVarAliasInputs;
3319
+ exports.vitePlugin = vitePlugin;
3320
+ exports.webpackPlugin = webpackPlugin;
3321
+ exports.writeGlobalVarScanCache = writeGlobalVarScanCache;