weapp-tailwindcss 5.0.0-next.3 → 5.0.0-next.30

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 (243) hide show
  1. package/README.md +6 -7
  2. package/bin/weapp-tailwindcss.js +1 -21
  3. package/dist/auto-TH1jG2UW.js +115 -0
  4. package/dist/auto-XyKTOP7B.mjs +78 -0
  5. package/dist/bundle-state-Bi-cQua6.mjs +413 -0
  6. package/dist/bundle-state-Ct_8GcSR.js +529 -0
  7. package/dist/bundlers/shared/cache.d.ts +6 -6
  8. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +1 -0
  9. package/dist/bundlers/shared/css-cleanup.d.ts +1 -4
  10. package/dist/bundlers/shared/css-imports.d.ts +3 -3
  11. package/dist/bundlers/shared/generated-css-marker.d.ts +3 -0
  12. package/dist/bundlers/shared/generator-css/config-directive.d.ts +2 -0
  13. package/dist/bundlers/shared/generator-css/directives.d.ts +20 -0
  14. package/dist/bundlers/shared/generator-css/legacy-compat.d.ts +7 -0
  15. package/dist/bundlers/shared/generator-css/legacy-selectors.d.ts +5 -0
  16. package/dist/bundlers/shared/generator-css/legacy-units.d.ts +1 -0
  17. package/dist/bundlers/shared/generator-css/markers.d.ts +28 -0
  18. package/dist/bundlers/shared/generator-css/source-files.d.ts +14 -0
  19. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +24 -0
  20. package/dist/bundlers/shared/generator-css.d.ts +16 -22
  21. package/dist/bundlers/shared/hmr-timing.d.ts +22 -0
  22. package/dist/bundlers/shared/style-requests.d.ts +2 -0
  23. package/dist/bundlers/vite/bundle-state.d.ts +1 -0
  24. package/dist/bundlers/vite/css-finalizer.d.ts +7 -1
  25. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +2 -0
  26. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +24 -0
  27. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +4 -0
  28. package/dist/bundlers/vite/generate-bundle/dirty-state.d.ts +1 -0
  29. package/dist/bundlers/vite/generate-bundle/js-entries.d.ts +2 -0
  30. package/dist/bundlers/vite/generate-bundle/js-handler-options.d.ts +8 -0
  31. package/dist/bundlers/vite/generate-bundle/js-linking.d.ts +13 -0
  32. package/dist/bundlers/vite/generate-bundle/metrics.d.ts +17 -0
  33. package/dist/bundlers/vite/generate-bundle/process-plan.d.ts +9 -0
  34. package/dist/bundlers/vite/generate-bundle/rollup-assets.d.ts +7 -0
  35. package/dist/bundlers/vite/generate-bundle/signatures.d.ts +8 -0
  36. package/dist/bundlers/vite/generate-bundle.d.ts +14 -2
  37. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +5 -1
  38. package/dist/bundlers/vite/index.d.ts +5 -2
  39. package/dist/bundlers/vite/official-tailwind-plugins.d.ts +5 -0
  40. package/dist/bundlers/vite/postcss-config.d.ts +6 -0
  41. package/dist/bundlers/vite/processed-css-assets.d.ts +32 -0
  42. package/dist/bundlers/vite/rewrite-css-imports.d.ts +8 -3
  43. package/dist/bundlers/vite/runtime-class-set.d.ts +25 -0
  44. package/dist/bundlers/vite/serve-css-generation.d.ts +11 -0
  45. package/dist/bundlers/vite/source-candidates.d.ts +19 -1
  46. package/dist/bundlers/vite/source-scan.d.ts +26 -0
  47. package/dist/bundlers/vite/static-config-content.d.ts +5 -0
  48. package/dist/bundlers/vite/tailwind-basedir.d.ts +1 -0
  49. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +6 -0
  50. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +6 -2
  51. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +9 -3
  52. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +2 -1
  53. package/dist/bundlers/webpack/loaders/runtime-registry.d.ts +31 -0
  54. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +2 -6
  55. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +3 -7
  56. package/dist/cache/index.d.ts +6 -6
  57. package/dist/{chunk-8l464Juk.js → chunk-C5U5_Hdc.js} +14 -0
  58. package/dist/cli/context.d.ts +1 -14
  59. package/dist/cli/doctor/types.d.ts +11 -11
  60. package/dist/cli/helpers.d.ts +1 -2
  61. package/dist/cli/mount-options.d.ts +2 -0
  62. package/dist/cli/types.d.ts +0 -2
  63. package/dist/cli/vscode-entry.d.ts +3 -3
  64. package/dist/cli.js +758 -604
  65. package/dist/cli.mjs +766 -612
  66. package/dist/constants.d.ts +1 -2
  67. package/dist/context/runtime-package-replacements.d.ts +2 -0
  68. package/dist/context/style-options.d.ts +3 -0
  69. package/dist/core.js +12 -20
  70. package/dist/core.mjs +8 -14
  71. package/dist/css-macro/auto.d.ts +10 -0
  72. package/dist/css-macro/constants.d.ts +5 -2
  73. package/dist/css-macro/postcss.d.ts +1 -0
  74. package/dist/css-macro/postcss.js +7 -46
  75. package/dist/css-macro/postcss.mjs +2 -46
  76. package/dist/css-macro.d.ts +1 -0
  77. package/dist/css-macro.js +16 -7
  78. package/dist/css-macro.mjs +15 -6
  79. package/dist/defaults-8xrgzxFY.mjs +151 -0
  80. package/dist/defaults-zKUH2mDe.js +193 -0
  81. package/dist/defaults.d.ts +15 -1
  82. package/dist/defaults.js +6 -131
  83. package/dist/defaults.mjs +2 -129
  84. package/dist/escape.js +10 -2
  85. package/dist/escape.mjs +10 -2
  86. package/dist/generator/index.d.ts +1 -1
  87. package/dist/generator/options.d.ts +9 -8
  88. package/dist/generator/types.d.ts +3 -3
  89. package/dist/generator-CrU-Ghc1.js +90 -0
  90. package/dist/generator-Qw-tZ0Z2.mjs +65 -0
  91. package/dist/generator.js +12 -12
  92. package/dist/generator.mjs +2 -1
  93. package/dist/gulp.js +187 -48
  94. package/dist/gulp.mjs +180 -41
  95. package/dist/incremental-runtime-class-set-BdZHkoTs.mjs +1975 -0
  96. package/dist/incremental-runtime-class-set-BxvZONkv.js +2038 -0
  97. package/dist/index.d.ts +3 -2
  98. package/dist/index.js +19 -7
  99. package/dist/index.mjs +6 -5
  100. package/dist/js/babel/cache-options.d.ts +3 -0
  101. package/dist/js/babel/parse.d.ts +7 -4
  102. package/dist/js/index.d.ts +1 -0
  103. package/dist/js/literal-transform.d.ts +2 -0
  104. package/dist/js/precheck.d.ts +2 -2
  105. package/dist/logger-BNzxZbZj.mjs +2 -0
  106. package/dist/logger-TlKT3xmR.js +1 -0
  107. package/dist/postcss/config-directive.d.ts +1 -0
  108. package/dist/postcss/context.d.ts +9 -0
  109. package/dist/postcss/source-files.d.ts +8 -0
  110. package/dist/postcss/tailwind-version.d.ts +3 -0
  111. package/dist/postcss-C6zOQqlL.mjs +228 -0
  112. package/dist/postcss-C7BMYpEF.mjs +169 -0
  113. package/dist/postcss-CiYLsqZn.js +192 -0
  114. package/dist/postcss-DAWf9D3C.js +237 -0
  115. package/dist/postcss-html-transform.js +1 -1
  116. package/dist/postcss.d.ts +2 -2
  117. package/dist/postcss.js +3 -276
  118. package/dist/postcss.mjs +1 -269
  119. package/dist/precheck-D7K12zeX.mjs +4716 -0
  120. package/dist/precheck-D7gJSmJz.js +4842 -0
  121. package/dist/presets/index.d.ts +1 -0
  122. package/dist/presets/uni-app-x.d.ts +1 -0
  123. package/dist/presets.js +29 -13
  124. package/dist/presets.mjs +25 -11
  125. package/dist/reset.d.ts +1 -0
  126. package/dist/reset.js +1 -1
  127. package/dist/runtime-registry-DpcR3IHI.js +5496 -0
  128. package/dist/shared/mpx.d.ts +1 -0
  129. package/dist/source-candidates-CX2ozpKM.mjs +322 -0
  130. package/dist/source-candidates-DNM8iwXW.js +335 -0
  131. package/dist/tailwindcss/miniprogram.d.ts +1 -1
  132. package/dist/tailwindcss/patcher-options.d.ts +3 -51
  133. package/dist/tailwindcss/patcher.d.ts +1 -2
  134. package/dist/tailwindcss/remove-unsupported-css.d.ts +1 -2
  135. package/dist/tailwindcss/runtime/cache.d.ts +4 -3
  136. package/dist/tailwindcss/runtime-patch.d.ts +5 -0
  137. package/dist/tailwindcss/runtime.d.ts +11 -12
  138. package/dist/tailwindcss/source-scan.d.ts +35 -0
  139. package/dist/tailwindcss/targets.d.ts +1 -5
  140. package/dist/tailwindcss/v3-engine/types.d.ts +17 -14
  141. package/dist/tailwindcss/v4/css-entries.d.ts +2 -2
  142. package/dist/tailwindcss/v4/css-sources.d.ts +5 -0
  143. package/dist/tailwindcss/v4/patcher-options.d.ts +1 -23
  144. package/dist/tailwindcss/v4/patcher.d.ts +1 -0
  145. package/dist/tailwindcss/v4-engine/source.d.ts +2 -2
  146. package/dist/tailwindcss/v4-engine/types.d.ts +17 -5
  147. package/dist/tailwindcss/version.d.ts +4 -0
  148. package/dist/tailwindcss-B-e2RiXr.js +642 -0
  149. package/dist/tailwindcss-C7dJHZ0G.mjs +591 -0
  150. package/dist/typedoc.export.d.ts +0 -2
  151. package/dist/types/index.d.ts +52 -49
  152. package/dist/types/shared.d.ts +6 -0
  153. package/dist/types/user-defined-options/general.d.ts +25 -24
  154. package/dist/types/user-defined-options/important.d.ts +33 -28
  155. package/dist/types/user-defined-options/lifecycle.d.ts +4 -4
  156. package/dist/types/user-defined-options/matcher.d.ts +6 -6
  157. package/dist/uni-app-x/vite.d.ts +1 -1
  158. package/dist/unocss/index.d.ts +2 -0
  159. package/dist/utils/disabled.d.ts +2 -3
  160. package/dist/utils/object.d.ts +9 -0
  161. package/dist/utils/options.d.ts +2 -0
  162. package/dist/utils/regex.d.ts +1 -0
  163. package/dist/{utils-DmC9_In3.js → utils-D7Ygohep.js} +2 -2
  164. package/dist/{utils-7DUGTFED.mjs → utils-DsaS975I.mjs} +1 -1
  165. package/dist/v3-engine-CHItlVq5.js +3616 -0
  166. package/dist/v3-engine-DcvCCHfs.mjs +3321 -0
  167. package/dist/vite-C65DdWEj.js +24439 -0
  168. package/dist/vite-rmL1rsA_.mjs +24425 -0
  169. package/dist/vite.d.ts +1 -2
  170. package/dist/vite.js +3 -4
  171. package/dist/vite.mjs +2 -2
  172. package/dist/weapp-tw-css-import-rewrite-loader.js +5032 -18
  173. package/dist/weapp-tw-runtime-classset-loader.js +32 -9
  174. package/dist/webpack-BU2Er4qg.mjs +841 -0
  175. package/dist/webpack-CqGvjvSQ.js +851 -0
  176. package/dist/webpack.d.ts +1 -3
  177. package/dist/webpack.js +3 -4
  178. package/dist/webpack.mjs +2 -2
  179. package/package.json +38 -48
  180. package/dist/bundlers/shared/generator-candidates.d.ts +0 -5
  181. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-assets.d.ts +0 -14
  182. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-loaders.d.ts +0 -15
  183. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4.d.ts +0 -9
  184. package/dist/bundlers/webpack/shared/css-imports.d.ts +0 -6
  185. package/dist/cli/config.d.ts +0 -5
  186. package/dist/cli/helpers/patch-cwd.d.ts +0 -1
  187. package/dist/cli/mount-options/patch-status.d.ts +0 -2
  188. package/dist/cli/patch-options.d.ts +0 -6
  189. package/dist/cli/tokens.d.ts +0 -4
  190. package/dist/cli/workspace/package-dirs.d.ts +0 -3
  191. package/dist/cli/workspace/patch-package.d.ts +0 -3
  192. package/dist/cli/workspace/patch-utils.d.ts +0 -3
  193. package/dist/cli/workspace/types.d.ts +0 -11
  194. package/dist/cli/workspace/workspace-globs.d.ts +0 -2
  195. package/dist/cli/workspace/workspace-io.d.ts +0 -1
  196. package/dist/cli/workspace/workspace-lock.d.ts +0 -1
  197. package/dist/cli/workspace.d.ts +0 -2
  198. package/dist/constants-B-_T5UnW.mjs +0 -44
  199. package/dist/constants-p1dyh1x1.js +0 -73
  200. package/dist/css-imports-BbrbluP9.js +0 -177
  201. package/dist/css-imports-CSdPq_Sc.mjs +0 -128
  202. package/dist/experimental/index.d.ts +0 -2
  203. package/dist/experimental/oxc/ast-utils.d.ts +0 -30
  204. package/dist/experimental/oxc/index.d.ts +0 -2
  205. package/dist/experimental/oxc/module-specifiers.d.ts +0 -2
  206. package/dist/experimental/shared/cache.d.ts +0 -3
  207. package/dist/experimental/shared/transform.d.ts +0 -3
  208. package/dist/experimental/shared.d.ts +0 -8
  209. package/dist/experimental/swc/ast-utils.d.ts +0 -30
  210. package/dist/experimental/swc/index.d.ts +0 -2
  211. package/dist/experimental/swc/module-specifiers.d.ts +0 -2
  212. package/dist/generator-Y-Ikv4Fu.mjs +0 -1177
  213. package/dist/generator-css-Bwy_Uz89.mjs +0 -1097
  214. package/dist/generator-css-CRLrHW4F.js +0 -1124
  215. package/dist/generator-mmhXzZnv.js +0 -1276
  216. package/dist/js/syntax.d.ts +0 -10
  217. package/dist/lightningcss/index.d.ts +0 -8
  218. package/dist/lightningcss/style-handler/options.d.ts +0 -3
  219. package/dist/lightningcss/style-handler/selector-transform.d.ts +0 -10
  220. package/dist/lightningcss/style-handler/selector-utils.d.ts +0 -10
  221. package/dist/lightningcss/style-handler.d.ts +0 -17
  222. package/dist/loader-anchors-1MumTAtA.mjs +0 -205
  223. package/dist/loader-anchors-TrFvT6g1.js +0 -273
  224. package/dist/logger-BZ45DZJT.js +0 -1003
  225. package/dist/logger-BoVx1Dbt.mjs +0 -935
  226. package/dist/patcher-options-6gJN2EXy.js +0 -115
  227. package/dist/patcher-options-DQfR5xxT.mjs +0 -92
  228. package/dist/recorder-GdTJ3QqX.js +0 -2878
  229. package/dist/recorder-XdFvVASS.mjs +0 -2763
  230. package/dist/tailwindcss/recorder.d.ts +0 -13
  231. package/dist/tailwindcss/targets/paths.d.ts +0 -13
  232. package/dist/tailwindcss/targets/record-io.d.ts +0 -5
  233. package/dist/tailwindcss/targets/recorder.d.ts +0 -3
  234. package/dist/tailwindcss/targets/types.d.ts +0 -35
  235. package/dist/types/disabled-options.d.ts +0 -4
  236. package/dist/vite-BDywuCjn.mjs +0 -2186
  237. package/dist/vite-DgRh_GXn.js +0 -2199
  238. package/dist/webpack-CAJR4hhP.js +0 -456
  239. package/dist/webpack-CiHqVZTg.mjs +0 -441
  240. package/dist/webpack4.d.ts +0 -4
  241. package/dist/webpack4.js +0 -387
  242. package/dist/webpack4.mjs +0 -379
  243. package/scripts/postinstall.mjs +0 -59
@@ -0,0 +1,2038 @@
1
+ const require_chunk = require("./chunk-C5U5_Hdc.js");
2
+ const require_v3_engine = require("./v3-engine-CHItlVq5.js");
3
+ const require_generator = require("./generator-CrU-Ghc1.js");
4
+ const require_precheck = require("./precheck-D7gJSmJz.js");
5
+ let node_fs = require("node:fs");
6
+ let postcss = require("postcss");
7
+ postcss = require_chunk.__toESM(postcss);
8
+ let node_path = require("node:path");
9
+ node_path = require_chunk.__toESM(node_path);
10
+ let node_process = require("node:process");
11
+ node_process = require_chunk.__toESM(node_process);
12
+ let tailwindcss_patch = require("tailwindcss-patch");
13
+ let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
14
+ //#region src/bundlers/shared/generator-css/markers.ts
15
+ const TAILWIND_V4_BANNER_RE = /\/\*!\s*tailwindcss v4\./;
16
+ const TAILWIND_GENERATED_CSS_MARKER_RE = /\/\*!\s*tailwindcss v|@property\s+--tw-|--tw-|:not\(#\\#\)|\.[^,{]*(?:\\:|\\\[|\\#)|(?::host|page|\.tw-root|wx-root-portal-content)[^{]*\{[^}]*--(?:color|spacing|text|font-weight|radius)-/;
17
+ const GENERATOR_PLACEHOLDER_MARKER_RE = /\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\//i;
18
+ const GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE = /\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\/\s*/gi;
19
+ const TAILWIND_BANNER_PREFIX_RE = /^\/\*!\s*tailwindcss v[^*]*\*\/\s*/i;
20
+ const TAILWIND_BANNER_RE = /\/\*!\s*tailwindcss v[^*]*\*\//i;
21
+ const TAILWIND_BANNER_GLOBAL_RE = /\/\*!\s*tailwindcss v[^*]*\*\/\s*/gi;
22
+ const VITE_MARKER_RE = /\/\*\$vite\$:[^*]*\*\//g;
23
+ function createCssAppend(base, extra) {
24
+ if (!base) return extra;
25
+ if (!extra) return base;
26
+ return `${base}\n${extra}`;
27
+ }
28
+ function splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss) {
29
+ const trimmedRaw = rawSource.trim();
30
+ const trimmedTailwind = rawTailwindCss.trim();
31
+ if (trimmedRaw === trimmedTailwind) return {
32
+ before: "",
33
+ after: ""
34
+ };
35
+ if (trimmedTailwind.startsWith(trimmedRaw)) return {
36
+ before: "",
37
+ after: ""
38
+ };
39
+ const start = rawSource.indexOf(rawTailwindCss);
40
+ if (start === -1) return;
41
+ return {
42
+ before: rawSource.slice(0, start),
43
+ after: rawSource.slice(start + rawTailwindCss.length)
44
+ };
45
+ }
46
+ function splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss) {
47
+ const match = GENERATOR_PLACEHOLDER_MARKER_RE.exec(rawSource);
48
+ if (!match || match.index === void 0) return;
49
+ let afterStart = match.index + match[0].length;
50
+ while (/\s/.test(rawSource[afterStart] ?? "")) afterStart++;
51
+ if (rawTailwindCss && rawSource.slice(afterStart).startsWith(rawTailwindCss)) {
52
+ afterStart += rawTailwindCss.length;
53
+ while (/\s/.test(rawSource[afterStart] ?? "")) afterStart++;
54
+ }
55
+ return {
56
+ before: rawSource.slice(0, match.index),
57
+ after: rawSource.slice(afterStart)
58
+ };
59
+ }
60
+ function splitTailwindGeneratedCssByBanner(rawSource, start) {
61
+ const match = start === void 0 ? TAILWIND_BANNER_RE.exec(rawSource) : { index: start };
62
+ if (!match || match.index === void 0) return;
63
+ return {
64
+ before: rawSource.slice(0, match.index),
65
+ after: [...rawSource.slice(match.index).matchAll(VITE_MARKER_RE)].map((item) => item[0]).join("\n")
66
+ };
67
+ }
68
+ function stripTailwindBanner(css) {
69
+ return css.replace(TAILWIND_BANNER_PREFIX_RE, "");
70
+ }
71
+ function stripTailwindBanners(css) {
72
+ return css.replace(TAILWIND_BANNER_GLOBAL_RE, "");
73
+ }
74
+ function stripGeneratorPlaceholderMarkers(css) {
75
+ return css.replace(GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE, "");
76
+ }
77
+ function hasTailwindGeneratedCss(rawSource) {
78
+ return TAILWIND_V4_BANNER_RE.test(rawSource);
79
+ }
80
+ function hasTailwindGeneratedCssMarkers(rawSource) {
81
+ return TAILWIND_GENERATED_CSS_MARKER_RE.test(rawSource) || GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource);
82
+ }
83
+ //#endregion
84
+ //#region src/bundlers/shared/generator-css/directives.ts
85
+ const TAILWIND_REMOVABLE_SOURCE_DIRECTIVE_NAMES = new Set([
86
+ "config",
87
+ "custom-variant",
88
+ "layer",
89
+ "plugin",
90
+ "reference",
91
+ "source",
92
+ "tailwind",
93
+ "theme",
94
+ "utility",
95
+ "variant"
96
+ ]);
97
+ const TAILWIND_ROOT_DIRECTIVE_NAMES = new Set([
98
+ "config",
99
+ "custom-variant",
100
+ "plugin",
101
+ "source",
102
+ "tailwind",
103
+ "theme",
104
+ "utility",
105
+ "variant"
106
+ ]);
107
+ const TAILWIND_ROOT_DIRECTIVE_RE = /@(?:import\s+(?:url\(\s*)?["']?tailwindcss4?(?:\/[^"')\s]*)?|(?:use|forward)\s+(?:url\(\s*)?["']?tailwindcss4?(?:\/[^"')\s]*)?|tailwind|config|custom-variant|plugin|source|theme|utility|variant)\b/;
108
+ const TAILWIND_EXTRACTABLE_DIRECTIVE_RE = /^\s*@(?:import|use|forward|tailwind|config|source|reference|plugin)\b[\s\S]*?(?:;|$)/;
109
+ const TAILWIND_EXTRACTABLE_LAYER_STATEMENT_RE = /^\s*@layer\s[^;{]+;\s*$/;
110
+ const TAILWIND_EXTRACTABLE_BLOCK_START_RE = /^\s*@(?:layer|theme|utility|variant|custom-variant)\b[\s\S]*\{/;
111
+ function parseImportRequest(params) {
112
+ return /^(?:url\(\s*)?(["']?)([^"')\s]+)\1\s*\)?/.exec(params.trim())?.[2];
113
+ }
114
+ function parseConfigRequest(params) {
115
+ return /^(["'])(.+)\1\s*;?$/.exec(params.trim())?.[2];
116
+ }
117
+ function isPackageJsonImportRequest(request) {
118
+ return typeof request === "string" && request.startsWith("#");
119
+ }
120
+ function isWeappTailwindcssImportRequest(request) {
121
+ return request === "weapp-tailwindcss" || request?.startsWith("weapp-tailwindcss/");
122
+ }
123
+ function normalizeTailwindImportRequest(request, options = {}) {
124
+ if (options.importFallback && isWeappTailwindcssImportRequest(request)) return request.replace(/^weapp-tailwindcss/, "tailwindcss");
125
+ return request;
126
+ }
127
+ function replaceImportRequest(params, request, replacement) {
128
+ const index = params.indexOf(request);
129
+ if (index === -1) return params;
130
+ return `${params.slice(0, index)}${replacement}${params.slice(index + request.length)}`;
131
+ }
132
+ function normalizeTailwindImportAtRules(root, options = {}) {
133
+ if (!options.importFallback) return false;
134
+ let changed = false;
135
+ const seenCanonicalImports = /* @__PURE__ */ new Set();
136
+ root.walkAtRules("import", (node) => {
137
+ const request = parseImportRequest(node.params);
138
+ const normalizedRequest = normalizeTailwindImportRequest(request, options);
139
+ if (!normalizedRequest || !isTailwindImportRequest(normalizedRequest)) return;
140
+ const normalizedParams = request && normalizedRequest !== request ? replaceImportRequest(node.params, request, normalizedRequest) : node.params;
141
+ const normalizedKey = normalizedParams.trim();
142
+ if (seenCanonicalImports.has(normalizedKey)) {
143
+ node.remove();
144
+ changed = true;
145
+ return;
146
+ }
147
+ seenCanonicalImports.add(normalizedKey);
148
+ if (normalizedParams !== node.params) {
149
+ node.params = normalizedParams;
150
+ changed = true;
151
+ }
152
+ });
153
+ return changed;
154
+ }
155
+ function normalizeTailwindDirectiveLine(line, options = {}) {
156
+ const trimmed = line.trimStart();
157
+ if (/^@(?:use|forward)\b/.test(trimmed)) {
158
+ const request = parseImportRequest(trimmed.replace(/^@(?:use|forward)\b/, ""));
159
+ if (isTailwindImportRequest(request) || options.importFallback && isWeappTailwindcssImportRequest(request)) {
160
+ const normalizedRequest = normalizeTailwindImportRequest(request, options);
161
+ return replaceImportRequest(line.replace(/^(\s*)@(?:use|forward)\b/, "$1@import"), request, normalizedRequest);
162
+ }
163
+ return line;
164
+ }
165
+ if (!options.importFallback || !trimmed.startsWith("@import")) return line;
166
+ const request = parseImportRequest(trimmed.replace(/^@import\b/, ""));
167
+ if (!request || !isWeappTailwindcssImportRequest(request)) return line;
168
+ return replaceImportRequest(line, request, request.replace(/^weapp-tailwindcss/, "tailwindcss"));
169
+ }
170
+ function extractTailwindDirectiveLines(rawSource, options = {}) {
171
+ const directives = [];
172
+ const seenImports = /* @__PURE__ */ new Set();
173
+ for (const line of stripGeneratorPlaceholderMarkers(rawSource).split(/\r?\n/)) {
174
+ const trimmed = line.trim();
175
+ if (!trimmed || trimmed.startsWith("//")) continue;
176
+ const directive = TAILWIND_EXTRACTABLE_DIRECTIVE_RE.exec(line)?.[0] ?? TAILWIND_EXTRACTABLE_LAYER_STATEMENT_RE.exec(line)?.[0];
177
+ if (!directive) continue;
178
+ const normalized = normalizeTailwindDirectiveLine(directive.trimEnd(), options);
179
+ const normalizedTrimmed = normalized.trim();
180
+ if (options.removeConfig && normalizedTrimmed.startsWith("@config")) continue;
181
+ const request = /^@(?:import|use|forward)\b/.test(normalizedTrimmed) ? parseImportRequest(normalizedTrimmed.replace(/^@(?:import|use|forward)\b/, "")) : void 0;
182
+ if (request && !isTailwindImportRequest(request) && !isPackageJsonImportRequest(request)) continue;
183
+ if (/^@(?:import|use|forward)\b/.test(normalizedTrimmed) && !request) continue;
184
+ if (request && isTailwindImportRequest(request)) {
185
+ const key = normalizedTrimmed;
186
+ if (seenImports.has(key)) continue;
187
+ seenImports.add(key);
188
+ }
189
+ directives.push(normalized);
190
+ }
191
+ return directives;
192
+ }
193
+ function stripPreprocessorLineComment(line) {
194
+ let quote;
195
+ let escaped = false;
196
+ for (let index = 0; index < line.length; index++) {
197
+ const char = line[index];
198
+ if (escaped) {
199
+ escaped = false;
200
+ continue;
201
+ }
202
+ if (char === "\\") {
203
+ escaped = true;
204
+ continue;
205
+ }
206
+ if (quote) {
207
+ if (char === quote) quote = void 0;
208
+ continue;
209
+ }
210
+ if (char === "\"" || char === "'") {
211
+ quote = char;
212
+ continue;
213
+ }
214
+ if (char === "/" && line[index + 1] === "/" && (index === 0 || /\s/.test(line[index - 1]))) return line.slice(0, index).trimEnd();
215
+ }
216
+ return line;
217
+ }
218
+ function countBlockBraceDelta(line) {
219
+ let quote;
220
+ let escaped = false;
221
+ let delta = 0;
222
+ for (let index = 0; index < line.length; index++) {
223
+ const char = line[index];
224
+ if (escaped) {
225
+ escaped = false;
226
+ continue;
227
+ }
228
+ if (char === "\\") {
229
+ escaped = true;
230
+ continue;
231
+ }
232
+ if (quote) {
233
+ if (char === quote) quote = void 0;
234
+ continue;
235
+ }
236
+ if (char === "\"" || char === "'") {
237
+ quote = char;
238
+ continue;
239
+ }
240
+ if (char === "{") delta++;
241
+ else if (char === "}") delta--;
242
+ }
243
+ return delta;
244
+ }
245
+ function extractTailwindFallbackBlocks(rawSource) {
246
+ const blocks = [];
247
+ let current;
248
+ let depth = 0;
249
+ for (const rawLine of stripGeneratorPlaceholderMarkers(rawSource).split(/\r?\n/)) {
250
+ const line = stripPreprocessorLineComment(rawLine);
251
+ if (!line.trim()) continue;
252
+ if (!current) {
253
+ if (!TAILWIND_EXTRACTABLE_BLOCK_START_RE.test(line)) continue;
254
+ current = [line];
255
+ depth = countBlockBraceDelta(line);
256
+ if (depth <= 0) {
257
+ blocks.push(current.join("\n"));
258
+ current = void 0;
259
+ depth = 0;
260
+ }
261
+ continue;
262
+ }
263
+ current.push(line);
264
+ depth += countBlockBraceDelta(line);
265
+ if (depth <= 0) {
266
+ blocks.push(current.join("\n"));
267
+ current = void 0;
268
+ depth = 0;
269
+ }
270
+ }
271
+ return blocks;
272
+ }
273
+ function extractTailwindSourceForPostcssFallback(rawSource, options = {}) {
274
+ const directives = [...extractTailwindDirectiveLines(rawSource, options), ...extractTailwindFallbackBlocks(rawSource)];
275
+ return directives.length > 0 ? directives.join("\n") : void 0;
276
+ }
277
+ function extractConfigRequestFromSource(rawSource) {
278
+ for (const line of rawSource.split(/\r?\n/)) {
279
+ const match = /^\s*@config\b([\s\S]*?)(?:;|$)/.exec(line);
280
+ const request = match ? parseConfigRequest(match[1] ?? "") : void 0;
281
+ if (request) return request;
282
+ }
283
+ }
284
+ function hasPreprocessorOnlySyntax(rawSource) {
285
+ return /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@[\w-]+\s*:|@(?:mixin|include|function|use|forward)\b)/.test(rawSource);
286
+ }
287
+ function normalizeTailwindSourceForGenerator(rawSource, options = {}) {
288
+ return hasPreprocessorOnlySyntax(rawSource) ? extractTailwindSourceForPostcssFallback(rawSource, options) ?? rawSource : rawSource;
289
+ }
290
+ function normalizeTailwindSourceDirectives(rawSource, options = {}) {
291
+ if (!options.importFallback) return rawSource;
292
+ try {
293
+ const root = postcss.default.parse(rawSource);
294
+ return normalizeTailwindImportAtRules(root, options) ? root.toString() : rawSource;
295
+ } catch {
296
+ return extractTailwindSourceForPostcssFallback(rawSource, options) ?? rawSource;
297
+ }
298
+ }
299
+ function isTailwindImportRequest(request) {
300
+ return request === "tailwindcss" || request === "tailwindcss4" || request?.startsWith("tailwindcss/") || request?.startsWith("tailwindcss4/");
301
+ }
302
+ function isTailwindImportAtRule(node, options = {}) {
303
+ if (node.name === "tailwind") return true;
304
+ if (node.name !== "import" && node.name !== "use" && node.name !== "forward") return false;
305
+ return isTailwindImportRequest(normalizeTailwindImportRequest(parseImportRequest(node.params), options));
306
+ }
307
+ function isTailwindSourceDirective(node, options = {}) {
308
+ if (node.type !== "atrule") return false;
309
+ const atRule = node;
310
+ if (isTailwindImportAtRule(atRule, options)) return true;
311
+ if (atRule.name === "import" && isPackageJsonImportRequest(parseImportRequest(atRule.params))) return true;
312
+ if (atRule.name === "layer") return !atRule.nodes || atRule.nodes.length === 0;
313
+ return TAILWIND_REMOVABLE_SOURCE_DIRECTIVE_NAMES.has(atRule.name);
314
+ }
315
+ function hasGeneratedCssArtifacts(rawSource) {
316
+ return hasTailwindGeneratedCssMarkers(rawSource) && !GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource);
317
+ }
318
+ function isTailwindGenerationDirective(node, options = {}) {
319
+ if (node.type !== "atrule") return false;
320
+ const atRule = node;
321
+ const request = atRule.name === "import" ? parseImportRequest(atRule.params) : atRule.name === "config" || atRule.name === "plugin" || atRule.name === "reference" ? parseConfigRequest(atRule.params) : void 0;
322
+ return isTailwindImportAtRule(atRule, options) || isPackageJsonImportRequest(request) || atRule.name === "apply" || !options.ignoreLayer && atRule.name === "layer" || atRule.name === "config" || atRule.name === "source";
323
+ }
324
+ function removeTailwindSourceDirectives(rawSource, options = {}) {
325
+ try {
326
+ const source = hasPreprocessorOnlySyntax(rawSource) ? extractTailwindSourceForPostcssFallback(rawSource, options) : stripGeneratorPlaceholderMarkers(rawSource);
327
+ if (!source) return "";
328
+ const root = postcss.default.parse(source);
329
+ let removed = false;
330
+ root.walk((node) => {
331
+ if (isTailwindSourceDirective(node, options)) {
332
+ node.remove();
333
+ removed = true;
334
+ }
335
+ });
336
+ return removed ? root.toString() : source;
337
+ } catch {
338
+ return stripGeneratorPlaceholderMarkers(rawSource);
339
+ }
340
+ }
341
+ function hasTailwindSourceDirectives(rawSource, options = {}) {
342
+ try {
343
+ if (GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource)) return true;
344
+ const root = postcss.default.parse(rawSource);
345
+ let found = false;
346
+ const ignoreLayer = hasGeneratedCssArtifacts(rawSource);
347
+ root.walk((node) => {
348
+ if (isTailwindGenerationDirective(node, {
349
+ ...options,
350
+ ignoreLayer
351
+ })) {
352
+ found = true;
353
+ return false;
354
+ }
355
+ });
356
+ return found;
357
+ } catch {
358
+ return extractTailwindDirectiveLines(rawSource, options).length > 0;
359
+ }
360
+ }
361
+ function hasTailwindRootDirectives(rawSource, options = {}) {
362
+ if (!TAILWIND_ROOT_DIRECTIVE_RE.test(rawSource) && !(options.importFallback && rawSource.includes("weapp-tailwindcss"))) return false;
363
+ try {
364
+ const root = postcss.default.parse(rawSource);
365
+ let found = false;
366
+ root.walkAtRules((node) => {
367
+ const request = node.name === "import" ? parseImportRequest(node.params) : node.name === "config" || node.name === "plugin" ? parseConfigRequest(node.params) : void 0;
368
+ if (isTailwindImportAtRule(node, options) || isPackageJsonImportRequest(request) || TAILWIND_ROOT_DIRECTIVE_NAMES.has(node.name)) {
369
+ found = true;
370
+ return false;
371
+ }
372
+ });
373
+ return found;
374
+ } catch {
375
+ return extractTailwindDirectiveLines(rawSource, options).length > 0;
376
+ }
377
+ }
378
+ function hasTailwindApplyDirective(rawSource) {
379
+ if (!rawSource.includes("@apply")) return false;
380
+ try {
381
+ const root = postcss.default.parse(rawSource);
382
+ let found = false;
383
+ root.walkAtRules("apply", () => {
384
+ found = true;
385
+ return false;
386
+ });
387
+ return found;
388
+ } catch {
389
+ return false;
390
+ }
391
+ }
392
+ function resolveCssEntrySource(rawSource, base, options = {}) {
393
+ try {
394
+ const root = postcss.default.parse(rawSource);
395
+ const normalizedImports = normalizeTailwindImportAtRules(root, options);
396
+ let found = false;
397
+ let config;
398
+ let configRequest;
399
+ let removedConfig = false;
400
+ const removeConfig = options.removeConfig ?? true;
401
+ const ignoreLayer = hasGeneratedCssArtifacts(rawSource);
402
+ root.walk((node) => {
403
+ if (isTailwindGenerationDirective(node, {
404
+ ...options,
405
+ ignoreLayer
406
+ })) found = true;
407
+ if (node.type === "atrule" && node.name === "config") {
408
+ const configPath = parseConfigRequest(node.params);
409
+ if (configPath && !config) {
410
+ configRequest = configPath;
411
+ config = isPackageJsonImportRequest(configPath) ? void 0 : node_path.default.isAbsolute(configPath) ? configPath : node_path.default.resolve(base, configPath);
412
+ }
413
+ if (removeConfig) {
414
+ node.remove();
415
+ removedConfig = true;
416
+ }
417
+ }
418
+ });
419
+ if (!found) return;
420
+ if (hasPreprocessorOnlySyntax(rawSource)) {
421
+ const css = extractTailwindSourceForPostcssFallback(rawSource, {
422
+ ...options,
423
+ removeConfig
424
+ });
425
+ if (css) return {
426
+ css,
427
+ config,
428
+ configRequest,
429
+ base
430
+ };
431
+ }
432
+ return {
433
+ css: removedConfig || normalizedImports ? root.toString() : rawSource,
434
+ config,
435
+ configRequest,
436
+ base
437
+ };
438
+ } catch {
439
+ const css = extractTailwindSourceForPostcssFallback(rawSource, options);
440
+ const configRequest = extractConfigRequestFromSource(rawSource);
441
+ const config = configRequest && !isPackageJsonImportRequest(configRequest) ? node_path.default.isAbsolute(configRequest) ? configRequest : node_path.default.resolve(base, configRequest) : void 0;
442
+ return css ? {
443
+ css,
444
+ config,
445
+ configRequest,
446
+ base
447
+ } : void 0;
448
+ }
449
+ }
450
+ //#endregion
451
+ //#region src/bundlers/shared/cache.ts
452
+ async function processCachedTask({ cache, cacheKey, hashKey = cacheKey, rawSource, hash, readCache, applyResult, transform, onCacheHit }) {
453
+ let cacheHit = false;
454
+ const result = await cache.process({
455
+ key: cacheKey,
456
+ hashKey,
457
+ rawSource,
458
+ hash,
459
+ resolveCache: readCache,
460
+ async onCacheHit(value) {
461
+ cacheHit = true;
462
+ await applyResult(value);
463
+ onCacheHit?.();
464
+ },
465
+ transform
466
+ });
467
+ if (!cacheHit) await applyResult(result);
468
+ }
469
+ //#endregion
470
+ //#region src/bundlers/shared/generator-css/legacy-selectors.ts
471
+ const CLASS_SELECTOR_RE = /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i;
472
+ const MINI_PROGRAM_THEME_SCOPE_SELECTORS = new Set([
473
+ ":host",
474
+ "page",
475
+ ".tw-root",
476
+ "wx-root-portal-content"
477
+ ]);
478
+ const SPECIFICITY_PLACEHOLDER_RE = /:not\(#(?:\\#|n)\)/g;
479
+ const SELECTOR_CACHE_LIMIT = 64;
480
+ const generatedSelectorCache = /* @__PURE__ */ new Map();
481
+ function setGeneratedSelectorCache(css, selectors) {
482
+ if (generatedSelectorCache.size >= SELECTOR_CACHE_LIMIT) {
483
+ const firstKey = generatedSelectorCache.keys().next().value;
484
+ if (firstKey !== void 0) generatedSelectorCache.delete(firstKey);
485
+ }
486
+ generatedSelectorCache.set(css, selectors);
487
+ }
488
+ function normalizeCompatSelector(selector) {
489
+ return selector.replace(SPECIFICITY_PLACEHOLDER_RE, "").replace(/\s+/g, " ").trim();
490
+ }
491
+ function isClassSelectorTerminator(char) {
492
+ return /[\s>+~#,.:()[\]]/.test(char);
493
+ }
494
+ function unescapeSimpleCssIdent(value) {
495
+ return value.replaceAll(/\\(.)/g, "$1");
496
+ }
497
+ function escapeCompatSelectorClasses(selector) {
498
+ let result = "";
499
+ let index = 0;
500
+ let changed = false;
501
+ while (index < selector.length) {
502
+ const char = selector[index];
503
+ if (char !== ".") {
504
+ result += char;
505
+ index += 1;
506
+ continue;
507
+ }
508
+ let end = index + 1;
509
+ let className = "";
510
+ while (end < selector.length) {
511
+ const current = selector[end];
512
+ if (current === void 0) break;
513
+ if (current === "\\" && end + 1 < selector.length) {
514
+ const escaped = selector[end + 1];
515
+ if (escaped === void 0) break;
516
+ className += current + escaped;
517
+ end += 2;
518
+ continue;
519
+ }
520
+ if (isClassSelectorTerminator(current)) break;
521
+ className += current;
522
+ end += 1;
523
+ }
524
+ if (className.includes("\\")) {
525
+ result += `.${require_precheck.replaceWxml(unescapeSimpleCssIdent(className))}`;
526
+ changed = true;
527
+ } else result += `.${className}`;
528
+ index = end;
529
+ }
530
+ return changed ? result : selector;
531
+ }
532
+ function normalizeCompatSelectors(selector) {
533
+ const normalized = normalizeCompatSelector(selector);
534
+ if (!normalized) return [];
535
+ const selectors = new Set([normalized]);
536
+ const escaped = normalizeCompatSelector(escapeCompatSelectorClasses(normalized));
537
+ if (escaped) selectors.add(escaped);
538
+ return [...selectors];
539
+ }
540
+ function normalizeCssSelector(selector) {
541
+ return selector.trim().replace(/\s+/g, "");
542
+ }
543
+ function getCompatSelectorKeys(selector) {
544
+ return normalizeCompatSelectors(selector).map(normalizeCssSelector);
545
+ }
546
+ function getRuleCompatSelectorKeys(rule) {
547
+ return (rule.selectors?.length ? rule.selectors : [rule.selector]).flatMap((selector) => getCompatSelectorKeys(selector));
548
+ }
549
+ function hasClassSelector(selector) {
550
+ return CLASS_SELECTOR_RE.test(selector);
551
+ }
552
+ function getNormalizedSelectorList(selector) {
553
+ return selector.split(",").map(normalizeCssSelector).filter(Boolean);
554
+ }
555
+ function isMiniProgramThemeScopeSelector(selector) {
556
+ const selectors = getNormalizedSelectorList(selector);
557
+ return selectors.length > 0 && selectors.every((item) => MINI_PROGRAM_THEME_SCOPE_SELECTORS.has(item));
558
+ }
559
+ function hasUtilityClassSelector(selector) {
560
+ return hasClassSelector(selector) && !isMiniProgramThemeScopeSelector(selector);
561
+ }
562
+ function isCustomPropertyOnlyRule(rule) {
563
+ let hasDeclaration = false;
564
+ let allCustomProperties = true;
565
+ rule.each((node) => {
566
+ if (node.type !== "decl") return;
567
+ hasDeclaration = true;
568
+ if (!node.prop.startsWith("--")) allCustomProperties = false;
569
+ });
570
+ return hasDeclaration && allCustomProperties;
571
+ }
572
+ function isPseudoContentInitRule(rule) {
573
+ let hasDeclaration = false;
574
+ let onlyContentVariable = true;
575
+ rule.each((node) => {
576
+ if (node.type !== "decl") return;
577
+ hasDeclaration = true;
578
+ if (node.prop !== "--tw-content") onlyContentVariable = false;
579
+ });
580
+ return hasDeclaration && onlyContentVariable;
581
+ }
582
+ function collectGeneratedSelectors(css) {
583
+ const cached = generatedSelectorCache.get(css);
584
+ if (cached) return cached;
585
+ const selectors = /* @__PURE__ */ new Set();
586
+ try {
587
+ postcss.default.parse(css).walkRules((rule) => {
588
+ if (isCustomPropertyOnlyRule(rule) && !isPseudoContentInitRule(rule) && !hasUtilityClassSelector(rule.selector)) return;
589
+ for (const selector of getRuleCompatSelectorKeys(rule)) selectors.add(selector);
590
+ });
591
+ } catch {
592
+ return selectors;
593
+ }
594
+ setGeneratedSelectorCache(css, selectors);
595
+ return selectors;
596
+ }
597
+ function collectGeneratedDeclarationPropsBySelector(generatedCss, selectors) {
598
+ const propsBySelector = /* @__PURE__ */ new Map();
599
+ try {
600
+ postcss.default.parse(generatedCss).walkRules((rule) => {
601
+ const matchedSelectors = getRuleCompatSelectorKeys(rule).filter((selector) => selectors.has(selector));
602
+ if (matchedSelectors.length === 0) return;
603
+ const props = /* @__PURE__ */ new Set();
604
+ rule.walkDecls((decl) => {
605
+ props.add(decl.prop);
606
+ });
607
+ for (const selector of matchedSelectors) {
608
+ const existing = propsBySelector.get(selector);
609
+ if (existing) for (const prop of props) existing.add(prop);
610
+ else propsBySelector.set(selector, new Set(props));
611
+ }
612
+ });
613
+ } catch {
614
+ return propsBySelector;
615
+ }
616
+ return propsBySelector;
617
+ }
618
+ function removeGeneratedSelectorCompatCss(css, generatedCss) {
619
+ const generatedSelectors = collectGeneratedSelectors(generatedCss);
620
+ if (generatedSelectors.size === 0) return css;
621
+ try {
622
+ const root = postcss.default.parse(css);
623
+ let removed = false;
624
+ root.walkRules((rule) => {
625
+ if (isPseudoContentInitRule(rule)) {
626
+ rule.remove();
627
+ removed = true;
628
+ return;
629
+ }
630
+ if (isCustomPropertyOnlyRule(rule) && !isPseudoContentInitRule(rule) && !hasUtilityClassSelector(rule.selector)) return;
631
+ if (getRuleCompatSelectorKeys(rule).some((selector) => generatedSelectors.has(selector))) {
632
+ rule.remove();
633
+ removed = true;
634
+ }
635
+ });
636
+ root.walkAtRules((atRule) => {
637
+ if (atRule.nodes && atRule.nodes.length === 0) atRule.remove();
638
+ });
639
+ return removed ? root.toString() : css;
640
+ } catch {
641
+ return css;
642
+ }
643
+ }
644
+ function collectDedupedPostTransformCompatCss(css, generatedCss) {
645
+ const generatedSelectors = collectGeneratedSelectors(generatedCss);
646
+ if (generatedSelectors.size === 0) return css;
647
+ const generatedDeclarationPropsBySelector = collectGeneratedDeclarationPropsBySelector(generatedCss, generatedSelectors);
648
+ const preservedNodes = [];
649
+ try {
650
+ const root = postcss.default.parse(css);
651
+ root.each((node) => {
652
+ if (node.type === "rule") {
653
+ const nodeSelectors = getRuleCompatSelectorKeys(node);
654
+ if (!nodeSelectors.some((selector) => generatedSelectors.has(selector))) {
655
+ preservedNodes.push(node.clone());
656
+ return;
657
+ }
658
+ if (isCustomPropertyOnlyRule(node) && !isPseudoContentInitRule(node) && !hasUtilityClassSelector(node.selector)) {
659
+ const declarationProps = /* @__PURE__ */ new Set();
660
+ node.walkDecls((decl) => {
661
+ declarationProps.add(decl.prop);
662
+ });
663
+ for (const selector of nodeSelectors) {
664
+ const generatedProps = generatedDeclarationPropsBySelector.get(selector);
665
+ if (!generatedProps) continue;
666
+ for (const prop of generatedProps) declarationProps.delete(prop);
667
+ }
668
+ const nextRule = node.clone();
669
+ nextRule.walkDecls((decl) => {
670
+ if (!declarationProps.has(decl.prop)) decl.remove();
671
+ });
672
+ if (nextRule.nodes.length > 0) preservedNodes.push(nextRule);
673
+ }
674
+ return;
675
+ }
676
+ preservedNodes.push(node.clone());
677
+ });
678
+ if (preservedNodes.length === root.nodes.length) return css;
679
+ const nextRoot = postcss.default.root();
680
+ nextRoot.append(preservedNodes);
681
+ return nextRoot.toString();
682
+ } catch {
683
+ return css;
684
+ }
685
+ }
686
+ function removeDuplicatedViteMarkers(css, baseCss) {
687
+ if (!VITE_MARKER_RE.test(baseCss)) return css;
688
+ VITE_MARKER_RE.lastIndex = 0;
689
+ return css.replace(VITE_MARKER_RE, "");
690
+ }
691
+ //#endregion
692
+ //#region src/bundlers/shared/generator-css/config-directive.ts
693
+ function quoteCssString(value) {
694
+ return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
695
+ }
696
+ function toCssPath(value) {
697
+ return value.replaceAll("\\", "/");
698
+ }
699
+ function prependConfigDirective(css, config) {
700
+ if (!config || /@config\s+/.test(css)) return css;
701
+ return `@config "${quoteCssString(toCssPath(config))}";\n${css}`;
702
+ }
703
+ function normalizeConfigDirective(css, config) {
704
+ if (!config || !/@config\s+/.test(css)) return css;
705
+ return css.replace(/@config\s+(["'])(.+?)\1\s*;?/, `@config "${quoteCssString(toCssPath(config))}";`);
706
+ }
707
+ //#endregion
708
+ //#region src/bundlers/shared/generator-css/source-files.ts
709
+ const SOURCE_STYLE_EXTENSIONS = [
710
+ ".vue",
711
+ ".uvue",
712
+ ".nvue",
713
+ ".css",
714
+ ".scss",
715
+ ".sass",
716
+ ".less",
717
+ ".styl",
718
+ ".stylus",
719
+ ".wxss",
720
+ ".acss",
721
+ ".jxss",
722
+ ".ttss",
723
+ ".qss"
724
+ ];
725
+ const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
726
+ function stripStyleExtension(file) {
727
+ return file.replace(/[?#].*$/, "").replace(/\.(?:wx|ac|jx|tt|q|c|ty)?ss$/i, "");
728
+ }
729
+ function createSourceStylePathCandidates(file, sourceOptions) {
730
+ const bases = [
731
+ sourceOptions.projectRoot,
732
+ sourceOptions.cwd,
733
+ node_process.default.cwd()
734
+ ].filter((item) => typeof item === "string" && item.length > 0);
735
+ const outputRoots = [sourceOptions.outputRoot].filter((item) => typeof item === "string" && item.length > 0);
736
+ const strippedFile = stripStyleExtension(file);
737
+ const relativeFiles = /* @__PURE__ */ new Set();
738
+ const addOutputRelativePath = (absoluteFile) => {
739
+ for (const outputRoot of outputRoots) {
740
+ const relative = node_path.default.relative(outputRoot, absoluteFile);
741
+ if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) continue;
742
+ relativeFiles.add(relative);
743
+ }
744
+ };
745
+ if (node_path.default.isAbsolute(strippedFile)) {
746
+ addOutputRelativePath(strippedFile);
747
+ for (const base of bases) {
748
+ const relative = node_path.default.relative(base, strippedFile);
749
+ if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) continue;
750
+ relativeFiles.add(relative);
751
+ }
752
+ } else relativeFiles.add(strippedFile);
753
+ const candidates = /* @__PURE__ */ new Set();
754
+ for (const relativeFile of relativeFiles) {
755
+ if (!relativeFile || node_path.default.isAbsolute(relativeFile)) continue;
756
+ for (const base of bases) for (const sourceRoot of ["", "src"]) {
757
+ const prefix = sourceRoot ? node_path.default.resolve(base, sourceRoot, relativeFile) : node_path.default.resolve(base, relativeFile);
758
+ for (const extension of SOURCE_STYLE_EXTENSIONS) candidates.add(`${prefix}${extension}`);
759
+ }
760
+ }
761
+ return [...candidates];
762
+ }
763
+ function extractStyleDirectiveSources(source) {
764
+ const styleSources = [];
765
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
766
+ let match = SFC_STYLE_BLOCK_RE.exec(source);
767
+ while (match !== null) {
768
+ const styleSource = match[1] ?? "";
769
+ if (hasTailwindSourceDirectives(styleSource)) styleSources.push(styleSource);
770
+ match = SFC_STYLE_BLOCK_RE.exec(source);
771
+ }
772
+ if (styleSources.length > 0) return styleSources;
773
+ return hasTailwindSourceDirectives(source) ? [source] : [];
774
+ }
775
+ function resolveSourceSideCssEntrySource(file, sourceOptions, resolveOptions = {}) {
776
+ for (const sourceFile of createSourceStylePathCandidates(file, sourceOptions)) {
777
+ if (!(0, node_fs.existsSync)(sourceFile)) continue;
778
+ try {
779
+ const source = (0, node_fs.readFileSync)(sourceFile, "utf8");
780
+ for (const styleSource of extractStyleDirectiveSources(source)) {
781
+ const cssEntrySource = resolveCssEntrySource(styleSource, node_path.default.dirname(sourceFile), resolveOptions);
782
+ if (cssEntrySource) return {
783
+ ...cssEntrySource,
784
+ file: sourceFile
785
+ };
786
+ }
787
+ } catch {
788
+ continue;
789
+ }
790
+ }
791
+ }
792
+ //#endregion
793
+ //#region src/bundlers/shared/generator-css/source-resolver.ts
794
+ function resolvePostcssFromOption(cssHandlerOptions) {
795
+ const from = cssHandlerOptions.postcssOptions?.options?.from;
796
+ return typeof from === "string" && from.length > 0 ? from : void 0;
797
+ }
798
+ function resolvePostcssSourceFile(cssHandlerOptions) {
799
+ const from = resolvePostcssFromOption(cssHandlerOptions);
800
+ if (!from || !node_path.default.isAbsolute(from)) return;
801
+ return from.replace(/[?#].*$/, "");
802
+ }
803
+ function resolveCssHandlerSourceOptions(cssHandlerOptions) {
804
+ return cssHandlerOptions.sourceOptions;
805
+ }
806
+ function createSingleTailwindV4SourceOptions(sourceOptions, options) {
807
+ return require_v3_engine.omitUndefined({
808
+ projectRoot: sourceOptions.projectRoot,
809
+ baseFallbacks: sourceOptions.baseFallbacks,
810
+ packageName: sourceOptions.packageName,
811
+ base: options.base,
812
+ css: options.css
813
+ });
814
+ }
815
+ function resolveCssSourceBase(file, cssHandlerOptions) {
816
+ const normalized = (resolvePostcssFromOption(cssHandlerOptions) ?? file).replace(/[?#].*$/, "");
817
+ return node_path.default.dirname(node_path.default.resolve(normalized));
818
+ }
819
+ function resolveExistingConfigPath(config, configRequest, file, sourceOptions) {
820
+ if (config && (0, node_fs.existsSync)(config)) return config;
821
+ if (!configRequest || node_path.default.isAbsolute(configRequest)) return sourceOptions.config;
822
+ const outputDir = node_path.default.dirname(file.replace(/[?#].*$/, ""));
823
+ const baseCandidates = [
824
+ sourceOptions.projectRoot,
825
+ sourceOptions.cwd,
826
+ node_process.default.cwd()
827
+ ].filter((item) => typeof item === "string" && item.length > 0);
828
+ for (const base of baseCandidates) {
829
+ const candidates = [
830
+ node_path.default.resolve(base, configRequest),
831
+ node_path.default.resolve(base, "src", configRequest),
832
+ node_path.default.resolve(base, outputDir, configRequest),
833
+ node_path.default.resolve(base, "src", outputDir, configRequest)
834
+ ];
835
+ for (const candidate of candidates) if ((0, node_fs.existsSync)(candidate)) return candidate;
836
+ }
837
+ return sourceOptions.config;
838
+ }
839
+ function canResolveSourceSideCssEntry(file, cssHandlerOptions) {
840
+ const from = resolvePostcssFromOption(cssHandlerOptions);
841
+ if (!from || !node_path.default.isAbsolute(from)) return node_path.default.isAbsolute(file);
842
+ return true;
843
+ }
844
+ function shouldResolveSourceSideCssEntry(rawSource) {
845
+ return rawSource.includes("@apply") || hasTailwindGeneratedCss(rawSource) || hasTailwindGeneratedCssMarkers(rawSource);
846
+ }
847
+ function shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) {
848
+ return Boolean(sourceSideEntrySource) && !hasTailwindSourceDirectives(rawSource, { importFallback: true });
849
+ }
850
+ function normalizeCssSourceForCompare(css) {
851
+ return stripGeneratorPlaceholderMarkers(stripTailwindBanners(css)).trim();
852
+ }
853
+ function getOutputFileStem(file) {
854
+ const normalized = file.replace(/[?#].*$/, "");
855
+ return node_path.default.basename(normalized, node_path.default.extname(normalized));
856
+ }
857
+ function getOutputFileWithoutExtension(file) {
858
+ const normalized = file.replace(/[?#].*$/, "");
859
+ const ext = node_path.default.extname(normalized);
860
+ return ext ? normalized.slice(0, -ext.length) : normalized;
861
+ }
862
+ function normalizeMatchPath(file) {
863
+ return file.split(node_path.default.sep).join("/");
864
+ }
865
+ function stripKnownBuildRootPrefix(file) {
866
+ const segments = normalizeMatchPath(file).split("/");
867
+ const knownRoots = new Set(["dist", "src"]);
868
+ for (let index = segments.length - 1; index >= 0; index--) if (knownRoots.has(segments[index])) return segments.slice(index + 1).join("/");
869
+ return segments.join("/");
870
+ }
871
+ function isMatchingTailwindV4CssSourceFile(file, cssSourceFile) {
872
+ const outputBase = normalizeMatchPath(getOutputFileWithoutExtension(node_path.default.resolve(file)));
873
+ const sourceBase = normalizeMatchPath(getOutputFileWithoutExtension(node_path.default.resolve(cssSourceFile)));
874
+ const outputRelativeBase = stripKnownBuildRootPrefix(outputBase);
875
+ const sourceRelativeBase = stripKnownBuildRootPrefix(sourceBase);
876
+ return outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`) || outputRelativeBase.length > 0 && outputRelativeBase === sourceRelativeBase;
877
+ }
878
+ function resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) {
879
+ const cssEntries = sourceOptions.cssEntries;
880
+ if (!cssEntries?.length) return;
881
+ const normalizedRawSource = normalizeCssSourceForCompare(rawSource);
882
+ const outputStem = getOutputFileStem(file);
883
+ const matchingEntry = cssEntries.find((cssEntry) => {
884
+ if (!(0, node_fs.existsSync)(cssEntry)) return false;
885
+ try {
886
+ if (normalizeCssSourceForCompare((0, node_fs.readFileSync)(cssEntry, "utf8")) === normalizedRawSource) return true;
887
+ return outputStem.length > 0 && getOutputFileStem(cssEntry) === outputStem;
888
+ } catch {
889
+ return false;
890
+ }
891
+ });
892
+ if (!matchingEntry) return;
893
+ return require_v3_engine.resolveTailwindV4Source({
894
+ ...require_v3_engine.omitUndefined(sourceOptions),
895
+ cssEntries: [matchingEntry]
896
+ });
897
+ }
898
+ async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions) {
899
+ const cssSources = sourceOptions.cssSources;
900
+ if (!cssSources?.length) return;
901
+ const normalizedRawSource = normalizeCssSourceForCompare(rawSource);
902
+ const sourceFile = resolvePostcssSourceFile(cssHandlerOptions);
903
+ const matchingSource = cssSources.find((cssSource) => {
904
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return false;
905
+ if (sourceFile && typeof cssSource.file === "string" && node_path.default.resolve(sourceFile) === node_path.default.resolve(cssSource.file)) return true;
906
+ if (typeof cssSource.file === "string" && isMatchingTailwindV4CssSourceFile(file, cssSource.file)) return true;
907
+ return normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource;
908
+ });
909
+ if (!matchingSource) return;
910
+ return resolveSingleTailwindV4CssSource(matchingSource, sourceOptions);
911
+ }
912
+ function tryResolveTailwindV4SourceOptions(runtimeState) {
913
+ try {
914
+ return require_v3_engine.resolveTailwindV4SourceOptionsFromPatcher(runtimeState.twPatcher);
915
+ } catch {
916
+ return;
917
+ }
918
+ }
919
+ function hasConfiguredTailwindV4CssSource(sourceOptions) {
920
+ return Boolean(sourceOptions?.css) || Boolean(sourceOptions?.cssSources?.length);
921
+ }
922
+ async function resolveSingleTailwindV4CssSource(cssSource, sourceOptions) {
923
+ const source = await require_v3_engine.resolveTailwindV4Source({
924
+ ...require_v3_engine.omitUndefined(sourceOptions),
925
+ cssSources: [cssSource]
926
+ });
927
+ const sourceBaseFallback = sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd();
928
+ return withGeneratorSourceMetadata(source, {
929
+ matchedCssSourceFile: typeof cssSource.file === "string" ? cssSource.file : void 0,
930
+ sourceBase: require_v3_engine.resolveTailwindV4CssSourceBase(cssSource, sourceBaseFallback),
931
+ sourceCss: cssSource.css
932
+ });
933
+ }
934
+ async function resolveTailwindV4CssSourceEntries(cssSource, sourceOptions) {
935
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return;
936
+ const sourceBase = require_v3_engine.resolveTailwindV4CssSourceBase(cssSource, sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd());
937
+ return require_v3_engine.resolveTailwindV4EntriesFromCss(cssSource.css, sourceBase);
938
+ }
939
+ function countRuntimeCandidateHits(candidates, runtime) {
940
+ if (!runtime?.size) return 0;
941
+ let hits = 0;
942
+ for (const candidate of candidates) if (runtime.has(candidate)) hits += 1;
943
+ return hits;
944
+ }
945
+ async function resolveCandidateMatchedTailwindV4CssSource(_rawSource, cssHandlerOptions, sourceOptions, selectionOptions) {
946
+ const cssSources = sourceOptions.cssSources;
947
+ const getSourceCandidatesForEntries = selectionOptions?.getSourceCandidatesForEntries;
948
+ if (!cssHandlerOptions.isMainChunk || !cssSources?.length || !getSourceCandidatesForEntries) return;
949
+ const matches = [];
950
+ await Promise.all(cssSources.map(async (cssSource, index) => {
951
+ const resolved = await resolveTailwindV4CssSourceEntries(cssSource, sourceOptions);
952
+ if (resolved?.entries === void 0) return;
953
+ const scopedCandidates = getSourceCandidatesForEntries(resolved?.entries);
954
+ const runtimeHits = countRuntimeCandidateHits(scopedCandidates, selectionOptions?.runtime);
955
+ if (runtimeHits === 0) return;
956
+ matches.push({
957
+ cssSource,
958
+ index,
959
+ runtimeHits,
960
+ totalCandidates: scopedCandidates.size
961
+ });
962
+ }));
963
+ if (matches.length === 0) return;
964
+ matches.sort((a, b) => b.runtimeHits - a.runtimeHits || b.totalCandidates - a.totalCandidates || a.index - b.index);
965
+ const best = matches[0];
966
+ const second = matches[1];
967
+ if (!best) return;
968
+ if (second && second.runtimeHits === best.runtimeHits && second.totalCandidates === best.totalCandidates) return;
969
+ return resolveSingleTailwindV4CssSource(best.cssSource, sourceOptions);
970
+ }
971
+ function createTailwindV4CssSourceResolver(sourceOptions, generatorOptions) {
972
+ return (cssSource) => require_v3_engine.resolveTailwindV4Source({
973
+ ...require_v3_engine.omitUndefined(sourceOptions),
974
+ cssSources: [cssSource]
975
+ }).then((source) => generatorOptions?.config ? {
976
+ ...source,
977
+ css: prependConfigDirective(source.css, generatorOptions.config)
978
+ } : source);
979
+ }
980
+ async function resolveTailwindV4SourceSideEntrySource(resolvedEntrySource, sourceOptions, generatorOptions, file) {
981
+ if (!resolvedEntrySource) return;
982
+ const resolvedSourceOptions = require_v3_engine.omitUndefined(sourceOptions);
983
+ const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, resolvedSourceOptions);
984
+ const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions);
985
+ return withMatchedSourceSideMetadata(await require_v3_engine.resolveTailwindV4Source(createSingleTailwindV4SourceOptions(resolvedSourceOptions, {
986
+ base: resolvedEntrySource.base,
987
+ css
988
+ })), resolvedEntrySource);
989
+ }
990
+ function withGeneratorSourceMetadata(source, metadata) {
991
+ return {
992
+ ...source,
993
+ __weappTailwindcssMeta: metadata
994
+ };
995
+ }
996
+ function withMatchedSourceSideMetadata(source, resolvedEntrySource) {
997
+ return resolvedEntrySource.file ? withGeneratorSourceMetadata(source, {
998
+ matchedCssSourceFile: resolvedEntrySource.file,
999
+ sourceBase: resolvedEntrySource.base,
1000
+ sourceCss: resolvedEntrySource.css
1001
+ }) : source;
1002
+ }
1003
+ function createTailwindV4ApplyReferenceSource(css, sourceOptions) {
1004
+ if (!hasTailwindApplyDirective(css) || hasTailwindRootDirectives(css)) return css;
1005
+ return `@reference "${sourceOptions.packageName ?? "tailwindcss"}";\n${css}`;
1006
+ }
1007
+ async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
1008
+ const base = resolveCssSourceBase(file, cssHandlerOptions);
1009
+ const cssEntrySource = resolveCssEntrySource(rawSource, base, {
1010
+ importFallback: generatorOptions?.importFallback ?? false,
1011
+ removeConfig: majorVersion === 3
1012
+ });
1013
+ if (majorVersion === 3) {
1014
+ const sourceOptions = require_v3_engine.resolveTailwindV3SourceOptionsFromPatcher(runtimeState.twPatcher);
1015
+ const mergedSourceOptions = require_v3_engine.omitUndefined({
1016
+ ...sourceOptions,
1017
+ config: generatorOptions?.config ?? sourceOptions.config,
1018
+ ...resolveCssHandlerSourceOptions(cssHandlerOptions)
1019
+ });
1020
+ const applyEntrySource = hasTailwindApplyDirective(rawSource) ? {
1021
+ base,
1022
+ css: rawSource
1023
+ } : void 0;
1024
+ const sourceSideEntrySource = canResolveSourceSideCssEntry(file, cssHandlerOptions) ? resolveSourceSideCssEntrySource(file, mergedSourceOptions, { removeConfig: true }) : void 0;
1025
+ const resolvedEntrySource = shouldResolveSourceSideCssEntry(rawSource) ? applyEntrySource ?? cssEntrySource ?? sourceSideEntrySource : shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) ? sourceSideEntrySource ?? cssEntrySource : cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource;
1026
+ if (!resolvedEntrySource) return generatorOptions?.config ? require_v3_engine.resolveTailwindV3Source(mergedSourceOptions) : require_v3_engine.resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher);
1027
+ if (cssEntrySource && !sourceSideEntrySource && !applyEntrySource && !hasTailwindRootDirectives(rawSource, { importFallback: true })) return generatorOptions?.config ? require_v3_engine.resolveTailwindV3Source(mergedSourceOptions) : require_v3_engine.resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher);
1028
+ const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, require_v3_engine.omitUndefined(mergedSourceOptions));
1029
+ return require_v3_engine.resolveTailwindV3Source({
1030
+ ...mergedSourceOptions,
1031
+ base: resolvedEntrySource.base,
1032
+ css: resolvedEntrySource.css,
1033
+ ...config ? { config } : {}
1034
+ });
1035
+ }
1036
+ const sourceOptions = tryResolveTailwindV4SourceOptions(runtimeState);
1037
+ const resolvedSourceOptions = sourceOptions ? require_v3_engine.omitUndefined({
1038
+ ...sourceOptions,
1039
+ ...resolveCssHandlerSourceOptions(cssHandlerOptions)
1040
+ }) : void 0;
1041
+ const shouldPreferSourceSideEntry = shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder"));
1042
+ const sourceSideEntrySource = resolvedSourceOptions && shouldPreferSourceSideEntry ? resolveSourceSideCssEntrySource(file, resolvedSourceOptions, { removeConfig: false }) : void 0;
1043
+ const matchedCssSource = sourceOptions ? await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions) : void 0;
1044
+ const candidateMatchedCssSource = sourceOptions ? await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions) : void 0;
1045
+ const configuredCssSource = sourceOptions && hasConfiguredTailwindV4CssSource(sourceOptions) && hasTailwindGeneratedCssMarkers(rawSource) ? matchedCssSource ?? candidateMatchedCssSource ?? await require_v3_engine.resolveTailwindV4Source(sourceOptions) : void 0;
1046
+ if (configuredCssSource) return generatorOptions?.config ? {
1047
+ ...configuredCssSource,
1048
+ css: prependConfigDirective(configuredCssSource.css, generatorOptions.config)
1049
+ } : configuredCssSource;
1050
+ const matchedCssEntrySource = sourceOptions && cssEntrySource ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
1051
+ const mainCssEntrySource = sourceOptions && cssHandlerOptions.isMainChunk && sourceOptions.cssEntries?.length === 1 ? await require_v3_engine.resolveTailwindV4Source({
1052
+ ...require_v3_engine.omitUndefined(sourceOptions),
1053
+ cssEntries: [sourceOptions.cssEntries[0]]
1054
+ }) : void 0;
1055
+ const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource ?? mainCssEntrySource;
1056
+ if (preferredCssEntrySource) return generatorOptions?.config ? {
1057
+ ...preferredCssEntrySource,
1058
+ css: prependConfigDirective(preferredCssEntrySource.css, generatorOptions.config)
1059
+ } : preferredCssEntrySource;
1060
+ const resolvedEntrySource = sourceSideEntrySource ?? cssEntrySource;
1061
+ if (!resolvedEntrySource) {
1062
+ const source = await require_v3_engine.resolveTailwindV4SourceFromPatcher(runtimeState.twPatcher);
1063
+ return generatorOptions?.config ? {
1064
+ ...source,
1065
+ css: prependConfigDirective(source.css, generatorOptions.config)
1066
+ } : source;
1067
+ }
1068
+ if (sourceSideEntrySource && resolvedSourceOptions) return resolveTailwindV4SourceSideEntrySource(sourceSideEntrySource, resolvedSourceOptions, generatorOptions, file);
1069
+ const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, resolvedSourceOptions ?? {});
1070
+ const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions ?? {});
1071
+ return require_v3_engine.resolveTailwindV4Source(createSingleTailwindV4SourceOptions(resolvedSourceOptions ?? {}, {
1072
+ base: resolvedEntrySource.base,
1073
+ css
1074
+ }));
1075
+ }
1076
+ async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
1077
+ const cssEntrySource = resolveCssEntrySource(rawSource, resolveCssSourceBase(file, cssHandlerOptions), {
1078
+ importFallback: generatorOptions?.importFallback ?? false,
1079
+ removeConfig: majorVersion === 3
1080
+ });
1081
+ if (majorVersion !== 4 || cssEntrySource && !cssHandlerOptions.isMainChunk) {
1082
+ const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
1083
+ return resolved ? [resolved] : [];
1084
+ }
1085
+ let sourceOptions;
1086
+ try {
1087
+ sourceOptions = require_v3_engine.omitUndefined({
1088
+ ...require_v3_engine.resolveTailwindV4SourceOptionsFromPatcher(runtimeState.twPatcher),
1089
+ ...resolveCssHandlerSourceOptions(cssHandlerOptions)
1090
+ });
1091
+ } catch {
1092
+ const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
1093
+ return resolved ? [resolved] : [];
1094
+ }
1095
+ const matchedCssEntrySource = cssEntrySource ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
1096
+ const matchedCssSource = await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions);
1097
+ const candidateMatchedCssSource = await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions);
1098
+ const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource(shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
1099
+ const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource;
1100
+ if (sourceSideCssSource) return [sourceSideCssSource];
1101
+ if (preferredCssEntrySource) return [generatorOptions?.config ? {
1102
+ ...preferredCssEntrySource,
1103
+ css: prependConfigDirective(preferredCssEntrySource.css, generatorOptions.config)
1104
+ } : preferredCssEntrySource];
1105
+ if (!sourceOptions.cssEntries || sourceOptions.cssEntries.length <= 1) {
1106
+ if (sourceOptions.cssSources?.length === 1) return [await createTailwindV4CssSourceResolver(sourceOptions, generatorOptions)(sourceOptions.cssSources[0])];
1107
+ const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
1108
+ return resolved ? [resolved] : [];
1109
+ }
1110
+ const cssEntrySources = await Promise.all(sourceOptions.cssEntries.map((cssEntry) => require_v3_engine.resolveTailwindV4Source({
1111
+ ...require_v3_engine.omitUndefined(sourceOptions),
1112
+ cssEntries: [cssEntry]
1113
+ }).then((source) => generatorOptions?.config ? {
1114
+ ...source,
1115
+ css: prependConfigDirective(source.css, generatorOptions.config)
1116
+ } : source)));
1117
+ const cssSources = sourceOptions.cssSources?.length ? await Promise.all(sourceOptions.cssSources.map(createTailwindV4CssSourceResolver(sourceOptions, generatorOptions))) : [];
1118
+ return [...cssEntrySources, ...cssSources];
1119
+ }
1120
+ async function resolveGeneratorSourceEntries(source, runtimeState) {
1121
+ if (!("css" in source) || !("base" in source) || !("baseFallbacks" in source)) return;
1122
+ const sourceMetadata = source.__weappTailwindcssMeta;
1123
+ const resolved = await require_v3_engine.resolveTailwindV4EntriesFromCss(sourceMetadata?.sourceCss ?? source.css, sourceMetadata?.sourceBase ?? source.base);
1124
+ if (resolved?.entries.length || !resolved?.explicit && !sourceMetadata?.matchedCssSourceFile || !runtimeState) return resolved?.entries;
1125
+ const matchingCssSource = tryResolveTailwindV4SourceOptions(runtimeState)?.cssSources?.find((cssSource) => {
1126
+ if (sourceMetadata?.matchedCssSourceFile && typeof cssSource.file === "string" && node_path.default.resolve(cssSource.file) === node_path.default.resolve(sourceMetadata.matchedCssSourceFile)) return true;
1127
+ return cssSource.css === source.css;
1128
+ });
1129
+ if (!matchingCssSource) return resolved?.entries;
1130
+ const sourceResolved = await require_v3_engine.resolveTailwindV4EntriesFromCss(matchingCssSource.css, typeof matchingCssSource.base === "string" && matchingCssSource.base.length > 0 ? matchingCssSource.base : typeof matchingCssSource.file === "string" && matchingCssSource.file.length > 0 ? node_path.default.dirname(matchingCssSource.file) : source.base);
1131
+ if (sourceResolved?.entries.length) return sourceResolved.entries;
1132
+ for (const dependency of matchingCssSource.dependencies ?? []) {
1133
+ if (!(0, node_fs.existsSync)(dependency)) continue;
1134
+ try {
1135
+ const dependencyResolved = await require_v3_engine.resolveTailwindV4EntriesFromCss((0, node_fs.readFileSync)(dependency, "utf8"), node_path.default.dirname(dependency));
1136
+ if (dependencyResolved?.entries.length) return dependencyResolved.entries;
1137
+ } catch {}
1138
+ }
1139
+ return resolved?.entries;
1140
+ }
1141
+ //#endregion
1142
+ //#region src/bundlers/shared/generator-css/legacy-compat.ts
1143
+ const LEGACY_CONTAINER_COMPAT_CSS = [
1144
+ ".container {",
1145
+ " width: 100%;",
1146
+ "}",
1147
+ "@media (min-width: 40rem) {",
1148
+ " .container {",
1149
+ " max-width: 40rem;",
1150
+ " }",
1151
+ "}",
1152
+ "@media (min-width: 48rem) {",
1153
+ " .container {",
1154
+ " max-width: 48rem;",
1155
+ " }",
1156
+ "}",
1157
+ "@media (min-width: 64rem) {",
1158
+ " .container {",
1159
+ " max-width: 64rem;",
1160
+ " }",
1161
+ "}",
1162
+ "@media (min-width: 80rem) {",
1163
+ " .container {",
1164
+ " max-width: 80rem;",
1165
+ " }",
1166
+ "}",
1167
+ "@media (min-width: 96rem) {",
1168
+ " .container {",
1169
+ " max-width: 96rem;",
1170
+ " }",
1171
+ "}"
1172
+ ].join("\n");
1173
+ const LEGACY_COMPAT_CACHE_LIMIT = 128;
1174
+ const legacyCompatSourceCache = /* @__PURE__ */ new Map();
1175
+ const legacyCompatTransformCache = /* @__PURE__ */ new Map();
1176
+ function setLimitedCacheValue(cache, key, value) {
1177
+ if (cache.size >= LEGACY_COMPAT_CACHE_LIMIT) {
1178
+ const firstKey = cache.keys().next().value;
1179
+ if (firstKey !== void 0) cache.delete(firstKey);
1180
+ }
1181
+ cache.set(key, value);
1182
+ }
1183
+ function createStableJson(value) {
1184
+ if (value === void 0) return "undefined";
1185
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1186
+ if (Array.isArray(value)) return `[${value.map((item) => createStableJson(item)).join(",")}]`;
1187
+ return `{${Object.keys(value).sort().map((key) => {
1188
+ const record = value;
1189
+ return `${JSON.stringify(key)}:${createStableJson(record[key])}`;
1190
+ }).join(",")}}`;
1191
+ }
1192
+ function createLegacyCompatTransformCacheKey(source, options) {
1193
+ return `${createStableJson(options)}\0${source}`;
1194
+ }
1195
+ function countUnclosedBlocks(source) {
1196
+ let depth = 0;
1197
+ let quote;
1198
+ let inComment = false;
1199
+ let escaped = false;
1200
+ for (let index = 0; index < source.length; index += 1) {
1201
+ const char = source[index];
1202
+ const next = source[index + 1];
1203
+ if (inComment) {
1204
+ if (char === "*" && next === "/") {
1205
+ inComment = false;
1206
+ index += 1;
1207
+ }
1208
+ continue;
1209
+ }
1210
+ if (quote) {
1211
+ if (escaped) {
1212
+ escaped = false;
1213
+ continue;
1214
+ }
1215
+ if (char === "\\") {
1216
+ escaped = true;
1217
+ continue;
1218
+ }
1219
+ if (char === quote) quote = void 0;
1220
+ continue;
1221
+ }
1222
+ if (char === "/" && next === "*") {
1223
+ inComment = true;
1224
+ index += 1;
1225
+ continue;
1226
+ }
1227
+ if (char === "\"" || char === "'") {
1228
+ quote = char;
1229
+ continue;
1230
+ }
1231
+ if (char === "{") depth += 1;
1232
+ else if (char === "}" && depth > 0) depth -= 1;
1233
+ }
1234
+ return depth;
1235
+ }
1236
+ function closeTrailingUnclosedBlocks(source) {
1237
+ try {
1238
+ postcss.default.parse(source);
1239
+ return source;
1240
+ } catch (error) {
1241
+ if (error.reason !== "Unclosed block") return source;
1242
+ const unclosedBlocks = countUnclosedBlocks(source);
1243
+ return unclosedBlocks > 0 ? `${source}${"}".repeat(unclosedBlocks)}` : source;
1244
+ }
1245
+ }
1246
+ function removeTailwindApplyRules(rawSource) {
1247
+ try {
1248
+ const root = postcss.default.parse(rawSource);
1249
+ let removed = false;
1250
+ root.walkAtRules("apply", (rule) => {
1251
+ const parent = rule.parent;
1252
+ if (parent?.type === "rule") parent.remove();
1253
+ else rule.remove();
1254
+ removed = true;
1255
+ });
1256
+ root.walkAtRules((rule) => {
1257
+ if (rule.nodes && rule.nodes.length === 0) rule.remove();
1258
+ });
1259
+ return removed ? root.toString() : rawSource;
1260
+ } catch {
1261
+ return rawSource;
1262
+ }
1263
+ }
1264
+ function resolveLegacyCompatCssSource(rawSource) {
1265
+ const cached = legacyCompatSourceCache.get(rawSource);
1266
+ if (cached !== void 0) return cached;
1267
+ const resolved = closeTrailingUnclosedBlocks((0, _weapp_tailwindcss_postcss.removeUnsupportedMiniProgramAtRules)(removeTailwindApplyRules(removeTailwindSourceDirectives(closeTrailingUnclosedBlocks(stripTailwindBanners(rawSource))))));
1268
+ setLimitedCacheValue(legacyCompatSourceCache, rawSource, resolved);
1269
+ return resolved;
1270
+ }
1271
+ function hasContainerConfigToken(rawSource) {
1272
+ return rawSource.includes("@config") && /\bcontainer\b/.test(rawSource);
1273
+ }
1274
+ function hasConfiguredContainerCompat(rawSource, file, cssHandlerOptions) {
1275
+ if (hasContainerConfigToken(rawSource)) return true;
1276
+ const cssEntrySource = resolveCssEntrySource(rawSource, resolveCssSourceBase(file, cssHandlerOptions));
1277
+ if (!cssEntrySource?.config) return false;
1278
+ try {
1279
+ return /\bcontainer\b/.test((0, node_fs.readFileSync)(cssEntrySource.config, "utf8"));
1280
+ } catch {
1281
+ return false;
1282
+ }
1283
+ }
1284
+ function hasConfiguredContainerCompatSource(source) {
1285
+ if (hasContainerConfigToken(source.css)) return true;
1286
+ const cssEntrySource = resolveCssEntrySource(source.css, source.base);
1287
+ if (cssEntrySource?.config) try {
1288
+ if (/\bcontainer\b/.test((0, node_fs.readFileSync)(cssEntrySource.config, "utf8"))) return true;
1289
+ } catch {}
1290
+ if ("config" in source && source.config) try {
1291
+ if (/\bcontainer\b/.test((0, node_fs.readFileSync)(source.config, "utf8"))) return true;
1292
+ } catch {}
1293
+ return false;
1294
+ }
1295
+ function hasConfiguredContainerCompatSources(sources) {
1296
+ return sources.some((source) => hasConfiguredContainerCompatSource(source));
1297
+ }
1298
+ async function appendLegacyCompatCss(css, rawSource, generatorTarget, styleHandler, cssHandlerOptions, generatorStyleOptions) {
1299
+ const compatSource = removeGeneratedSelectorCompatCss(resolveLegacyCompatCssSource(rawSource), css);
1300
+ if (compatSource.trim().length === 0) return css;
1301
+ if (generatorTarget !== "weapp") return createCssAppend(css, compatSource);
1302
+ const styleOptions = {
1303
+ ...cssHandlerOptions,
1304
+ ...generatorStyleOptions
1305
+ };
1306
+ const compatCssCacheKey = createLegacyCompatTransformCacheKey(compatSource, styleOptions);
1307
+ let compatCss = legacyCompatTransformCache.get(compatCssCacheKey);
1308
+ if (compatCss === void 0) {
1309
+ compatCss = (await styleHandler(compatSource, styleOptions)).css;
1310
+ setLimitedCacheValue(legacyCompatTransformCache, compatCssCacheKey, compatCss);
1311
+ }
1312
+ const cleanedCompatCss = collectDedupedPostTransformCompatCss(removeDuplicatedViteMarkers((0, _weapp_tailwindcss_postcss.removeUnsupportedMiniProgramAtRules)(compatCss), css), css);
1313
+ if (cleanedCompatCss.trim().length === 0) return css;
1314
+ return createCssAppend(css, cleanedCompatCss);
1315
+ }
1316
+ async function appendLegacyContainerCompatCss(css, rawSource, file, runtime, configuredContainerCompat, generatorTarget, styleHandler, cssHandlerOptions, generatorStyleOptions) {
1317
+ const compatSource = resolveLegacyCompatCssSource(rawSource);
1318
+ const shouldAppendContainer = runtime.has("container") || hasConfiguredContainerCompat(rawSource, file, cssHandlerOptions) || configuredContainerCompat || collectGeneratedSelectors(compatSource).has(".container");
1319
+ if (generatorTarget !== "weapp" || !shouldAppendContainer || collectGeneratedSelectors(css).has(".container")) return css;
1320
+ const styleOptions = {
1321
+ ...cssHandlerOptions,
1322
+ ...generatorStyleOptions
1323
+ };
1324
+ const compatCssCacheKey = createLegacyCompatTransformCacheKey(LEGACY_CONTAINER_COMPAT_CSS, styleOptions);
1325
+ let compatCss = legacyCompatTransformCache.get(compatCssCacheKey);
1326
+ if (compatCss === void 0) {
1327
+ compatCss = (await styleHandler(LEGACY_CONTAINER_COMPAT_CSS, styleOptions)).css;
1328
+ setLimitedCacheValue(legacyCompatTransformCache, compatCssCacheKey, compatCss);
1329
+ }
1330
+ const cleanedCompatCss = collectDedupedPostTransformCompatCss((0, _weapp_tailwindcss_postcss.removeUnsupportedMiniProgramAtRules)(compatCss), css);
1331
+ if (cleanedCompatCss.trim().length === 0) return css;
1332
+ return createCssAppend(css, cleanedCompatCss);
1333
+ }
1334
+ //#endregion
1335
+ //#region src/bundlers/shared/generator-css/legacy-units.ts
1336
+ const CSS_LENGTH_UNIT_RE = /(?:^|[\s(,])[-+]?(?:\d+|\d*\.\d+)(?:px|rem)\b/i;
1337
+ const RPX_UNIT_RE = /(?:^|[\s(,])[-+]?(?:\d+|\d*\.\d+)rpx\b/i;
1338
+ function createLegacyDeclarationValueMap(css) {
1339
+ const values = /* @__PURE__ */ new Map();
1340
+ postcss.default.parse(css).walkRules((rule) => {
1341
+ if (!rule.selectors || rule.selectors.length === 0) return;
1342
+ for (const selector of rule.selectors) {
1343
+ const normalizedSelectors = normalizeCompatSelectors(selector);
1344
+ rule.walkDecls((decl) => {
1345
+ if (RPX_UNIT_RE.test(decl.value)) for (const normalizedSelector of normalizedSelectors) values.set(`${normalizedSelector}\n${decl.prop}`, decl.value);
1346
+ });
1347
+ }
1348
+ });
1349
+ return values;
1350
+ }
1351
+ function inheritLegacyUnitConvertedDeclarations(css, legacyCss) {
1352
+ try {
1353
+ const legacyValues = createLegacyDeclarationValueMap(legacyCss);
1354
+ if (legacyValues.size === 0) return css;
1355
+ const root = postcss.default.parse(css);
1356
+ let changed = false;
1357
+ root.walkRules((rule) => {
1358
+ if (!rule.selectors || rule.selectors.length === 0) return;
1359
+ const selectors = rule.selectors.flatMap((selector) => normalizeCompatSelectors(selector));
1360
+ if (selectors.length === 0) return;
1361
+ rule.walkDecls((decl) => {
1362
+ if (!CSS_LENGTH_UNIT_RE.test(decl.value)) return;
1363
+ for (const selector of selectors) {
1364
+ const legacyValue = legacyValues.get(`${selector}\n${decl.prop}`);
1365
+ if (legacyValue && legacyValue !== decl.value) {
1366
+ decl.value = legacyValue;
1367
+ changed = true;
1368
+ return;
1369
+ }
1370
+ }
1371
+ });
1372
+ });
1373
+ return changed ? root.toString() : css;
1374
+ } catch {
1375
+ return css;
1376
+ }
1377
+ }
1378
+ //#endregion
1379
+ //#region src/bundlers/shared/generator-css.ts
1380
+ const SUPPORTED_GENERATOR_MAJOR_VERSIONS = new Set([3, 4]);
1381
+ const REMOTE_IMPORT_RE = /^(?:https?:)?\/\//i;
1382
+ function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight, options = {}) {
1383
+ if (target !== "weapp") return css;
1384
+ return (0, _weapp_tailwindcss_postcss.finalizeMiniProgramCss)(css, {
1385
+ cssPreflight: majorVersion === 4 && options.injectPreflight !== false ? cssPreflight : void 0,
1386
+ preservePseudoContentInit: majorVersion === 3
1387
+ });
1388
+ }
1389
+ function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
1390
+ if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.isolateCssSource) return scopedRuntime;
1391
+ return new Set([...scopedRuntime, ...runtime]);
1392
+ }
1393
+ function shouldIsolateMatchedCssSource(source, sourceEntries) {
1394
+ return Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile && sourceEntries !== void 0);
1395
+ }
1396
+ function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
1397
+ if (majorVersion !== 4 || isolateCssSource) return false;
1398
+ return target === "web" || generatorRuntime.size === 0;
1399
+ }
1400
+ function shouldAppendWebBundleCssFallback(target, options) {
1401
+ return target === "web" && !options.hasMatchedCssSourceFile && !options.hasSourceDirectives;
1402
+ }
1403
+ function isEmptyCssSourceOrderParts(parts) {
1404
+ return parts.before.trim().length === 0 && parts.after.trim().length === 0;
1405
+ }
1406
+ function resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorStyleOptions) {
1407
+ const preflightStyleOptions = {
1408
+ cssPreflight: opts.cssPreflight,
1409
+ cssPreflightRange: opts.cssPreflightRange
1410
+ };
1411
+ return {
1412
+ ...require_precheck.resolveStyleOptionsFromContext(opts),
1413
+ atRules: opts.atRules,
1414
+ uniAppXCssTarget: opts.uniAppXCssTarget,
1415
+ uniAppXUnsupported: opts.uniAppXUnsupported,
1416
+ ...cssHandlerOptions,
1417
+ ...preflightStyleOptions,
1418
+ ...generatorStyleOptions
1419
+ };
1420
+ }
1421
+ function isLocalImportRequest(request) {
1422
+ return request.length > 0 && !request.startsWith("tailwindcss") && !request.startsWith("weapp-tailwindcss") && !request.startsWith("data:") && !REMOTE_IMPORT_RE.test(request);
1423
+ }
1424
+ function isCommentOnlyCss(source) {
1425
+ try {
1426
+ const root = postcss.default.parse(source);
1427
+ return root.nodes.length > 0 && root.nodes.every((node) => node.type === "comment");
1428
+ } catch {
1429
+ return false;
1430
+ }
1431
+ }
1432
+ function stripTailwindSourceMediaFragments(source) {
1433
+ return source.replace(/^\s*@media\s+source\([^)]*\)\s*\{\s*$/gm, "").replace(/^\s*\}\s*(?=@(?:source|theme|config|plugin|utility|variant|custom-variant)\b)/gm, "").replace(/^\s*\}\s*\/\*\s*source\([^)]*\)\s*\*\/\s*$/gm, "");
1434
+ }
1435
+ function stripLeadingTailwindSourceMediaCloseFragment(source) {
1436
+ return source.replace(/^\s*\}\s*(?:\n|$)/, "");
1437
+ }
1438
+ function stripUnmatchedTailwindSourceMediaCloseFragments(source) {
1439
+ try {
1440
+ postcss.default.parse(source);
1441
+ return source;
1442
+ } catch {
1443
+ return stripLeadingTailwindSourceMediaCloseFragment(source).replace(/\s*\}\s*$/, "");
1444
+ }
1445
+ }
1446
+ function createCssSourceOrderAppend(base, extra) {
1447
+ if (!base) return extra;
1448
+ if (!extra) return base;
1449
+ if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1450
+ return `${base}\n${extra}`;
1451
+ }
1452
+ function splitRawSourceByGeneratedCssOrder(rawSource, rawTailwindCss) {
1453
+ const placeholderParts = splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss);
1454
+ if (placeholderParts) return placeholderParts;
1455
+ const exactParts = splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss);
1456
+ if (exactParts) return exactParts;
1457
+ return splitTailwindGeneratedCssByBanner(rawSource);
1458
+ }
1459
+ async function transformGeneratorUserCss(source, options) {
1460
+ if (source.trim().length === 0) return "";
1461
+ const cleanedSource = removeTailwindSourceDirectives(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(source)), { importFallback: options.importFallback });
1462
+ if (cleanedSource.trim().length === 0) return "";
1463
+ const userSource = stripUnmatchedTailwindSourceMediaCloseFragments(removeTailwindSourceDirectives(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(options.generatorTarget === "weapp" ? (0, _weapp_tailwindcss_postcss.removeUnsupportedMiniProgramAtRules)(cleanedSource) : cleanedSource)), { importFallback: options.importFallback }));
1464
+ if (userSource.trim().length === 0) return "";
1465
+ if (isCommentOnlyCss(userSource)) return userSource;
1466
+ if (options.generatorTarget !== "weapp") return userSource;
1467
+ const { css } = await options.styleHandler(userSource, {
1468
+ ...options.generatorStyleOptions,
1469
+ ...options.cssUserHandlerOptions
1470
+ });
1471
+ return (0, _weapp_tailwindcss_postcss.removeUnsupportedMiniProgramAtRules)(css);
1472
+ }
1473
+ function isPureLocalCssImportWrapper(css) {
1474
+ let hasImport = false;
1475
+ try {
1476
+ const root = postcss.default.parse(css);
1477
+ for (const node of root.nodes) {
1478
+ if (node.type === "comment") continue;
1479
+ if (node.type !== "atrule" || node.name !== "import") return false;
1480
+ const request = parseImportRequest(node.params);
1481
+ if (!request || !isLocalImportRequest(request)) return false;
1482
+ hasImport = true;
1483
+ }
1484
+ } catch {
1485
+ return false;
1486
+ }
1487
+ return hasImport;
1488
+ }
1489
+ function cleanLocalCssImportWrapperTailwindDirectives(css) {
1490
+ let hasLocalImport = false;
1491
+ let hasTailwindDirective = false;
1492
+ try {
1493
+ const root = postcss.default.parse(css);
1494
+ for (const node of root.nodes) {
1495
+ if (node.type === "comment") continue;
1496
+ if (node.type === "atrule" && node.name === "import") {
1497
+ const request = parseImportRequest(node.params);
1498
+ if (!request || !isLocalImportRequest(request)) return;
1499
+ hasLocalImport = true;
1500
+ continue;
1501
+ }
1502
+ if (node.type === "atrule" && node.name === "source") {
1503
+ hasTailwindDirective = true;
1504
+ continue;
1505
+ }
1506
+ return;
1507
+ }
1508
+ } catch {
1509
+ return;
1510
+ }
1511
+ return hasLocalImport && hasTailwindDirective ? prefixLocalCssImportsWithWebpackIgnore(removeTailwindSourceDirectives(css)) : void 0;
1512
+ }
1513
+ function prefixLocalCssImportsWithWebpackIgnore(css) {
1514
+ try {
1515
+ const root = postcss.default.parse(css);
1516
+ root.walkAtRules("import", (atRule) => {
1517
+ const request = parseImportRequest(atRule.params);
1518
+ if (request && isLocalImportRequest(request)) atRule.raws.before = `${atRule.raws.before ?? ""}/* webpackIgnore: true */\n`;
1519
+ });
1520
+ return root.toString();
1521
+ } catch {
1522
+ return css;
1523
+ }
1524
+ }
1525
+ async function generateCssByGenerator(options) {
1526
+ const { opts, runtimeState, runtime, rawSource, file, cssHandlerOptions, cssUserHandlerOptions, getSourceCandidatesForEntries, styleHandler, debug } = options;
1527
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1528
+ const majorVersion = runtimeState.twPatcher.majorVersion;
1529
+ const effectiveRawSource = stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(normalizeTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })));
1530
+ const cleanedLocalImportWrapper = cleanLocalCssImportWrapperTailwindDirectives(effectiveRawSource);
1531
+ if (cleanedLocalImportWrapper !== void 0) return {
1532
+ css: generatorOptions.target === "weapp" ? (0, _weapp_tailwindcss_postcss.removeUnsupportedMiniProgramAtRules)(cleanedLocalImportWrapper) : cleanedLocalImportWrapper,
1533
+ target: generatorOptions.target,
1534
+ source: "generator",
1535
+ dependencies: []
1536
+ };
1537
+ if (isPureLocalCssImportWrapper(effectiveRawSource)) return;
1538
+ const hasGeneratedCss = hasTailwindGeneratedCss(effectiveRawSource);
1539
+ const hasSourceDirectives = hasTailwindSourceDirectives(effectiveRawSource, { importFallback: generatorOptions.importFallback });
1540
+ const hasGeneratedMarkers = hasTailwindGeneratedCssMarkers(effectiveRawSource);
1541
+ const shouldGenerateCurrentCss = hasGeneratedCss || hasGeneratedMarkers || hasSourceDirectives || cssHandlerOptions.isMainChunk;
1542
+ if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
1543
+ try {
1544
+ await runtimeState.readyPromise;
1545
+ const currentCssCandidates = majorVersion === 4 ? await (0, tailwindcss_patch.extractSourceCandidates)(effectiveRawSource, "css") : [];
1546
+ const runtimeWithCurrentCss = currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
1547
+ const sources = await resolveGeneratorSources(majorVersion, runtimeState, effectiveRawSource, file, cssHandlerOptions, generatorOptions, {
1548
+ getSourceCandidatesForEntries,
1549
+ runtime: runtimeWithCurrentCss
1550
+ });
1551
+ const generatorStyleOptions = resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorOptions.styleOptions);
1552
+ const configuredContainerCompat = hasConfiguredContainerCompatSources(sources);
1553
+ const generatedResults = await Promise.all(sources.map(async (source) => {
1554
+ const generator = require_generator.createWeappTailwindcssGenerator(source);
1555
+ const sourceEntries = getSourceCandidatesForEntries && majorVersion === 4 ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
1556
+ const scopedRuntime = sourceEntries ? getSourceCandidatesForEntries?.(sourceEntries) : void 0;
1557
+ const isolateCssSource = shouldIsolateMatchedCssSource(source, sourceEntries);
1558
+ const sourceRuntime = scopedRuntime && (scopedRuntime.size > 0 || isolateCssSource) ? mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtimeWithCurrentCss, {
1559
+ cssHandlerOptions,
1560
+ isolateCssSource
1561
+ }) : runtimeWithCurrentCss;
1562
+ const generatorRuntime = majorVersion === 4 && generatorOptions.target === "weapp" ? require_v3_engine.filterUnsupportedMiniProgramTailwindV4Candidates(sourceRuntime) : sourceRuntime;
1563
+ return generator.generate({
1564
+ candidates: generatorRuntime,
1565
+ incrementalCache: majorVersion === 3 || majorVersion === 4,
1566
+ scanSources: shouldScanTailwindV4Sources(majorVersion, generatorOptions.target, generatorRuntime, isolateCssSource),
1567
+ styleOptions: generatorStyleOptions,
1568
+ tailwindcssV3Compatibility: generatorOptions.tailwindcssV3Compatibility,
1569
+ target: generatorOptions.target
1570
+ });
1571
+ }));
1572
+ const firstGenerated = generatedResults[0];
1573
+ if (!firstGenerated) return;
1574
+ const incrementalCssResults = generatedResults.map((item) => item.incrementalCss).filter((css) => typeof css === "string");
1575
+ const incrementalRawCssResults = generatedResults.map((item) => item.incrementalRawCss).filter((css) => typeof css === "string");
1576
+ const generated = generatedResults.length === 1 ? firstGenerated : {
1577
+ ...firstGenerated,
1578
+ css: generatedResults.map((item) => item.css).join("\n"),
1579
+ rawCss: generatedResults.map((item) => item.rawCss).join("\n"),
1580
+ incrementalCss: incrementalCssResults.length === generatedResults.length ? incrementalCssResults.filter(Boolean).join("\n") : void 0,
1581
+ incrementalRawCss: incrementalRawCssResults.length === generatedResults.length ? incrementalRawCssResults.filter(Boolean).join("\n") : void 0,
1582
+ classSet: new Set(generatedResults.flatMap((item) => [...item.classSet])),
1583
+ dependencies: [...new Set(generatedResults.flatMap((item) => item.dependencies))],
1584
+ sources: generatedResults.flatMap((item) => item.sources)
1585
+ };
1586
+ debug("tailwind generator result: %s rawBytes=%d cssBytes=%d candidates=%d", file, generated.rawCss.length, generated.css.length, generated.classSet.size);
1587
+ if (typeof options.previousCss === "string" && typeof generated.incrementalCss === "string") {
1588
+ const incrementalCss = stripTailwindBanner(generated.incrementalCss);
1589
+ return {
1590
+ css: incrementalCss.trim().length > 0 ? createCssAppend(options.previousCss, finalizeMiniProgramGeneratorCss(incrementalCss, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: false })) : options.previousCss,
1591
+ target: generated.target,
1592
+ source: "generator",
1593
+ dependencies: generated.dependencies,
1594
+ incremental: true
1595
+ };
1596
+ }
1597
+ const hasMatchedCssSourceFile = sources.some((source) => source.__weappTailwindcssMeta?.matchedCssSourceFile);
1598
+ const orderedExtraCss = hasMatchedCssSourceFile ? splitTailwindV4GeneratedCssBySourceOrder(effectiveRawSource, generated.rawCss) : splitRawSourceByGeneratedCssOrder(effectiveRawSource, generated.rawCss);
1599
+ if (orderedExtraCss) {
1600
+ let css = stripTailwindBanner(generated.css);
1601
+ if (generated.target === "weapp") css = inheritLegacyUnitConvertedDeclarations(css, effectiveRawSource);
1602
+ const userCssOptions = {
1603
+ generatorTarget: generated.target,
1604
+ generatorStyleOptions,
1605
+ cssUserHandlerOptions,
1606
+ styleHandler,
1607
+ importFallback: generatorOptions.importFallback
1608
+ };
1609
+ const beforeUserCss = await transformGeneratorUserCss(orderedExtraCss.before, userCssOptions);
1610
+ const afterUserCss = await transformGeneratorUserCss(orderedExtraCss.after, userCssOptions);
1611
+ css = createCssSourceOrderAppend(createCssSourceOrderAppend(beforeUserCss, css), afterUserCss);
1612
+ if (isEmptyCssSourceOrderParts(orderedExtraCss) && shouldAppendWebBundleCssFallback(generated.target, {
1613
+ hasSourceDirectives,
1614
+ hasMatchedCssSourceFile
1615
+ })) {
1616
+ const userCss = await transformGeneratorUserCss(effectiveRawSource, userCssOptions);
1617
+ css = createCssSourceOrderAppend(css, userCss);
1618
+ }
1619
+ if (generated.target === "weapp") {
1620
+ css = await appendLegacyCompatCss(css, effectiveRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1621
+ css = await appendLegacyContainerCompatCss(css, effectiveRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1622
+ }
1623
+ return {
1624
+ css: finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight),
1625
+ target: generated.target,
1626
+ source: "generator",
1627
+ dependencies: generated.dependencies
1628
+ };
1629
+ }
1630
+ debug("tailwind direct css generation prefix mismatch, append transformed bundle css %s", file);
1631
+ let css = stripTailwindBanner(generated.css);
1632
+ if (generated.target === "weapp") css = inheritLegacyUnitConvertedDeclarations(css, effectiveRawSource);
1633
+ if (hasMatchedCssSourceFile || generated.target === "web") {
1634
+ if (shouldAppendWebBundleCssFallback(generated.target, {
1635
+ hasSourceDirectives,
1636
+ hasMatchedCssSourceFile
1637
+ })) {
1638
+ const userCss = await transformGeneratorUserCss(effectiveRawSource, {
1639
+ generatorTarget: generated.target,
1640
+ generatorStyleOptions,
1641
+ cssUserHandlerOptions,
1642
+ styleHandler,
1643
+ importFallback: generatorOptions.importFallback
1644
+ });
1645
+ css = createCssSourceOrderAppend(css, userCss);
1646
+ }
1647
+ return {
1648
+ css: finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight),
1649
+ target: generated.target,
1650
+ source: "generator",
1651
+ dependencies: generated.dependencies
1652
+ };
1653
+ }
1654
+ css = await appendLegacyCompatCss(css, effectiveRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1655
+ css = await appendLegacyContainerCompatCss(css, effectiveRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1656
+ return {
1657
+ css: finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight),
1658
+ target: generated.target,
1659
+ source: "generator",
1660
+ dependencies: generated.dependencies
1661
+ };
1662
+ } catch (error) {
1663
+ debug("tailwind direct css generation failed: %s %O", file, error);
1664
+ throw error;
1665
+ }
1666
+ }
1667
+ async function validateCandidatesByGenerator(options) {
1668
+ const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState } = options;
1669
+ const majorVersion = runtimeState.twPatcher.majorVersion;
1670
+ if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || candidates.size === 0) return /* @__PURE__ */ new Set();
1671
+ const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator), { runtime: candidates });
1672
+ const classSets = await Promise.all(sources.map(async (source) => {
1673
+ const generator = require_generator.createWeappTailwindcssGenerator(source);
1674
+ if (typeof generator.validateCandidates === "function") return generator.validateCandidates(candidates);
1675
+ return (await generator.generate({
1676
+ candidates,
1677
+ target: "tailwind"
1678
+ })).classSet;
1679
+ }));
1680
+ const classSet = new Set(classSets.flatMap((item) => [...item]));
1681
+ debug("tailwind generator validated candidates: %s candidates=%d classSet=%d", file, candidates.size, classSet.size);
1682
+ return classSet;
1683
+ }
1684
+ //#endregion
1685
+ //#region src/bundlers/shared/hmr-timing.ts
1686
+ function shouldEmitHmrTiming() {
1687
+ return node_process.default.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || node_process.default.env["WEAPP_TW_HMR_TIMING"] === "1";
1688
+ }
1689
+ function shouldEmitHumanReadableTiming() {
1690
+ return node_process.default.env["WEAPP_TW_HMR_TIMING"] === "1" && node_process.default.env["WEAPP_TW_HMR_TIMING_LOG"] !== "0";
1691
+ }
1692
+ function emitHmrTiming(bundler, phase, durationMs, details = {}) {
1693
+ if (!shouldEmitHmrTiming()) return;
1694
+ const serializableDetails = { ...details };
1695
+ delete serializableDetails.emit;
1696
+ const payload = {
1697
+ bundler,
1698
+ phase,
1699
+ durationMs: Math.max(0, Math.round(durationMs)),
1700
+ ...serializableDetails,
1701
+ ...typeof details.wallMs === "number" ? { wallMs: Math.max(0, Math.round(details.wallMs)) } : {}
1702
+ };
1703
+ node_process.default.stdout.write(`[weapp-tailwindcss:hmr] ${JSON.stringify(payload)}\n`);
1704
+ if (shouldEmitHumanReadableTiming()) {
1705
+ const fileSuffix = details.file ? ` file=${details.file}` : "";
1706
+ if (details.metric === "total") {
1707
+ const hooks = details.hooks ? Object.entries(details.hooks).map(([hook, summary]) => `${hook}=${Math.max(0, Math.round(summary.durationMs))}ms/${summary.count}`).join(", ") : "";
1708
+ const hookSuffix = hooks ? ` (${hooks})` : "";
1709
+ const wallSuffix = typeof payload.wallMs === "number" ? ` wall=${payload.wallMs}ms` : "";
1710
+ node_process.default.stdout.write(`[weapp-tailwindcss] ${bundler}:weapp-tailwindcss 总耗时 ${payload.durationMs}ms${wallSuffix}${hookSuffix}\n`);
1711
+ return;
1712
+ }
1713
+ node_process.default.stdout.write(`[weapp-tailwindcss] ${bundler}:${phase} 耗时 ${payload.durationMs}ms${fileSuffix}\n`);
1714
+ }
1715
+ }
1716
+ function createHmrTimingRecorder(bundler) {
1717
+ const session = {
1718
+ hooks: {},
1719
+ totalMs: 0
1720
+ };
1721
+ const record = (phase, durationMs, details = {}) => {
1722
+ const roundedDuration = Math.max(0, Math.round(durationMs));
1723
+ if (session.startedAt === void 0) session.startedAt = performance.now() - Math.max(0, durationMs);
1724
+ session.totalMs += Math.max(0, durationMs);
1725
+ const current = session.hooks[phase] ?? {
1726
+ count: 0,
1727
+ durationMs: 0,
1728
+ maxMs: 0
1729
+ };
1730
+ current.count += 1;
1731
+ current.durationMs += roundedDuration;
1732
+ current.maxMs = Math.max(current.maxMs, roundedDuration);
1733
+ session.hooks[phase] = current;
1734
+ if (details.emit !== false) emitHmrTiming(bundler, phase, durationMs, details);
1735
+ };
1736
+ const measure = async (phase, task, details = {}) => {
1737
+ const startedAt = performance.now();
1738
+ try {
1739
+ return await task();
1740
+ } finally {
1741
+ record(phase, performance.now() - startedAt, details);
1742
+ }
1743
+ };
1744
+ const emitTotal = (phase = "total") => {
1745
+ if (session.totalMs <= 0) return;
1746
+ const wallMs = session.startedAt === void 0 ? session.totalMs : performance.now() - session.startedAt;
1747
+ emitHmrTiming(bundler, phase, session.totalMs, {
1748
+ hooks: session.hooks,
1749
+ metric: "total",
1750
+ wallMs
1751
+ });
1752
+ session.hooks = {};
1753
+ delete session.startedAt;
1754
+ session.totalMs = 0;
1755
+ };
1756
+ return {
1757
+ emitTotal,
1758
+ measure,
1759
+ record
1760
+ };
1761
+ }
1762
+ //#endregion
1763
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
1764
+ const debug = require_v3_engine.createDebug("[vite:runtime-set] ");
1765
+ const EXTENSION_DOT_PREFIX_RE = /^\./;
1766
+ const VENDOR_CHUNK_BASENAME_RE = /^(?:vendor|vendors|chunk-vendors|common_vendor)(?:[.-]|$)/i;
1767
+ const COMMON_VENDOR_CHUNK_RE = /^(?:common|static|assets|chunks?)\/(?:vendor|vendors|chunk-vendors|common_vendor|runtime)(?:[.-]|$)/i;
1768
+ function toPosixPath(value) {
1769
+ return value.split("\\").join("/");
1770
+ }
1771
+ function isDependencyModuleId(id) {
1772
+ const normalized = toPosixPath(id);
1773
+ return normalized.includes("/node_modules/") || normalized.includes("/.pnpm/") || normalized.includes("/node_modules_");
1774
+ }
1775
+ function collectChunkModuleIds(entry) {
1776
+ if (entry.output.type !== "chunk") return [];
1777
+ return [...entry.output.moduleIds, ...Object.keys(entry.output.modules ?? {})].filter((id, index, ids) => ids.indexOf(id) === index);
1778
+ }
1779
+ function isKnownVendorChunkFile(file) {
1780
+ const normalized = toPosixPath(file).replace(/^\.\//, "");
1781
+ const basename = normalized.slice(normalized.lastIndexOf("/") + 1);
1782
+ return VENDOR_CHUNK_BASENAME_RE.test(basename) || COMMON_VENDOR_CHUNK_RE.test(normalized) || normalized.includes("/node_modules/") || normalized.includes("/node_modules_");
1783
+ }
1784
+ function isDependencyOnlyChunk(entry) {
1785
+ if (entry.output.type !== "chunk") return false;
1786
+ if (entry.output.isEntry || entry.output.isDynamicEntry || entry.output.isImplicitEntry) return false;
1787
+ const moduleIds = collectChunkModuleIds(entry);
1788
+ return moduleIds.length > 0 && moduleIds.every(isDependencyModuleId);
1789
+ }
1790
+ function isRuntimeCandidateEntry(entry) {
1791
+ if (entry.type === "html") return true;
1792
+ if (entry.type !== "js") return false;
1793
+ if (isDependencyOnlyChunk(entry)) return false;
1794
+ if (!isKnownVendorChunkFile(entry.file)) return true;
1795
+ if (entry.output.type !== "chunk") return false;
1796
+ if (entry.output.facadeModuleId && !isDependencyModuleId(entry.output.facadeModuleId)) return true;
1797
+ return collectChunkModuleIds(entry).some((id) => !isDependencyModuleId(id));
1798
+ }
1799
+ function createExtractOptions(context, source) {
1800
+ return {
1801
+ cwd: context.projectRoot,
1802
+ base: context.base,
1803
+ baseFallbacks: context.baseFallbacks,
1804
+ css: context.css,
1805
+ content: source,
1806
+ extension: "html"
1807
+ };
1808
+ }
1809
+ function createRuntimeEntries(snapshot) {
1810
+ return snapshot.entries.filter(isRuntimeCandidateEntry);
1811
+ }
1812
+ function collectChangedRuntimeFiles(snapshot) {
1813
+ return new Set([...snapshot.runtimeAffectingChangedByType.html, ...snapshot.runtimeAffectingChangedByType.js]);
1814
+ }
1815
+ function resolveEntryExtension(entry) {
1816
+ if (entry.type === "html") return "html";
1817
+ const ext = entry.file.split(/[?#]/, 1)[0]?.split(".").pop()?.replace(EXTENSION_DOT_PREFIX_RE, "") ?? "";
1818
+ if (ext.length > 0) return ext;
1819
+ return "js";
1820
+ }
1821
+ function createCandidateValidationSource(candidates) {
1822
+ return [...new Set(candidates)].sort().join("\n");
1823
+ }
1824
+ function removeCandidateSet(candidateCountByClass, candidates) {
1825
+ for (const className of candidates) {
1826
+ const count = candidateCountByClass.get(className);
1827
+ if (count == null) continue;
1828
+ if (count <= 1) {
1829
+ candidateCountByClass.delete(className);
1830
+ continue;
1831
+ }
1832
+ candidateCountByClass.set(className, count - 1);
1833
+ }
1834
+ }
1835
+ function addCandidateSet(candidateCountByClass, candidates) {
1836
+ for (const className of candidates) {
1837
+ const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
1838
+ candidateCountByClass.set(className, nextCount);
1839
+ }
1840
+ }
1841
+ function createRuntimeClassSet(baseClassSet, candidateCountByClass) {
1842
+ return new Set([...baseClassSet, ...candidateCountByClass.keys()]);
1843
+ }
1844
+ function createNonSourceBaseClassSet(baseClassSet, candidateCountByClass) {
1845
+ const nextBaseClassSet = new Set(baseClassSet);
1846
+ for (const candidate of candidateCountByClass.keys()) nextBaseClassSet.delete(candidate);
1847
+ return nextBaseClassSet;
1848
+ }
1849
+ function createBundleRuntimeClassSetManager(options = {}) {
1850
+ const customExtractCandidates = options.extractCandidates;
1851
+ const extractCandidates = customExtractCandidates ?? tailwindcss_patch.extractValidCandidates;
1852
+ const extractRawCandidates = options.extractRawCandidates ?? tailwindcss_patch.extractRawCandidatesWithPositions;
1853
+ let baseClassSet = /* @__PURE__ */ new Set();
1854
+ const candidateCountByClass = /* @__PURE__ */ new Map();
1855
+ const candidatesByFile = /* @__PURE__ */ new Map();
1856
+ const candidateValidityCache = /* @__PURE__ */ new Map();
1857
+ let runtimeSignature;
1858
+ let validationContext;
1859
+ let designSystemPromise;
1860
+ async function reset() {
1861
+ baseClassSet = /* @__PURE__ */ new Set();
1862
+ candidateCountByClass.clear();
1863
+ candidatesByFile.clear();
1864
+ candidateValidityCache.clear();
1865
+ runtimeSignature = void 0;
1866
+ validationContext = void 0;
1867
+ designSystemPromise = void 0;
1868
+ }
1869
+ async function resolveValidationContextCached(patcher) {
1870
+ if (!validationContext) validationContext = await require_v3_engine.resolveTailwindV4SourceFromPatcher(patcher);
1871
+ return validationContext;
1872
+ }
1873
+ async function loadDesignSystem(context) {
1874
+ if (!designSystemPromise) designSystemPromise = (0, tailwindcss_patch.loadTailwindV4DesignSystem)(context);
1875
+ return designSystemPromise;
1876
+ }
1877
+ function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
1878
+ const parsedCandidates = [...unknownCandidates].filter((candidate) => designSystem.parseCandidate(candidate).length > 0);
1879
+ const cssByCandidate = parsedCandidates.length > 0 ? designSystem.candidatesToCss(parsedCandidates) : [];
1880
+ const validCandidates = /* @__PURE__ */ new Set();
1881
+ for (let index = 0; index < parsedCandidates.length; index += 1) {
1882
+ const candidate = parsedCandidates[index];
1883
+ const css = cssByCandidate[index];
1884
+ if (candidate && typeof css === "string" && css.trim().length > 0) validCandidates.add(candidate);
1885
+ }
1886
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1887
+ }
1888
+ async function validateUnknownCandidates(patcher, unknownCandidates) {
1889
+ if (unknownCandidates.size === 0) return;
1890
+ if (patcher.majorVersion === 3 && !customExtractCandidates) {
1891
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, true);
1892
+ return;
1893
+ }
1894
+ const context = await resolveValidationContextCached(patcher);
1895
+ if (!customExtractCandidates) try {
1896
+ populateCandidateValidityCacheFromDesignSystem(await loadDesignSystem(context), unknownCandidates);
1897
+ return;
1898
+ } catch (error) {
1899
+ debug("incremental design-system validation failed: %O", error);
1900
+ designSystemPromise = void 0;
1901
+ throw error;
1902
+ }
1903
+ const source = createCandidateValidationSource(unknownCandidates);
1904
+ const validCandidates = new Set(await extractCandidates(createExtractOptions(context, source)));
1905
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1906
+ }
1907
+ async function extractEntryRawCandidates(entry) {
1908
+ const matches = await extractRawCandidates(entry.source, resolveEntryExtension(entry));
1909
+ const candidates = /* @__PURE__ */ new Set();
1910
+ for (const match of matches) {
1911
+ const candidate = match?.rawCandidate;
1912
+ if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
1913
+ }
1914
+ return candidates;
1915
+ }
1916
+ async function sync(patcher, snapshot, options = {}) {
1917
+ const nextSignature = require_v3_engine.getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1918
+ const runtimeEntries = createRuntimeEntries(snapshot);
1919
+ const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1920
+ const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
1921
+ const hadTrackedRuntimeFiles = candidatesByFile.size > 0;
1922
+ const fullRebuild = runtimeSignature !== nextSignature || candidatesByFile.size === 0;
1923
+ if (runtimeSignature !== nextSignature) {
1924
+ debug("runtime signature changed, reset incremental runtime set: %s", nextSignature);
1925
+ await reset();
1926
+ }
1927
+ runtimeSignature = nextSignature;
1928
+ const nextBaseClassSet = options.baseClassSet;
1929
+ const canUseBaseWithoutInitialFullScan = Boolean(fullRebuild && !hadTrackedRuntimeFiles && options.skipInitialFullScanWithBase === true && nextBaseClassSet && nextBaseClassSet.size > 0);
1930
+ for (const [file, previousCandidates] of candidatesByFile) {
1931
+ if (currentRuntimeFiles.has(file)) continue;
1932
+ removeCandidateSet(candidateCountByClass, previousCandidates);
1933
+ candidatesByFile.delete(file);
1934
+ }
1935
+ const changedRuntimeFiles = canUseBaseWithoutInitialFullScan ? [...collectChangedRuntimeFiles(snapshot)] : fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
1936
+ if (changedRuntimeFiles.length === 0) {
1937
+ if (nextBaseClassSet) baseClassSet = canUseBaseWithoutInitialFullScan ? new Set(nextBaseClassSet) : createNonSourceBaseClassSet(nextBaseClassSet, candidateCountByClass);
1938
+ return createRuntimeClassSet(baseClassSet, candidateCountByClass);
1939
+ }
1940
+ const rawCandidatesByFile = /* @__PURE__ */ new Map();
1941
+ const unknownCandidates = /* @__PURE__ */ new Set();
1942
+ await Promise.all(changedRuntimeFiles.map(async (file) => {
1943
+ const entry = runtimeEntriesByFile.get(file);
1944
+ if (!entry) return;
1945
+ const candidates = await extractEntryRawCandidates(entry);
1946
+ rawCandidatesByFile.set(file, candidates);
1947
+ for (const candidate of candidates) if (!candidateValidityCache.has(candidate)) unknownCandidates.add(candidate);
1948
+ }));
1949
+ await validateUnknownCandidates(patcher, unknownCandidates);
1950
+ let rawCandidateCount = 0;
1951
+ for (const file of changedRuntimeFiles) {
1952
+ const nextRawCandidates = rawCandidatesByFile.get(file);
1953
+ const previousCandidates = candidatesByFile.get(file);
1954
+ if (previousCandidates) removeCandidateSet(candidateCountByClass, previousCandidates);
1955
+ if (!nextRawCandidates || nextRawCandidates.size === 0) {
1956
+ candidatesByFile.delete(file);
1957
+ continue;
1958
+ }
1959
+ rawCandidateCount += nextRawCandidates.size;
1960
+ const nextCandidates = new Set([...nextRawCandidates].filter((candidate) => candidateValidityCache.get(candidate) === true));
1961
+ if (nextCandidates.size === 0) {
1962
+ candidatesByFile.delete(file);
1963
+ continue;
1964
+ }
1965
+ addCandidateSet(candidateCountByClass, nextCandidates);
1966
+ candidatesByFile.set(file, nextCandidates);
1967
+ }
1968
+ if (nextBaseClassSet) baseClassSet = canUseBaseWithoutInitialFullScan ? new Set(nextBaseClassSet) : createNonSourceBaseClassSet(nextBaseClassSet, candidateCountByClass);
1969
+ const runtimeSet = createRuntimeClassSet(baseClassSet, candidateCountByClass);
1970
+ debug("incremental runtime set synced, changedFiles=%d rawCandidates=%d validateMisses=%d runtimeSize=%d trackedFiles=%d", changedRuntimeFiles.length, rawCandidateCount, unknownCandidates.size, runtimeSet.size, candidatesByFile.size);
1971
+ return new Set(runtimeSet);
1972
+ }
1973
+ return {
1974
+ sync,
1975
+ reset
1976
+ };
1977
+ }
1978
+ //#endregion
1979
+ Object.defineProperty(exports, "createBundleRuntimeClassSetManager", {
1980
+ enumerable: true,
1981
+ get: function() {
1982
+ return createBundleRuntimeClassSetManager;
1983
+ }
1984
+ });
1985
+ Object.defineProperty(exports, "createHmrTimingRecorder", {
1986
+ enumerable: true,
1987
+ get: function() {
1988
+ return createHmrTimingRecorder;
1989
+ }
1990
+ });
1991
+ Object.defineProperty(exports, "emitHmrTiming", {
1992
+ enumerable: true,
1993
+ get: function() {
1994
+ return emitHmrTiming;
1995
+ }
1996
+ });
1997
+ Object.defineProperty(exports, "generateCssByGenerator", {
1998
+ enumerable: true,
1999
+ get: function() {
2000
+ return generateCssByGenerator;
2001
+ }
2002
+ });
2003
+ Object.defineProperty(exports, "hasTailwindGeneratedCssMarkers", {
2004
+ enumerable: true,
2005
+ get: function() {
2006
+ return hasTailwindGeneratedCssMarkers;
2007
+ }
2008
+ });
2009
+ Object.defineProperty(exports, "hasTailwindRootDirectives", {
2010
+ enumerable: true,
2011
+ get: function() {
2012
+ return hasTailwindRootDirectives;
2013
+ }
2014
+ });
2015
+ Object.defineProperty(exports, "hasTailwindSourceDirectives", {
2016
+ enumerable: true,
2017
+ get: function() {
2018
+ return hasTailwindSourceDirectives;
2019
+ }
2020
+ });
2021
+ Object.defineProperty(exports, "normalizeTailwindSourceForGenerator", {
2022
+ enumerable: true,
2023
+ get: function() {
2024
+ return normalizeTailwindSourceForGenerator;
2025
+ }
2026
+ });
2027
+ Object.defineProperty(exports, "processCachedTask", {
2028
+ enumerable: true,
2029
+ get: function() {
2030
+ return processCachedTask;
2031
+ }
2032
+ });
2033
+ Object.defineProperty(exports, "validateCandidatesByGenerator", {
2034
+ enumerable: true,
2035
+ get: function() {
2036
+ return validateCandidatesByGenerator;
2037
+ }
2038
+ });