@weapp-tailwindcss/postcss 3.3.7 → 3.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- import { CLAMP_PX, COLOR_GAMUT_P3_RE, DISPLAY_P3_COLOR_RE, DISPLAY_P3_VALUE_RE, INFINITY_CALC_VALUE_REGEXP, LINEAR_GRADIENT_LAB_RE, MINI_PROGRAM_ELEMENT_SCOPE_SELECTOR, MINI_PROGRAM_ELEMENT_SCOPE_SELECTORS, MODERN_CHECK_COLOR_RGB_RE, MODERN_CHECK_MARGIN_TRIM_RE, MODERN_CHECK_MOZ_ORIENT_RE, MODERN_CHECK_WEBKIT_HYPHENS_RE, analyzeApplyOnlySource, analyzeTailwindCssDirectives, appendTailwindcssV4MiniProgramGradientRules, collectUsedTailwindcssV4Variables, consumeCascadeLayers, createMissingCssVarsV4Nodes, createUsedCssVarsV4Nodes, getRuleSelectors, isBrowserElementPreflightRule, isCustomPropertyRule, isEmptyTwContentDeclaration, isMiniProgramNativeElementSelector, isMiniProgramPreflightRule as isMiniProgramPreflightRule$1, isMiniProgramThemeScopeSelector as isMiniProgramThemeScopeSelector$1, isMiniProgramThemeVariableRule, isPseudoContentInitRule as isPseudoContentInitRule$1, isTailwindCssGenerationDirective, isTailwindCssImportAtRule, isTailwindCssPackageJsonImportRequest, isTailwindcssV4, isTailwindcssV4ThemeVariable, isUnsupportedBrowserPreflightSelector, mergeTailwindcssV4GradientDirectionRules, normalizeGeneratedSelector, normalizeMiniProgramPrefixedDeclaration, normalizeTailwindCssImportRequest, normalizeTailwindcssV4Declaration, parseTailwindCssConfigRequest, parseTailwindCssDirectiveRequest, protectDynamicColorMixAlpha, protectDynamicVarFallbacks, removeEmptyAtRules as removeEmptyAtRules$1, removeEmptyBlockAtRules, removeEmptyRules, removeEmptyStandardDeclarations, removeSpecificityPlaceholders, removeTailwindContainerMaxWidthMediaRules, removeTailwindContainerWidthRules, removeUnsupportedCascadeLayers, removeUnsupportedMiniProgramAtRules, removeUnsupportedMiniProgramPrefixedAtRule, removeUnsupportedModernColorDeclarations, repairTrailingUnclosedTailwindSourceMedia, testIfRootHostForV4, usesTailwindcssV4ContentVariable, usesTwContentVariable } from "./directives-C7XTve1w.js";
2
- import { collectCssInlineSourceCandidates, describeCssSources, parseConfigParam, parseCssImportSpecifier, quoteCssImportSpecifier } from "./resolve-D-FbFBpF.js";
3
- import { composeIsPseudo, internalCssSelectorReplacer } from "./shared-CfQUwapA.js";
1
+ import { CLAMP_PX, COLOR_GAMUT_P3_RE, DISPLAY_P3_COLOR_RE, DISPLAY_P3_VALUE_RE, INFINITY_CALC_VALUE_REGEXP, LINEAR_GRADIENT_LAB_RE, MINI_PROGRAM_ELEMENT_SCOPE_SELECTOR, MINI_PROGRAM_ELEMENT_SCOPE_SELECTORS, MINI_PROGRAM_THEME_SCOPE_SELECTORS as MINI_PROGRAM_THEME_SCOPE_SELECTORS$1, MODERN_CHECK_COLOR_RGB_RE, MODERN_CHECK_MARGIN_TRIM_RE, MODERN_CHECK_MOZ_ORIENT_RE, MODERN_CHECK_WEBKIT_HYPHENS_RE, analyzeApplyOnlySource, analyzeTailwindCssDirectives, appendTailwindcssV4MiniProgramGradientRules, collectUsedTailwindcssV4Variables, consumeCascadeLayers, createMissingCssVarsV4Nodes, createUsedCssVarsV4Nodes, getRuleSelectors, isBrowserElementPreflightRule, isCustomPropertyRule, isEmptyTwContentDeclaration, isMiniProgramNativeElementSelector, isMiniProgramPreflightRule as isMiniProgramPreflightRule$1, isMiniProgramThemeScopeSelector as isMiniProgramThemeScopeSelector$1, isMiniProgramThemeVariableRule, isPseudoContentInitRule as isPseudoContentInitRule$1, isTailwindCssGenerationDirective, isTailwindCssImportAtRule, isTailwindCssPackageJsonImportRequest, isTailwindcssV4, isTailwindcssV4ThemeVariable, isUnsupportedBrowserPreflightSelector, mergeTailwindcssV4GradientDirectionRules, normalizeGeneratedSelector, normalizeMiniProgramPrefixedDeclaration, normalizeTailwindCssImportRequest, normalizeTailwindcssV4Declaration, parseTailwindCssConfigRequest, parseTailwindCssDirectiveRequest, protectDynamicColorMixAlpha, protectDynamicVarFallbacks, removeEmptyAtRules as removeEmptyAtRules$1, removeEmptyBlockAtRules, removeEmptyRules, removeEmptyStandardDeclarations, removeSpecificityPlaceholders, removeTailwindContainerMaxWidthMediaRules, removeTailwindContainerWidthRules, removeUnsupportedCascadeLayers, removeUnsupportedMiniProgramAtRules, removeUnsupportedMiniProgramPrefixedAtRule, removeUnsupportedModernColorDeclarations, repairTrailingUnclosedTailwindSourceMedia, testIfRootHostForV4, usesTailwindcssV4ContentVariable, usesTwContentVariable } from "./directives-Cr-gZPUc.js";
2
+ import { collectCssInlineSourceCandidates, describeCssSources, parseConfigParam, parseCssImportSpecifier, quoteCssImportSpecifier, tokenize, u } from "./resolve-D-FbFBpF.js";
4
3
  import { postcss as postcss$1 } from "./postcss-runtime-i5rHe_mj.js";
4
+ import { composeIsPseudo, internalCssSelectorReplacer } from "./shared-CfQUwapA.js";
5
5
  import { parseScssSource, parseUniAppXStyleSource, stringifyScssSource } from "./rewrite-imports-Dk9TKKSF.js";
6
6
  import { creator, ifdefAtRule, ifndefAtRule } from "./postcss-CICDAfoB.js";
7
7
  import { createInjectPreflight } from "./preflight-DVg4eehD.js";
@@ -16,7 +16,7 @@ import { escape } from "@weapp-core/escape";
16
16
  import { splitCandidateTokens } from "@weapp-tailwindcss/engine";
17
17
  import process from "node:process";
18
18
  import { performance } from "node:perf_hooks";
19
- import { defu, defuOverrideArray, regExpTest } from "@weapp-tailwindcss/shared";
19
+ import { defu, defuOverrideArray } from "@weapp-tailwindcss/shared";
20
20
  import { LRUCache } from "lru-cache";
21
21
  import autoprefixerPlugin from "autoprefixer";
22
22
  import postcssPxtrans from "postcss-pxtrans";
@@ -283,19 +283,236 @@ function normalizeTailwindV4RuntimeCss(css) {
283
283
  return root.toString();
284
284
  }
285
285
  //#endregion
286
+ //#region src/utils/css-custom-property.ts
287
+ function decodeCssIdentifier(source) {
288
+ if (/^[-_a-z][\w-]*$/i.test(source)) return source;
289
+ const tokens = tokenize({ css: source }).filter((token) => token[0] !== u.Whitespace && token[0] !== u.Comment && token[0] !== u.EOF);
290
+ const token = tokens[0];
291
+ return tokens.length === 1 && token?.[0] === u.Ident ? token[4].value : void 0;
292
+ }
293
+ /** PostCSS 可能把十六进制转义的终止空白拆入 params,需要按原始前导 token 还原。 */
294
+ function getCssAtRulePrelude(rule) {
295
+ if (!rule.name.includes("\\") && !(rule.raws.afterName === "" && rule.params.startsWith("\\"))) return {
296
+ name: rule.name,
297
+ params: rule.params
298
+ };
299
+ const source = `@${rule.name}${rule.raws.afterName ?? " "}${rule.params}`;
300
+ const token = tokenize({ css: source })[0];
301
+ return token?.[0] === u.AtKeyword ? {
302
+ name: token[4].value,
303
+ params: source.slice(token[3] + 1).trimStart()
304
+ } : {
305
+ name: rule.name,
306
+ params: rule.params
307
+ };
308
+ }
309
+ /** 按 CSS token 解码名称,保留自定义属性的大小写及转义终止空白语义。 */
310
+ function getCssCustomPropertyName(source) {
311
+ if (/^--[\w-]+$/.test(source)) return source;
312
+ if (!source.trimStart().startsWith("--") && !source.includes("\\")) return;
313
+ const name = decodeCssIdentifier(source);
314
+ return name?.startsWith("--") && name.length > 2 ? name : void 0;
315
+ }
316
+ function isCssVarFunction(name) {
317
+ return (name.includes("\\") ? decodeCssIdentifier(name) : name)?.toLowerCase() === "var";
318
+ }
319
+ /** 同时保留引用处的原始拼写,供底层 calc 匹配;安全判断只使用解码后的身份。 */
320
+ function getCssCalcVariableReferences(value) {
321
+ const references = /* @__PURE__ */ new Map();
322
+ if (!value.includes("(")) return references;
323
+ valueParser(value).walk((node) => {
324
+ if (node.type !== "function" || !isCssVarFunction(node.value)) return;
325
+ const comma = node.nodes.findIndex((child) => child.type === "div" && child.value === ",");
326
+ const raw = valueParser.stringify(comma < 0 ? node.nodes : node.nodes.slice(0, comma));
327
+ references.set(raw.trim(), getCssCustomPropertyName(raw) ?? raw.trim());
328
+ });
329
+ return references;
330
+ }
331
+ /** 内部共享匹配入口:字符串按 CSS 名称解码,正则匹配解码后的身份。 */
332
+ function isCssCalcCustomPropertySelected(name, includes) {
333
+ return includes?.some((entry) => typeof entry === "string" ? getCssCustomPropertyName(entry) === name : new RegExp(entry.source, entry.flags).test(name)) ?? false;
334
+ }
335
+ //#endregion
336
+ //#region src/utils/css-calc-context.ts
337
+ /** 只接受无条件主题根;层叠层允许提供候选值,冲突统一在后续排除。 */
338
+ function isCssCalcThemeDeclaration(decl) {
339
+ const rule = decl.parent;
340
+ if (rule?.type !== "rule" || !rule.selectors.length || !rule.selectors.every((selector) => MINI_PROGRAM_THEME_SCOPE_SELECTORS$1.has(selector.trim()))) return false;
341
+ if (!rule.selectors.some((selector) => [":root", "page"].includes(selector.trim()))) return false;
342
+ let parent = rule.parent;
343
+ while (parent && parent.type !== "root") {
344
+ if (parent.type !== "atrule" || getCssAtRulePrelude(parent).name.toLowerCase() !== "layer") return false;
345
+ parent = parent.parent;
346
+ }
347
+ return parent?.type === "root";
348
+ }
349
+ function isSourceThemeDeclaration(decl) {
350
+ let parent = decl.parent;
351
+ while (parent && parent.type !== "root") {
352
+ if (parent.type === "atrule" && getCssAtRulePrelude(parent).name.toLowerCase() === "theme") return true;
353
+ parent = parent.parent;
354
+ }
355
+ return false;
356
+ }
357
+ function getDependencies(value) {
358
+ return new Set(getCssCalcVariableReferences(value).values());
359
+ }
360
+ function isCssWideValue(value) {
361
+ return /^(?:initial|inherit|unset|revert|revert-layer)$/i.test(decodeCssIdentifier(value) ?? value);
362
+ }
363
+ /**
364
+ * 推导可供 calc 静态化的主题变量;局部、条件、冲突及未解析依赖一律保留运行时语义。
365
+ * 原始 @theme 由编译器处理,此处只消费其生成的有效主题根。
366
+ */
367
+ function analyzeCssCalcContext(css, explicitValues) {
368
+ const customPropertyValues = /* @__PURE__ */ new Map();
369
+ const unsafeCustomProperties = /* @__PURE__ */ new Set();
370
+ try {
371
+ const root = postcss.parse(css);
372
+ root.walkAtRules((rule) => {
373
+ const prelude = getCssAtRulePrelude(rule);
374
+ if (prelude.name.toLowerCase() === "property") unsafeCustomProperties.add(getCssCustomPropertyName(prelude.params) ?? prelude.params.trim());
375
+ });
376
+ root.walkDecls((decl) => {
377
+ const name = getCssCustomPropertyName(decl.prop);
378
+ if (!name || isSourceThemeDeclaration(decl)) return;
379
+ const value = decl.value.trim();
380
+ if (!isCssCalcThemeDeclaration(decl) || isCssWideValue(value) || customPropertyValues.has(name) && customPropertyValues.get(name) !== value) unsafeCustomProperties.add(name);
381
+ else customPropertyValues.set(name, value);
382
+ });
383
+ } catch {
384
+ return {
385
+ customPropertyValues,
386
+ unsafeCustomProperties
387
+ };
388
+ }
389
+ const dependencies = new Map([...customPropertyValues].map(([name, value]) => [name, getDependencies(value)]));
390
+ for (const [rawName, value] of explicitValues ?? []) {
391
+ const name = getCssCustomPropertyName(rawName);
392
+ if (name && !unsafeCustomProperties.has(name)) {
393
+ customPropertyValues.set(name, value);
394
+ dependencies.set(name, /* @__PURE__ */ new Set([...dependencies.get(name) ?? [], ...getDependencies(value)]));
395
+ }
396
+ }
397
+ const visiting = /* @__PURE__ */ new Set();
398
+ const resolved = /* @__PURE__ */ new Set();
399
+ function isSafe(name) {
400
+ if (unsafeCustomProperties.has(name)) return false;
401
+ if (resolved.has(name)) return true;
402
+ const value = customPropertyValues.get(name);
403
+ if (value === void 0 || isCssWideValue(value) || visiting.has(name) || visiting.size >= 256) {
404
+ unsafeCustomProperties.add(name);
405
+ return false;
406
+ }
407
+ visiting.add(name);
408
+ for (const dependency of dependencies.get(name) ?? []) if (!isSafe(dependency)) {
409
+ visiting.delete(name);
410
+ unsafeCustomProperties.add(name);
411
+ return false;
412
+ }
413
+ visiting.delete(name);
414
+ if (dependencies.get(name)?.size) {
415
+ const parsed = valueParser(value);
416
+ parsed.walk((node, index, nodes) => {
417
+ if (node.type !== "function" || !isCssVarFunction(node.value)) return;
418
+ const comma = node.nodes.findIndex((child) => child.type === "div" && child.value === ",");
419
+ const rawDependency = valueParser.stringify(comma < 0 ? node.nodes : node.nodes.slice(0, comma));
420
+ const dependency = getCssCustomPropertyName(rawDependency) ?? rawDependency.trim();
421
+ nodes[index] = {
422
+ type: "word",
423
+ value: customPropertyValues.get(dependency),
424
+ sourceIndex: node.sourceIndex,
425
+ sourceEndIndex: node.sourceEndIndex
426
+ };
427
+ return false;
428
+ });
429
+ customPropertyValues.set(name, parsed.toString());
430
+ }
431
+ resolved.add(name);
432
+ return true;
433
+ }
434
+ for (const name of customPropertyValues.keys()) if (!isSafe(name)) customPropertyValues.delete(name);
435
+ return {
436
+ customPropertyValues,
437
+ unsafeCustomProperties
438
+ };
439
+ }
440
+ //#endregion
441
+ //#region src/plugins/getCalcPlugin.ts
442
+ function getCalcPlugin(options) {
443
+ if (!options.cssCalc) return null;
444
+ const configured = typeof options.cssCalc === "object" && !Array.isArray(options.cssCalc) ? { ...options.cssCalc } : {};
445
+ const includes = [...(Array.isArray(options.cssCalc) ? options.cssCalc : configured.includeCustomProperties) ?? []];
446
+ const inputValues = options.customPropertyValues ?? configured.customPropertyValues;
447
+ const explicitValues = inputValues ? new Map(inputValues) : void 0;
448
+ const contextCss = options.customPropertyContextCss ?? "";
449
+ const selectAll = options.cssCalc === true;
450
+ return {
451
+ postcssPlugin: "postcss-calc",
452
+ Once(root, helpers) {
453
+ const context = analyzeCssCalcContext([contextCss, root.toString()].join("\n"), explicitValues);
454
+ const selectedValues = new Map([...context.customPropertyValues].filter(([name]) => selectAll || isCssCalcCustomPropertySelected(name, includes)));
455
+ const customPropertyValues = /* @__PURE__ */ new Map();
456
+ root.walk((node) => {
457
+ const value = node.type === "decl" ? node.value : node.type === "atrule" && configured.mediaQueries ? node.params : node.type === "rule" && configured.selectors ? node.selector : void 0;
458
+ if (!value) return;
459
+ for (const [rawName, name] of getCssCalcVariableReferences(value)) {
460
+ const resolved = selectedValues.get(name);
461
+ if (resolved !== void 0) customPropertyValues.set(rawName, resolved);
462
+ }
463
+ });
464
+ return postcssCalc({
465
+ ...configured,
466
+ customPropertyValues,
467
+ includeCustomProperties: [...customPropertyValues.keys()]
468
+ }).OnceExit?.(root, helpers);
469
+ }
470
+ };
471
+ }
472
+ //#endregion
473
+ //#region src/plugins/applyConfiguredCssCalc.ts
474
+ function resolveCssCalcOption(options) {
475
+ return options.cssOptions?.cssCalc ?? options.cssCalc;
476
+ }
477
+ /**
478
+ * 仅按 `cssCalc` 配置预计算 `calc()` / `var()`,不跑小程序选择器替换或单位转换。
479
+ */
480
+ async function applyConfiguredCssCalc(css, options = {}) {
481
+ const cssCalc = resolveCssCalcOption(options);
482
+ if (!cssCalc || !css.includes("calc(")) return css;
483
+ const plugin = getCalcPlugin({
484
+ cssCalc,
485
+ customPropertyValues: options.customPropertyValues,
486
+ customPropertyContextCss: [options.customPropertyContextCss ?? "", options.contextCss ?? ""].join("\n")
487
+ });
488
+ if (!plugin) return css;
489
+ try {
490
+ return (await postcss$1([plugin]).process(css, { from: void 0 })).css;
491
+ } catch {
492
+ return css;
493
+ }
494
+ }
495
+ //#endregion
286
496
  //#region src/compat/mini-program-css/prune-generated.ts
287
497
  const DEFAULT_WEAPP_VARIABLE_SCOPE = "page,.tw-root,wx-root-portal-content,:host";
288
498
  const MINI_PROGRAM_PSEUDO_CONTENT_SCOPE_SELECTOR = "::before,\n::after";
289
499
  const CLASS_SELECTOR_RE$2 = /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i;
290
500
  /**
291
- * 在交给框架 PostCSS 前展开 Tailwind 生成的嵌套规则,并裁剪 Web-only 结构。
501
+ * 在主题作用域改写前按配置预计算 calc,再展开 Tailwind 生成的嵌套规则并裁剪 Web-only 结构。
292
502
  */
293
503
  async function normalizeMiniProgramGeneratedCssForPostcss(css, options = {}) {
504
+ const calculatedCss = await applyConfiguredCssCalc(css, {
505
+ cssCalc: options.cssCalc,
506
+ cssOptions: options.cssOptions,
507
+ customPropertyValues: options.customPropertyValues,
508
+ customPropertyContextCss: options.customPropertyContextCss,
509
+ contextCss: options.contextCss ?? css
510
+ });
294
511
  return pruneMiniProgramGeneratedCss((await postcss([postcssPresetEnv({
295
512
  stage: false,
296
513
  features: { "nesting-rules": true },
297
514
  autoprefixer: false
298
- })]).process(css, { from: void 0 })).css, options);
515
+ })]).process(calculatedCss, { from: void 0 })).css, options);
299
516
  }
300
517
  function isConditionalCompilationComment(text) {
301
518
  return /#(?:ifn?def|endif)\b/.test(text);
@@ -1027,7 +1244,7 @@ function applyUniAppXUvueCompatibility(result, options) {
1027
1244
  const sfcStyleRequest = options?.isMainChunk !== true && isUvueSfcStyleRequest(result);
1028
1245
  let root = result.root;
1029
1246
  let calcMessages = [];
1030
- consumeUniAppXSystemRootTheme(root, options?.customPropertyValues);
1247
+ consumeUniAppXSystemRootTheme(root, new Map([...options?.customPropertyCompatibilityValues ?? [], ...options?.customPropertyValues ?? []]));
1031
1248
  if (root.type === "root" && Array.isArray(root.nodes) && typeof root.walkDecls === "function") {
1032
1249
  root.walkDecls((decl) => {
1033
1250
  normalizeTailwindcssV4Declaration(decl);
@@ -4369,7 +4586,7 @@ function getDefaultOptions(options) {
4369
4586
  "oklab-function": true,
4370
4587
  "color-mix": true,
4371
4588
  "color-functional-notation": options?.cssPresetEnv?.features?.["color-functional-notation"] ?? { preserve: false },
4372
- "custom-properties": options?.cssPresetEnv?.features?.["custom-properties"] ?? options?.cssCalc ? { preserve: true } : false
4589
+ "custom-properties": options?.cssPresetEnv?.features?.["custom-properties"] ?? false
4373
4590
  },
4374
4591
  autoprefixer: { add: false }
4375
4592
  },
@@ -4402,12 +4619,17 @@ function fingerprintOptions(value, state = {
4402
4619
  const marker = `ref:${state.counter++}`;
4403
4620
  state.map.set(objectValue, marker);
4404
4621
  if (Array.isArray(objectValue)) return `[${objectValue.map((entry) => fingerprintOptions(entry, state)).join(",")}]`;
4622
+ if (objectValue instanceof RegExp) return `regexp:${objectValue.source}/${objectValue.flags}`;
4405
4623
  if (objectValue instanceof Map) return `map:{${[...objectValue.entries()].map(([key, entry]) => [fingerprintOptions(key, state), fingerprintOptions(entry, state)]).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${key}:${entry}`).join(",")}}@${marker}`;
4406
4624
  return `{${Object.keys(objectValue).sort().map((key) => `${key}:${fingerprintOptions(objectValue[key], state)}`).join(",")}}@${marker}`;
4407
4625
  }
4626
+ /** 处理器运行时状态不参与输入签名,其余选项每次按实际内容计算。 */
4627
+ function fingerprintStyleOptions(options) {
4628
+ const { ctx: _ctx, ...inputs } = options;
4629
+ return fingerprintOptions(inputs);
4630
+ }
4408
4631
  //#endregion
4409
4632
  //#region src/options-resolver.ts
4410
- const BASE_CACHE_KEY = "base";
4411
4633
  const SIMPLE_OVERRIDE_UNSET = "__unset__";
4412
4634
  const CSS_OPTION_KEYS = [
4413
4635
  "cssPreflight",
@@ -4582,32 +4804,17 @@ function normalizeCssOptions(options, mirrorTopLevel = false) {
4582
4804
  function createOptionsResolver(baseOptions) {
4583
4805
  const normalizedBaseOptions = normalizeCssOptions(baseOptions);
4584
4806
  const cacheByKey = /* @__PURE__ */ new Map();
4585
- const cacheByRef = /* @__PURE__ */ new WeakMap();
4586
- const cacheKeyByRef = /* @__PURE__ */ new WeakMap();
4587
- const emptyOverrideRefs = /* @__PURE__ */ new WeakSet();
4588
- cacheByKey.set(BASE_CACHE_KEY, normalizedBaseOptions);
4589
4807
  const resolve = (overrides) => {
4590
4808
  if (!overrides) return normalizedBaseOptions;
4591
- const refCached = cacheByRef.get(overrides);
4592
- if (refCached) return refCached;
4593
- if (emptyOverrideRefs.has(overrides)) return normalizedBaseOptions;
4594
- if (!hasOverrides(overrides)) {
4595
- emptyOverrideRefs.add(overrides);
4596
- return normalizedBaseOptions;
4597
- }
4598
- let key = cacheKeyByRef.get(overrides);
4599
- if (!key) {
4600
- key = getSimpleOverrideCacheKey(overrides) ?? fingerprintOptions(overrides);
4601
- cacheKeyByRef.set(overrides, key);
4602
- }
4809
+ if (!hasOverrides(overrides)) return normalizedBaseOptions;
4810
+ const key = getSimpleOverrideCacheKey(overrides) ?? fingerprintOptions(overrides);
4603
4811
  const cached = cacheByKey.get(key);
4604
- if (cached) {
4605
- cacheByRef.set(overrides, cached);
4606
- return cached;
4607
- }
4812
+ if (cached && fingerprintStyleOptions(cached.options) === cached.fingerprint) return cached.options;
4608
4813
  const normalized = normalizeCssOptions(defuOverrideArray(normalizeCssOptions({ ...overrides }, true), normalizedBaseOptions));
4609
- cacheByKey.set(key, normalized);
4610
- cacheByRef.set(overrides, normalized);
4814
+ cacheByKey.set(key, {
4815
+ options: normalized,
4816
+ fingerprint: fingerprintStyleOptions(normalized)
4817
+ });
4611
4818
  return normalized;
4612
4819
  };
4613
4820
  return { resolve };
@@ -4758,70 +4965,15 @@ function getCalcDuplicateCleaner(options) {
4758
4965
  return calcDuplicateCleanerPlugin;
4759
4966
  }
4760
4967
  //#endregion
4761
- //#region src/plugins/getCalcPlugin.ts
4762
- const EMPTY_CALC_OPTIONS = {};
4763
- function getCalcPlugin(options) {
4764
- if (!options.cssCalc) return null;
4765
- if (options.cssCalc === true || Array.isArray(options.cssCalc)) {
4766
- const calcOptions = Array.isArray(options.cssCalc) ? {
4767
- includeCustomProperties: options.cssCalc,
4768
- ...options.customPropertyValues ? { customPropertyValues: options.customPropertyValues } : {}
4769
- } : options.customPropertyValues ? {
4770
- customPropertyValues: options.customPropertyValues,
4771
- includeCustomProperties: [...options.customPropertyValues.keys()]
4772
- } : EMPTY_CALC_OPTIONS;
4773
- return postcssCalc(calcOptions);
4774
- }
4775
- return postcssCalc({
4776
- ...options.cssCalc,
4777
- ...options.customPropertyValues ? { customPropertyValues: options.customPropertyValues } : {}
4778
- });
4779
- }
4780
- //#endregion
4781
4968
  //#region src/plugins/getCustomPropertyCleaner.ts
4782
4969
  function getCustomPropertyCleaner(options) {
4783
- const includeCustomProperties = Array.isArray(options.cssCalc) ? options.cssCalc : typeof options.cssCalc === "object" ? options.cssCalc.includeCustomProperties : [];
4784
- if (!(Array.isArray(includeCustomProperties) && includeCustomProperties.length > 0)) return null;
4785
- const shouldInspectValue = (value) => value.includes("var(") && value.includes("--");
4786
- const containsIncludedCustomProperty = (value) => {
4787
- if (!shouldInspectValue(value)) return false;
4788
- const parsed = valueParser(value);
4789
- let containsIncludedCustomProperty = false;
4790
- parsed.walk((node) => {
4791
- if (node.type !== "function" || node.value !== "var" || containsIncludedCustomProperty) return;
4792
- if (node.nodes.find((x) => {
4793
- return x.type === "word" && regExpTest(includeCustomProperties, x.value);
4794
- })) containsIncludedCustomProperty = true;
4795
- });
4796
- return containsIncludedCustomProperty;
4797
- };
4798
- const hasSameSourceRange = (left, right) => {
4799
- const leftSource = left.source;
4800
- const rightSource = right.source;
4801
- if (!leftSource?.start || !leftSource.end || !rightSource?.start || !rightSource.end || leftSource.input !== rightSource.input) return false;
4802
- return leftSource.start.line === rightSource.start.line && leftSource.start.column === rightSource.start.column && leftSource.end.line === rightSource.end.line && leftSource.end.column === rightSource.end.column;
4803
- };
4970
+ if (!(Array.isArray(options.cssCalc) ? options.cssCalc : typeof options.cssCalc === "object" ? options.cssCalc.includeCustomProperties : void 0)?.length) return null;
4804
4971
  return {
4805
4972
  postcssPlugin: "postcss-remove-include-custom-properties",
4806
4973
  OnceExit(root) {
4807
4974
  root.walkDecls((decl) => {
4808
- const prevNode = decl.prev();
4809
- if (prevNode && prevNode.type === "decl" && prevNode.prop === decl.prop && prevNode.important === decl.important && prevNode.value === decl.value) {
4810
- decl.remove();
4811
- return;
4812
- }
4813
- if (!containsIncludedCustomProperty(decl.value)) return;
4814
- let fallbackDecl;
4815
- let node = prevNode;
4816
- while (node) {
4817
- if (node.type === "decl" && node.prop === decl.prop) {
4818
- fallbackDecl = node;
4819
- break;
4820
- }
4821
- node = node.prev();
4822
- }
4823
- if (!fallbackDecl || fallbackDecl.important !== decl.important || fallbackDecl !== prevNode && !hasSameSourceRange(fallbackDecl, decl) || containsIncludedCustomProperty(fallbackDecl.value)) return;
4824
- decl.remove();
4975
+ const previous = decl.prev();
4976
+ if (previous?.type === "decl" && previous.prop === decl.prop && previous.important === decl.important && previous.value === decl.value) decl.remove();
4825
4977
  });
4826
4978
  }
4827
4979
  };
@@ -6223,11 +6375,12 @@ function removeTailwindV4EmptyContentInit(node) {
6223
6375
  if (isEmptyContentInitDeclaration(decl)) decl.remove();
6224
6376
  });
6225
6377
  }
6226
- function injectPreflightDeclarations(node, options) {
6378
+ function injectPreflightDeclarations(node, options, contentUsage) {
6227
6379
  const preflightDeclarations = options.cssInjectPreflight?.();
6228
6380
  if (!preflightDeclarations || preflightDeclarations.length === 0) return;
6229
6381
  node.prepend(...preflightDeclarations);
6230
6382
  node.raws.semicolon = true;
6383
+ contentUsage?.invalidate();
6231
6384
  }
6232
6385
  function hasClassSelector$1(node) {
6233
6386
  return node.selectors.some((selector) => selector.includes("."));
@@ -6253,7 +6406,7 @@ function resolveUniAppXVariableScopeSelectors(options) {
6253
6406
  if (typeof universal === "string" && universal.length > 0) return [universal];
6254
6407
  return ["view", "text"];
6255
6408
  }
6256
- function commonChunkPreflight(node, options) {
6409
+ function commonChunkPreflight(node, options, contentUsage) {
6257
6410
  const { ctx, injectAdditionalCssVarScope } = options;
6258
6411
  const uniAppXEnabled = isUniAppXEnabled(options);
6259
6412
  const isTailwindcss4 = isTailwindcssV4(options);
@@ -6266,14 +6419,16 @@ function commonChunkPreflight(node, options) {
6266
6419
  phase: "pre",
6267
6420
  reason: "append-host-selector"
6268
6421
  });
6269
- if (isTailwindcss4 && !usesTailwindcssV4ContentVariable(node.root()) && (!hasClassSelector$1(node) || isRootThemeScopeRule(node))) removeTailwindV4EmptyContentInit(node);
6422
+ if (isTailwindcss4 && (!hasClassSelector$1(node) || isRootThemeScopeRule(node))) {
6423
+ if (!(contentUsage?.read() ?? usesTailwindcssV4ContentVariable(node.root()))) removeTailwindV4EmptyContentInit(node);
6424
+ }
6270
6425
  if (testIfVariablesScope(node) || uniAppXEnabled && node.selectors.includes("*") && hasTwVars(node, 2)) {
6271
6426
  ctx?.markVariablesScope(node);
6272
6427
  assignRuleSelectors(node, uniAppXEnabled ? resolveUniAppXVariableScopeSelectors(options) : remakeCssVarSelector(node.selectors, options), {
6273
6428
  phase: "pre",
6274
6429
  reason: "rewrite-variable-scope"
6275
6430
  });
6276
- injectPreflightDeclarations(node, options);
6431
+ injectPreflightDeclarations(node, options, contentUsage);
6277
6432
  }
6278
6433
  if (injectAdditionalCssVarScope && isTailwindcss4 && testIfRootHostForV4(node)) {
6279
6434
  const nodes = createUsedCssVarsV4Nodes(collectUsedTailwindcssV4Variables(node.root()));
@@ -6291,7 +6446,8 @@ function commonChunkPreflight(node, options) {
6291
6446
  reason: "rewrite-synthetic-variable-scope"
6292
6447
  });
6293
6448
  node.before(syntheticRule);
6294
- injectPreflightDeclarations(syntheticRule, options);
6449
+ contentUsage?.invalidate();
6450
+ injectPreflightDeclarations(syntheticRule, options, contentUsage);
6295
6451
  }
6296
6452
  }
6297
6453
  //#endregion
@@ -6357,14 +6513,39 @@ const postcssWeappTailwindcssPrePlugin = (options) => {
6357
6513
  }
6358
6514
  });
6359
6515
  consumeCascadeLayers(root);
6516
+ let contentVariableUsedInRoot = isTailwindcssV4(opts) ? usesTailwindcssV4ContentVariable(root) : void 0;
6517
+ const contentUsage = {
6518
+ read: () => contentVariableUsedInRoot ??= usesTailwindcssV4ContentVariable(root),
6519
+ invalidate: () => {
6520
+ contentVariableUsedInRoot = void 0;
6521
+ }
6522
+ };
6360
6523
  root.walkRules((rule) => {
6361
- commonChunkPreflight(rule, opts);
6524
+ commonChunkPreflight(rule, opts, contentUsage);
6362
6525
  });
6363
6526
  };
6364
6527
  return p;
6365
6528
  };
6366
6529
  postcssWeappTailwindcssPrePlugin.postcss = true;
6367
6530
  //#endregion
6531
+ //#region src/plugins/user-plugin-stage.ts
6532
+ /** 完成作者插件的全部 visitor 后再进入平台适配,避免 calc 读取中间态。 */
6533
+ function createUserPluginStage(plugins) {
6534
+ const processor = postcss(plugins);
6535
+ return {
6536
+ postcssPlugin: "weapp-tailwindcss-author-stage",
6537
+ async Once(root, { result }) {
6538
+ const processed = await processor.process(root, {
6539
+ ...result.opts,
6540
+ map: false
6541
+ }).async();
6542
+ result.messages.push(...processed.messages);
6543
+ root.markDirty();
6544
+ root.walk((node) => node.markDirty());
6545
+ }
6546
+ };
6547
+ }
6548
+ //#endregion
6368
6549
  //#region src/pipeline.ts
6369
6550
  function normalizeUserPlugins(plugins) {
6370
6551
  if (!plugins) return [];
@@ -6400,11 +6581,11 @@ function isUniAppXNativeAuthorStyle(options) {
6400
6581
  function appendUniAppXNativeAuthorDeclarationNodes(preparedNodes, options) {
6401
6582
  if (options.uniAppXCssSource !== "author-apply") return;
6402
6583
  const declarationPlugins = [
6584
+ ["normal:calc", getCalcPlugin(options)],
6403
6585
  ["normal:units-to-px", getUnitsToPxPlugin(options)],
6404
6586
  ["normal:px-transform", getPxTransformPlugin(options)],
6405
6587
  ["normal:rem-transform", getRemTransformPlugin(options)],
6406
- ["normal:unit-conversion", getUnitConversionPlugin(options)],
6407
- ["normal:calc", getCalcPlugin(options)]
6588
+ ["normal:unit-conversion", getUnitConversionPlugin(options)]
6408
6589
  ];
6409
6590
  for (const [id, plugin] of declarationPlugins) if (plugin) preparedNodes.push(createPreparedNode(id, "normal", () => plugin));
6410
6591
  }
@@ -6422,9 +6603,11 @@ function createPreparedNodes(options, signal) {
6422
6603
  "cascade-layers": false
6423
6604
  }
6424
6605
  };
6425
- userPlugins.forEach((plugin, index) => {
6606
+ (options.cssCalc && userPlugins.length > 0 ? [createUserPluginStage(userPlugins)] : userPlugins).forEach((plugin, index) => {
6426
6607
  preparedNodes.push(createPreparedNode(`pre:user-${index}`, "pre", () => plugin));
6427
6608
  });
6609
+ const calcPlugin = getCalcPlugin(options);
6610
+ if (calcPlugin) preparedNodes.push(createPreparedNode("pre:calc", "pre", () => calcPlugin));
6428
6611
  preparedNodes.push(createPreparedNode("pre:core", "pre", () => postcssWeappTailwindcssPrePlugin(options)));
6429
6612
  if (!signal || signal.hasPresetEnvFeatures) preparedNodes.push(createPreparedNode("normal:preset-env", "normal", () => postcssPresetEnv(presetEnvOptions)));
6430
6613
  if (!signal || signal.hasModernColorFunction) preparedNodes.push(createPreparedNode("normal:color-functional-fallback", "normal", () => createColorFunctionalFallback()));
@@ -6436,8 +6619,6 @@ function createPreparedNodes(options, signal) {
6436
6619
  if (remTransformPlugin) preparedNodes.push(createPreparedNode("normal:rem-transform", "normal", () => remTransformPlugin));
6437
6620
  const unitConversionPlugin = getUnitConversionPlugin(options);
6438
6621
  if (unitConversionPlugin) preparedNodes.push(createPreparedNode("normal:unit-conversion", "normal", () => unitConversionPlugin));
6439
- const calcPlugin = getCalcPlugin(options);
6440
- if (calcPlugin) preparedNodes.push(createPreparedNode("normal:calc", "normal", () => calcPlugin));
6441
6622
  const calcDuplicateCleaner = getCalcDuplicateCleaner(options);
6442
6623
  if (calcDuplicateCleaner) preparedNodes.push(createPreparedNode("normal:calc-duplicate-cleaner", "normal", () => calcDuplicateCleaner));
6443
6624
  const customPropertyCleaner = getCustomPropertyCleaner(options);
@@ -6546,10 +6727,9 @@ var StyleProcessorCache = class {
6546
6727
  pipelineCacheByKey = /* @__PURE__ */ new Map();
6547
6728
  processOptionsCache = /* @__PURE__ */ new WeakMap();
6548
6729
  processorCacheByKey = /* @__PURE__ */ new Map();
6549
- processorKeyCache = /* @__PURE__ */ new WeakMap();
6550
6730
  createProcessorCacheKey(options) {
6551
- if (options.postcssOptions?.options?.from == null) return fingerprintOptions(options);
6552
- return fingerprintOptions({
6731
+ if (options.postcssOptions?.options?.from == null) return fingerprintStyleOptions(options);
6732
+ return fingerprintStyleOptions({
6553
6733
  ...options,
6554
6734
  postcssOptions: {
6555
6735
  ...options.postcssOptions ?? {},
@@ -6568,11 +6748,7 @@ var StyleProcessorCache = class {
6568
6748
  return `${optionsFingerprint}|${signalToCacheKey(signal)}`;
6569
6749
  }
6570
6750
  getPipeline(options, signal) {
6571
- let optionsKey = this.processorKeyCache.get(options);
6572
- if (!optionsKey) {
6573
- optionsKey = this.createProcessorCacheKey(options);
6574
- this.processorKeyCache.set(options, optionsKey);
6575
- }
6751
+ const optionsKey = this.createProcessorCacheKey(options);
6576
6752
  const compositeKey = this.createCompositeCacheKey(optionsKey, signal);
6577
6753
  let pipeline = this.pipelineCacheByKey.get(compositeKey);
6578
6754
  if (!pipeline) {
@@ -6596,11 +6772,7 @@ var StyleProcessorCache = class {
6596
6772
  return { ...cached.value };
6597
6773
  }
6598
6774
  getProcessor(options, signal) {
6599
- let optionsKey = this.processorKeyCache.get(options);
6600
- if (!optionsKey) {
6601
- optionsKey = this.createProcessorCacheKey(options);
6602
- this.processorKeyCache.set(options, optionsKey);
6603
- }
6775
+ const optionsKey = this.createProcessorCacheKey(options);
6604
6776
  const compositeKey = this.createCompositeCacheKey(optionsKey, signal);
6605
6777
  let processor = this.processorCacheByKey.get(compositeKey);
6606
6778
  if (!processor) {
@@ -6628,25 +6800,14 @@ function simpleHash(str) {
6628
6800
  return (hash >>> 0).toString(36);
6629
6801
  }
6630
6802
  function createStyleHandler(options) {
6631
- const cachedOptions = defuOverrideArray(options, getDefaultOptions(options));
6803
+ const normalizedOptions = normalizeCssOptions(options ?? {});
6804
+ const cachedOptions = defuOverrideArray(normalizedOptions, normalizeCssOptions(getDefaultOptions(normalizedOptions), normalizedOptions.cssOptions !== void 0));
6632
6805
  cachedOptions.cssInjectPreflight = createInjectPreflight(cachedOptions.cssPreflight);
6633
6806
  const resolver = createOptionsResolver(cachedOptions);
6634
6807
  const processorCache = new StyleProcessorCache();
6635
6808
  const base = resolver.resolve();
6636
6809
  processorCache.getProcessor(base);
6637
6810
  processorCache.getProcessOptions(base);
6638
- /** 选项指纹缓存,避免重复序列化 */
6639
- const optionsFingerprintCache = /* @__PURE__ */ new WeakMap();
6640
- /**
6641
- * 获取选项指纹(带缓存)
6642
- */
6643
- function getOptionsFingerprint(opts) {
6644
- const cached = optionsFingerprintCache.get(opts);
6645
- if (cached) return cached;
6646
- const fp = fingerprintOptions(opts);
6647
- optionsFingerprintCache.set(opts, fp);
6648
- return fp;
6649
- }
6650
6811
  /** CSS 处理结果 LRU 缓存 */
6651
6812
  const resultCache = new LRUCache({ max: CSS_RESULT_CACHE_MAX });
6652
6813
  /** 检测是否配置了用户 postcss 插件(如 tailwindcss),有用户插件时不做内容探测 */
@@ -6674,7 +6835,7 @@ function createStyleHandler(options) {
6674
6835
  } catch {
6675
6836
  signal = void 0;
6676
6837
  }
6677
- const cacheKey = `${getOptionsFingerprint(resolvedOptions)}|${signal ? signalToCacheKey(signal) : ""}|${simpleHash(source)}`;
6838
+ const cacheKey = `${fingerprintStyleOptions(resolvedOptions)}|${signal ? signalToCacheKey(signal) : ""}|${simpleHash(source)}`;
6678
6839
  const cachedResult = resultCache.get(cacheKey);
6679
6840
  if (cachedResult) {
6680
6841
  resolvedOptions.onDiagnostic?.({
@@ -6763,51 +6924,6 @@ function assertRootResult(result) {
6763
6924
  if (result.root.type !== "root") throw new TypeError("StyleHandler.transformRoot must return a single PostCSS Root.");
6764
6925
  }
6765
6926
  //#endregion
6766
- //#region src/utils/custom-property-values.ts
6767
- /** 按声明顺序收集构建期上下文,不推断级联或运行时作用域。 */
6768
- function collectCustomPropertyValues(css) {
6769
- const values = /* @__PURE__ */ new Map();
6770
- mergeCustomPropertyValues$1(values, css);
6771
- return values;
6772
- }
6773
- /** 直接合并到调用方上下文,避免中间 Map;后出现的声明覆盖旧值。 */
6774
- function mergeCustomPropertyValues$1(target, css) {
6775
- if (!css.includes("--")) return;
6776
- try {
6777
- postcss.parse(css).walkDecls((decl) => {
6778
- if (decl.prop.startsWith("--")) target.set(decl.prop, decl.value.trim());
6779
- });
6780
- } catch {}
6781
- }
6782
- //#endregion
6783
- //#region src/plugins/applyConfiguredCssCalc.ts
6784
- function resolveCssCalcOption(options) {
6785
- return options.cssOptions?.cssCalc ?? options.cssCalc;
6786
- }
6787
- function mergeCustomPropertyValues(css, options) {
6788
- const values = collectCustomPropertyValues(options.contextCss ?? "");
6789
- mergeCustomPropertyValues$1(values, css);
6790
- for (const [name, value] of options.customPropertyValues ?? []) values.set(name, value);
6791
- return values;
6792
- }
6793
- /**
6794
- * 仅按 `cssCalc` 配置预计算 `calc()` / `var()`,不跑小程序选择器替换或单位转换。
6795
- */
6796
- async function applyConfiguredCssCalc(css, options = {}) {
6797
- const cssCalc = resolveCssCalcOption(options);
6798
- if (!cssCalc || !css.includes("calc(")) return css;
6799
- const plugin = getCalcPlugin({
6800
- cssCalc,
6801
- customPropertyValues: mergeCustomPropertyValues(css, options)
6802
- });
6803
- if (!plugin) return css;
6804
- try {
6805
- return (await postcss$1([plugin]).process(css, { from: void 0 })).css;
6806
- } catch {
6807
- return css;
6808
- }
6809
- }
6810
- //#endregion
6811
6927
  //#region src/compat/tailwindcss-v4/generated-output.ts
6812
6928
  const defaultStyleHandler = createStyleHandler({
6813
6929
  cssChildCombinatorReplaceValue: ["view", "text"],
@@ -6829,7 +6945,7 @@ function normalizeTailwindV4GeneratedUrlValues(css) {
6829
6945
  }
6830
6946
  async function transformTailwindV4CssToWeapp(css, options) {
6831
6947
  const compatibleCss = normalizeTailwindV4GeneratedUrlValues(hasCssMacroStyleOptions(options) ? await transformCssMacroCss(css, options) : css);
6832
- const customPropertyValues = options?.customPropertyValues;
6948
+ const customPropertyValues = new Map([...options?.customPropertyCompatibilityValues ?? [], ...options?.customPropertyValues ?? []]);
6833
6949
  const protectedCss = protectDynamicColorMixAlpha(compatibleCss, { customPropertyValues });
6834
6950
  const result = await defaultStyleHandler(protectedCss.css, {
6835
6951
  cssChildCombinatorReplaceValue: ["view", "text"],
@@ -7986,6 +8102,7 @@ async function transformGeneratorUserCss(source, options) {
7986
8102
  if (options.generatorTarget !== "weapp") return applyConfiguredCssCalc(userSource, {
7987
8103
  cssCalc: options.generatorStyleOptions.cssOptions?.cssCalc ?? options.generatorStyleOptions.cssCalc ?? options.cssUserHandlerOptions.cssOptions?.cssCalc ?? options.cssUserHandlerOptions.cssCalc,
7988
8104
  customPropertyValues: options.generatorStyleOptions.customPropertyValues ?? options.cssUserHandlerOptions.customPropertyValues,
8105
+ customPropertyContextCss: options.generatorStyleOptions.customPropertyContextCss ?? options.cssUserHandlerOptions.customPropertyContextCss,
7989
8106
  contextCss: typeof options.generatedSource === "string" ? options.generatedSource : void 0
7990
8107
  });
7991
8108
  const { css } = await options.styleHandler(userSource, {
@@ -8983,6 +9100,27 @@ async function processFrameworkCss(css, options) {
8983
9100
  });
8984
9101
  }
8985
9102
  //#endregion
9103
+ //#region src/plugins/applyConfiguredCssUnits.ts
9104
+ /** 在跨资产 calc 求值之后按原管线顺序转换单位,不重复选择器和框架兼容变换。 */
9105
+ async function applyConfiguredCssUnits(css, options = {}) {
9106
+ const resolved = {
9107
+ ...options,
9108
+ platform: options.cssOptions?.platform ?? options.platform,
9109
+ rem2rpx: options.cssOptions?.rem2rpx ?? options.rem2rpx,
9110
+ px2rpx: options.cssOptions?.px2rpx ?? options.px2rpx,
9111
+ unitsToPx: options.cssOptions?.unitsToPx ?? options.unitsToPx,
9112
+ unitConversion: options.cssOptions?.unitConversion ?? options.unitConversion
9113
+ };
9114
+ const plugins = [
9115
+ getUnitsToPxPlugin(resolved),
9116
+ getPxTransformPlugin(resolved),
9117
+ getRemTransformPlugin(resolved),
9118
+ getUnitConversionPlugin(resolved)
9119
+ ].filter((plugin) => plugin !== null);
9120
+ if (plugins.length === 0) return css;
9121
+ return (await postcss$1(plugins).process(css, { from: options.postcssOptions?.options?.from })).css;
9122
+ }
9123
+ //#endregion
8986
9124
  //#region src/source-scan/tailwind-v4/entry-source.ts
8987
9125
  function collectSourceDirectives(root) {
8988
9126
  const descriptor = describeCssSources(root, isTailwindV4CssImportParam);
@@ -9236,4 +9374,21 @@ function annotateCssTokenSources(css, tokenSources) {
9236
9374
  }
9237
9375
  }
9238
9376
  //#endregion
9239
- export { CSS_MACRO_STYLE_OPTIONS_MARKER, GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE, GENERATOR_PLACEHOLDER_MARKER_RE, TAILWIND_BANNER_GLOBAL_RE, TAILWIND_BANNER_PREFIX_RE, TAILWIND_BANNER_RE, TAILWIND_GENERATED_CSS_MARKER_RE, TAILWIND_V4_BANNER_RE, TAILWIND_V4_GENERATOR_AT_RULES, UNI_APP_X_BORDER_PREFLIGHT_CLASS, UNI_APP_X_IMPORTANT_APPLY_MARKER, VITE_MARKER_RE, analyzeTailwindV4EntrySource, analyzeTailwindV4Source, annotateCssTokenSources, applyConfiguredCssCalc, canProcessSourceStyleAsCss, cleanLocalCssImportWrapperTailwindDirectives, cleanLocalCssImportWrapperTailwindDirectivesRoot, collectApplyOnlySourceSelectors, collectBareSelectorUserCss, collectCssApplyCandidates, collectCssApplyUtilities, collectCssImportRequestsRoot, collectCssReferenceDirectives, collectCustomPropertyValues, collectDedupedPostTransformCompatCss, collectGeneratedCssClassCandidates, collectGeneratedSelectors, collectGeneratorCssCandidates, collectImportedCssFiles, collectRawSourceClassSelectors, collectRootScopedComparableCssCoverage, collectRpxThemeVariables, collectRuntimeApplyCandidates, collectWebpackAssetUserCssMarkers, collectWebpackBareSelectorUserCss, collectWebpackCssRuleIdentityMarkers, compileCssMacroConditionalComments, compileTailwindAuthorFunctions, composeFrameworkProcessedCss, composeProcessedCssSources, containsCssAfterMinify, convertTailwindcssRpxDeclarationToRem, convertTailwindcssRpxDeclarationsToRem, convertTailwindcssRpxValueToRem, createAuthorSelectorMatcher, createBundlerGeneratedCssEndMarker, createBundlerGeneratedCssMarker, createCssAppend, createCssRuleMatcher, createCssSourceOrderAppend, createFallbackPlaceholderReplacer, createGeneratedThemeDeclarationResolver, createPostcssStyleTargetProfile, createStyleHandler, createStylePipeline, createTailwindAuthorFunctionProbe, createTailwindV4SourceReferenceSource, createUniAppXBorderPreflight, createUniAppXHarmonyApplyCssExpander, createUniAppXHarmonyApplyGeneratorSource, cssToClassStyleValue, dedupeCoveredCssRules, dedupeMiniProgramPreflightSelectorRules, deduplicateGeneratedCssRules, ensureWebpackMiniProgramTwContentInit, expandCssApplySourcesToStyleValue, extractConfigRequestFromSource, extractGeneratedCssForUserLayerSelectors, extractMarkedUserLayerComponentsCss, extractTailwindDirectiveLines, extractTailwindSourceForPostcssFallback, filterExistingCssRules, filterTailwindV4ApplyOnlyGeneratedCss, finalizeMiniProgramCssStructure, getPostcssPluginName, hasAdditionalWebpackAssetUserCssMarkers, hasBundlerGeneratedCssMarker, hasCssMacroStyleOptions, hasCssMacroTailwindV4CustomVariantConditionalComments, hasCssMacroTailwindV4Directive, hasCssMacroTailwindV4InternalAtRules, hasCssMacroTailwindV4Source, hasEmptyCssBlockCandidate, hasLocalCssImport, hasMiniProgramPreflightSelector, hasNonCommentCss, hasOnlyApplyBackedSourceRules, hasScopedMiniProgramTailwindContentInitRule, hasScopedUniAppWebTailwindPreflightRule, hasTailwindApplyContextDirective, hasTailwindApplyDirective, hasTailwindGeneratedCss, hasTailwindGeneratedCssMarkers, hasTailwindNonRootGenerationDirectives, hasTailwindRootDirectives, hasTailwindRootImportDirectives, hasTailwindSourceDirectives, hasUnscopedMiniProgramTailwindPreflightRule, hasUserCssLayerBlocks, hasVueScopedAttr, hasWebpackTailwindSourceDirectives, hoistUniAppXBorderPreflight, includesTailwindV4PreflightDirective, inheritLegacyUnitConvertedDeclarations, injectTailwindDirectives, insertTailwindThemeCss, inspectRpxCalcUsage, isCommentOnlyCss, isCssAlreadyRepresentedByMarkers, isCssImportOnly, isEmptyCustomVariantBlock, isLikelyTailwindGlobalRule, isLikelyTailwindLayerOrderAtRule, isLikelyTailwindPropertyAtRule, isLocalCssImportRequest, isMiniProgramLocalCssImportRequest, isOnlyWebpackTailwindGeneratedPreflightCss, isPureLocalCssImportWrapper, isPureLocalCssImportWrapperRoot, isRuleCoveredByRootCss, isScopedMiniProgramTailwindContentInitRule, isScopedUniAppWebTailwindPreflightRule, isScopedUniversalTailwindPreflightRule, isStyleImportRequest, isTailwindRuntimePropertyRule, isTailwindV4CssImportParam, isTailwindV4PreflightImportParam, isUnscopedMiniProgramTailwindPreflightRule, isWebpackCssSourceRepresentedInAsset, isWebpackTailwindImportRequest, mergeCoveredCssRuleDeclarations, mergeCustomPropertyValues$1 as mergeCustomPropertyValues, mergeMarkedUserLayerComponentsCss, mergeMiniProgramPreflightRuleDeclarations, mergeMiniProgramThemeScopeRuleDeclarations, normalizeCompatSelectors, normalizeCssClassSelector, normalizeCssSignatureValue, normalizeEmptyTailwindCustomVariants, normalizeFrameworkProcessedUserCss, normalizeInjectableCssWithImports, normalizeLegacyCompatCssSource, normalizeMiniProgramGeneratedCssForPostcss, normalizeMiniProgramGeneratorCssSource, normalizeMiniProgramImportShell, normalizeOutputImportRequest, normalizeRpxLengthCandidates, normalizeTailwindConfigDirectives, normalizeTailwindSourceDirectives, normalizeTailwindSourceForGenerator, normalizeTailwindV4GeneratedUrlValues, normalizeTailwindV4RuntimeCss, normalizeTailwindcssRpxDeclaration, normalizeTailwindcssRpxDeclarations, normalizeTailwindcssV4InfinityRadiusCss, normalizeTailwindcssWebRpxDeclarations, normalizeUniAppXImportantApplyForSass, normalizeUniAppXStyleProperty, normalizeUniAppXStyleValue, normalizeWebpackUserCssFallbackSource, parseBundlerGeneratedCssMarkerBlocks, parseImportRequest$1 as parseImportRequest, parseWebpackCssLayerNames, preferScopedGeneratedCssRules, preferScopedGeneratedCssRulesRoot, prefixLocalCssImportsWithWebpackIgnoreRoot, processFrameworkCss, pruneMiniProgramGeneratedCss, removeBalancedAtRuleBlock, removeCommentOnlyAtRules, removeCssComments, removeCssCoveredByRootStyleSources, removeCssRulesCoveredBySources, removeDuplicatedViteMarkers, removeGeneratedSelectorCompatCss, removeMatchingLocalCssImports, removeMatchingLocalCssImportsRoot, removeMiniProgramContainerCompatCss, removeMiniProgramHoverSelectors, removeMiniProgramInteractiveSelectors, removeMiniProgramOutputImports, removeMiniProgramPreflightSelectorRule, removeProcessedMiniProgramUnsupportedCss, removeScopedTailwindPreflightCss, removeSelfMiniProgramOutputImports, removeTailwindApplyAtRules, removeTailwindApplyRules, removeTailwindEntryDirectivesFromCss, removeTailwindGeneratedCssByBanner, removeTailwindPostcssPlugins, removeTailwindSourceDirectives, removeTailwindSourceDirectivesRoot, removeTailwindSourceMediaBlocks, removeTailwindV4GeneratedUserCssArtifacts, removeTailwindV4GeneratorAtRules, removeTailwindV4GeneratorAtRulesFallback, removeTailwindV4PreflightImports, removeTailwindV4StandaloneHostPreflightRule, removeUnsupportedMiniProgramCssImportsRoot, removeUnsupportedThemeVendorKeyframes, removeUnusedMiniProgramContentInit, removeWebpackGeneratorNonTailwindImports, removeWebpackTailwindGeneratedAssetCss, removeWebpackUserCssFallbackImports, reorderMarkedUserLayerComponentsCss, replaceViteGeneratedCssModule, resolveCssEntrySource, resolveFilteredPostcssConfig, resolvePostcssConfig, resolvePostcssFrameworkProfile, resolvePostcssFrameworkStrategy, resolvePostcssStyleBranch, resolvePostcssStyleBranchProfile, resolvePostcssStyleTarget, restoreLocalCssImports, restoreProcessedCssImports, restoreRpxLengthCandidates, restoreRpxLengthCssSelectors, restoreUniAppXImportantApplyMarker, retainUniAppXAuthorApplyCss, rewriteLocalCssImportRequestsForOutput, rewriteLocalCssImportRequestsForOutputRoot, rewriteTailwindPackageImportStatements, rewriteUniAppXStyleReferences, selectorContainsPseudoClass, splitGeneratorPlaceholderCssBySourceOrder, splitLocalCssImports, splitLocalCssImportsRoot, splitTailwindGeneratedCssByBanner, splitTailwindV4GeneratedCss, splitTailwindV4GeneratedCssBySourceOrder, splitUserCssLayerBlocks, stripBundlerGeneratedCssMarkers, stripGeneratorPlaceholderMarkers, stripTailwindBanner, stripTailwindBannerComments, stripTailwindBanners, stripTailwindSourceMediaFragments, stripTrailingLineWhitespace, stripUnmatchedTailwindSourceMediaCloseFragments, terminateTailwindSourceAtRulesBeforeNextDirective, transformCssMacroCss, transformCssMacroTailwindV4Source, transformGeneratorUserCss, transformTailwindV4CssToWeapp, transformTailwindV4GeneratedCss, transformTailwindV4WebRpxCss, unescapeCssIdentifier, unitConversionComposeRules, unitConversionPresets, unwrapMiniProgramCascadeLayers, withCssMacroStyleOptions, wrapUserLayerComponentsCss };
9377
+ //#region src/utils/custom-property-values.ts
9378
+ /** 按声明顺序收集构建期上下文,不推断级联或运行时作用域。 */
9379
+ function collectCustomPropertyValues(css) {
9380
+ const values = /* @__PURE__ */ new Map();
9381
+ mergeCustomPropertyValues(values, css);
9382
+ return values;
9383
+ }
9384
+ /** 直接合并到调用方上下文,避免中间 Map;后出现的声明覆盖旧值。 */
9385
+ function mergeCustomPropertyValues(target, css) {
9386
+ if (!css.includes("--")) return;
9387
+ try {
9388
+ postcss.parse(css).walkDecls((decl) => {
9389
+ if (decl.prop.startsWith("--")) target.set(decl.prop, decl.value.trim());
9390
+ });
9391
+ } catch {}
9392
+ }
9393
+ //#endregion
9394
+ export { CSS_MACRO_STYLE_OPTIONS_MARKER, GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE, GENERATOR_PLACEHOLDER_MARKER_RE, TAILWIND_BANNER_GLOBAL_RE, TAILWIND_BANNER_PREFIX_RE, TAILWIND_BANNER_RE, TAILWIND_GENERATED_CSS_MARKER_RE, TAILWIND_V4_BANNER_RE, TAILWIND_V4_GENERATOR_AT_RULES, UNI_APP_X_BORDER_PREFLIGHT_CLASS, UNI_APP_X_IMPORTANT_APPLY_MARKER, VITE_MARKER_RE, analyzeCssCalcContext, analyzeTailwindV4EntrySource, analyzeTailwindV4Source, annotateCssTokenSources, applyConfiguredCssCalc, applyConfiguredCssUnits, canProcessSourceStyleAsCss, cleanLocalCssImportWrapperTailwindDirectives, cleanLocalCssImportWrapperTailwindDirectivesRoot, collectApplyOnlySourceSelectors, collectBareSelectorUserCss, collectCssApplyCandidates, collectCssApplyUtilities, collectCssImportRequestsRoot, collectCssReferenceDirectives, collectCustomPropertyValues, collectDedupedPostTransformCompatCss, collectGeneratedCssClassCandidates, collectGeneratedSelectors, collectGeneratorCssCandidates, collectImportedCssFiles, collectRawSourceClassSelectors, collectRootScopedComparableCssCoverage, collectRpxThemeVariables, collectRuntimeApplyCandidates, collectWebpackAssetUserCssMarkers, collectWebpackBareSelectorUserCss, collectWebpackCssRuleIdentityMarkers, compileCssMacroConditionalComments, compileTailwindAuthorFunctions, composeFrameworkProcessedCss, composeProcessedCssSources, containsCssAfterMinify, convertTailwindcssRpxDeclarationToRem, convertTailwindcssRpxDeclarationsToRem, convertTailwindcssRpxValueToRem, createAuthorSelectorMatcher, createBundlerGeneratedCssEndMarker, createBundlerGeneratedCssMarker, createCssAppend, createCssRuleMatcher, createCssSourceOrderAppend, createFallbackPlaceholderReplacer, createGeneratedThemeDeclarationResolver, createPostcssStyleTargetProfile, createStyleHandler, createStylePipeline, createTailwindAuthorFunctionProbe, createTailwindV4SourceReferenceSource, createUniAppXBorderPreflight, createUniAppXHarmonyApplyCssExpander, createUniAppXHarmonyApplyGeneratorSource, cssToClassStyleValue, dedupeCoveredCssRules, dedupeMiniProgramPreflightSelectorRules, deduplicateGeneratedCssRules, ensureWebpackMiniProgramTwContentInit, expandCssApplySourcesToStyleValue, extractConfigRequestFromSource, extractGeneratedCssForUserLayerSelectors, extractMarkedUserLayerComponentsCss, extractTailwindDirectiveLines, extractTailwindSourceForPostcssFallback, filterExistingCssRules, filterTailwindV4ApplyOnlyGeneratedCss, finalizeMiniProgramCssStructure, getPostcssPluginName, hasAdditionalWebpackAssetUserCssMarkers, hasBundlerGeneratedCssMarker, hasCssMacroStyleOptions, hasCssMacroTailwindV4CustomVariantConditionalComments, hasCssMacroTailwindV4Directive, hasCssMacroTailwindV4InternalAtRules, hasCssMacroTailwindV4Source, hasEmptyCssBlockCandidate, hasLocalCssImport, hasMiniProgramPreflightSelector, hasNonCommentCss, hasOnlyApplyBackedSourceRules, hasScopedMiniProgramTailwindContentInitRule, hasScopedUniAppWebTailwindPreflightRule, hasTailwindApplyContextDirective, hasTailwindApplyDirective, hasTailwindGeneratedCss, hasTailwindGeneratedCssMarkers, hasTailwindNonRootGenerationDirectives, hasTailwindRootDirectives, hasTailwindRootImportDirectives, hasTailwindSourceDirectives, hasUnscopedMiniProgramTailwindPreflightRule, hasUserCssLayerBlocks, hasVueScopedAttr, hasWebpackTailwindSourceDirectives, hoistUniAppXBorderPreflight, includesTailwindV4PreflightDirective, inheritLegacyUnitConvertedDeclarations, injectTailwindDirectives, insertTailwindThemeCss, inspectRpxCalcUsage, isCommentOnlyCss, isCssAlreadyRepresentedByMarkers, isCssCalcCustomPropertySelected, isCssImportOnly, isEmptyCustomVariantBlock, isLikelyTailwindGlobalRule, isLikelyTailwindLayerOrderAtRule, isLikelyTailwindPropertyAtRule, isLocalCssImportRequest, isMiniProgramLocalCssImportRequest, isOnlyWebpackTailwindGeneratedPreflightCss, isPureLocalCssImportWrapper, isPureLocalCssImportWrapperRoot, isRuleCoveredByRootCss, isScopedMiniProgramTailwindContentInitRule, isScopedUniAppWebTailwindPreflightRule, isScopedUniversalTailwindPreflightRule, isStyleImportRequest, isTailwindRuntimePropertyRule, isTailwindV4CssImportParam, isTailwindV4PreflightImportParam, isUnscopedMiniProgramTailwindPreflightRule, isWebpackCssSourceRepresentedInAsset, isWebpackTailwindImportRequest, mergeCoveredCssRuleDeclarations, mergeCustomPropertyValues, mergeMarkedUserLayerComponentsCss, mergeMiniProgramPreflightRuleDeclarations, mergeMiniProgramThemeScopeRuleDeclarations, normalizeCompatSelectors, normalizeCssClassSelector, normalizeCssSignatureValue, normalizeEmptyTailwindCustomVariants, normalizeFrameworkProcessedUserCss, normalizeInjectableCssWithImports, normalizeLegacyCompatCssSource, normalizeMiniProgramGeneratedCssForPostcss, normalizeMiniProgramGeneratorCssSource, normalizeMiniProgramImportShell, normalizeOutputImportRequest, normalizeRpxLengthCandidates, normalizeTailwindConfigDirectives, normalizeTailwindSourceDirectives, normalizeTailwindSourceForGenerator, normalizeTailwindV4GeneratedUrlValues, normalizeTailwindV4RuntimeCss, normalizeTailwindcssRpxDeclaration, normalizeTailwindcssRpxDeclarations, normalizeTailwindcssV4InfinityRadiusCss, normalizeTailwindcssWebRpxDeclarations, normalizeUniAppXImportantApplyForSass, normalizeUniAppXStyleProperty, normalizeUniAppXStyleValue, normalizeWebpackUserCssFallbackSource, parseBundlerGeneratedCssMarkerBlocks, parseImportRequest$1 as parseImportRequest, parseWebpackCssLayerNames, preferScopedGeneratedCssRules, preferScopedGeneratedCssRulesRoot, prefixLocalCssImportsWithWebpackIgnoreRoot, processFrameworkCss, pruneMiniProgramGeneratedCss, removeBalancedAtRuleBlock, removeCommentOnlyAtRules, removeCssComments, removeCssCoveredByRootStyleSources, removeCssRulesCoveredBySources, removeDuplicatedViteMarkers, removeGeneratedSelectorCompatCss, removeMatchingLocalCssImports, removeMatchingLocalCssImportsRoot, removeMiniProgramContainerCompatCss, removeMiniProgramHoverSelectors, removeMiniProgramInteractiveSelectors, removeMiniProgramOutputImports, removeMiniProgramPreflightSelectorRule, removeProcessedMiniProgramUnsupportedCss, removeScopedTailwindPreflightCss, removeSelfMiniProgramOutputImports, removeTailwindApplyAtRules, removeTailwindApplyRules, removeTailwindEntryDirectivesFromCss, removeTailwindGeneratedCssByBanner, removeTailwindPostcssPlugins, removeTailwindSourceDirectives, removeTailwindSourceDirectivesRoot, removeTailwindSourceMediaBlocks, removeTailwindV4GeneratedUserCssArtifacts, removeTailwindV4GeneratorAtRules, removeTailwindV4GeneratorAtRulesFallback, removeTailwindV4PreflightImports, removeTailwindV4StandaloneHostPreflightRule, removeUnsupportedMiniProgramCssImportsRoot, removeUnsupportedThemeVendorKeyframes, removeUnusedMiniProgramContentInit, removeWebpackGeneratorNonTailwindImports, removeWebpackTailwindGeneratedAssetCss, removeWebpackUserCssFallbackImports, reorderMarkedUserLayerComponentsCss, replaceViteGeneratedCssModule, resolveCssEntrySource, resolveFilteredPostcssConfig, resolvePostcssConfig, resolvePostcssFrameworkProfile, resolvePostcssFrameworkStrategy, resolvePostcssStyleBranch, resolvePostcssStyleBranchProfile, resolvePostcssStyleTarget, restoreLocalCssImports, restoreProcessedCssImports, restoreRpxLengthCandidates, restoreRpxLengthCssSelectors, restoreUniAppXImportantApplyMarker, retainUniAppXAuthorApplyCss, rewriteLocalCssImportRequestsForOutput, rewriteLocalCssImportRequestsForOutputRoot, rewriteTailwindPackageImportStatements, rewriteUniAppXStyleReferences, selectorContainsPseudoClass, splitGeneratorPlaceholderCssBySourceOrder, splitLocalCssImports, splitLocalCssImportsRoot, splitTailwindGeneratedCssByBanner, splitTailwindV4GeneratedCss, splitTailwindV4GeneratedCssBySourceOrder, splitUserCssLayerBlocks, stripBundlerGeneratedCssMarkers, stripGeneratorPlaceholderMarkers, stripTailwindBanner, stripTailwindBannerComments, stripTailwindBanners, stripTailwindSourceMediaFragments, stripTrailingLineWhitespace, stripUnmatchedTailwindSourceMediaCloseFragments, terminateTailwindSourceAtRulesBeforeNextDirective, transformCssMacroCss, transformCssMacroTailwindV4Source, transformGeneratorUserCss, transformTailwindV4CssToWeapp, transformTailwindV4GeneratedCss, transformTailwindV4WebRpxCss, unescapeCssIdentifier, unitConversionComposeRules, unitConversionPresets, unwrapMiniProgramCascadeLayers, withCssMacroStyleOptions, wrapUserLayerComponentsCss };