@csszyx/unplugin 0.11.11 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,10 +13,11 @@ const svelteAdapter = require('@csszyx/svelte-adapter');
13
13
  const types = require('@csszyx/types');
14
14
  const vueAdapter = require('@csszyx/vue-adapter');
15
15
  const unplugin$1 = require('unplugin');
16
- const transformCache = require('./unplugin.CKIOVNOg.cjs');
16
+ const transformCache = require('./unplugin.DbZ7tCfN.cjs');
17
17
  const cssMangler = require('../css-mangler.cjs');
18
- const runtimeImportScan = require('./unplugin.Cnxm1DcC.cjs');
18
+ const nextRuntimeInjection = require('./unplugin.C2lHQFii.cjs');
19
19
  const htmlEscape = require('./unplugin.BkRah5Ot.cjs');
20
+ const node_zlib = require('node:zlib');
20
21
  const postcss = require('postcss');
21
22
  const valueParser = require('postcss-value-parser');
22
23
 
@@ -1883,17 +1884,19 @@ function injectMangleMapScript(html, mangleMap, options = {}) {
1883
1884
  const {
1884
1885
  prettyPrint = false,
1885
1886
  varMangleMap = {},
1886
- globalVarAliasPrefix = types.CSSZYX_GLOBAL_ALIAS_PREFIX
1887
+ globalVarAliasPrefix = types.CSSZYX_GLOBAL_ALIAS_PREFIX,
1888
+ installRuntimeObject = true
1887
1889
  } = options;
1888
1890
  const checksumMap = createHydrationMangleMap(mangleMap, varMangleMap);
1889
1891
  const jsonContent = safeJsonForScriptTag(checksumMap, prettyPrint);
1890
- const classMapContent = safeJsonForScriptTag(mangleMap);
1891
1892
  const varMapContent = safeJsonForScriptTag(varMangleMap);
1893
+ const reuseChecksumPayload = Object.keys(varMangleMap).length === 0;
1894
+ const classMapExpr = reuseChecksumPayload ? '(function(){var e=document.getElementById("__CSSZYX_MANGLE_MAP__");return e?JSON.parse(e.textContent):{}})()' : safeJsonForScriptTag(mangleMap);
1892
1895
  const scriptTag = `<script id="__CSSZYX_MANGLE_MAP__" type="application/json">${jsonContent}<\/script>`;
1893
1896
  const prefixContent = safeJsonForScriptTag(globalVarAliasPrefix);
1894
- 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>`;
1895
- const combined = `${scriptTag}
1896
- ${debugScript}`;
1897
+ const debugScript = `<script>(function(){var m=${classMapExpr};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>`;
1898
+ const combined = installRuntimeObject ? `${scriptTag}
1899
+ ${debugScript}` : scriptTag;
1897
1900
  if (html.includes("</head>")) {
1898
1901
  return html.replace("</head>", `${combined}
1899
1902
  </head>`);
@@ -1998,6 +2001,42 @@ function escapeForDoubleQuotedString(value) {
1998
2001
  return htmlEscape.escapeDoubleQuotedString(value);
1999
2002
  }
2000
2003
 
2004
+ function createMangleSizeAccount() {
2005
+ return { cssGzBefore: 0, cssGzAfter: 0, channels: /* @__PURE__ */ new Set() };
2006
+ }
2007
+ function resetMangleSizeAccount(account) {
2008
+ account.cssGzBefore = 0;
2009
+ account.cssGzAfter = 0;
2010
+ account.channels.clear();
2011
+ }
2012
+ function gzipBytes(text) {
2013
+ if (text.length === 0) return 0;
2014
+ return node_zlib.gzipSync(Buffer.from(text, "utf8")).length;
2015
+ }
2016
+ function recordCssPair(account, before, after) {
2017
+ if (before === after) {
2018
+ const bytes = gzipBytes(before);
2019
+ account.cssGzBefore += bytes;
2020
+ account.cssGzAfter += bytes;
2021
+ return;
2022
+ }
2023
+ account.cssGzBefore += gzipBytes(before);
2024
+ account.cssGzAfter += gzipBytes(after);
2025
+ }
2026
+ function computeMangleSizeVerdict(account, mapPayload) {
2027
+ const channels = htmlEscape.sortStrings(account.channels);
2028
+ const mapCost = gzipBytes(mapPayload) * channels.length;
2029
+ const cssSaving = account.cssGzBefore - account.cssGzAfter;
2030
+ return { mapCost, cssSaving, net: mapCost - cssSaving, channels };
2031
+ }
2032
+ function mangleSizeMessage(verdict) {
2033
+ if (verdict.channels.length === 0) return null;
2034
+ if (verdict.net <= 0) return null;
2035
+ const cssPart = verdict.cssSaving >= 0 ? `the mangled CSS saves ${verdict.cssSaving} B` : `the mangled CSS COSTS ${-verdict.cssSaving} B (short tokens compress worse than the names they replaced)`;
2036
+ const channelPart = verdict.channels.length > 1 ? `${verdict.channels.join(" + ")} (${verdict.channels.length} copies)` : verdict.channels[0];
2037
+ return `[csszyx] production.mangle is making this build BIGGER: +${verdict.net} B gzipped. The runtime mangle map costs ${verdict.mapCost} B via ${channelPart}, while ${cssPart}. Mangling is a name-obfuscation feature; over a compressed response it does not reduce payload, because utility class names compress far better than the map they need. If you enabled it for size, set \`production.mangle: false\`. If you enabled it to hide class names, this is the expected price and you can ignore this. Narrowing \`production.mangleMapDelivery\` removes a map copy when only one channel is needed. (Measured on CSS and the map; class shortening inside JS chunks is not counted, so the real net is slightly better than this figure.)`;
2038
+ }
2039
+
2001
2040
  function isParserMode(value) {
2002
2041
  return value === "rust" || value === "oxc" || value === "babel";
2003
2042
  }
@@ -2042,6 +2081,41 @@ function isSameFileVersion(before, after) {
2042
2081
  return before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeNs === after.mtimeNs && before.ctimeNs === after.ctimeNs;
2043
2082
  }
2044
2083
 
2084
+ function recordSzvRegistryFile(registry, filePath, content) {
2085
+ const key = transformCache.normalizePathSeparators(filePath);
2086
+ const qualifies = content.includes("szv(") && content.includes("export");
2087
+ const entries = qualifies ? compiler.extractSzvRegistryEntries(content, filePath) : [];
2088
+ if (entries.length === 0) {
2089
+ registry.delete(key);
2090
+ return;
2091
+ }
2092
+ const byName = {};
2093
+ for (const entry of entries) {
2094
+ byName[entry.exportName] = entry.config;
2095
+ }
2096
+ registry.set(key, byName);
2097
+ }
2098
+ const SPECIFIER_PROBES = ["", ".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx"];
2099
+ function resolveCrossModuleStaticsFor(registry, filename, source) {
2100
+ if (registry.size === 0 || !source.includes("from")) return void 0;
2101
+ const directory = path__namespace.dirname(filename);
2102
+ let resolved;
2103
+ for (const match of source.matchAll(/from\s*['"](\.[^'"]*)['"]/g)) {
2104
+ const specifier = match[1];
2105
+ if (resolved?.[specifier] !== void 0) continue;
2106
+ const base = transformCache.normalizePathSeparators(path__namespace.resolve(directory, specifier));
2107
+ for (const probe of SPECIFIER_PROBES) {
2108
+ const entries = registry.get(`${base}${probe}`);
2109
+ if (entries !== void 0) {
2110
+ resolved ??= {};
2111
+ resolved[specifier] = entries;
2112
+ break;
2113
+ }
2114
+ }
2115
+ }
2116
+ return resolved;
2117
+ }
2118
+
2045
2119
  function generateThemeDts(opts) {
2046
2120
  const { theme, sourceFiles } = opts;
2047
2121
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -2276,9 +2350,9 @@ let _hasWarnedTransformCacheVersion = false;
2276
2350
  let _hasWarnedNativeFallback = false;
2277
2351
  const _loggedActiveParsers = /* @__PURE__ */ new Set();
2278
2352
  const _babelFallbackFiles = /* @__PURE__ */ new Set();
2279
- 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.CJcFsJcf.cjs', document.baseURI).href)));
2353
+ 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.BK3XVHe8.cjs', document.baseURI).href)));
2280
2354
  const PLUGIN_VERSION = findPackageVersionFromFile(
2281
- node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/unplugin.CJcFsJcf.cjs', document.baseURI).href))),
2355
+ node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/unplugin.BK3XVHe8.cjs', document.baseURI).href))),
2282
2356
  UNKNOWN_PACKAGE_VERSION
2283
2357
  );
2284
2358
  const COMPILER_VERSION = findPackageVersionFromModule("@csszyx/compiler", UNKNOWN_PACKAGE_VERSION);
@@ -2431,6 +2505,13 @@ function shouldEmitWarning(quiet, devOnly, isProduction) {
2431
2505
  }
2432
2506
  return true;
2433
2507
  }
2508
+ function shouldEmitMissingCssFallback(quiet, message) {
2509
+ return !quiet && compiler.szFallbackConsequenceOf(message) === "missing-css";
2510
+ }
2511
+ function emitMissingCssFallback(quiet, message, id, emit) {
2512
+ if (shouldEmitMissingCssFallback(quiet, message)) emit(`[csszyx] ${id}
2513
+ ${message}`);
2514
+ }
2434
2515
  function normalizeForMatch(p) {
2435
2516
  const n = transformCache.normalizePathSeparators(p);
2436
2517
  return n.length > 1 && n.endsWith("/") ? n.slice(0, -1) : n;
@@ -2936,7 +3017,7 @@ function matchesScriptExtension(id, extensions) {
2936
3017
  return extensions.some((ext) => id.endsWith(ext) || id.includes(`${ext}?`));
2937
3018
  }
2938
3019
  function insertRuntimeImport(code, importStmt) {
2939
- return runtimeImportScan.insertAfterUseDirective(code, importStmt);
3020
+ return nextRuntimeInjection.insertAfterUseDirective(code, importStmt);
2940
3021
  }
2941
3022
  function scanClassExpression(source, from) {
2942
3023
  let depth = 0;
@@ -3192,8 +3273,19 @@ ${errors.join("\n")}`
3192
3273
  }
3193
3274
  function createCsszyxPlugins(options = {}) {
3194
3275
  assertGlobalVarMangleConfig(options);
3195
- let manglingEnabled = options.production?.mangle !== false;
3276
+ let manglingEnabled = options.production?.mangle === true;
3277
+ let crossModuleRegistryEnabled = process.env.NODE_ENV !== "development";
3278
+ const szvCrossModuleRegistry = /* @__PURE__ */ new Map();
3196
3279
  const mangleReserved = new Set(options.production?.mangleExclude ?? []);
3280
+ const mangleMapDelivery = options.production?.mangleMapDelivery ?? "both";
3281
+ if (!["both", "html", "bundle"].includes(mangleMapDelivery)) {
3282
+ throw new Error(
3283
+ `[csszyx] production.mangleMapDelivery must be 'both', 'html' or 'bundle'; got ${JSON.stringify(mangleMapDelivery)}.`
3284
+ );
3285
+ }
3286
+ const deliverMapInHtml = mangleMapDelivery !== "bundle";
3287
+ const deliverMapInBundle = mangleMapDelivery !== "html";
3288
+ const sizeAccount = createMangleSizeAccount();
3197
3289
  const astBudgetOverride = options.build?.astBudgetLimit;
3198
3290
  const prescanAstBudget = astBudgetOverride ?? 5e5;
3199
3291
  const cacheRequested = (options.build?.cache ?? types.DEFAULT_BUILD_CONFIG.cache) !== false;
@@ -3419,6 +3511,14 @@ function createCsszyxPlugins(options = {}) {
3419
3511
  function transformConfiguredSource(source, filename, astBudget) {
3420
3512
  const compilerOptions = createCompilerOptions(astBudget);
3421
3513
  const effectiveFilename = normalizeSourceFilename(filename);
3514
+ const crossModuleStatics = resolveCrossModuleStaticsFor(
3515
+ szvCrossModuleRegistry,
3516
+ filename,
3517
+ source
3518
+ );
3519
+ if (crossModuleStatics !== void 0) {
3520
+ compilerOptions.crossModuleStatics = crossModuleStatics;
3521
+ }
3422
3522
  const cacheRoot = transformCache.resolveTransformCacheDir(state.rootDir, options.build?.cacheDir);
3423
3523
  if (cacheEnabled) {
3424
3524
  evictTransformCacheOnce();
@@ -3530,6 +3630,10 @@ function createCsszyxPlugins(options = {}) {
3530
3630
  mangleVars: compilerOptions.mangleVars,
3531
3631
  mangleVarHoistMaxDepth: compilerOptions.mangleVarHoistMaxDepth,
3532
3632
  globalVarAliases: normalizeGlobalVarAliasesForCache(compilerOptions.globalVarAliases),
3633
+ // The registry entries fed to this file are part of its identity:
3634
+ // module A's config change must miss B's cached transform, or the
3635
+ // cache serves a stale table.
3636
+ crossModuleStatics: compilerOptions.crossModuleStatics === void 0 ? void 0 : JSON.stringify(compilerOptions.crossModuleStatics),
3533
3637
  filename: effectiveFilename,
3534
3638
  source
3535
3639
  };
@@ -3741,6 +3845,7 @@ function createCsszyxPlugins(options = {}) {
3741
3845
  }
3742
3846
  function prescanAndWriteClasses() {
3743
3847
  refreshCompileSourceDirs();
3848
+ szvCrossModuleRegistry.clear();
3744
3849
  const prescanStarted = node_perf_hooks.performance.now();
3745
3850
  const discoveredClasses = /* @__PURE__ */ new Set();
3746
3851
  const rawDiscoveredClasses = /* @__PURE__ */ new Set();
@@ -3757,10 +3862,15 @@ function createCsszyxPlugins(options = {}) {
3757
3862
  return;
3758
3863
  }
3759
3864
  recordAuthoredClasses(content);
3865
+ recordSzvRegistryEntries(filePath, content);
3760
3866
  if (fileMayContainSafelistableSz(content)) {
3761
3867
  prescanSources.push({ filePath, content });
3762
3868
  }
3763
3869
  }
3870
+ function recordSzvRegistryEntries(filePath, content) {
3871
+ if (!crossModuleRegistryEnabled) return;
3872
+ recordSzvRegistryFile(szvCrossModuleRegistry, filePath, content);
3873
+ }
3764
3874
  function scanDir(dir) {
3765
3875
  let entries;
3766
3876
  try {
@@ -3981,6 +4091,9 @@ function createCsszyxPlugins(options = {}) {
3981
4091
  usesMerge: false,
3982
4092
  usesSzcn: false,
3983
4093
  usesSzPart: false,
4094
+ usesSzvPick: false,
4095
+ usesSzvPick1: false,
4096
+ szPartArgsProvable: true,
3984
4097
  usesColorVar: false,
3985
4098
  usesSpacingVar: false,
3986
4099
  usesUnitVar: false
@@ -4001,16 +4114,20 @@ function createCsszyxPlugins(options = {}) {
4001
4114
  if (message.includes("unresolvable sz spread")) {
4002
4115
  state.spreadWarnings.add(`${id}
4003
4116
  ${message}`);
4004
- } else if (message.includes("AST budget exceeded")) {
4117
+ continue;
4118
+ }
4119
+ if (message.includes("AST budget exceeded")) {
4005
4120
  console.warn(`[csszyx] ${id}
4006
4121
  ${message}`);
4122
+ continue;
4007
4123
  }
4124
+ emitMissingCssFallback(quiet, message, id, console.warn);
4008
4125
  }
4009
4126
  if (quiet || result.diagnostics.length === 0 || process.env.NODE_ENV === "production") {
4010
4127
  return;
4011
4128
  }
4012
4129
  for (const message of result.diagnostics) {
4013
- if (message.includes("unresolvable sz spread") || message.includes("AST budget exceeded")) {
4130
+ if (message.includes("unresolvable sz spread") || message.includes("AST budget exceeded") || compiler.szFallbackConsequenceOf(message) === "missing-css") {
4014
4131
  continue;
4015
4132
  }
4016
4133
  warn(`[csszyx] ${id}
@@ -4025,6 +4142,9 @@ function createCsszyxPlugins(options = {}) {
4025
4142
  usesMerge: result.usesMerge,
4026
4143
  usesSzcn: result.usesSzcn,
4027
4144
  usesSzPart: result.usesSzPart,
4145
+ usesSzvPick: result.usesSzvPick,
4146
+ usesSzvPick1: result.usesSzvPick1,
4147
+ szPartArgsProvable: result.szPartArgsProvable,
4028
4148
  usesColorVar: result.usesColorVar,
4029
4149
  usesSpacingVar: result.usesSpacingVar,
4030
4150
  usesUnitVar: result.usesUnitVar,
@@ -4067,31 +4187,34 @@ function createCsszyxPlugins(options = {}) {
4067
4187
  return transformedCode;
4068
4188
  }
4069
4189
  function requiredRuntimeHelpers(output) {
4070
- const helpers = [];
4071
- if (output.usesRuntime) helpers.push("_sz");
4072
- if (output.usesMerge) helpers.push("_szMerge");
4073
- if (output.usesSzcn) helpers.push("_szcn");
4074
- if (output.usesSzPart) helpers.push("_szPart");
4075
- if (output.usesColorVar) helpers.push("__szColorVar");
4076
- if (output.usesSpacingVar) helpers.push("__szSpacingVar");
4077
- if (output.usesUnitVar) helpers.push("__szUnitVar");
4078
- return helpers;
4190
+ return nextRuntimeInjection.runtimeHelperGroupsFromUsage(output);
4079
4191
  }
4080
4192
  function injectRuntimeHelpers(code, output) {
4081
- const imports = requiredRuntimeHelpers(output);
4082
- const hasRuntimeImport = imports.length > 0 && code.includes("@csszyx/runtime");
4083
- const needed = hasRuntimeImport ? imports.filter((name) => !runtimeImportScan.importsRuntimeHelper(code, name)) : imports;
4084
- if (needed.length === 0) return null;
4085
- const existingImport = runtimeImportScan.findRuntimeImportClause(code);
4193
+ const groups = requiredRuntimeHelpers(output);
4194
+ let result = null;
4195
+ let current = code;
4196
+ if (groups.merge.length > 0 && !current.includes("@csszyx/runtime/merge")) {
4197
+ current = insertRuntimeImport(
4198
+ current,
4199
+ `import { ${groups.merge.join(", ")} } from '@csszyx/runtime/merge';
4200
+ `
4201
+ );
4202
+ result = current;
4203
+ }
4204
+ const imports = groups.barrel;
4205
+ const hasRuntimeImport = imports.length > 0 && current.includes("@csszyx/runtime");
4206
+ const needed = hasRuntimeImport ? imports.filter((name) => !nextRuntimeInjection.importsRuntimeHelper(current, name)) : imports;
4207
+ if (needed.length === 0) return result;
4208
+ const existingImport = nextRuntimeInjection.findRuntimeImportClause(current);
4086
4209
  if (existingImport) {
4087
- return code.replace(
4210
+ return current.replace(
4088
4211
  existingImport.statement,
4089
4212
  `${existingImport.prefixWithBody}, ${needed.join(", ")} } from '@csszyx/runtime'`
4090
4213
  );
4091
4214
  }
4092
4215
  const importStatement = `import { ${needed.join(", ")} } from '@csszyx/runtime';
4093
4216
  `;
4094
- return insertRuntimeImport(code, importStatement);
4217
+ return insertRuntimeImport(current, importStatement);
4095
4218
  }
4096
4219
  function injectThemeGroups(code, transformedCode, id, usesSzcn) {
4097
4220
  if (!usesSzcn && !/\bszcn\s*\(/.test(code) || transformedCode.includes(THEME_GROUPS_VIRTUAL_ID) || !shouldProcessSource(id)) {
@@ -4106,7 +4229,7 @@ ${transformedCode}`;
4106
4229
  if (activeFramework !== "vite" && activeFramework !== "rollup") {
4107
4230
  return null;
4108
4231
  }
4109
- if (!manglingEnabled || !shouldProcessSource(id) || !MANGLE_RUNTIME_CONSUMER_RE.test(transformedCode) || transformedCode.includes(MANGLE_RUNTIME_VIRTUAL_ID)) {
4232
+ if (!manglingEnabled || !deliverMapInBundle || !shouldProcessSource(id) || !MANGLE_RUNTIME_CONSUMER_RE.test(transformedCode) || transformedCode.includes(MANGLE_RUNTIME_VIRTUAL_ID)) {
4110
4233
  return null;
4111
4234
  }
4112
4235
  return insertRuntimeImport(transformedCode, `import '${MANGLE_RUNTIME_VIRTUAL_ID}';
@@ -4176,6 +4299,7 @@ ${transformedCode}`;
4176
4299
  return createChecksumModule(state.checksum);
4177
4300
  }
4178
4301
  if (id === RESOLVED_MANGLE_RUNTIME_VIRTUAL_ID) {
4302
+ sizeAccount.channels.add("bundle");
4179
4303
  return createMangleRuntimeModule(globalVarAliasPrefix);
4180
4304
  }
4181
4305
  if (id === RESOLVED_THEME_GROUPS_VIRTUAL_ID) {
@@ -4223,7 +4347,12 @@ ${transformedCode}`;
4223
4347
  if (matchesScriptExtension(id, [".css"])) {
4224
4348
  return transformTailwindCssEntry(code, id);
4225
4349
  }
4226
- const hasSzProp = code.includes("sz=") || code.includes("szs=") || /\bsz\s*:\s*["'{]/.test(code) || code.includes('sz: "');
4350
+ const hasSzProp = code.includes("sz=") || code.includes("szs=") || /\bsz\s*:\s*["'{]/.test(code) || code.includes('sz: "') || // szr-only modules (no sz attribute) historically skipped the
4351
+ // compiler entirely — which also skipped the szr import
4352
+ // rewrite AND the szr fallback diagnostics. The substring is
4353
+ // deliberately loose; a false positive only costs one file
4354
+ // the compiler pass, which then changes nothing.
4355
+ code.includes("szr(");
4227
4356
  const output = hasSzProp ? transformSzSource(code, id, (message) => this.warn(message)) : unchangedPreTransform(code);
4228
4357
  if (!hasSzProp && shouldProcessSource(id)) {
4229
4358
  recordFileVarMangleEntries(state, id, []);
@@ -4316,6 +4445,14 @@ ${transformedCode}`;
4316
4445
  if (compiler.options?.mode === "development") {
4317
4446
  manglingEnabled = false;
4318
4447
  }
4448
+ if (compiler.watchMode === true || compiler.options?.watch === true) {
4449
+ crossModuleRegistryEnabled = false;
4450
+ }
4451
+ if (manglingEnabled && mangleMapDelivery !== "both") {
4452
+ console.warn(
4453
+ `[csszyx] production.mangleMapDelivery: '${mangleMapDelivery}' has no effect on the webpack lane \u2014 map delivery only narrows on vite/rollup builds.`
4454
+ );
4455
+ }
4319
4456
  compiler.hooks.beforeCompile.tap("csszyx:prescan", () => {
4320
4457
  announceActiveParser();
4321
4458
  const root = compiler.context || process.cwd();
@@ -4340,6 +4477,10 @@ ${transformedCode}`;
4340
4477
  /** Records the rollup lane for the mangle-runtime gate. */
4341
4478
  buildStart() {
4342
4479
  activeFramework = "rollup";
4480
+ const meta = this.meta;
4481
+ if (meta?.watchMode) {
4482
+ crossModuleRegistryEnabled = false;
4483
+ }
4343
4484
  }
4344
4485
  },
4345
4486
  vite: {
@@ -4355,6 +4496,10 @@ ${transformedCode}`;
4355
4496
  state.rootDir = root;
4356
4497
  if (config.command === "serve") {
4357
4498
  manglingEnabled = false;
4499
+ crossModuleRegistryEnabled = false;
4500
+ }
4501
+ if (config.build?.watch) {
4502
+ crossModuleRegistryEnabled = false;
4358
4503
  }
4359
4504
  evictTransformCacheOnce();
4360
4505
  prescanAndWriteClasses();
@@ -4456,8 +4601,12 @@ ${transformedCode}`;
4456
4601
  mode: "script",
4457
4602
  minify: process.env.NODE_ENV === "production",
4458
4603
  varMangleMap: state.varMangleMap,
4459
- globalVarAliasPrefix
4604
+ globalVarAliasPrefix,
4605
+ installRuntimeObject: deliverMapInHtml
4460
4606
  });
4607
+ if (manglingEnabled) {
4608
+ sizeAccount.channels.add("html");
4609
+ }
4461
4610
  if (state.recoveryTokens.size > 0) {
4462
4611
  const isProduction = process.env.NODE_ENV === "production";
4463
4612
  const { manifest, strippedDevOnlyPaths } = buildRecoveryManifest(
@@ -4506,7 +4655,7 @@ ${transformedCode}`;
4506
4655
  return manifest;
4507
4656
  }
4508
4657
  function rewriteOutputCss(source, file, shouldMangle, mangledSources, externalClasses) {
4509
- let css = rewriteCssWithValidatedGlobalVarPlan(
4658
+ const css = rewriteCssWithValidatedGlobalVarPlan(
4510
4659
  source,
4511
4660
  file,
4512
4661
  state.globalVarValidationResult
@@ -4519,8 +4668,9 @@ ${transformedCode}`;
4519
4668
  });
4520
4669
  for (const className of result.mangledClasses) mangledSources.add(className);
4521
4670
  for (const className of result.unmangledClasses) externalClasses.add(className);
4522
- if (result.transformedCount > 0) css = result.css;
4523
- return css;
4671
+ const mangled = result.transformedCount > 0 ? result.css : css;
4672
+ recordCssPair(sizeAccount, css, mangled);
4673
+ return mangled;
4524
4674
  } catch (error) {
4525
4675
  if (isCssSyntaxError(error)) return css;
4526
4676
  throw error;
@@ -4532,6 +4682,16 @@ ${transformedCode}`;
4532
4682
  collectMangleHybridHazards(state.mangleMap, mangledSources, externalClasses)
4533
4683
  );
4534
4684
  if (message) console.warn(message);
4685
+ reportMangleSize();
4686
+ }
4687
+ function reportMangleSize() {
4688
+ const verdict = computeMangleSizeVerdict(
4689
+ sizeAccount,
4690
+ JSON.stringify(createHydrationMangleMap(state.mangleMap, state.varMangleMap))
4691
+ );
4692
+ const message = mangleSizeMessage(verdict);
4693
+ if (message) console.warn(message);
4694
+ resetMangleSizeAccount(sizeAccount);
4535
4695
  }
4536
4696
  function rewriteWebpackCodeAsset(file, source, shouldMangle, compilation, compiler) {
4537
4697
  if (shouldMangle && file.endsWith(".html")) {
@@ -4729,6 +4889,7 @@ exports.createRSCModuleRecord = createRSCModuleRecord;
4729
4889
  exports.cssHasContentScope = cssHasContentScope;
4730
4890
  exports.cssImportsTailwind = cssImportsTailwind;
4731
4891
  exports.deleteRSCModuleRecord = deleteRSCModuleRecord;
4892
+ exports.emitMissingCssFallback = emitMissingCssFallback;
4732
4893
  exports.esbuildPlugin = esbuildPlugin;
4733
4894
  exports.extractGlobalVarAliasesForManifest = extractGlobalVarAliasesForManifest;
4734
4895
  exports.fileMayContainSafelistableSz = fileMayContainSafelistableSz;
@@ -4762,6 +4923,7 @@ exports.rewriteGlobalVarCssAliases = rewriteGlobalVarCssAliases;
4762
4923
  exports.rollupPlugin = rollupPlugin;
4763
4924
  exports.scanCustomPropertyNames = scanCustomPropertyNames;
4764
4925
  exports.scanGlobalVarCss = scanGlobalVarCss;
4926
+ exports.shouldEmitMissingCssFallback = shouldEmitMissingCssFallback;
4765
4927
  exports.shouldEmitWarning = shouldEmitWarning;
4766
4928
  exports.shouldTrackGlobalVarSources = shouldTrackGlobalVarSources;
4767
4929
  exports.shouldWarnMissingTailwindEntry = shouldWarnMissingTailwindEntry;
@@ -2,7 +2,7 @@
2
2
 
3
3
  const fs = require('node:fs');
4
4
  const compiler = require('@csszyx/compiler');
5
- const transformCache = require('./unplugin.CKIOVNOg.cjs');
5
+ const transformCache = require('./unplugin.DbZ7tCfN.cjs');
6
6
  const node_crypto = require('node:crypto');
7
7
  const htmlEscape = require('./unplugin.BkRah5Ot.cjs');
8
8
 
@@ -0,0 +1,114 @@
1
+ 'use strict';
2
+
3
+ const LEADING_WHITESPACE_RE = /^\s+/;
4
+ const LINE_COMMENT_RE = /^\/\/[^\n]*(?:\n|$)/;
5
+ const BLOCK_COMMENT_RE = /^\/\*[\s\S]*?\*\//;
6
+ const USE_DIRECTIVE_RE = /^['"]use (?:client|server)['"];?\s*/;
7
+ function insertAfterUseDirective(code, insertion) {
8
+ let offset = 0;
9
+ while (offset < code.length) {
10
+ const triviaLength = leadingTriviaLength(code.slice(offset));
11
+ if (triviaLength === 0) break;
12
+ offset += triviaLength;
13
+ }
14
+ const directive = USE_DIRECTIVE_RE.exec(code.slice(offset));
15
+ if (!directive) return `${insertion}${code}`;
16
+ const insertionOffset = offset + directive[0].length;
17
+ return `${code.slice(0, insertionOffset)}${insertion}${code.slice(insertionOffset)}`;
18
+ }
19
+ function leadingTriviaLength(source) {
20
+ return LEADING_WHITESPACE_RE.exec(source)?.[0].length ?? LINE_COMMENT_RE.exec(source)?.[0].length ?? BLOCK_COMMENT_RE.exec(source)?.[0].length ?? 0;
21
+ }
22
+
23
+ const RUNTIME_IMPORT_CLAUSE_RE = /(?:import|export)\s+\{([^{}]*)\}\s*from\s*['"]@csszyx\/runtime['"]/g;
24
+ function clauseNames(clauseBody) {
25
+ const names = [];
26
+ for (const part of clauseBody.split(",")) {
27
+ const trimmed = part.trim();
28
+ if (!trimmed) {
29
+ continue;
30
+ }
31
+ const spaceAt = trimmed.search(/\s/);
32
+ names.push(spaceAt === -1 ? trimmed : trimmed.slice(0, spaceAt));
33
+ }
34
+ return names;
35
+ }
36
+ function importsRuntimeHelper(code, helper) {
37
+ RUNTIME_IMPORT_CLAUSE_RE.lastIndex = 0;
38
+ for (let match = RUNTIME_IMPORT_CLAUSE_RE.exec(code); match; match = RUNTIME_IMPORT_CLAUSE_RE.exec(code)) {
39
+ if (clauseNames(match[1]).includes(helper)) {
40
+ return true;
41
+ }
42
+ }
43
+ return false;
44
+ }
45
+ const RUNTIME_IMPORT_APPEND_RE = /(import\s+\{[^{}]*)\}\s*from\s*['"]@csszyx\/runtime['"]/;
46
+ function findRuntimeImportClause(code) {
47
+ const match = RUNTIME_IMPORT_APPEND_RE.exec(code);
48
+ return match ? { statement: match[0], prefixWithBody: match[1] } : null;
49
+ }
50
+
51
+ function runtimeHelperGroupsFromUsage(usage) {
52
+ const slim = usage.usesSzPart === true && usage.szPartArgsProvable === true && usage.usesRuntime !== true && usage.usesMerge !== true;
53
+ const groups = { all: [], barrel: [], merge: [] };
54
+ const append = (helper, toMerge = false) => {
55
+ groups.all.push(helper);
56
+ (toMerge ? groups.merge : groups.barrel).push(helper);
57
+ };
58
+ if (usage.usesRuntime) append("_sz");
59
+ if (usage.usesMerge) append("_szMerge");
60
+ if (usage.usesSzcn) append("_szcn", slim);
61
+ if (usage.usesSzPart) append("_szPart", slim);
62
+ if (usage.usesSzvPick) append("__szvPick");
63
+ if (usage.usesSzvPick1) append("__szvPick1");
64
+ if (usage.usesColorVar) append("__szColorVar");
65
+ if (usage.usesSpacingVar) append("__szSpacingVar");
66
+ if (usage.usesUnitVar) append("__szUnitVar");
67
+ return groups;
68
+ }
69
+ function injectNextRuntimeImports(code, usage) {
70
+ const groups = runtimeHelperGroupsFromUsage(usage);
71
+ const helpers = groups.all;
72
+ if (helpers.length === 0) {
73
+ return { code, injected: [] };
74
+ }
75
+ const hasRuntimeImport = code.includes("@csszyx/runtime");
76
+ const missing = hasRuntimeImport ? helpers.filter((helper) => !importsRuntimeHelper(code, helper)) : helpers;
77
+ if (missing.length === 0) {
78
+ return { code, injected: [] };
79
+ }
80
+ if (groups.merge.length > 0) {
81
+ const mergeHelpers = missing.filter((helper) => groups.merge.includes(helper));
82
+ const barrelHelpers = missing.filter((helper) => groups.barrel.includes(helper));
83
+ let next = insertRuntimeImport(
84
+ code,
85
+ `import { ${mergeHelpers.join(", ")} } from '@csszyx/runtime/merge';
86
+ `
87
+ );
88
+ if (barrelHelpers.length > 0) {
89
+ next = insertRuntimeImport(
90
+ next,
91
+ `import { ${barrelHelpers.join(", ")} } from '@csszyx/runtime';
92
+ `
93
+ );
94
+ }
95
+ return { code: next, injected: missing };
96
+ }
97
+ return {
98
+ code: insertRuntimeImport(
99
+ code,
100
+ `import { ${missing.join(", ")} } from '@csszyx/runtime';
101
+ `
102
+ ),
103
+ injected: missing
104
+ };
105
+ }
106
+ function insertRuntimeImport(code, importStmt) {
107
+ return insertAfterUseDirective(code, importStmt);
108
+ }
109
+
110
+ exports.findRuntimeImportClause = findRuntimeImportClause;
111
+ exports.importsRuntimeHelper = importsRuntimeHelper;
112
+ exports.injectNextRuntimeImports = injectNextRuntimeImports;
113
+ exports.insertAfterUseDirective = insertAfterUseDirective;
114
+ exports.runtimeHelperGroupsFromUsage = runtimeHelperGroupsFromUsage;