weapp-tailwindcss 5.0.0-next.1 → 5.0.0-next.11

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 (215) hide show
  1. package/README.md +4 -5
  2. package/bin/weapp-tailwindcss.js +1 -21
  3. package/dist/bundle-state-BRkhpjio.js +448 -0
  4. package/dist/bundle-state-BrtFgX-A.mjs +369 -0
  5. package/dist/bundlers/shared/cache.d.ts +6 -6
  6. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +2 -0
  7. package/dist/bundlers/shared/css-cleanup/color-gamut.d.ts +3 -0
  8. package/dist/bundlers/shared/css-cleanup/root-cleanups.d.ts +4 -0
  9. package/dist/bundlers/shared/css-cleanup/selectors.d.ts +8 -0
  10. package/dist/bundlers/shared/css-cleanup.d.ts +1 -2
  11. package/dist/bundlers/shared/css-imports.d.ts +3 -3
  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 +16 -0
  18. package/dist/bundlers/shared/generator-css/source-files.d.ts +11 -0
  19. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +10 -0
  20. package/dist/bundlers/shared/generator-css.d.ts +12 -20
  21. package/dist/bundlers/shared/hmr-timing.d.ts +5 -0
  22. package/dist/bundlers/shared/style-requests.d.ts +2 -0
  23. package/dist/bundlers/vite/css-finalizer.d.ts +4 -1
  24. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +2 -0
  25. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +20 -0
  26. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +3 -0
  27. package/dist/bundlers/vite/generate-bundle/dirty-state.d.ts +1 -0
  28. package/dist/bundlers/vite/generate-bundle/js-entries.d.ts +2 -0
  29. package/dist/bundlers/vite/generate-bundle/js-handler-options.d.ts +8 -0
  30. package/dist/bundlers/vite/generate-bundle/js-linking.d.ts +13 -0
  31. package/dist/bundlers/vite/generate-bundle/metrics.d.ts +17 -0
  32. package/dist/bundlers/vite/generate-bundle/process-plan.d.ts +9 -0
  33. package/dist/bundlers/vite/generate-bundle/rollup-assets.d.ts +7 -0
  34. package/dist/bundlers/vite/generate-bundle/signatures.d.ts +8 -0
  35. package/dist/bundlers/vite/generate-bundle.d.ts +16 -2
  36. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +4 -1
  37. package/dist/bundlers/vite/index.d.ts +1 -1
  38. package/dist/bundlers/vite/official-tailwind-plugins.d.ts +5 -0
  39. package/dist/bundlers/vite/postcss-config.d.ts +6 -0
  40. package/dist/bundlers/vite/rewrite-css-imports.d.ts +5 -3
  41. package/dist/bundlers/vite/runtime-class-set.d.ts +22 -0
  42. package/dist/bundlers/vite/source-candidates.d.ts +18 -0
  43. package/dist/bundlers/vite/source-scan.d.ts +9 -0
  44. package/dist/bundlers/vite/tailwind-basedir.d.ts +1 -0
  45. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +1 -0
  46. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +5 -2
  47. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +4 -3
  48. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +1 -0
  49. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +3 -1
  50. package/dist/cache/index.d.ts +6 -6
  51. package/dist/cache-B_9E7FxF.js +517 -0
  52. package/dist/cache-DEDxBMIw.mjs +443 -0
  53. package/dist/cli/context.d.ts +1 -14
  54. package/dist/cli/doctor/types.d.ts +11 -11
  55. package/dist/cli/helpers.d.ts +1 -2
  56. package/dist/cli/mount-options.d.ts +2 -0
  57. package/dist/cli/types.d.ts +0 -2
  58. package/dist/cli/vscode-entry.d.ts +3 -3
  59. package/dist/cli.js +126 -602
  60. package/dist/cli.mjs +135 -610
  61. package/dist/constants.d.ts +1 -2
  62. package/dist/core.js +13 -20
  63. package/dist/core.mjs +8 -14
  64. package/dist/css-macro/postcss.js +3 -2
  65. package/dist/css-macro/postcss.mjs +3 -2
  66. package/dist/css-macro.d.ts +1 -0
  67. package/dist/css-macro.js +2 -2
  68. package/dist/css-macro.mjs +2 -2
  69. package/dist/defaults.d.ts +15 -1
  70. package/dist/defaults.js +33 -14
  71. package/dist/defaults.mjs +30 -15
  72. package/dist/escape.js +10 -2
  73. package/dist/escape.mjs +10 -2
  74. package/dist/generator/index.d.ts +1 -1
  75. package/dist/generator/options.d.ts +10 -7
  76. package/dist/generator/types.d.ts +3 -2
  77. package/dist/generator-CahkD2vq.mjs +1469 -0
  78. package/dist/generator-Ck1Dd1V0.js +1568 -0
  79. package/dist/generator.js +1 -1
  80. package/dist/generator.mjs +1 -1
  81. package/dist/gulp.js +149 -47
  82. package/dist/gulp.mjs +144 -42
  83. package/dist/incremental-runtime-class-set-CBMefNHQ.js +1744 -0
  84. package/dist/incremental-runtime-class-set-DaS2yw5c.mjs +1687 -0
  85. package/dist/index.d.ts +1 -1
  86. package/dist/index.js +6 -6
  87. package/dist/index.mjs +5 -5
  88. package/dist/js/index.d.ts +1 -0
  89. package/dist/js/literal-transform.d.ts +2 -0
  90. package/dist/js/precheck.d.ts +2 -2
  91. package/dist/lightningcss/style-handler/selector-transform.d.ts +1 -1
  92. package/dist/lightningcss/style-handler.d.ts +3 -3
  93. package/dist/logger-CZUxvJJD.mjs +2 -0
  94. package/dist/logger-EVNB9z7i.js +1 -0
  95. package/dist/postcss/config-directive.d.ts +1 -0
  96. package/dist/postcss/context.d.ts +9 -0
  97. package/dist/postcss/source-files.d.ts +8 -0
  98. package/dist/postcss/tailwind-version.d.ts +3 -0
  99. package/dist/postcss-BdcRlSpp.js +243 -0
  100. package/dist/postcss-Bs-RbNzK.js +5477 -0
  101. package/dist/postcss-xZDiTRII.mjs +234 -0
  102. package/dist/postcss.d.ts +2 -2
  103. package/dist/postcss.js +3 -274
  104. package/dist/postcss.mjs +1 -267
  105. package/dist/{recorder-rn_2v_nd.js → precheck-D5eEdqeH.js} +168 -304
  106. package/dist/{recorder-B_XyZ576.mjs → precheck-DtBGFS-n.mjs} +134 -269
  107. package/dist/presets.js +13 -11
  108. package/dist/presets.mjs +11 -9
  109. package/dist/reset.d.ts +1 -0
  110. package/dist/runtime-patch-CqB-A4zA.js +85 -0
  111. package/dist/runtime-patch-DGKsVkiG.mjs +71 -0
  112. package/dist/shared/mpx.d.ts +1 -0
  113. package/dist/source-scan-CIVTa3Cj.js +297 -0
  114. package/dist/source-scan-CJ0y0XBj.mjs +258 -0
  115. package/dist/tailwindcss/miniprogram.d.ts +5 -1
  116. package/dist/tailwindcss/patcher-options.d.ts +3 -51
  117. package/dist/tailwindcss/patcher.d.ts +1 -2
  118. package/dist/tailwindcss/runtime/cache.d.ts +3 -3
  119. package/dist/tailwindcss/runtime-patch.d.ts +5 -0
  120. package/dist/tailwindcss/runtime.d.ts +11 -12
  121. package/dist/tailwindcss/source-scan.d.ts +25 -0
  122. package/dist/tailwindcss/targets.d.ts +1 -5
  123. package/dist/tailwindcss/v3-engine/types.d.ts +14 -14
  124. package/dist/tailwindcss/v4/css-entries.d.ts +2 -2
  125. package/dist/tailwindcss/v4/css-sources.d.ts +5 -0
  126. package/dist/tailwindcss/v4/patcher-options.d.ts +1 -23
  127. package/dist/tailwindcss/v4/patcher.d.ts +1 -0
  128. package/dist/tailwindcss/v4-engine/candidates.d.ts +2 -0
  129. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +1 -0
  130. package/dist/tailwindcss/v4-engine/tailwind-v3-compatibility.d.ts +1 -0
  131. package/dist/tailwindcss/v4-engine/tailwind-v3-default-colors.d.ts +1 -0
  132. package/dist/tailwindcss/v4-engine/tailwind-v4-default-colors.d.ts +1 -0
  133. package/dist/tailwindcss/v4-engine/types.d.ts +6 -3
  134. package/dist/tailwindcss/version.d.ts +4 -0
  135. package/dist/tailwindcss-B78nj6n7.js +644 -0
  136. package/dist/tailwindcss-DGM8lHUj.mjs +593 -0
  137. package/dist/typedoc.export.d.ts +0 -2
  138. package/dist/types/index.d.ts +45 -48
  139. package/dist/types/shared.d.ts +3 -0
  140. package/dist/types/user-defined-options/general.d.ts +21 -23
  141. package/dist/types/user-defined-options/important.d.ts +31 -28
  142. package/dist/types/user-defined-options/lifecycle.d.ts +4 -4
  143. package/dist/types/user-defined-options/matcher.d.ts +6 -6
  144. package/dist/uni-app-x/vite.d.ts +1 -1
  145. package/dist/utils/disabled.d.ts +2 -3
  146. package/dist/utils/object.d.ts +9 -0
  147. package/dist/{utils-DmC9_In3.js → utils-4ODFyoqD.js} +1 -1
  148. package/dist/{utils-7DUGTFED.mjs → utils-CGBVVNm6.mjs} +1 -1
  149. package/dist/{vite-BHpAqldo.js → vite-BEj9JOOA.js} +1245 -876
  150. package/dist/{vite-C8JlHiyR.mjs → vite-C8S1wfyQ.mjs} +1208 -842
  151. package/dist/vite.d.ts +1 -2
  152. package/dist/vite.js +3 -4
  153. package/dist/vite.mjs +2 -2
  154. package/dist/weapp-tw-css-import-rewrite-loader.js +129 -15
  155. package/dist/weapp-tw-runtime-classset-loader.js +44 -6
  156. package/dist/webpack-Dm1IXTIh.js +778 -0
  157. package/dist/webpack-ZGIKKpFf.mjs +768 -0
  158. package/dist/webpack.js +1 -1
  159. package/dist/webpack.mjs +1 -1
  160. package/package.json +26 -39
  161. package/dist/bundlers/shared/generator-candidates.d.ts +0 -5
  162. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-assets.d.ts +0 -14
  163. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-loaders.d.ts +0 -15
  164. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4.d.ts +0 -9
  165. package/dist/bundlers/webpack/shared/css-imports.d.ts +0 -6
  166. package/dist/cli/config.d.ts +0 -5
  167. package/dist/cli/helpers/patch-cwd.d.ts +0 -1
  168. package/dist/cli/mount-options/patch-status.d.ts +0 -2
  169. package/dist/cli/patch-options.d.ts +0 -6
  170. package/dist/cli/tokens.d.ts +0 -4
  171. package/dist/cli/workspace/package-dirs.d.ts +0 -3
  172. package/dist/cli/workspace/patch-package.d.ts +0 -3
  173. package/dist/cli/workspace/patch-utils.d.ts +0 -3
  174. package/dist/cli/workspace/types.d.ts +0 -11
  175. package/dist/cli/workspace/workspace-globs.d.ts +0 -2
  176. package/dist/cli/workspace/workspace-io.d.ts +0 -1
  177. package/dist/cli/workspace/workspace-lock.d.ts +0 -1
  178. package/dist/cli/workspace.d.ts +0 -2
  179. package/dist/css-imports-BbrbluP9.js +0 -177
  180. package/dist/css-imports-CSdPq_Sc.mjs +0 -128
  181. package/dist/experimental/index.d.ts +0 -2
  182. package/dist/experimental/oxc/ast-utils.d.ts +0 -30
  183. package/dist/experimental/oxc/index.d.ts +0 -2
  184. package/dist/experimental/oxc/module-specifiers.d.ts +0 -2
  185. package/dist/experimental/shared/cache.d.ts +0 -3
  186. package/dist/experimental/shared/transform.d.ts +0 -3
  187. package/dist/experimental/shared.d.ts +0 -8
  188. package/dist/experimental/swc/ast-utils.d.ts +0 -30
  189. package/dist/experimental/swc/index.d.ts +0 -2
  190. package/dist/experimental/swc/module-specifiers.d.ts +0 -2
  191. package/dist/generator-CZ-JXw6T.js +0 -492
  192. package/dist/generator-Dwxgra97.mjs +0 -399
  193. package/dist/generator-css-CnYjiMrD.js +0 -1084
  194. package/dist/generator-css-DhPFjSzK.mjs +0 -1057
  195. package/dist/js/syntax.d.ts +0 -10
  196. package/dist/loader-anchors-DvwgIYdA.mjs +0 -205
  197. package/dist/loader-anchors-cprm4Klq.js +0 -273
  198. package/dist/logger-BZ45DZJT.js +0 -1003
  199. package/dist/logger-BoVx1Dbt.mjs +0 -935
  200. package/dist/patcher-options-6gJN2EXy.js +0 -115
  201. package/dist/patcher-options-DQfR5xxT.mjs +0 -92
  202. package/dist/tailwindcss/recorder.d.ts +0 -13
  203. package/dist/tailwindcss/targets/paths.d.ts +0 -13
  204. package/dist/tailwindcss/targets/record-io.d.ts +0 -5
  205. package/dist/tailwindcss/targets/recorder.d.ts +0 -3
  206. package/dist/tailwindcss/targets/types.d.ts +0 -35
  207. package/dist/types/disabled-options.d.ts +0 -4
  208. package/dist/webpack-CABjKGGQ.mjs +0 -441
  209. package/dist/webpack-DNIJ0ysE.js +0 -456
  210. package/dist/webpack4.d.ts +0 -4
  211. package/dist/webpack4.js +0 -387
  212. package/dist/webpack4.mjs +0 -379
  213. package/scripts/postinstall.mjs +0 -59
  214. /package/dist/{constants-B-_T5UnW.mjs → constants-BG12WAKw.mjs} +0 -0
  215. /package/dist/{constants-p1dyh1x1.js → constants-BeeyfJ9k.js} +0 -0
@@ -1,32 +1,41 @@
1
1
  const require_chunk = require("./chunk-8l464Juk.js");
2
- const require_generator = require("./generator-CZ-JXw6T.js");
3
- const require_patcher_options = require("./patcher-options-6gJN2EXy.js");
4
- const require_recorder = require("./recorder-rn_2v_nd.js");
5
- const require_utils = require("./utils-DmC9_In3.js");
6
- const require_logger = require("./logger-BZ45DZJT.js");
7
- const require_generator_css = require("./generator-css-CnYjiMrD.js");
8
- const require_css_imports = require("./css-imports-BbrbluP9.js");
2
+ const require_cache = require("./cache-B_9E7FxF.js");
3
+ const require_runtime_patch = require("./runtime-patch-CqB-A4zA.js");
4
+ const require_generator = require("./generator-Ck1Dd1V0.js");
5
+ const require_incremental_runtime_class_set = require("./incremental-runtime-class-set-CBMefNHQ.js");
6
+ const require_precheck = require("./precheck-D5eEdqeH.js");
7
+ const require_utils = require("./utils-4ODFyoqD.js");
8
+ const require_tailwindcss = require("./tailwindcss-B78nj6n7.js");
9
+ const require_source_scan = require("./source-scan-CIVTa3Cj.js");
10
+ const require_bundle_state = require("./bundle-state-BRkhpjio.js");
11
+ require("./logger-EVNB9z7i.js");
12
+ let postcss = require("postcss");
13
+ postcss = require_chunk.__toESM(postcss);
9
14
  let node_path = require("node:path");
10
15
  node_path = require_chunk.__toESM(node_path);
11
16
  let node_process = require("node:process");
12
17
  node_process = require_chunk.__toESM(node_process);
18
+ let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
19
+ let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
13
20
  let tailwindcss_patch = require("tailwindcss-patch");
14
- let node_buffer = require("node:buffer");
15
21
  let node_fs = require("node:fs");
16
22
  node_fs = require_chunk.__toESM(node_fs);
17
- let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
18
- let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
23
+ let tailwindcss_config = require("tailwindcss-config");
24
+ let node_fs_promises = require("node:fs/promises");
19
25
  let magic_string = require("magic-string");
20
26
  magic_string = require_chunk.__toESM(magic_string);
21
27
  let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
22
- let htmlparser2 = require("htmlparser2");
28
+ let fast_glob = require("fast-glob");
29
+ fast_glob = require_chunk.__toESM(fast_glob);
30
+ let micromatch = require("micromatch");
31
+ micromatch = require_chunk.__toESM(micromatch);
23
32
  let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
24
33
  _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
25
- let postcss_load_config = require("postcss-load-config");
26
- postcss_load_config = require_chunk.__toESM(postcss_load_config);
27
34
  let _vue_compiler_dom = require("@vue/compiler-dom");
28
35
  let _vue_compiler_sfc = require("@vue/compiler-sfc");
29
36
  let comment_json = require("comment-json");
37
+ let postcss_load_config = require("postcss-load-config");
38
+ postcss_load_config = require_chunk.__toESM(postcss_load_config);
30
39
  //#region src/uni-app-x/component-local-style.ts
31
40
  const EXPRESSION_WRAPPER_PREFIX = "(\n";
32
41
  const EXPRESSION_WRAPPER_SUFFIX = "\n)";
@@ -57,7 +66,7 @@ function createAlias(fileId, utility, index) {
57
66
  }
58
67
  function isRuntimeCandidate(candidate, runtimeSet) {
59
68
  if (!runtimeSet || runtimeSet.size === 0) return false;
60
- return runtimeSet.has(candidate) || runtimeSet.has(require_recorder.replaceWxml(candidate));
69
+ return runtimeSet.has(candidate) || runtimeSet.has(require_precheck.replaceWxml(candidate));
61
70
  }
62
71
  function shouldEnableComponentLocalStyle(id) {
63
72
  return COMPONENT_RE.test(id);
@@ -66,8 +75,8 @@ var UniAppXComponentLocalStyleCollector = class {
66
75
  constructor(fileId, runtimeSet) {
67
76
  this.fileId = fileId;
68
77
  this.runtimeSet = runtimeSet;
69
- this.aliasByUtility = /* @__PURE__ */ new Map();
70
- this.aliasByLookup = /* @__PURE__ */ new Map();
78
+ require_precheck._defineProperty(this, "aliasByUtility", /* @__PURE__ */ new Map());
79
+ require_precheck._defineProperty(this, "aliasByLookup", /* @__PURE__ */ new Map());
71
80
  }
72
81
  ensureAlias(utility) {
73
82
  const cached = this.aliasByUtility.get(utility);
@@ -75,7 +84,7 @@ var UniAppXComponentLocalStyleCollector = class {
75
84
  const alias = createAlias(this.fileId, utility, this.aliasByUtility.size);
76
85
  this.aliasByUtility.set(utility, alias);
77
86
  this.aliasByLookup.set(utility, alias);
78
- this.aliasByLookup.set(require_recorder.replaceWxml(utility), alias);
87
+ this.aliasByLookup.set(require_precheck.replaceWxml(utility), alias);
79
88
  return alias;
80
89
  }
81
90
  rewriteLiteral(literal, shouldInclude) {
@@ -94,14 +103,14 @@ var UniAppXComponentLocalStyleCollector = class {
94
103
  collectRuntimeClasses(rawSource, options = {}) {
95
104
  const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
96
105
  try {
97
- const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
106
+ const analysis = require_precheck.analyzeSource(require_precheck.babelParse(wrapped, {
98
107
  plugins: ["typescript"],
99
108
  sourceType: options.wrapExpression ? "module" : "unambiguous"
100
109
  }), {}, void 0, false);
101
110
  for (const path of analysis.targetPaths) {
102
111
  const { literal, allowDoubleQuotes } = extractLiteralValue(path);
103
112
  const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
104
- const classContext = options.wrapExpression || require_recorder.isClassContextLiteralPath(path);
113
+ const classContext = options.wrapExpression || require_precheck.isClassContextLiteralPath(path);
105
114
  for (const candidate of candidates) {
106
115
  if (!candidate || !classContext && !isRuntimeCandidate(candidate, this.runtimeSet)) continue;
107
116
  if (isRuntimeCandidate(candidate, this.runtimeSet)) this.ensureAlias(candidate);
@@ -113,12 +122,12 @@ var UniAppXComponentLocalStyleCollector = class {
113
122
  if (this.aliasByLookup.size === 0) return rawSource;
114
123
  const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
115
124
  try {
116
- const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
125
+ const analysis = require_precheck.analyzeSource(require_precheck.babelParse(wrapped, {
117
126
  plugins: ["typescript"],
118
127
  sourceType: options.wrapExpression ? "module" : "unambiguous"
119
128
  }), {}, void 0, false);
120
129
  if (analysis.targetPaths.length === 0) return rawSource;
121
- const updater = new require_recorder.JsTokenUpdater();
130
+ const updater = new require_precheck.JsTokenUpdater();
122
131
  for (const path of analysis.targetPaths) {
123
132
  const { literal, allowDoubleQuotes, offset } = extractLiteralValue(path);
124
133
  const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
@@ -181,7 +190,7 @@ function updateStaticAttribute(ms, prop, content = prop.value?.content) {
181
190
  if (!prop.value) return;
182
191
  const start = prop.value.loc.start.offset + 1;
183
192
  const end = prop.value.loc.end.offset - 1;
184
- if (start < end) ms.update(start, end, require_recorder.replaceWxml(content ?? ""));
193
+ if (start < end) ms.update(start, end, require_precheck.replaceWxml(content ?? ""));
185
194
  }
186
195
  function updateStaticAttributeWithLocalStyle(ms, prop, collector, content = prop.value?.content) {
187
196
  if (!prop.value) return;
@@ -195,7 +204,7 @@ function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
195
204
  const start = prop.exp.loc.start.offset;
196
205
  const end = prop.exp.loc.end.offset;
197
206
  if (start >= end) return;
198
- const generated = require_recorder.generateCode(expression, {
207
+ const generated = require_precheck.generateCode(expression, {
199
208
  jsHandler,
200
209
  runtimeSet,
201
210
  wrapExpression: true
@@ -209,7 +218,7 @@ function updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, collector,
209
218
  const end = prop.exp.loc.end.offset;
210
219
  if (start >= end) return;
211
220
  collector.collectRuntimeClasses(expression, { wrapExpression: true });
212
- const generated = require_recorder.generateCode(expression, {
221
+ const generated = require_precheck.generateCode(expression, {
213
222
  jsHandler,
214
223
  runtimeSet,
215
224
  wrapExpression: true
@@ -231,7 +240,7 @@ const UVUE_NVUE_RE$1 = /\.(?:uvue|nvue)(?:\?.*)?$/;
231
240
  function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
232
241
  if (!UVUE_NVUE_RE$1.test(id)) return;
233
242
  const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
234
- const matchCustomAttribute = require_recorder.createAttributeMatcher(customAttributesEntities);
243
+ const matchCustomAttribute = require_precheck.createAttributeMatcher(customAttributesEntities);
235
244
  const ms = new magic_string.default(code);
236
245
  const { descriptor, errors } = (0, _vue_compiler_sfc.parse)(code);
237
246
  const localStyleCollector = options.enableComponentLocalStyle && shouldEnableComponentLocalStyle(id) ? new UniAppXComponentLocalStyleCollector(id, runtimeSet) : void 0;
@@ -281,7 +290,7 @@ function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
281
290
  //#endregion
282
291
  //#region src/bundlers/vite/query.ts
283
292
  function parseVueRequest(id) {
284
- const [filename, rawQuery] = id.split(`?`, 2);
293
+ const [filename = id, rawQuery] = id.split(`?`, 2);
285
294
  const searchParams = new URLSearchParams(rawQuery);
286
295
  const query = Object.fromEntries(searchParams);
287
296
  if (query.vue != null) query.vue = true;
@@ -305,7 +314,7 @@ function slash(p) {
305
314
  const isWindows = node_process.default.platform === "win32";
306
315
  const cssLangRE = new RegExp(`\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`);
307
316
  function isCSSRequest(request) {
308
- return cssLangRE.test(request);
317
+ return cssLangRE.test(request) || require_bundle_state.isSourceStyleRequest(request);
309
318
  }
310
319
  function normalizePath(id) {
311
320
  return node_path.default.posix.normalize(isWindows ? (0, _weapp_tailwindcss_shared.ensurePosix)(id) : id);
@@ -360,19 +369,19 @@ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
360
369
  function isPreprocessorRequest(id, lang) {
361
370
  const normalizedLang = lang?.toLowerCase();
362
371
  if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
363
- const inlineLangMatch = id.match(INLINE_LANG_RE);
364
- if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) return true;
372
+ const inlineLang = id.match(INLINE_LANG_RE)?.[1];
373
+ if (inlineLang && preprocessorLangs.has(inlineLang.toLowerCase())) return true;
365
374
  return PREPROCESSOR_EXT_RE.test(id);
366
375
  }
367
376
  function resolveUniAppXCssTarget(id) {
368
377
  return UVUE_NVUE_RE.test((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ? "uvue" : void 0;
369
378
  }
370
379
  function resolveUniAppXJsTransformEnabled$1(uniAppX) {
371
- return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
380
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
372
381
  }
373
382
  function createUniAppXPlugins(options) {
374
383
  const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
375
- const resolvedUniAppXOptions = require_logger.resolveUniAppXOptions(uniAppX);
384
+ const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(uniAppX);
376
385
  const isIosPlatform = providedIosPlatform ?? require_utils.resolveUniUtsPlatform().isAppIos;
377
386
  const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
378
387
  let componentLocalStyleEnabled;
@@ -396,7 +405,7 @@ function createUniAppXPlugins(options) {
396
405
  const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
397
406
  let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
398
407
  if (!styleHandlerOptions) {
399
- styleHandlerOptions = {
408
+ styleHandlerOptions = require_cache.omitUndefined({
400
409
  isMainChunk: mainCssChunkMatcher(id, appType),
401
410
  uniAppXCssTarget: resolveUniAppXCssTarget(id),
402
411
  uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
@@ -408,7 +417,7 @@ function createUniAppXPlugins(options) {
408
417
  sourcesContent: true
409
418
  }
410
419
  } }
411
- };
420
+ });
412
421
  cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
413
422
  }
414
423
  const postcssResult = await styleHandler(code, styleHandlerOptions);
@@ -424,14 +433,14 @@ function createUniAppXPlugins(options) {
424
433
  const cssPlugins = [{
425
434
  name: "weapp-tailwindcss:uni-app-x:css",
426
435
  async transform(code, id) {
427
- await runtimeState.patchPromise;
436
+ await runtimeState.readyPromise;
428
437
  return transformStyle(code, id);
429
438
  }
430
439
  }, {
431
440
  name: "weapp-tailwindcss:uni-app-x:css:pre",
432
441
  enforce: "pre",
433
442
  async transform(code, id) {
434
- await runtimeState.patchPromise;
443
+ await runtimeState.readyPromise;
435
444
  const { query } = parseVueRequest(id);
436
445
  const lang = query.lang;
437
446
  if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
@@ -477,9 +486,9 @@ function createUniAppXPlugins(options) {
477
486
  function createUniAppXAssetTask(file, originalSource, outDir, options) {
478
487
  return async () => {
479
488
  const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
480
- const absoluteFile = require_css_imports.toAbsoluteOutputPath(file, outDir);
489
+ const absoluteFile = require_bundle_state.toAbsoluteOutputPath(file, outDir);
481
490
  const rawSource = originalSource.source.toString();
482
- await require_generator_css.processCachedTask({
491
+ await require_incremental_runtime_class_set.processCachedTask({
483
492
  cache,
484
493
  cacheKey: file,
485
494
  hashKey,
@@ -508,33 +517,37 @@ function createUniAppXAssetTask(file, originalSource, outDir, options) {
508
517
  };
509
518
  }
510
519
  //#endregion
511
- //#region src/bundlers/shared/generator-candidates.ts
512
- async function collectGeneratorCandidatesFromSources(sources, baseCandidates = []) {
513
- const candidates = new Set(baseCandidates);
514
- await Promise.all(sources.map(async (source) => {
515
- const matches = await (0, tailwindcss_patch.extractRawCandidatesWithPositions)(source.content, source.extension);
516
- for (const match of matches) {
517
- const candidate = match.rawCandidate;
518
- if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
520
+ //#region src/bundlers/vite/css-finalizer.ts
521
+ function isAddWatchFileInvalidRollupPhaseError$1(error) {
522
+ const candidate = error;
523
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
524
+ }
525
+ function registerGeneratorDependencies$1(ctx, dependencies) {
526
+ if (typeof ctx.addWatchFile !== "function") return;
527
+ for (const dependency of dependencies ?? []) try {
528
+ ctx.addWatchFile(dependency);
529
+ } catch (error) {
530
+ if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
531
+ _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
532
+ continue;
519
533
  }
520
- }));
521
- return candidates;
534
+ throw error;
535
+ }
522
536
  }
523
- //#endregion
524
- //#region src/bundlers/vite/css-finalizer.ts
525
537
  function createCssHandlerOptions(opts, majorVersion, file) {
526
538
  return {
527
539
  isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
528
540
  postcssOptions: { options: { from: file } },
529
- majorVersion
541
+ ...majorVersion === void 0 ? {} : { majorVersion }
530
542
  };
531
543
  }
532
544
  function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
533
- if (require_generator_css.hasTailwindGeneratedCssMarkers(rawSource) || require_generator_css.hasTailwindSourceDirectives(rawSource)) return true;
545
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
546
+ if (require_incremental_runtime_class_set.hasTailwindGeneratedCssMarkers(rawSource) || require_incremental_runtime_class_set.hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return true;
534
547
  return processed && shouldFinalizeProcessedCssAsset(opts, file);
535
548
  }
536
549
  function shouldFinalizeProcessedCssAsset(opts, file) {
537
- return require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType);
550
+ return opts.mainCssChunkMatcher(file, opts.appType);
538
551
  }
539
552
  function createViteCssFinalizerOutputPlugin(context) {
540
553
  return {
@@ -542,16 +555,20 @@ function createViteCssFinalizerOutputPlugin(context) {
542
555
  generateBundle: {
543
556
  order: "post",
544
557
  async handler(_options, bundle) {
545
- const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates } = context;
558
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource } = context;
546
559
  if (getResolvedConfig()?.command !== "build") return;
547
- const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
560
+ const isCssOutputAssetEntry = (entry) => {
561
+ const [, output] = entry;
562
+ return output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName));
563
+ };
564
+ const entries = Object.entries(bundle).filter(isCssOutputAssetEntry);
548
565
  if (entries.length === 0) return;
549
- await runtimeState.patchPromise;
550
- const runtime = getRecordedGeneratorCandidates?.() ?? await ensureRuntimeClassSet();
551
- const generatorRuntime = await collectGeneratorCandidatesFromSources(Object.entries(bundle).filter(([, output]) => output.type === "asset" || output.type === "chunk").filter(([file]) => opts.htmlMatcher(file) || opts.jsMatcher(file) || opts.wxsMatcher(file)).map(([file, output]) => ({
552
- content: output.type === "chunk" ? output.code : output.source.toString(),
553
- extension: node_path.default.extname(file).replace(/^\./, "") || (opts.htmlMatcher(file) ? "html" : "js")
554
- })), runtime);
566
+ await runtimeState.readyPromise;
567
+ await waitForSourceCandidateSyncs?.();
568
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
569
+ const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
570
+ const collectedGeneratorCandidates = new Set([...runtime, ...getSourceCandidates?.() ?? []]);
571
+ const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
555
572
  await Promise.all(entries.map(async ([bundleFile, output]) => {
556
573
  const file = output.fileName || bundleFile;
557
574
  const rawSource = output.source.toString();
@@ -560,7 +577,7 @@ function createViteCssFinalizerOutputPlugin(context) {
560
577
  ...cssHandlerOptions,
561
578
  isMainChunk: false
562
579
  };
563
- const generated = shouldGenerateCssByGenerator(opts, file, rawSource, isCssAssetProcessed(output, file)) ? await require_generator_css.generateCssByGenerator({
580
+ const generated = shouldGenerateCssByGenerator(opts, file, rawSource, isCssAssetProcessed(output, file)) ? await require_incremental_runtime_class_set.generateCssByGenerator({
564
581
  opts,
565
582
  runtimeState,
566
583
  runtime: generatorRuntime,
@@ -573,8 +590,10 @@ function createViteCssFinalizerOutputPlugin(context) {
573
590
  }) : void 0;
574
591
  const nextCss = generated?.css ?? (await opts.styleHandler(rawSource, cssHandlerOptions)).css;
575
592
  if (generated) {
593
+ registerGeneratorDependencies$1(this, generated.dependencies);
576
594
  debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
577
595
  recordCssAssetResult?.(file, nextCss);
596
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource);
578
597
  }
579
598
  output.source = nextCss;
580
599
  markCssAssetProcessed(output, file);
@@ -586,256 +605,160 @@ function createViteCssFinalizerOutputPlugin(context) {
586
605
  };
587
606
  }
588
607
  //#endregion
589
- //#region src/bundlers/vite/bundle-entries.ts
590
- function readOutputEntry(entry) {
591
- if (entry.output.type === "chunk") return entry.output.code;
592
- const source = entry.output.source;
593
- if (typeof source === "string") return source;
594
- if (source instanceof Uint8Array) return node_buffer.Buffer.from(source).toString();
595
- const fallbackSource = source;
596
- if (fallbackSource == null) return;
597
- if (typeof fallbackSource.toString === "function") return fallbackSource.toString();
598
- }
599
- function isJavaScriptEntry(entry) {
600
- if (entry.output.type === "chunk") return true;
601
- return entry.fileName.endsWith(".js");
602
- }
603
- function createBundleModuleGraphOptions(outputDir, entries) {
604
- const normalizedEntries = /* @__PURE__ */ new Map();
605
- for (const [id, entry] of entries) normalizedEntries.set(require_css_imports.normalizeOutputPathKey(id), entry);
606
- const getEntry = (id) => entries.get(id) ?? normalizedEntries.get(require_css_imports.normalizeOutputPathKey(id));
607
- return {
608
- resolve(specifier, importer) {
609
- return require_css_imports.resolveOutputSpecifier(specifier, importer, outputDir, (candidate) => Boolean(getEntry(candidate)));
610
- },
611
- load(id) {
612
- const entry = getEntry(id);
613
- if (!entry) return;
614
- return readOutputEntry(entry);
615
- },
616
- filter(id) {
617
- return Boolean(getEntry(id));
618
- }
619
- };
620
- }
621
- function applyLinkedResults(linked, entries, onLinkedUpdate, onApplied) {
622
- if (!linked) return;
623
- const normalizedEntries = /* @__PURE__ */ new Map();
624
- for (const [entryId, entry] of entries) normalizedEntries.set(require_css_imports.normalizeOutputPathKey(entryId), entry);
625
- for (const [id, { code }] of Object.entries(linked)) {
626
- const entry = entries.get(id) ?? normalizedEntries.get(require_css_imports.normalizeOutputPathKey(id));
627
- if (!entry) continue;
628
- const previous = readOutputEntry(entry);
629
- if (previous == null || previous === code) continue;
630
- if (entry.output.type === "chunk") entry.output.code = code;
631
- else entry.output.source = code;
632
- onApplied?.(entry, code);
633
- onLinkedUpdate(entry.fileName, previous, code);
634
- }
635
- }
636
- //#endregion
637
- //#region src/bundlers/vite/runtime-affecting-signature.ts
638
- const CSS_BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
639
- const CSS_AROUND_PUNCTUATION_RE = /\s*([{}:;,>+~()])\s*/g;
640
- const CSS_TRAILING_DECLARATION_SEMICOLON_RE = /;\}/g;
641
- const CSS_WHITESPACE_RE = /\s+/g;
642
- function createHtmlRuntimeAffectingSignature(source) {
643
- try {
644
- const parts = [];
645
- const parser = new htmlparser2.Parser({
646
- onattribute(name, value) {
647
- parts.push(`a:${name}=${value}`);
648
- },
649
- oncomment(data) {
650
- parts.push(`c:${data}`);
651
- },
652
- ontext(data) {
653
- const value = data.trim();
654
- if (value.length > 0) parts.push(`t:${value}`);
655
- }
656
- }, { xmlMode: true });
657
- parser.write(source);
658
- parser.end();
659
- return parts.join("\n");
660
- } catch {
661
- return source;
662
- }
608
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
609
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
610
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
611
+ function isArbitraryValueCandidate(candidate) {
612
+ return candidate.includes("[") && candidate.includes("]");
663
613
  }
664
- function createJsRuntimeAffectingSignature(source) {
665
- try {
666
- const ast = require_recorder.babelParse(source, {
667
- cache: true,
668
- cacheKey: "vite-runtime-affecting:unambiguous",
669
- plugins: ["jsx", "typescript"],
670
- sourceType: "unambiguous"
671
- });
672
- const parts = [];
673
- require_recorder.traverse(ast, {
674
- noScope: true,
675
- StringLiteral(path) {
676
- parts.push(`s:${path.node.value}`);
677
- },
678
- TemplateElement(path) {
679
- parts.push(`t:${path.node.value.raw}`);
680
- },
681
- JSXText(path) {
682
- const value = path.node.value.trim();
683
- if (value.length > 0) parts.push(`x:${value}`);
614
+ function collectUnescapedDynamicCandidates(source) {
615
+ const matches = /* @__PURE__ */ new Set();
616
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
617
+ QUOTED_LITERAL_RE.lastIndex = 0;
618
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
619
+ while (quoted !== null) {
620
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
621
+ for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, true)) {
622
+ const normalized = candidate.trim();
623
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
624
+ matches.add(normalized);
684
625
  }
685
- });
686
- const comments = ast.comments;
687
- if (Array.isArray(comments)) {
688
- for (const comment of comments) if (typeof comment?.value === "string" && comment.value.length > 0) parts.push(`c:${comment.value}`);
626
+ quoted = QUOTED_LITERAL_RE.exec(expression);
689
627
  }
690
- return parts.join("\n");
691
- } catch {
692
- return source;
693
628
  }
629
+ return [...matches];
694
630
  }
695
- function createCssRuntimeAffectingSignature(source) {
696
- return source.replace(CSS_BLOCK_COMMENT_RE, "").replace(CSS_AROUND_PUNCTUATION_RE, "$1").replace(CSS_TRAILING_DECLARATION_SEMICOLON_RE, "}").replace(CSS_WHITESPACE_RE, " ").trim();
697
- }
698
- function createRuntimeAffectingSourceSignature(source, type) {
699
- if (type === "html") return createHtmlRuntimeAffectingSignature(source);
700
- if (type === "js") return createJsRuntimeAffectingSignature(source);
701
- if (type === "css") return createCssRuntimeAffectingSignature(source);
702
- return source;
631
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
632
+ if (candidates.has("container")) return candidates;
633
+ if (!sourceCandidates.has("container")) return candidates;
634
+ return new Set([...candidates, "container"]);
703
635
  }
704
636
  //#endregion
705
- //#region src/bundlers/vite/bundle-state.ts
706
- function createBundleBuildState() {
707
- return {
708
- iteration: 0,
709
- sourceHashByFile: /* @__PURE__ */ new Map(),
710
- runtimeAffectingSignatureByFile: /* @__PURE__ */ new Map(),
711
- runtimeAffectingHashByFile: /* @__PURE__ */ new Map(),
712
- linkedByEntry: /* @__PURE__ */ new Map(),
713
- dependentsByLinkedFile: /* @__PURE__ */ new Map()
637
+ //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
638
+ function createCssHandlerOptionsCache(options) {
639
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
640
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
641
+ const getCssHandlerOptions = (file) => {
642
+ const majorVersion = options.getMajorVersion();
643
+ const isMainChunk = options.mainCssChunkMatcher(file, options.appType);
644
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
645
+ const cached = cssHandlerOptionsCache.get(cacheKey);
646
+ if (cached) return cached;
647
+ const created = {
648
+ isMainChunk,
649
+ postcssOptions: { options: { from: file } },
650
+ majorVersion
651
+ };
652
+ cssHandlerOptionsCache.set(cacheKey, created);
653
+ return created;
714
654
  };
715
- }
716
- function createChangedByType() {
717
- return {
718
- html: /* @__PURE__ */ new Set(),
719
- js: /* @__PURE__ */ new Set(),
720
- css: /* @__PURE__ */ new Set(),
721
- other: /* @__PURE__ */ new Set()
655
+ const getCssUserHandlerOptions = (file) => {
656
+ const cacheKey = `${options.getMajorVersion() ?? "unknown"}:${file}`;
657
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
658
+ if (cached) return cached;
659
+ const created = {
660
+ ...getCssHandlerOptions(file),
661
+ isMainChunk: false
662
+ };
663
+ cssUserHandlerOptionsCache.set(cacheKey, created);
664
+ return created;
722
665
  };
723
- }
724
- function createProcessFiles() {
725
666
  return {
726
- html: /* @__PURE__ */ new Set(),
727
- js: /* @__PURE__ */ new Set(),
728
- css: /* @__PURE__ */ new Set()
667
+ getCssHandlerOptions,
668
+ getCssUserHandlerOptions
729
669
  };
730
670
  }
731
- function readEntrySource(output) {
732
- if (output.type === "chunk") return output.code;
733
- return output.source.toString();
671
+ //#endregion
672
+ //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
673
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
674
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
675
+ const CSS_IMPORT_RE = /@import\b/i;
676
+ function isPathIndependentCssUrl(value) {
677
+ const normalized = value.trim();
678
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
679
+ }
680
+ function hasPathDependentCssUrl(rawSource) {
681
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
682
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
683
+ while (match !== null) {
684
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
685
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
686
+ }
687
+ return false;
688
+ }
689
+ function createCssTransformShareScope(file, rawSource) {
690
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_bundle_state.normalizeOutputPathKey(node_path.default.dirname(file))}`;
691
+ return "global";
692
+ }
693
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
694
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_bundle_state.normalizeOutputPathKey(file)}`;
695
+ return createCssTransformShareScope(file, rawSource);
734
696
  }
735
- function classifyBundleEntry(file, opts) {
736
- if (opts.cssMatcher(file)) return "css";
737
- if (opts.htmlMatcher(file)) return "html";
738
- if (opts.jsMatcher(file) || opts.wxsMatcher(file)) return "js";
739
- return "other";
697
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
698
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
740
699
  }
741
- function collectJsEntries(fileName, output, outDir, store) {
742
- const entry = {
743
- fileName,
744
- output
700
+ //#endregion
701
+ //#region src/bundlers/vite/generate-bundle/dirty-state.ts
702
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
703
+ const currentFileSet = new Set(currentBundleFiles);
704
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
705
+ return false;
706
+ }
707
+ //#endregion
708
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
709
+ function createJsEntryResolver(jsEntries) {
710
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
711
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_bundle_state.normalizeOutputPathKey(id), entry);
712
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_bundle_state.normalizeOutputPathKey(id));
713
+ }
714
+ //#endregion
715
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
716
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
717
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
718
+ }
719
+ function createJsHandlerOptionsFactory(options) {
720
+ return (absoluteFilename, extra) => ({
721
+ ...extra,
722
+ filename: absoluteFilename,
723
+ tailwindcssMajorVersion: options.getMajorVersion(),
724
+ moduleGraph: options.moduleGraph,
725
+ babelParserOptions: {
726
+ ...extra?.babelParserOptions ?? {},
727
+ sourceFilename: absoluteFilename
728
+ }
729
+ });
730
+ }
731
+ //#endregion
732
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
733
+ function createLinkedUpdateHelpers(options) {
734
+ const pendingLinkedUpdates = [];
735
+ const handleLinkedUpdate = (fileName, previous, next) => {
736
+ options.onUpdate(fileName, previous, next);
737
+ options.debug("js linked handle: %s", fileName);
745
738
  };
746
- if (!isJavaScriptEntry(entry)) return;
747
- const absolute = require_css_imports.toAbsoluteOutputPath(fileName, outDir);
748
- store.set(absolute, entry);
749
- }
750
- function markProcessFile(type, file, processFiles) {
751
- if (type === "html" || type === "js" || type === "css") processFiles[type].add(file);
752
- }
753
- function buildBundleSnapshot(bundle, opts, outDir, state, forceAll = false) {
754
- const sourceHashByFile = /* @__PURE__ */ new Map();
755
- const runtimeAffectingSignatureByFile = /* @__PURE__ */ new Map();
756
- const runtimeAffectingHashByFile = /* @__PURE__ */ new Map();
757
- const changedByType = createChangedByType();
758
- const runtimeAffectingChangedByType = createChangedByType();
759
- const processFiles = createProcessFiles();
760
- const linkedImpactsByEntry = /* @__PURE__ */ new Map();
761
- const jsEntries = /* @__PURE__ */ new Map();
762
- const entries = [];
763
- const firstRun = state.linkedByEntry.size === 0;
764
- for (const [file, output] of Object.entries(bundle)) {
765
- const type = classifyBundleEntry(file, opts);
766
- const source = readEntrySource(output);
767
- const hash = opts.cache.computeHash(source);
768
- sourceHashByFile.set(file, hash);
769
- const previousHash = state.sourceHashByFile.get(file);
770
- const changed = previousHash == null || previousHash !== hash;
771
- const previousRuntimeAffectingSignature = state.runtimeAffectingSignatureByFile.get(file);
772
- const previousRuntimeAffectingHash = state.runtimeAffectingHashByFile.get(file);
773
- const canReuseRuntimeAffectingSignature = !changed && previousRuntimeAffectingSignature != null && previousRuntimeAffectingHash != null;
774
- const runtimeAffectingSignature = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingSignature : createRuntimeAffectingSourceSignature(source, type);
775
- const runtimeAffectingHash = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingHash : opts.cache.computeHash(runtimeAffectingSignature);
776
- runtimeAffectingSignatureByFile.set(file, runtimeAffectingSignature);
777
- runtimeAffectingHashByFile.set(file, runtimeAffectingHash);
778
- if (changed) changedByType[type].add(file);
779
- if (previousRuntimeAffectingHash == null || previousRuntimeAffectingHash !== runtimeAffectingHash) runtimeAffectingChangedByType[type].add(file);
780
- if (forceAll || firstRun) markProcessFile(type, file, processFiles);
781
- else if (type === "html") processFiles.html.add(file);
782
- else if (changed && (type === "js" || type === "css")) processFiles[type].add(file);
783
- collectJsEntries(file, output, outDir, jsEntries);
784
- entries.push({
785
- file,
786
- output,
787
- source,
788
- type
739
+ const scheduleLinkedApply = (entry, code) => {
740
+ pendingLinkedUpdates.push(() => {
741
+ if (entry.output.type === "chunk") entry.output.code = code;
742
+ else entry.output.source = code;
789
743
  });
790
- }
791
- if (!forceAll && !firstRun) for (const changedFile of changedByType.js) {
792
- const dependents = state.dependentsByLinkedFile.get(changedFile);
793
- if (!dependents) continue;
794
- for (const entryFile of dependents) {
795
- processFiles.js.add(entryFile);
796
- let impacts = linkedImpactsByEntry.get(entryFile);
797
- if (!impacts) {
798
- impacts = /* @__PURE__ */ new Set();
799
- linkedImpactsByEntry.set(entryFile, impacts);
800
- }
801
- impacts.add(changedFile);
802
- }
803
- }
744
+ };
745
+ const applyLinkedUpdates = (linked) => {
746
+ require_bundle_state.applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
747
+ };
804
748
  return {
805
- entries,
806
- jsEntries,
807
- sourceHashByFile,
808
- runtimeAffectingSignatureByFile,
809
- runtimeAffectingHashByFile,
810
- changedByType,
811
- runtimeAffectingChangedByType,
812
- processFiles,
813
- linkedImpactsByEntry
749
+ applyLinkedUpdates,
750
+ pendingLinkedUpdates
814
751
  };
815
752
  }
816
- function invertLinkedByEntry(linkedByEntry) {
817
- const dependentsByLinkedFile = /* @__PURE__ */ new Map();
818
- for (const [entryFile, linkedFiles] of linkedByEntry.entries()) for (const linkedFile of linkedFiles) {
819
- let dependents = dependentsByLinkedFile.get(linkedFile);
820
- if (!dependents) {
821
- dependents = /* @__PURE__ */ new Set();
822
- dependentsByLinkedFile.set(linkedFile, dependents);
823
- }
824
- dependents.add(entryFile);
753
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
754
+ if (!linked || !linkedSet) return;
755
+ for (const id of Object.keys(linked)) {
756
+ const linkedEntry = getJsEntry(id);
757
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
825
758
  }
826
- return dependentsByLinkedFile;
827
- }
828
- function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
829
- const incremental = options.incremental === true;
830
- state.iteration += 1;
831
- state.sourceHashByFile = incremental ? new Map([...state.sourceHashByFile, ...snapshot.sourceHashByFile]) : snapshot.sourceHashByFile;
832
- state.runtimeAffectingSignatureByFile = incremental ? new Map([...state.runtimeAffectingSignatureByFile, ...snapshot.runtimeAffectingSignatureByFile]) : snapshot.runtimeAffectingSignatureByFile;
833
- state.runtimeAffectingHashByFile = incremental ? new Map([...state.runtimeAffectingHashByFile, ...snapshot.runtimeAffectingHashByFile]) : snapshot.runtimeAffectingHashByFile;
834
- state.linkedByEntry = incremental ? new Map([...state.linkedByEntry, ...linkedByEntry]) : linkedByEntry;
835
- state.dependentsByLinkedFile = invertLinkedByEntry(state.linkedByEntry);
836
759
  }
837
760
  //#endregion
838
- //#region src/bundlers/vite/generate-bundle.ts
761
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
839
762
  function formatDebugFileList(files, limit = 8) {
840
763
  if (files.size === 0) return "-";
841
764
  const sorted = [...files].sort();
@@ -861,9 +784,6 @@ function createEmptyMetrics() {
861
784
  function measureElapsed(start) {
862
785
  return performance.now() - start;
863
786
  }
864
- function resolveUniAppXJsTransformEnabled(uniAppX) {
865
- return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
866
- }
867
787
  function formatCacheHitRate(metric) {
868
788
  if (metric.total === 0) return "0.00%";
869
789
  return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
@@ -871,6 +791,50 @@ function formatCacheHitRate(metric) {
871
791
  function formatMs(value) {
872
792
  return value.toFixed(2);
873
793
  }
794
+ //#endregion
795
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
796
+ function logBundleProcessPlan(options) {
797
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
798
+ const { processFiles } = snapshot;
799
+ if (useIncrementalMode) {
800
+ debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
801
+ debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
802
+ return;
803
+ }
804
+ debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
805
+ }
806
+ //#endregion
807
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
808
+ function createReplayCssAsset(fileName, source) {
809
+ return {
810
+ type: "asset",
811
+ fileName,
812
+ name: void 0,
813
+ source,
814
+ needsCodeReference: false,
815
+ names: [],
816
+ originalFileName: null,
817
+ originalFileNames: []
818
+ };
819
+ }
820
+ function isAddWatchFileInvalidRollupPhaseError(error) {
821
+ const candidate = error;
822
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
823
+ }
824
+ function registerGeneratorDependencies(ctx, dependencies) {
825
+ if (typeof ctx.addWatchFile !== "function") return;
826
+ for (const dependency of dependencies ?? []) try {
827
+ ctx.addWatchFile(dependency);
828
+ } catch (error) {
829
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
830
+ _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
831
+ continue;
832
+ }
833
+ throw error;
834
+ }
835
+ }
836
+ //#endregion
837
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
874
838
  function summarizeStringDiff(previous, next) {
875
839
  if (previous === next) return "same";
876
840
  const previousLength = previous.length;
@@ -899,183 +863,113 @@ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
899
863
  if (!linkedImpactSignature) return runtimeSignature;
900
864
  return `${runtimeSignature}:linked:${linkedImpactSignature}`;
901
865
  }
866
+ function createStableTextSignature(input) {
867
+ let hash = 2166136261;
868
+ for (let i = 0; i < input.length; i++) {
869
+ hash ^= input.charCodeAt(i);
870
+ hash = Math.imul(hash, 16777619);
871
+ }
872
+ return (hash >>> 0).toString(36);
873
+ }
874
+ function createCandidateSignature(candidates) {
875
+ if (candidates.size === 0) return "empty";
876
+ return createStableTextSignature([...candidates].sort().join("\n"));
877
+ }
902
878
  function getSnapshotHash(snapshotMap, file, fallback) {
903
879
  return snapshotMap.get(file) ?? fallback;
904
880
  }
905
881
  function hasRuntimeAffectingSourceChanges(changedByType) {
906
882
  return changedByType.html.size > 0 || changedByType.js.size > 0;
907
883
  }
908
- const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
909
- const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
910
- const CSS_IMPORT_RE = /@import\b/i;
911
- function isPathIndependentCssUrl(value) {
912
- const normalized = value.trim();
913
- return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
914
- }
915
- function hasPathDependentCssUrl(rawSource) {
916
- CSS_URL_FUNCTION_RE.lastIndex = 0;
917
- let match = CSS_URL_FUNCTION_RE.exec(rawSource);
918
- while (match !== null) {
919
- if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
920
- match = CSS_URL_FUNCTION_RE.exec(rawSource);
921
- }
922
- return false;
923
- }
924
- function createCssTransformShareScope(file, rawSource) {
925
- if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_css_imports.normalizeOutputPathKey(node_path.default.dirname(file))}`;
926
- return "global";
927
- }
928
- function createCssTransformShareScopeKey(opts, file, rawSource) {
929
- if (require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_css_imports.normalizeOutputPathKey(file)}`;
930
- return createCssTransformShareScope(file, rawSource);
931
- }
932
- function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
933
- const currentFileSet = new Set(currentBundleFiles);
934
- for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
935
- return false;
936
- }
937
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
938
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
939
- function isArbitraryValueCandidate(candidate) {
940
- return candidate.includes("[") && candidate.includes("]");
941
- }
942
- function collectUnescapedDynamicCandidates(source) {
943
- const matches = /* @__PURE__ */ new Set();
944
- for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
945
- QUOTED_LITERAL_RE.lastIndex = 0;
946
- let quoted = QUOTED_LITERAL_RE.exec(expression);
947
- while (quoted !== null) {
948
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
949
- for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, true)) {
950
- const normalized = candidate.trim();
951
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
952
- matches.add(normalized);
953
- }
954
- quoted = QUOTED_LITERAL_RE.exec(expression);
955
- }
956
- }
957
- return [...matches];
958
- }
959
- function collectLegacyContainerCompatCandidates(sources, runtime) {
960
- if (runtime.has("container")) return runtime;
961
- if (!sources.some((source) => /\bcontainer\b/.test(source.content))) return runtime;
962
- return new Set([...runtime, "container"]);
963
- }
964
- async function collectTailwindV4ContentCandidates(runtimeState, runtime, generatorMode, debug) {
965
- const collectContentTokens = runtimeState.twPatcher.collectContentTokens;
966
- if (generatorMode !== "force" || runtimeState.twPatcher.majorVersion !== 4 || typeof collectContentTokens !== "function") return runtime;
967
- try {
968
- const generator = require_generator.createWeappTailwindcssGenerator(await require_generator.resolveTailwindV4SourceFromPatcher(runtimeState.twPatcher));
969
- const report = await collectContentTokens.call(runtimeState.twPatcher);
970
- const rawCandidates = new Set(report.entries.map((entry) => entry.rawCandidate));
971
- const validCandidates = await generator.validateCandidates(rawCandidates);
972
- if (rawCandidates.size === 0 && validCandidates.size === 0) return runtime;
973
- return new Set([
974
- ...runtime,
975
- ...rawCandidates,
976
- ...validCandidates
977
- ]);
978
- } catch (error) {
979
- debug("collect Tailwind v4 content candidates for generator failed: %O", error);
980
- return runtime;
981
- }
982
- }
884
+ //#endregion
885
+ //#region src/bundlers/vite/generate-bundle.ts
983
886
  function createGenerateBundleHook(context) {
984
- const state = createBundleBuildState();
985
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
986
- const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
887
+ const state = require_bundle_state.createBundleBuildState();
888
+ const cssHandlerOptions = createCssHandlerOptionsCache({
889
+ appType: context.opts.appType,
890
+ mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
891
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion
892
+ });
987
893
  return async function generateBundle(_opt, bundle) {
988
- const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, recordGeneratorCandidates } = context;
989
- const { appType, cache, mainCssChunkMatcher, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
894
+ const addWatchFile = (id) => this.addWatchFile?.(id);
895
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
896
+ const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
990
897
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
991
- const getCssHandlerOptions = (file) => {
992
- const majorVersion = runtimeState.twPatcher.majorVersion;
993
- const isMainChunk = mainCssChunkMatcher(file, appType);
994
- const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
995
- const cached = cssHandlerOptionsCache.get(cacheKey);
996
- if (cached) return cached;
997
- const created = {
998
- isMainChunk,
999
- postcssOptions: { options: { from: file } },
1000
- majorVersion
1001
- };
1002
- cssHandlerOptionsCache.set(cacheKey, created);
1003
- return created;
1004
- };
1005
- const getCssUserHandlerOptions = (file) => {
1006
- const cacheKey = `${runtimeState.twPatcher.majorVersion ?? "unknown"}:${file}`;
1007
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
1008
- if (cached) return cached;
1009
- const created = {
1010
- ...getCssHandlerOptions(file),
1011
- isMainChunk: false
1012
- };
1013
- cssUserHandlerOptionsCache.set(cacheKey, created);
1014
- return created;
1015
- };
1016
- await runtimeState.patchPromise;
898
+ const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
899
+ await runtimeState.readyPromise;
1017
900
  debug("start");
1018
901
  onStart();
902
+ const hmrTimingStartedAt = performance.now();
1019
903
  const metrics = createEmptyMetrics();
1020
- const forceRuntimeRefreshByEnv = node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1021
- const disableDirtyOptimization = node_process.default.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
1022
- const disableJsPrecheck = node_process.default.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
1023
- const debugCssDiff = node_process.default.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
904
+ const forceRuntimeRefreshByEnv = node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
905
+ const disableDirtyOptimization = node_process.default.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1";
906
+ const disableJsPrecheck = node_process.default.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1";
907
+ const debugCssDiff = node_process.default.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
1024
908
  const resolvedConfig = getResolvedConfig();
1025
909
  const bundleFiles = Object.keys(bundle);
1026
910
  const useIncrementalMode = !(resolvedConfig?.command === "build") || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1027
911
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
1028
912
  const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1029
- const snapshot = buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
913
+ const snapshot = require_bundle_state.buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
1030
914
  const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
1031
915
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1032
916
  const processFiles = snapshot.processFiles;
1033
- if (useIncrementalMode) {
1034
- debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", state.iteration + 1, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
1035
- debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", state.iteration + 1, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1036
- } else debug("build mode full process html=%d[%s] js=%d[%s] css=%d[%s]", processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
917
+ logBundleProcessPlan({
918
+ debug,
919
+ snapshot,
920
+ useIncrementalMode,
921
+ iteration: state.iteration + 1
922
+ });
1037
923
  const jsEntries = snapshot.jsEntries;
1038
- const normalizedJsEntries = /* @__PURE__ */ new Map();
1039
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_css_imports.normalizeOutputPathKey(id), entry);
1040
- const getJsEntry = (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_css_imports.normalizeOutputPathKey(id));
1041
- const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
924
+ const getJsEntry = createJsEntryResolver(jsEntries);
925
+ const moduleGraphOptions = require_bundle_state.createBundleModuleGraphOptions(outDir, jsEntries);
1042
926
  const runtimeStart = performance.now();
1043
927
  const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1044
- const generatorBaseRuntime = await collectTailwindV4ContentCandidates(runtimeState, runtime, generatorOptions.mode, debug);
1045
- const generatorCandidateSources = snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js").map((entry) => ({
1046
- content: entry.source,
1047
- extension: node_path.default.extname(entry.file).replace(/^\./, "") || (entry.type === "html" ? "html" : "js")
1048
- }));
1049
- const generatorRuntime = collectLegacyContainerCompatCandidates(generatorCandidateSources, await collectGeneratorCandidatesFromSources(generatorCandidateSources, generatorBaseRuntime));
928
+ const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
929
+ await waitForSourceCandidateSyncs?.();
930
+ const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
931
+ const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
932
+ let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
933
+ let transformRuntime = runtime;
934
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0) {
935
+ const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
936
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
937
+ if (mainCssEntry) {
938
+ const validatedRuntime = await require_incremental_runtime_class_set.validateCandidatesByGenerator({
939
+ opts,
940
+ runtimeState,
941
+ candidates: generatorRuntime,
942
+ rawSource: mainCssEntry.source,
943
+ file: mainCssEntry.file,
944
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
945
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
946
+ styleHandler,
947
+ debug
948
+ });
949
+ if (validatedRuntime.size > 0) {
950
+ generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, validatedRuntime);
951
+ transformRuntime = generatorRuntime;
952
+ } else {
953
+ generatorRuntime = validatedRuntime;
954
+ transformRuntime = validatedRuntime;
955
+ }
956
+ }
957
+ }
958
+ const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1050
959
  recordGeneratorCandidates?.(generatorRuntime);
1051
- const defaultTemplateHandlerOptions = { runtimeSet: runtime };
960
+ const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
1052
961
  metrics.runtimeSet = measureElapsed(runtimeStart);
1053
962
  if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1054
- debug("get runtimeSet, class count: %d", runtime.size);
1055
- const runtimeSignature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1056
- const handleLinkedUpdate = (fileName, previous, next) => {
1057
- onUpdate(fileName, previous, next);
1058
- debug("js linked handle: %s", fileName);
1059
- };
1060
- const pendingLinkedUpdates = [];
1061
- const scheduleLinkedApply = (entry, code) => {
1062
- pendingLinkedUpdates.push(() => {
1063
- if (entry.output.type === "chunk") entry.output.code = code;
1064
- else entry.output.source = code;
1065
- });
1066
- };
1067
- const applyLinkedUpdates = (linked) => {
1068
- applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1069
- };
1070
- const createHandlerOptions = (absoluteFilename, extra) => ({
1071
- ...extra,
1072
- filename: absoluteFilename,
1073
- tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
1074
- moduleGraph: moduleGraphOptions,
1075
- babelParserOptions: {
1076
- ...extra?.babelParserOptions ?? {},
1077
- sourceFilename: absoluteFilename
1078
- }
963
+ debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
964
+ const runtimeSignature = require_cache.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
965
+ const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
966
+ jsEntries,
967
+ onUpdate,
968
+ debug
969
+ });
970
+ const createHandlerOptions = createJsHandlerOptionsFactory({
971
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
972
+ moduleGraph: moduleGraphOptions
1079
973
  });
1080
974
  const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1081
975
  const sharedCssResultCache = /* @__PURE__ */ new Map();
@@ -1087,7 +981,7 @@ function createGenerateBundleHook(context) {
1087
981
  metrics.html.total++;
1088
982
  if (!processFiles.html.has(file)) continue;
1089
983
  const rawSource = originalEntrySource;
1090
- tasks.push(require_generator_css.processCachedTask({
984
+ tasks.push(require_incremental_runtime_class_set.processCachedTask({
1091
985
  cache,
1092
986
  cacheKey: file,
1093
987
  hashKey: `${file}:html:${runtimeSignature}`,
@@ -1105,7 +999,7 @@ function createGenerateBundleHook(context) {
1105
999
  let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1106
1000
  if (unresolvedDynamicCandidates.length > 0) {
1107
1001
  _weapp_tailwindcss_logger.logger.warn("检测到 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
1108
- transformed = await templateHandler(rawSource, { runtimeSet: await context.ensureRuntimeClassSet(true) });
1002
+ transformed = await templateHandler(rawSource, { runtimeSet: new Set([...await context.ensureRuntimeClassSet(true), ...unresolvedDynamicCandidates]) });
1109
1003
  unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1110
1004
  if (unresolvedDynamicCandidates.length > 0) _weapp_tailwindcss_logger.logger.warn("WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
1111
1005
  }
@@ -1124,15 +1018,17 @@ function createGenerateBundleHook(context) {
1124
1018
  const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1125
1019
  const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
1126
1020
  const cssHandlerOptions = getCssHandlerOptions(file);
1127
- const cssSharedCacheKey = `${cssShareScope}:${runtimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1128
- tasks.push(require_generator_css.processCachedTask({
1021
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1022
+ const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1023
+ tasks.push(require_incremental_runtime_class_set.processCachedTask({
1129
1024
  cache,
1130
1025
  cacheKey: file,
1131
- hashKey: `${file}:css:${runtimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1132
- hash: getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature),
1026
+ hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1027
+ hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${generatorCandidateSignature}`,
1133
1028
  applyResult(source) {
1134
1029
  originalSource.source = source;
1135
1030
  markCssAssetProcessed?.(originalSource, file);
1031
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource, cssRuntimeSignature);
1136
1032
  },
1137
1033
  onCacheHit() {
1138
1034
  metrics.css.cacheHits++;
@@ -1151,8 +1047,8 @@ function createGenerateBundleHook(context) {
1151
1047
  }
1152
1048
  const runTransform = async () => {
1153
1049
  const start = performance.now();
1154
- await runtimeState.patchPromise;
1155
- const generated = await require_generator_css.generateCssByGenerator({
1050
+ await runtimeState.readyPromise;
1051
+ const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
1156
1052
  opts,
1157
1053
  runtimeState,
1158
1054
  runtime: generatorRuntime,
@@ -1164,6 +1060,7 @@ function createGenerateBundleHook(context) {
1164
1060
  debug
1165
1061
  });
1166
1062
  if (generated) {
1063
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1167
1064
  if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, generated.css));
1168
1065
  debug("css generated result: %s bytes=%d", file, generated.css.length);
1169
1066
  recordCssAssetResult?.(file, generated.css);
@@ -1199,7 +1096,7 @@ function createGenerateBundleHook(context) {
1199
1096
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1200
1097
  jsTaskFactories.push(async () => {
1201
1098
  const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1202
- await require_generator_css.processCachedTask({
1099
+ await require_incremental_runtime_class_set.processCachedTask({
1203
1100
  cache,
1204
1101
  cacheKey: file,
1205
1102
  hashKey: `${file}:js`,
@@ -1216,20 +1113,17 @@ function createGenerateBundleHook(context) {
1216
1113
  const rawSource = originalSource.code;
1217
1114
  if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1218
1115
  const handlerOptions = createHandlerOptions(absoluteFile);
1219
- if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(rawSource, handlerOptions)) {
1116
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
1220
1117
  metrics.js.elapsed += measureElapsed(start);
1221
1118
  metrics.js.transformed++;
1222
1119
  return { result: rawSource };
1223
1120
  }
1224
- const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1121
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1225
1122
  metrics.js.elapsed += measureElapsed(start);
1226
1123
  metrics.js.transformed++;
1227
1124
  onUpdate(file, rawSource, code);
1228
1125
  debug("js handle: %s", file);
1229
- if (linked) for (const id of Object.keys(linked)) {
1230
- const linkedEntry = getJsEntry(id);
1231
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1232
- }
1126
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1233
1127
  applyLinkedUpdates(linked);
1234
1128
  return { result: code };
1235
1129
  }
@@ -1240,10 +1134,7 @@ function createGenerateBundleHook(context) {
1240
1134
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1241
1135
  const baseApplyLinkedUpdates = applyLinkedUpdates;
1242
1136
  const wrappedApplyLinkedUpdates = (linked) => {
1243
- if (linked) for (const id of Object.keys(linked)) {
1244
- const linkedEntry = getJsEntry(id);
1245
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1246
- }
1137
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1247
1138
  baseApplyLinkedUpdates(linked);
1248
1139
  };
1249
1140
  const factory = createUniAppXAssetTask(file, originalSource, outDir, {
@@ -1254,7 +1145,7 @@ function createGenerateBundleHook(context) {
1254
1145
  debug,
1255
1146
  jsHandler,
1256
1147
  onUpdate,
1257
- runtimeSet: runtime,
1148
+ runtimeSet: transformRuntime,
1258
1149
  applyLinkedResults: wrappedApplyLinkedUpdates,
1259
1150
  uniAppX
1260
1151
  });
@@ -1275,7 +1166,7 @@ function createGenerateBundleHook(context) {
1275
1166
  sourceType: "unambiguous"
1276
1167
  }
1277
1168
  });
1278
- if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(currentSource, precheckOptions)) {
1169
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
1279
1170
  metrics.js.elapsed += measureElapsed(start);
1280
1171
  metrics.js.transformed++;
1281
1172
  return;
@@ -1286,178 +1177,138 @@ function createGenerateBundleHook(context) {
1286
1177
  });
1287
1178
  }
1288
1179
  }
1289
- require_css_imports.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1180
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1181
+ if (useIncrementalMode) for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1182
+ if (bundleFiles.includes(file) || getRememberedMainCssSignature?.(file) === cssRuntimeSignature) continue;
1183
+ tasks.push((async () => {
1184
+ const start = performance.now();
1185
+ const cssHandlerOptions = getCssHandlerOptions(file);
1186
+ const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
1187
+ opts,
1188
+ runtimeState,
1189
+ runtime: generatorRuntime,
1190
+ rawSource,
1191
+ file,
1192
+ cssHandlerOptions,
1193
+ cssUserHandlerOptions: getCssUserHandlerOptions(file),
1194
+ styleHandler,
1195
+ debug
1196
+ });
1197
+ const css = generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css;
1198
+ setRememberedMainCssSignature?.(file, cssRuntimeSignature);
1199
+ if (generated) {
1200
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1201
+ recordCssAssetResult?.(file, generated.css);
1202
+ debug("css replay generated result: %s bytes=%d", file, css.length);
1203
+ }
1204
+ const replayAsset = createReplayCssAsset(file, css);
1205
+ if (typeof this.emitFile === "function") this.emitFile({
1206
+ type: "asset",
1207
+ fileName: file,
1208
+ source: css
1209
+ });
1210
+ else bundle[file] = replayAsset;
1211
+ markCssAssetProcessed?.(replayAsset, file);
1212
+ metrics.css.elapsed += measureElapsed(start);
1213
+ metrics.css.transformed++;
1214
+ onUpdate(file, rawSource, css);
1215
+ debug("css replay handle: %s", file);
1216
+ })());
1217
+ }
1218
+ require_bundle_state.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1290
1219
  await Promise.all(tasks);
1291
1220
  for (const apply of pendingLinkedUpdates) apply();
1292
- updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1221
+ require_bundle_state.updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1293
1222
  debug("metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)", useIncrementalMode ? state.iteration : 0, formatMs(metrics.runtimeSet), metrics.html.total, metrics.html.transformed, metrics.html.cacheHits, formatCacheHitRate(metrics.html), formatMs(metrics.html.elapsed), metrics.js.total, metrics.js.transformed, metrics.js.cacheHits, formatCacheHitRate(metrics.js), formatMs(metrics.js.elapsed), metrics.css.total, metrics.css.transformed, metrics.css.cacheHits, formatCacheHitRate(metrics.css), formatMs(metrics.css.elapsed));
1223
+ require_incremental_runtime_class_set.emitHmrTiming("vite", "generateBundle", performance.now() - hmrTimingStartedAt);
1294
1224
  onEnd();
1295
1225
  debug("end");
1296
1226
  };
1297
1227
  }
1298
1228
  //#endregion
1299
- //#region src/bundlers/vite/incremental-runtime-class-set.ts
1300
- const debug$1 = require_recorder.createDebug("[vite:runtime-set] ");
1301
- const EXTENSION_DOT_PREFIX_RE = /^\./;
1302
- function createExtractOptions(context, source) {
1303
- return {
1304
- cwd: context.projectRoot,
1305
- base: context.base,
1306
- baseFallbacks: context.baseFallbacks,
1307
- css: context.css,
1308
- content: source,
1309
- extension: "html"
1310
- };
1311
- }
1312
- function createRuntimeEntries(snapshot) {
1313
- return snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js");
1314
- }
1315
- function collectChangedRuntimeFiles(snapshot) {
1316
- return new Set([...snapshot.runtimeAffectingChangedByType.html, ...snapshot.runtimeAffectingChangedByType.js]);
1317
- }
1318
- function resolveEntryExtension(entry) {
1319
- const ext = entry.file.split(/[?#]/, 1)[0]?.split(".").pop()?.replace(EXTENSION_DOT_PREFIX_RE, "") ?? "";
1320
- if (ext.length > 0) return ext;
1321
- return entry.type === "html" ? "html" : "js";
1322
- }
1323
- function createCandidateValidationSource(candidates) {
1324
- return [...new Set(candidates)].sort().join("\n");
1325
- }
1326
- function removeCandidateSet(candidateCountByClass, runtimeSet, candidates) {
1327
- for (const className of candidates) {
1328
- const count = candidateCountByClass.get(className);
1329
- if (count == null) continue;
1330
- if (count <= 1) {
1331
- candidateCountByClass.delete(className);
1332
- runtimeSet.delete(className);
1333
- continue;
1334
- }
1335
- candidateCountByClass.set(className, count - 1);
1229
+ //#region src/bundlers/vite/official-tailwind-plugins.ts
1230
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1231
+ function getPostcssPluginName(plugin) {
1232
+ if (!plugin) return;
1233
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1234
+ return getPostcssPluginName(plugin());
1235
+ } catch {
1236
+ return;
1336
1237
  }
1238
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1239
+ const { postcssPlugin } = plugin;
1240
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1337
1241
  }
1338
- function addCandidateSet(candidateCountByClass, runtimeSet, candidates) {
1339
- for (const className of candidates) {
1340
- const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
1341
- candidateCountByClass.set(className, nextCount);
1342
- runtimeSet.add(className);
1343
- }
1242
+ function isTailwindPostcssPlugin(plugin) {
1243
+ const name = getPostcssPluginName(plugin);
1244
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1344
1245
  }
1345
- function createBundleRuntimeClassSetManager(options = {}) {
1346
- const customExtractCandidates = options.extractCandidates;
1347
- const extractCandidates = customExtractCandidates ?? tailwindcss_patch.extractValidCandidates;
1348
- const extractRawCandidates = options.extractRawCandidates ?? tailwindcss_patch.extractRawCandidatesWithPositions;
1349
- const runtimeSet = /* @__PURE__ */ new Set();
1350
- const candidateCountByClass = /* @__PURE__ */ new Map();
1351
- const candidatesByFile = /* @__PURE__ */ new Map();
1352
- const candidateValidityCache = /* @__PURE__ */ new Map();
1353
- let runtimeSignature;
1354
- let validationContext;
1355
- let designSystemPromise;
1356
- async function reset() {
1357
- runtimeSet.clear();
1358
- candidateCountByClass.clear();
1359
- candidatesByFile.clear();
1360
- candidateValidityCache.clear();
1361
- runtimeSignature = void 0;
1362
- validationContext = void 0;
1363
- designSystemPromise = void 0;
1364
- }
1365
- async function resolveValidationContextCached(patcher) {
1366
- if (!validationContext) validationContext = await require_generator.resolveTailwindV4SourceFromPatcher(patcher);
1367
- return validationContext;
1368
- }
1369
- async function loadDesignSystem(context) {
1370
- if (!designSystemPromise) designSystemPromise = (0, tailwindcss_patch.loadTailwindV4DesignSystem)(context);
1371
- return designSystemPromise;
1246
+ function removeTailwindPostcssPlugins(plugins) {
1247
+ let removed = 0;
1248
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1249
+ plugins.splice(i, 1);
1250
+ removed++;
1372
1251
  }
1373
- function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
1374
- const parsedCandidates = [...unknownCandidates].filter((candidate) => designSystem.parseCandidate(candidate).length > 0);
1375
- const cssByCandidate = parsedCandidates.length > 0 ? designSystem.candidatesToCss(parsedCandidates) : [];
1376
- const validCandidates = /* @__PURE__ */ new Set();
1377
- for (let index = 0; index < parsedCandidates.length; index += 1) {
1378
- const candidate = parsedCandidates[index];
1379
- const css = cssByCandidate[index];
1380
- if (candidate && typeof css === "string" && css.trim().length > 0) validCandidates.add(candidate);
1381
- }
1382
- for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1252
+ return removed;
1253
+ }
1254
+ function isTailwindVitePlugin(plugin) {
1255
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1256
+ const { name } = plugin;
1257
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1258
+ }
1259
+ function removeTailwindVitePlugins(plugins) {
1260
+ let removed = 0;
1261
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1262
+ plugins.splice(i, 1);
1263
+ removed++;
1383
1264
  }
1384
- async function validateUnknownCandidates(patcher, unknownCandidates) {
1385
- if (unknownCandidates.size === 0) return;
1386
- const context = await resolveValidationContextCached(patcher);
1387
- if (!customExtractCandidates) try {
1388
- populateCandidateValidityCacheFromDesignSystem(await loadDesignSystem(context), unknownCandidates);
1389
- return;
1390
- } catch (error) {
1391
- debug$1("incremental design-system validation failed: %O", error);
1392
- designSystemPromise = void 0;
1393
- throw error;
1265
+ return removed;
1266
+ }
1267
+ function disableTailwindVitePlugin(plugin) {
1268
+ if (!isTailwindVitePlugin(plugin)) return false;
1269
+ const mutablePlugin = plugin;
1270
+ for (const hook of [
1271
+ "configResolved",
1272
+ "configureServer",
1273
+ "transform",
1274
+ "hotUpdate",
1275
+ "handleHotUpdate"
1276
+ ]) delete mutablePlugin[hook];
1277
+ return true;
1278
+ }
1279
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1280
+ let removed = 0;
1281
+ for (let i = plugins.length - 1; i >= 0; i--) {
1282
+ const plugin = plugins[i];
1283
+ if (Array.isArray(plugin)) {
1284
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1285
+ if (plugin.length === 0) plugins.splice(i, 1);
1286
+ continue;
1394
1287
  }
1395
- const source = createCandidateValidationSource(unknownCandidates);
1396
- const validCandidates = new Set(await extractCandidates(createExtractOptions(context, source)));
1397
- for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1398
- }
1399
- async function extractEntryRawCandidates(entry) {
1400
- const matches = await extractRawCandidates(entry.source, resolveEntryExtension(entry));
1401
- const candidates = /* @__PURE__ */ new Set();
1402
- for (const match of matches) {
1403
- const candidate = match?.rawCandidate;
1404
- if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
1288
+ if (disableTailwindVitePlugin(plugin)) {
1289
+ plugins.splice(i, 1);
1290
+ removed++;
1405
1291
  }
1406
- return candidates;
1407
1292
  }
1408
- async function sync(patcher, snapshot) {
1409
- const nextSignature = require_logger.getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1410
- const runtimeEntries = createRuntimeEntries(snapshot);
1411
- const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1412
- const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
1413
- const fullRebuild = runtimeSignature !== nextSignature || candidatesByFile.size === 0;
1414
- if (runtimeSignature !== nextSignature) {
1415
- debug$1("runtime signature changed, reset incremental runtime set: %s", nextSignature);
1416
- await reset();
1417
- }
1418
- runtimeSignature = nextSignature;
1419
- for (const [file, previousCandidates] of candidatesByFile) {
1420
- if (currentRuntimeFiles.has(file)) continue;
1421
- removeCandidateSet(candidateCountByClass, runtimeSet, previousCandidates);
1422
- candidatesByFile.delete(file);
1423
- }
1424
- const changedRuntimeFiles = fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
1425
- if (changedRuntimeFiles.length === 0) return new Set(runtimeSet);
1426
- const rawCandidatesByFile = /* @__PURE__ */ new Map();
1427
- const unknownCandidates = /* @__PURE__ */ new Set();
1428
- await Promise.all(changedRuntimeFiles.map(async (file) => {
1429
- const entry = runtimeEntriesByFile.get(file);
1430
- if (!entry) return;
1431
- const candidates = await extractEntryRawCandidates(entry);
1432
- rawCandidatesByFile.set(file, candidates);
1433
- for (const candidate of candidates) if (!candidateValidityCache.has(candidate)) unknownCandidates.add(candidate);
1434
- }));
1435
- await validateUnknownCandidates(patcher, unknownCandidates);
1436
- let rawCandidateCount = 0;
1437
- for (const file of changedRuntimeFiles) {
1438
- const nextRawCandidates = rawCandidatesByFile.get(file);
1439
- const previousCandidates = candidatesByFile.get(file);
1440
- if (previousCandidates) removeCandidateSet(candidateCountByClass, runtimeSet, previousCandidates);
1441
- if (!nextRawCandidates || nextRawCandidates.size === 0) {
1442
- candidatesByFile.delete(file);
1443
- continue;
1444
- }
1445
- rawCandidateCount += nextRawCandidates.size;
1446
- const nextCandidates = new Set([...nextRawCandidates].filter((candidate) => candidateValidityCache.get(candidate) === true));
1447
- if (nextCandidates.size === 0) {
1448
- candidatesByFile.delete(file);
1449
- continue;
1450
- }
1451
- addCandidateSet(candidateCountByClass, runtimeSet, nextCandidates);
1452
- candidatesByFile.set(file, nextCandidates);
1453
- }
1454
- debug$1("incremental runtime set synced, changedFiles=%d rawCandidates=%d validateMisses=%d runtimeSize=%d trackedFiles=%d", changedRuntimeFiles.length, rawCandidateCount, unknownCandidates.size, runtimeSet.size, candidatesByFile.size);
1455
- return new Set(runtimeSet);
1293
+ return removed;
1294
+ }
1295
+ //#endregion
1296
+ //#region src/bundlers/vite/postcss-config.ts
1297
+ async function resolveFilteredPostcssConfig(root) {
1298
+ try {
1299
+ const loaded = await (0, postcss_load_config.default)({}, root);
1300
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1301
+ const removed = removeTailwindPostcssPlugins(plugins);
1302
+ if (removed === 0) return;
1303
+ return {
1304
+ options: loaded.options,
1305
+ plugins,
1306
+ removed
1307
+ };
1308
+ } catch (error) {
1309
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1310
+ throw error;
1456
1311
  }
1457
- return {
1458
- sync,
1459
- reset
1460
- };
1461
1312
  }
1462
1313
  //#endregion
1463
1314
  //#region src/bundlers/vite/resolve-app-type.ts
@@ -1521,6 +1372,34 @@ function resolveImplicitAppTypeFromViteRoot(root) {
1521
1372
  }
1522
1373
  }
1523
1374
  //#endregion
1375
+ //#region src/bundlers/shared/css-imports.ts
1376
+ const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
1377
+ const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1378
+ function normalizeTailwindcssSpecifier(specifier) {
1379
+ if (specifier === "tailwindcss$" || specifier === "weapp-tailwindcss$") return specifier.slice(0, -1);
1380
+ return specifier;
1381
+ }
1382
+ function getTailwindcssSubpath(specifier) {
1383
+ if (specifier === "tailwindcss" || specifier === "weapp-tailwindcss") return "index.css";
1384
+ return specifier.replace(/^(?:tailwindcss|weapp-tailwindcss)\//, "");
1385
+ }
1386
+ function resolveTailwindcssImport(specifier, pkgDir, options) {
1387
+ const normalized = normalizeTailwindcssSpecifier(specifier);
1388
+ if (!tailwindcssImportRE.test(normalized)) return null;
1389
+ if (normalized === "tailwindcss" || normalized === "weapp-tailwindcss") return options?.rootImport ?? (options?.join ?? node_path.default.join)(pkgDir, "index.css");
1390
+ return (options?.join ?? node_path.default.join)(pkgDir, getTailwindcssSubpath(normalized));
1391
+ }
1392
+ function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1393
+ let hasReplacements = false;
1394
+ const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1395
+ const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1396
+ if (!replacement) return full;
1397
+ hasReplacements = true;
1398
+ return `${prefix}${quote}${replacement}${suffix}`;
1399
+ });
1400
+ return hasReplacements ? rewritten : void 0;
1401
+ }
1402
+ //#endregion
1524
1403
  //#region src/bundlers/vite/rewrite-css-imports.ts
1525
1404
  function joinPosixPath(base, subpath) {
1526
1405
  if (base.endsWith("/")) return `${base}${subpath}`;
@@ -1529,19 +1408,22 @@ function joinPosixPath(base, subpath) {
1529
1408
  function isCssLikeImporter(importer) {
1530
1409
  if (!importer) return false;
1531
1410
  const normalized = (0, _weapp_tailwindcss_shared.cleanUrl)(importer);
1532
- return isCSSRequest(normalized) || normalized.endsWith("/*");
1411
+ return require_bundle_state.isSourceStyleRequest(importer) || isCSSRequest(normalized) || normalized.endsWith("/*");
1412
+ }
1413
+ function stripTailwindConfigDirectives(code) {
1414
+ return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1533
1415
  }
1534
1416
  function createRewriteCssImportsPlugins(options) {
1535
1417
  if (!options.shouldRewrite) return [];
1536
- const { appType, getAppType, rootImport, weappTailwindcssDirPosix } = options;
1418
+ const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1537
1419
  const resolveAppType = () => getAppType?.() ?? appType;
1538
1420
  return [{
1539
- name: `${require_recorder.vitePluginName}:rewrite-css-imports`,
1421
+ name: `${require_precheck.vitePluginName}:rewrite-css-imports`,
1540
1422
  enforce: "pre",
1541
1423
  resolveId: {
1542
1424
  order: "pre",
1543
1425
  handler(id, importer) {
1544
- const replacement = require_css_imports.resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1426
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1545
1427
  join: joinPosixPath,
1546
1428
  appType: resolveAppType(),
1547
1429
  rootImport
@@ -1553,16 +1435,18 @@ function createRewriteCssImportsPlugins(options) {
1553
1435
  },
1554
1436
  transform: {
1555
1437
  order: "pre",
1556
- handler(code, id) {
1438
+ async handler(code, id) {
1557
1439
  if (!isCSSRequest(id)) return null;
1558
- const rewritten = require_css_imports.rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1440
+ if (require_incremental_runtime_class_set.hasTailwindRootDirectives(code)) await options.onTailwindRootCss?.(id, code);
1441
+ const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1559
1442
  join: joinPosixPath,
1560
1443
  appType: resolveAppType(),
1561
1444
  rootImport
1562
1445
  });
1563
- if (!rewritten) return null;
1446
+ const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1447
+ if (!nextCode || nextCode === code) return null;
1564
1448
  return {
1565
- code: rewritten,
1449
+ code: nextCode,
1566
1450
  map: null
1567
1451
  };
1568
1452
  }
@@ -1570,162 +1454,28 @@ function createRewriteCssImportsPlugins(options) {
1570
1454
  }];
1571
1455
  }
1572
1456
  //#endregion
1573
- //#region src/bundlers/vite/index.ts
1574
- const debug = require_recorder.createDebug();
1575
- const weappTailwindcssPackageDir = require_css_imports.resolvePackageDir("weapp-tailwindcss");
1576
- const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1577
- const PACKAGE_JSON_FILE = "package.json";
1578
- const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1579
- function getPostcssPluginName(plugin) {
1580
- if (!plugin) return;
1581
- if (typeof plugin === "function" && "postcss" in plugin) try {
1582
- return getPostcssPluginName(plugin());
1583
- } catch {
1584
- return;
1585
- }
1586
- if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1587
- const { postcssPlugin } = plugin;
1588
- return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1589
- }
1590
- function isTailwindPostcssPlugin(plugin) {
1591
- const name = getPostcssPluginName(plugin);
1592
- return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1593
- }
1594
- function removeTailwindPostcssPlugins(plugins) {
1595
- let removed = 0;
1596
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1597
- plugins.splice(i, 1);
1598
- removed++;
1599
- }
1600
- return removed;
1601
- }
1602
- async function resolveFilteredPostcssConfig(root) {
1603
- try {
1604
- const loaded = await (0, postcss_load_config.default)({}, root);
1605
- const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1606
- const removed = removeTailwindPostcssPlugins(plugins);
1607
- if (removed === 0) return;
1608
- return {
1609
- options: loaded.options,
1610
- plugins,
1611
- removed
1612
- };
1613
- } catch (error) {
1614
- if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1615
- throw error;
1616
- }
1617
- }
1618
- function isTailwindVitePlugin(plugin) {
1619
- if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1620
- const { name } = plugin;
1621
- return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1622
- }
1623
- function removeTailwindVitePlugins(plugins) {
1624
- let removed = 0;
1625
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1626
- plugins.splice(i, 1);
1627
- removed++;
1628
- }
1629
- return removed;
1630
- }
1631
- function disableTailwindVitePlugin(plugin) {
1632
- if (!isTailwindVitePlugin(plugin)) return false;
1633
- const mutablePlugin = plugin;
1634
- for (const hook of [
1635
- "configResolved",
1636
- "configureServer",
1637
- "transform",
1638
- "hotUpdate",
1639
- "handleHotUpdate"
1640
- ]) delete mutablePlugin[hook];
1641
- return true;
1642
- }
1643
- function disableAndRemoveTailwindVitePlugins(plugins) {
1644
- let removed = 0;
1645
- for (let i = plugins.length - 1; i >= 0; i--) {
1646
- const plugin = plugins[i];
1647
- if (Array.isArray(plugin)) {
1648
- removed += disableAndRemoveTailwindVitePlugins(plugin);
1649
- if (plugin.length === 0) plugins.splice(i, 1);
1650
- continue;
1651
- }
1652
- if (disableTailwindVitePlugin(plugin)) {
1653
- plugins.splice(i, 1);
1654
- removed++;
1655
- }
1656
- }
1657
- return removed;
1658
- }
1659
- function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1660
- const resolvedRoot = node_path.default.resolve(root);
1661
- if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
1662
- const searchRoots = [];
1663
- let current = resolvedRoot;
1664
- while (true) {
1665
- searchRoots.push(current);
1666
- const parent = node_path.default.dirname(current);
1667
- if (parent === current) break;
1668
- current = parent;
1669
- }
1670
- const tailwindConfigPath = require_logger.findTailwindConfig(searchRoots);
1671
- if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
1672
- const packageRoot = require_logger.findNearestPackageRoot(resolvedRoot);
1673
- if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1674
- return resolvedRoot;
1675
- }
1676
- /**
1677
- * @name UnifiedViteWeappTailwindcssPlugin
1678
- * @description uni-app vite / uni-app-x 版本插件
1679
- * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1680
- */
1681
- function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1682
- const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1683
- const rewriteCssImportsSpecified = Object.hasOwn(options, "rewriteCssImports");
1684
- const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1685
- const opts = require_recorder.getCompilerContext(options);
1686
- const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1687
- const uniAppXEnabled = require_logger.isUniAppXEnabled(uniAppX);
1688
- const disabledOptions = require_css_imports.resolveDisabledOptions(disabled);
1689
- const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1690
- const shouldOwnTailwindGeneration = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force";
1691
- const shouldRewriteCssImports = opts.rewriteCssImports !== false && !disabledOptions.rewriteCssImports && (rewriteCssImportsSpecified || tailwindcssMajorVersion >= 4);
1692
- const rewritePlugins = createRewriteCssImportsPlugins({
1693
- getAppType: () => opts.appType,
1694
- rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
1695
- shouldRewrite: shouldRewriteCssImports,
1696
- weappTailwindcssDirPosix
1697
- });
1698
- if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1699
- const customAttributesEntities = require_recorder.toCustomAttributesEntities(customAttributes);
1700
- const patchRecorderState = require_recorder.setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1701
- source: "runtime",
1702
- cwd: opts.tailwindcssBasedir ?? node_process.default.cwd()
1703
- });
1457
+ //#region src/bundlers/vite/runtime-class-set.ts
1458
+ function createViteRuntimeClassSet(options) {
1459
+ const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
1704
1460
  const runtimeState = {
1705
1461
  twPatcher: initialTwPatcher,
1706
- patchPromise: patchRecorderState.patchPromise,
1707
- refreshTailwindcssPatcher,
1708
- onPatchCompleted: patchRecorderState.onPatchCompleted
1462
+ readyPromise: require_precheck.createTailwindRuntimeReadyPromise(initialTwPatcher),
1463
+ refreshTailwindcssPatcher
1709
1464
  };
1465
+ const bundleRuntimeClassSetManager = require_incremental_runtime_class_set.createBundleRuntimeClassSetManager();
1710
1466
  let runtimeSet;
1711
1467
  let runtimeSetPromise;
1712
- let resolvedConfig;
1713
1468
  let runtimeRefreshSignature;
1714
1469
  let runtimeRefreshOptionsKey;
1715
- let recordedGeneratorCandidates;
1716
- const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1717
- const processedCssAssets = /* @__PURE__ */ new WeakSet();
1718
- const processedCssAssetFiles = /* @__PURE__ */ new Set();
1719
1470
  function resolveRuntimeRefreshOptions() {
1720
- const configPath = require_patcher_options.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1721
- const signature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher);
1471
+ const configPath = require_cache.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1472
+ const signature = require_cache.getRuntimeClassSetSignature(runtimeState.twPatcher);
1722
1473
  const optionsKey = JSON.stringify({
1723
1474
  appType: opts.appType,
1724
1475
  uniAppX: uniAppXEnabled,
1725
1476
  customAttributesEntities,
1726
1477
  disabledDefaultTemplateHandler,
1727
- configPath,
1728
- rewriteCssImports: shouldRewriteCssImports
1478
+ configPath
1729
1479
  });
1730
1480
  const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1731
1481
  runtimeRefreshSignature = signature;
@@ -1738,7 +1488,7 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1738
1488
  }
1739
1489
  async function refreshRuntimeState(force) {
1740
1490
  const invalidation = resolveRuntimeRefreshOptions();
1741
- const refreshed = await require_recorder.refreshTailwindRuntimeState(runtimeState, {
1491
+ const refreshed = await require_precheck.refreshTailwindRuntimeState(runtimeState, {
1742
1492
  force: force || invalidation.changed,
1743
1493
  clearCache: force || invalidation.changed
1744
1494
  });
@@ -1749,13 +1499,13 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1749
1499
  }
1750
1500
  }
1751
1501
  async function ensureRuntimeClassSet(force = false) {
1752
- const forceRuntimeRefresh = force || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1502
+ const forceRuntimeRefresh = force || node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1753
1503
  await refreshRuntimeState(force);
1754
- await runtimeState.patchPromise;
1504
+ await runtimeState.readyPromise;
1755
1505
  if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1756
1506
  if (forceRuntimeRefresh || !runtimeSetPromise) {
1757
1507
  const invalidation = resolveRuntimeRefreshOptions();
1758
- runtimeSetPromise = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1508
+ runtimeSetPromise = require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1759
1509
  force: forceRuntimeRefresh || invalidation.changed,
1760
1510
  skipRefresh: forceRuntimeRefresh,
1761
1511
  clearCache: forceRuntimeRefresh || invalidation.changed
@@ -1770,12 +1520,12 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1770
1520
  }
1771
1521
  }
1772
1522
  async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1773
- const forceRuntimeRefresh = forceRefresh || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1523
+ const forceRuntimeRefresh = forceRefresh || node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1774
1524
  const invalidation = resolveRuntimeRefreshOptions();
1775
1525
  const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1776
1526
  const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1777
1527
  await refreshRuntimeState(shouldRefreshPatcher);
1778
- await runtimeState.patchPromise;
1528
+ await runtimeState.readyPromise;
1779
1529
  if (shouldRefreshPatcher) {
1780
1530
  runtimeSet = void 0;
1781
1531
  runtimeSetPromise = void 0;
@@ -1783,21 +1533,28 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1783
1533
  }
1784
1534
  if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1785
1535
  const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1786
- const shouldForceFullRuntimeSet = forceRuntimeRefresh || invalidation.changed || forceCollectBySource;
1787
- const fullRuntimeSet = !shouldForceFullRuntimeSet && runtimeSet ? runtimeSet : await require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1788
- force: shouldForceFullRuntimeSet,
1789
- skipRefresh: forceRuntimeRefresh,
1790
- clearCache: forceRuntimeRefresh || invalidation.changed
1536
+ runtimeSet = nextRuntimeSet;
1537
+ return nextRuntimeSet;
1538
+ } catch (error) {
1539
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1540
+ await bundleRuntimeClassSetManager.reset();
1541
+ }
1542
+ if (runtimeState.twPatcher.majorVersion === 3 && !forceRuntimeRefresh) try {
1543
+ let baseClassSet;
1544
+ if (!runtimeSet || shouldRefreshPatcher) baseClassSet = await require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1545
+ force: true,
1546
+ skipRefresh: shouldRefreshPatcher,
1547
+ clearCache: shouldRefreshPatcher
1791
1548
  });
1792
- const mergedRuntimeSet = new Set([...fullRuntimeSet, ...nextRuntimeSet]);
1793
- runtimeSet = mergedRuntimeSet;
1794
- return mergedRuntimeSet;
1549
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot, { baseClassSet });
1550
+ runtimeSet = nextRuntimeSet;
1551
+ return nextRuntimeSet;
1795
1552
  } catch (error) {
1796
1553
  debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1797
1554
  await bundleRuntimeClassSetManager.reset();
1798
1555
  }
1799
1556
  if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1800
- const task = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1557
+ const task = require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1801
1558
  force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1802
1559
  skipRefresh: forceRuntimeRefresh,
1803
1560
  clearCache: forceRuntimeRefresh || invalidation.changed
@@ -1810,23 +1567,592 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1810
1567
  if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1811
1568
  }
1812
1569
  }
1570
+ return {
1571
+ runtimeState,
1572
+ refreshRuntimeState,
1573
+ ensureRuntimeClassSet,
1574
+ ensureBundleRuntimeClassSet
1575
+ };
1576
+ }
1577
+ //#endregion
1578
+ //#region src/bundlers/vite/source-candidates.ts
1579
+ const CLEAN_URL_RE = /[?#].*$/;
1580
+ const SOURCE_CANDIDATE_EXTENSIONS = [
1581
+ "js",
1582
+ "jsx",
1583
+ "mjs",
1584
+ "cjs",
1585
+ "ts",
1586
+ "tsx",
1587
+ "mts",
1588
+ "cts",
1589
+ "vue",
1590
+ "uvue",
1591
+ "nvue",
1592
+ "svelte",
1593
+ "mpx",
1594
+ "html",
1595
+ "wxml",
1596
+ "axml",
1597
+ "jxml",
1598
+ "ksml",
1599
+ "ttml",
1600
+ "qml",
1601
+ "tyml",
1602
+ "xhsml",
1603
+ "swan",
1604
+ "css",
1605
+ "wxss",
1606
+ "acss",
1607
+ "jxss",
1608
+ "ttss",
1609
+ "qss",
1610
+ "tyss",
1611
+ "scss",
1612
+ "sass",
1613
+ "less",
1614
+ "styl",
1615
+ "stylus"
1616
+ ];
1617
+ const SOURCE_CANDIDATE_EXTENSION_RE = /\.(?:[cm]?[jt]sx?|vue|uvue|nvue|svelte|mpx|html|wxml|axml|jxml|ksml|ttml|qml|tyml|xhsml|swan|css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|stylus?)$/;
1618
+ const CSS_SOURCE_CANDIDATE_EXTENSION_RE = /^(?:css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|styl|stylus)$/;
1619
+ const SOURCE_CANDIDATE_GLOB = `**/*.{${SOURCE_CANDIDATE_EXTENSIONS.join(",")}}`;
1620
+ const DEFAULT_SCAN_IGNORE = ["**/node_modules/**", "**/.git/**"];
1621
+ function cleanUrl(id) {
1622
+ return id.replace(CLEAN_URL_RE, "");
1623
+ }
1624
+ function toPosixPath$1(value) {
1625
+ return value.split(node_path.default.sep).join("/");
1626
+ }
1627
+ function resolveOutDirIgnorePattern(root, outDir) {
1628
+ if (!outDir) return;
1629
+ const relative = node_path.default.relative(root, node_path.default.resolve(root, outDir));
1630
+ if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) return;
1631
+ return `${toPosixPath$1(relative)}/**`;
1632
+ }
1633
+ function resolveSourceCandidateExtension(id) {
1634
+ const normalized = cleanUrl(id);
1635
+ return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
1636
+ }
1637
+ function isSourceCandidateRequest(id) {
1638
+ return SOURCE_CANDIDATE_EXTENSION_RE.test(cleanUrl(id));
1639
+ }
1640
+ function removeCandidateSet(candidateCount, candidates) {
1641
+ for (const candidate of candidates) {
1642
+ const count = candidateCount.get(candidate);
1643
+ if (count == null) continue;
1644
+ if (count <= 1) {
1645
+ candidateCount.delete(candidate);
1646
+ continue;
1647
+ }
1648
+ candidateCount.set(candidate, count - 1);
1649
+ }
1650
+ }
1651
+ function addCandidateSet(candidateCount, candidates) {
1652
+ for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
1653
+ }
1654
+ const CSS_APPLY_RE = /@apply\s+([^;{}]+)/g;
1655
+ const CSS_APPLY_IMPORTANT = "!important";
1656
+ function extractCssApplyCandidates(source) {
1657
+ const candidates = /* @__PURE__ */ new Set();
1658
+ CSS_APPLY_RE.lastIndex = 0;
1659
+ let match = CSS_APPLY_RE.exec(source);
1660
+ while (match !== null) {
1661
+ const params = match[1] ?? "";
1662
+ for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(params, true)) {
1663
+ const normalized = candidate.trim();
1664
+ if (normalized && normalized !== CSS_APPLY_IMPORTANT) candidates.add(normalized);
1665
+ }
1666
+ match = CSS_APPLY_RE.exec(source);
1667
+ }
1668
+ return candidates;
1669
+ }
1670
+ function createSourceCandidateCollector() {
1671
+ const candidatesById = /* @__PURE__ */ new Map();
1672
+ const candidateCount = /* @__PURE__ */ new Map();
1673
+ let inlineIncludedCandidates = /* @__PURE__ */ new Set();
1674
+ let inlineExcludedCandidates = /* @__PURE__ */ new Set();
1675
+ async function sync(id, source) {
1676
+ const normalizedId = cleanUrl(id);
1677
+ const extension = resolveSourceCandidateExtension(normalizedId);
1678
+ const nextCandidates = /* @__PURE__ */ new Set();
1679
+ if (CSS_SOURCE_CANDIDATE_EXTENSION_RE.test(extension)) for (const candidate of extractCssApplyCandidates(source)) nextCandidates.add(candidate);
1680
+ else {
1681
+ const matches = await (0, tailwindcss_patch.extractRawCandidatesWithPositions)(source, extension);
1682
+ for (const match of matches) {
1683
+ const candidate = match.rawCandidate;
1684
+ if (typeof candidate === "string" && candidate.length > 0) nextCandidates.add(candidate);
1685
+ }
1686
+ }
1687
+ remove(normalizedId);
1688
+ if (nextCandidates.size === 0) return;
1689
+ candidatesById.set(normalizedId, nextCandidates);
1690
+ addCandidateSet(candidateCount, nextCandidates);
1691
+ }
1692
+ async function syncFile(id) {
1693
+ const normalizedId = cleanUrl(id);
1694
+ await sync(normalizedId, await (0, node_fs_promises.readFile)(normalizedId, "utf8"));
1695
+ }
1696
+ async function scanRoot({ entries, root, outDir }) {
1697
+ const resolvedRoot = node_path.default.resolve(root);
1698
+ const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, outDir);
1699
+ const ignore = outDirIgnore ? [...DEFAULT_SCAN_IGNORE, outDirIgnore] : DEFAULT_SCAN_IGNORE;
1700
+ const files = entries ? await require_source_scan.expandTailwindSourceEntries(entries, { ignore }) : await (0, fast_glob.default)(SOURCE_CANDIDATE_GLOB, {
1701
+ absolute: true,
1702
+ cwd: resolvedRoot,
1703
+ ignore,
1704
+ onlyFiles: true,
1705
+ unique: true
1706
+ });
1707
+ await Promise.all(files.map((file) => syncFile(file)));
1708
+ }
1709
+ function syncInline(inlineCandidates) {
1710
+ inlineIncludedCandidates = new Set(inlineCandidates?.included ?? []);
1711
+ inlineExcludedCandidates = new Set(inlineCandidates?.excluded ?? []);
1712
+ }
1713
+ function remove(id) {
1714
+ const normalizedId = cleanUrl(id);
1715
+ const previousCandidates = candidatesById.get(normalizedId);
1716
+ if (!previousCandidates) return;
1717
+ removeCandidateSet(candidateCount, previousCandidates);
1718
+ candidatesById.delete(normalizedId);
1719
+ }
1720
+ function values() {
1721
+ const values = new Set([...candidateCount.keys(), ...inlineIncludedCandidates]);
1722
+ for (const candidate of inlineExcludedCandidates) values.delete(candidate);
1723
+ return values;
1724
+ }
1725
+ function clear() {
1726
+ candidatesById.clear();
1727
+ candidateCount.clear();
1728
+ inlineIncludedCandidates.clear();
1729
+ inlineExcludedCandidates.clear();
1730
+ }
1731
+ return {
1732
+ sync,
1733
+ syncFile,
1734
+ scanRoot,
1735
+ syncInline,
1736
+ remove,
1737
+ values,
1738
+ clear
1739
+ };
1740
+ }
1741
+ //#endregion
1742
+ //#region src/bundlers/vite/source-scan.ts
1743
+ const VITE_SOURCE_CANDIDATE_PATTERN = require_source_scan.createSourceScanPattern([
1744
+ "js",
1745
+ "jsx",
1746
+ "mjs",
1747
+ "cjs",
1748
+ "ts",
1749
+ "tsx",
1750
+ "mts",
1751
+ "cts",
1752
+ "vue",
1753
+ "uvue",
1754
+ "nvue",
1755
+ "svelte",
1756
+ "mpx",
1757
+ "html",
1758
+ "wxml",
1759
+ "axml",
1760
+ "jxml",
1761
+ "ksml",
1762
+ "ttml",
1763
+ "qml",
1764
+ "tyml",
1765
+ "xhsml",
1766
+ "swan",
1767
+ "css",
1768
+ "wxss",
1769
+ "acss",
1770
+ "jxss",
1771
+ "ttss",
1772
+ "qss",
1773
+ "tyss",
1774
+ "scss",
1775
+ "sass",
1776
+ "less",
1777
+ "styl",
1778
+ "stylus"
1779
+ ]);
1780
+ function parseImportSourceParam(params) {
1781
+ const match = /\bsource\(\s*(none|(['"])(.*?)\2)\s*\)/.exec(params);
1782
+ if (!match) return;
1783
+ return {
1784
+ none: match[1] === "none",
1785
+ sourcePath: match[3]
1786
+ };
1787
+ }
1788
+ function isTailwindCssImport(params) {
1789
+ return /^\s*(['"])tailwindcss(?:\/[^'"]*)?\1/.test(params);
1790
+ }
1791
+ function resolveSourceBase(base, sourcePath) {
1792
+ return node_path.default.isAbsolute(sourcePath) ? sourcePath : node_path.default.resolve(base, sourcePath);
1793
+ }
1794
+ function resolveConfigPath(base, configPath) {
1795
+ return node_path.default.isAbsolute(configPath) ? node_path.default.resolve(configPath) : node_path.default.resolve(base, configPath);
1796
+ }
1797
+ async function resolveConfigContentEntries(root, base) {
1798
+ const configPaths = /* @__PURE__ */ new Set();
1799
+ root.walkAtRules("config", (rule) => {
1800
+ const configPath = require_source_scan.parseConfigParam(rule.params);
1801
+ if (configPath) configPaths.add(resolveConfigPath(base, configPath));
1802
+ });
1803
+ const entries = [];
1804
+ for (const configPath of configPaths) try {
1805
+ const loaded = await (0, tailwindcss_config.loadConfig)({
1806
+ config: configPath,
1807
+ cwd: node_path.default.dirname(configPath)
1808
+ });
1809
+ entries.push(...require_source_scan.normalizeLegacyContentEntries(loaded?.config.content, node_path.default.dirname(configPath)));
1810
+ } catch {}
1811
+ return {
1812
+ dependencies: [...configPaths],
1813
+ entries
1814
+ };
1815
+ }
1816
+ async function resolveTailwindV4EntriesFromCss(css, base) {
1817
+ let root;
1818
+ try {
1819
+ root = postcss.default.parse(css);
1820
+ } catch {
1821
+ return;
1822
+ }
1823
+ let importSourceBase;
1824
+ let hasSourceNone = false;
1825
+ const [sourceEntries, configEntries] = await Promise.all([require_source_scan.resolveCssSourceEntries(root, base, VITE_SOURCE_CANDIDATE_PATTERN), resolveConfigContentEntries(root, base)]);
1826
+ const entries = [...configEntries.entries, ...sourceEntries];
1827
+ const inlineCandidates = require_source_scan.collectCssInlineSourceCandidates(root);
1828
+ root.walkAtRules("import", (rule) => {
1829
+ if (!isTailwindCssImport(rule.params)) return;
1830
+ const sourceParam = parseImportSourceParam(rule.params);
1831
+ if (sourceParam?.none) hasSourceNone = true;
1832
+ if (sourceParam?.sourcePath) importSourceBase = resolveSourceBase(base, sourceParam.sourcePath);
1833
+ });
1834
+ if (importSourceBase) return {
1835
+ entries: [{
1836
+ base: importSourceBase,
1837
+ negated: false,
1838
+ pattern: VITE_SOURCE_CANDIDATE_PATTERN
1839
+ }, ...entries],
1840
+ explicit: true,
1841
+ inlineCandidates,
1842
+ dependencies: configEntries.dependencies
1843
+ };
1844
+ if (hasSourceNone) return {
1845
+ entries,
1846
+ explicit: true,
1847
+ inlineCandidates,
1848
+ dependencies: configEntries.dependencies
1849
+ };
1850
+ return entries.length > 0 ? {
1851
+ entries,
1852
+ explicit: true,
1853
+ inlineCandidates,
1854
+ dependencies: configEntries.dependencies
1855
+ } : inlineCandidates.included.size > 0 || inlineCandidates.excluded.size > 0 ? {
1856
+ entries: [],
1857
+ explicit: true,
1858
+ inlineCandidates,
1859
+ dependencies: configEntries.dependencies
1860
+ } : void 0;
1861
+ }
1862
+ async function resolveViteTailwindV4CssDependencies(css, base) {
1863
+ return (await resolveTailwindV4EntriesFromCss(css, base))?.dependencies ?? [];
1864
+ }
1865
+ function collectExistingCssEntries(options) {
1866
+ return [
1867
+ ...options.cssEntries ?? [],
1868
+ ...options.tailwindcss?.v4?.cssEntries ?? [],
1869
+ ...options.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssEntries ?? []
1870
+ ].filter((item) => typeof item === "string" && item.length > 0).map((item) => node_path.default.resolve(item)).filter((item) => (0, node_fs.existsSync)(item));
1871
+ }
1872
+ function mergeInlineCandidates(allInlineCandidates) {
1873
+ const merged = {
1874
+ included: /* @__PURE__ */ new Set(),
1875
+ excluded: /* @__PURE__ */ new Set()
1876
+ };
1877
+ for (const inlineCandidates of allInlineCandidates) {
1878
+ if (!inlineCandidates) continue;
1879
+ for (const candidate of inlineCandidates.included) if (!merged.excluded.has(candidate)) merged.included.add(candidate);
1880
+ for (const candidate of inlineCandidates.excluded) {
1881
+ merged.excluded.add(candidate);
1882
+ merged.included.delete(candidate);
1883
+ }
1884
+ }
1885
+ return merged.included.size > 0 || merged.excluded.size > 0 ? merged : void 0;
1886
+ }
1887
+ async function resolveViteSourceScanEntries(options, patcher) {
1888
+ if (patcher.majorVersion === 3) {
1889
+ const source = await require_generator.resolveTailwindV3SourceFromPatcher(patcher);
1890
+ const contentEntries = require_source_scan.normalizeLegacyContentEntries(source.configObject?.content, source.config ? node_path.default.dirname(source.config) : source.cwd);
1891
+ return contentEntries.length > 0 ? { entries: contentEntries } : void 0;
1892
+ }
1893
+ if (patcher.majorVersion === 4) {
1894
+ const sourceOptions = require_generator.resolveTailwindV4SourceOptionsFromPatcher(patcher);
1895
+ const cssEntries = collectExistingCssEntries(options);
1896
+ const entries = [];
1897
+ const cssInlineCandidates = [];
1898
+ for (const cssEntry of cssEntries) {
1899
+ const resolved = await resolveTailwindV4EntriesFromCss((0, node_fs.readFileSync)(cssEntry, "utf8"), node_path.default.dirname(cssEntry));
1900
+ if (resolved) {
1901
+ entries.push(...resolved.entries);
1902
+ cssInlineCandidates.push(resolved.inlineCandidates);
1903
+ }
1904
+ }
1905
+ const inlineCandidates = mergeInlineCandidates(cssInlineCandidates);
1906
+ if (entries.length > 0 || inlineCandidates) return {
1907
+ entries,
1908
+ inlineCandidates
1909
+ };
1910
+ if (typeof sourceOptions.css === "string" && sourceOptions.css.length > 0) {
1911
+ const resolved = await resolveTailwindV4EntriesFromCss(sourceOptions.css, sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd());
1912
+ return resolved ? {
1913
+ entries: resolved.entries,
1914
+ inlineCandidates: resolved.inlineCandidates
1915
+ } : void 0;
1916
+ }
1917
+ const source = await require_generator.resolveTailwindV4SourceFromPatcher(patcher);
1918
+ const resolved = await resolveTailwindV4EntriesFromCss(source.css, source.base);
1919
+ return resolved ? {
1920
+ entries: resolved.entries,
1921
+ inlineCandidates: resolved.inlineCandidates
1922
+ } : void 0;
1923
+ }
1924
+ }
1925
+ function toPosixPath(value) {
1926
+ return value.split(node_path.default.sep).join("/");
1927
+ }
1928
+ function createViteSourceScanMatcher(entries) {
1929
+ if (!entries?.length) return;
1930
+ const positiveEntries = entries.filter((entry) => !entry.negated);
1931
+ const negativeEntries = entries.filter((entry) => entry.negated);
1932
+ if (positiveEntries.length === 0) return () => false;
1933
+ return (file) => {
1934
+ const resolvedFile = node_path.default.resolve(file);
1935
+ if (!positiveEntries.some((entry) => {
1936
+ const relative = toPosixPath(node_path.default.relative(node_path.default.resolve(entry.base), resolvedFile));
1937
+ return relative && !relative.startsWith("../") && !node_path.default.isAbsolute(relative) && micromatch.default.isMatch(relative, entry.pattern);
1938
+ })) return false;
1939
+ return !negativeEntries.some((entry) => {
1940
+ const relative = toPosixPath(node_path.default.relative(node_path.default.resolve(entry.base), resolvedFile));
1941
+ return relative && !relative.startsWith("../") && !node_path.default.isAbsolute(relative) && micromatch.default.isMatch(relative, entry.pattern);
1942
+ });
1943
+ };
1944
+ }
1945
+ //#endregion
1946
+ //#region src/bundlers/vite/tailwind-basedir.ts
1947
+ const PACKAGE_JSON_FILE = "package.json";
1948
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1949
+ const resolvedRoot = node_path.default.resolve(root);
1950
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
1951
+ const searchRoots = [];
1952
+ let current = resolvedRoot;
1953
+ while (true) {
1954
+ searchRoots.push(current);
1955
+ const parent = node_path.default.dirname(current);
1956
+ if (parent === current) break;
1957
+ current = parent;
1958
+ }
1959
+ const tailwindConfigPath = require_cache.findTailwindConfig(searchRoots);
1960
+ if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
1961
+ const packageRoot = require_cache.findNearestPackageRoot(resolvedRoot);
1962
+ if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1963
+ return resolvedRoot;
1964
+ }
1965
+ //#endregion
1966
+ //#region src/bundlers/vite/index.ts
1967
+ const debug = require_runtime_patch.createDebug();
1968
+ const weappTailwindcssPackageDir = require_bundle_state.resolvePackageDir("weapp-tailwindcss");
1969
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1970
+ function normalizeSignaturePath(value) {
1971
+ return slash(node_path.default.resolve(value));
1972
+ }
1973
+ function serializeInlineCandidates(inlineCandidates) {
1974
+ return {
1975
+ excluded: [...inlineCandidates?.excluded ?? []].sort(),
1976
+ included: [...inlineCandidates?.included ?? []].sort()
1977
+ };
1978
+ }
1979
+ function serializeSourceEntries(entries) {
1980
+ return (entries ?? []).map((entry) => ({
1981
+ base: normalizeSignaturePath(entry.base),
1982
+ negated: entry.negated,
1983
+ pattern: entry.pattern
1984
+ })).sort((a, b) => `${a.base}\0${a.pattern}\0${a.negated}`.localeCompare(`${b.base}\0${b.pattern}\0${b.negated}`));
1985
+ }
1986
+ function createSourceCandidateScanSignature(input) {
1987
+ return JSON.stringify({
1988
+ inlineCandidates: serializeInlineCandidates(input.inlineCandidates),
1989
+ outDir: input.outDir ? normalizeSignaturePath(input.outDir) : void 0,
1990
+ roots: input.roots.map((root) => ({
1991
+ entries: serializeSourceEntries(root.entries),
1992
+ root: normalizeSignaturePath(root.root)
1993
+ }))
1994
+ });
1995
+ }
1996
+ /**
1997
+ * @name WeappTailwindcss
1998
+ * @description uni-app vite / uni-app-x 版本插件
1999
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
2000
+ */
2001
+ function WeappTailwindcss(options = {}) {
2002
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
2003
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
2004
+ const opts = require_precheck.getCompilerContext({
2005
+ ...options,
2006
+ __internalDeferMissingCssEntriesWarning: true
2007
+ });
2008
+ const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
2009
+ const uniAppXEnabled = require_tailwindcss.isUniAppXEnabled(uniAppX);
2010
+ const disabledOptions = require_bundle_state.resolvePluginDisabledState(disabled);
2011
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
2012
+ const shouldOwnTailwindGeneration = !disabledOptions.plugin;
2013
+ const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
2014
+ const hasInitialTailwindCssRoots = require_tailwindcss.hasConfiguredTailwindV4CssRoots({
2015
+ ...options,
2016
+ cssEntries: opts.cssEntries ?? options.cssEntries
2017
+ });
2018
+ const autoCssSourceContent = /* @__PURE__ */ new Map();
2019
+ let refreshRuntimeStateForAutoCssSources;
2020
+ let autoCssSourcesRefresh;
2021
+ const registerAutoCssSource = async (id, css) => {
2022
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
2023
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2024
+ if (!node_path.default.isAbsolute(file)) return;
2025
+ const sourceFile = node_path.default.normalize(file);
2026
+ const sourceCss = require_incremental_runtime_class_set.normalizeTailwindSourceForGenerator(css, { importFallback: true });
2027
+ if (autoCssSourceContent.get(sourceFile) === sourceCss) return;
2028
+ autoCssSourceContent.set(sourceFile, sourceCss);
2029
+ require_tailwindcss.upsertTailwindV4CssSource(opts, {
2030
+ file: sourceFile,
2031
+ css: sourceCss,
2032
+ dependencies: await resolveViteTailwindV4CssDependencies(sourceCss, node_path.default.dirname(sourceFile))
2033
+ });
2034
+ debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
2035
+ autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
2036
+ await refreshRuntimeStateForAutoCssSources?.(true);
2037
+ });
2038
+ await autoCssSourcesRefresh;
2039
+ };
2040
+ const rewritePlugins = createRewriteCssImportsPlugins({
2041
+ getAppType: () => opts.appType,
2042
+ rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
2043
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
2044
+ shouldOwnTailwindGeneration,
2045
+ shouldRewrite: shouldRewriteCssImports,
2046
+ weappTailwindcssDirPosix
2047
+ });
2048
+ if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
2049
+ const customAttributesEntities = require_precheck.toCustomAttributesEntities(customAttributes);
2050
+ let resolvedConfig;
2051
+ let recordedGeneratorCandidates;
2052
+ const sourceCandidateCollector = createSourceCandidateCollector();
2053
+ let sourceScanEntries;
2054
+ let sourceScanMatcher;
2055
+ let sourceCandidateScanSignature;
2056
+ const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
2057
+ const processedCssAssets = /* @__PURE__ */ new WeakSet();
2058
+ const processedCssAssetFiles = /* @__PURE__ */ new Set();
2059
+ const rememberedMainCssSources = /* @__PURE__ */ new Map();
2060
+ const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
2061
+ const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
2062
+ opts,
2063
+ initialTwPatcher,
2064
+ refreshTailwindcssPatcher,
2065
+ uniAppXEnabled,
2066
+ customAttributesEntities,
2067
+ disabledDefaultTemplateHandler,
2068
+ debug
2069
+ });
2070
+ refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
1813
2071
  onLoad();
1814
2072
  const getResolvedConfig = () => resolvedConfig;
1815
2073
  const markCssAssetProcessed = (asset, file) => {
1816
2074
  processedCssAssets.add(asset);
1817
- if (file) processedCssAssetFiles.add(require_css_imports.normalizeOutputPathKey(file));
2075
+ if (file) processedCssAssetFiles.add(require_bundle_state.normalizeOutputPathKey(file));
1818
2076
  };
1819
2077
  const isCssAssetProcessed = (asset, file) => {
1820
- return processedCssAssets.has(asset) || (file ? processedCssAssetFiles.has(require_css_imports.normalizeOutputPathKey(file)) : false);
2078
+ return processedCssAssets.has(asset) || (file ? processedCssAssetFiles.has(require_bundle_state.normalizeOutputPathKey(file)) : false);
1821
2079
  };
1822
2080
  const recordGeneratorCandidates = (candidates) => {
1823
- if (!recordedGeneratorCandidates) {
1824
- recordedGeneratorCandidates = new Set(candidates);
1825
- return;
1826
- }
1827
- for (const candidate of candidates) recordedGeneratorCandidates.add(candidate);
2081
+ recordedGeneratorCandidates = new Set(candidates);
1828
2082
  };
1829
2083
  const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2084
+ const getSourceCandidates = () => sourceCandidateCollector.values();
2085
+ const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
2086
+ const collectSourceCandidateScanRoots = (root, entries) => {
2087
+ const roots = [{
2088
+ entries,
2089
+ root
2090
+ }];
2091
+ const normalizedRoot = node_path.default.resolve(root);
2092
+ const seenRoots = new Set([normalizedRoot]);
2093
+ const basedir = opts.tailwindcssBasedir ? node_path.default.resolve(opts.tailwindcssBasedir) : void 0;
2094
+ if (basedir && !seenRoots.has(basedir)) {
2095
+ roots.push({ root: basedir });
2096
+ seenRoots.add(basedir);
2097
+ }
2098
+ for (const cssEntry of opts.tailwindcss?.v4?.cssEntries ?? []) {
2099
+ const cssEntryRoot = node_path.default.dirname(node_path.default.resolve(cssEntry));
2100
+ if (seenRoots.has(cssEntryRoot)) continue;
2101
+ roots.push({ root: cssEntryRoot });
2102
+ seenRoots.add(cssEntryRoot);
2103
+ }
2104
+ return roots;
2105
+ };
2106
+ const scanSourceCandidateRoots = async (roots, outDir) => {
2107
+ await Promise.all(roots.map((root) => sourceCandidateCollector.scanRoot({
2108
+ entries: root.entries,
2109
+ root: root.root,
2110
+ outDir
2111
+ })));
2112
+ };
2113
+ const waitForSourceCandidateSyncs = async () => {
2114
+ while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2115
+ };
2116
+ const syncChangedSourceCandidateFile = (id) => {
2117
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return Promise.resolve();
2118
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2119
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2120
+ sourceCandidateCollector.remove(file);
2121
+ return Promise.resolve();
2122
+ }
2123
+ const task = sourceCandidateCollector.syncFile(id).catch((error) => {
2124
+ debug("source candidate watch sync failed: %s %O", id, error);
2125
+ }).finally(() => {
2126
+ pendingSourceCandidateSyncs.delete(task);
2127
+ });
2128
+ pendingSourceCandidateSyncs.add(task);
2129
+ return task;
2130
+ };
2131
+ const rememberMainCssSource = (file, rawSource, cssRuntimeSignature) => {
2132
+ rememberedMainCssSources.set(file, rawSource);
2133
+ if (cssRuntimeSignature) rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2134
+ };
2135
+ const getRememberedMainCssSources = () => rememberedMainCssSources;
2136
+ const getRememberedMainCssSignature = (file) => rememberedMainCssSignatureByFile.get(file);
2137
+ const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2138
+ rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2139
+ };
2140
+ const generateBundleHook = createGenerateBundleHook({
2141
+ opts,
2142
+ runtimeState,
2143
+ ensureRuntimeClassSet,
2144
+ ensureBundleRuntimeClassSet,
2145
+ debug,
2146
+ getResolvedConfig,
2147
+ markCssAssetProcessed,
2148
+ getSourceCandidates,
2149
+ waitForSourceCandidateSyncs,
2150
+ rememberMainCssSource,
2151
+ getRememberedMainCssSources,
2152
+ getRememberedMainCssSignature,
2153
+ setRememberedMainCssSignature,
2154
+ recordGeneratorCandidates
2155
+ });
1830
2156
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
1831
2157
  opts,
1832
2158
  runtimeState,
@@ -1835,7 +2161,10 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1835
2161
  getResolvedConfig,
1836
2162
  markCssAssetProcessed,
1837
2163
  isCssAssetProcessed,
1838
- getRecordedGeneratorCandidates
2164
+ getRecordedGeneratorCandidates,
2165
+ getSourceCandidates,
2166
+ waitForSourceCandidateSyncs,
2167
+ rememberMainCssSource
1839
2168
  });
1840
2169
  const isIosPlatform = require_utils.resolveUniUtsPlatform().isAppIos;
1841
2170
  const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
@@ -1851,102 +2180,142 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1851
2180
  getResolvedConfig,
1852
2181
  uniAppX
1853
2182
  }) : void 0;
1854
- const plugins = [...rewritePlugins, {
1855
- name: `${require_recorder.vitePluginName}:post`,
1856
- enforce: "post",
1857
- config(config) {
1858
- if (!shouldOwnTailwindGeneration) return;
1859
- if (Array.isArray(config.plugins)) {
1860
- const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
1861
- if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
1862
- }
1863
- const root = config.root ? node_path.default.resolve(config.root) : node_process.default.cwd();
1864
- const baseConfig = { resolve: { alias: [{
1865
- find: /^tailwindcss$/,
1866
- replacement: node_path.default.join(weappTailwindcssPackageDir, "generator-placeholder.css")
1867
- }] } };
1868
- if (config.css?.postcss !== void 0) return baseConfig;
1869
- return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
1870
- if (!postcssConfig) return baseConfig;
1871
- debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
1872
- return {
1873
- ...baseConfig,
1874
- css: { postcss: {
1875
- ...postcssConfig.options,
1876
- plugins: postcssConfig.plugins
1877
- } }
1878
- };
1879
- });
1880
- },
1881
- async configResolved(config) {
1882
- resolvedConfig = config;
1883
- if (shouldOwnTailwindGeneration) {
1884
- const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
1885
- if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
1886
- }
1887
- const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
1888
- let shouldRefreshRuntime = false;
1889
- if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
1890
- const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
1891
- if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
1892
- const previousBasedir = opts.tailwindcssBasedir;
1893
- opts.tailwindcssBasedir = nextTailwindcssBasedir;
1894
- debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
1895
- shouldRefreshRuntime = true;
2183
+ const plugins = [
2184
+ ...rewritePlugins,
2185
+ {
2186
+ name: `${require_precheck.vitePluginName}:source-candidates`,
2187
+ enforce: "pre",
2188
+ async transform(code, id) {
2189
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return;
2190
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2191
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2192
+ sourceCandidateCollector.remove(file);
2193
+ return;
1896
2194
  }
1897
- }
1898
- if (!hasExplicitAppType && resolvedRoot) {
1899
- const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
1900
- if (nextAppType && opts.appType !== nextAppType) {
1901
- const previousAppType = opts.appType;
1902
- opts.appType = nextAppType;
1903
- _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
1904
- debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
1905
- shouldRefreshRuntime = true;
2195
+ await sourceCandidateCollector.sync(id, code);
2196
+ },
2197
+ async watchChange(id, change) {
2198
+ if (change.event === "delete") {
2199
+ sourceCandidateCollector.remove(id);
2200
+ return;
2201
+ }
2202
+ await syncChangedSourceCandidateFile(id);
2203
+ },
2204
+ async handleHotUpdate(ctx) {
2205
+ await syncChangedSourceCandidateFile(ctx.file);
2206
+ },
2207
+ async buildStart() {
2208
+ if (!shouldOwnTailwindGeneration) return;
2209
+ const root = resolvedConfig?.root ?? node_process.default.cwd();
2210
+ const outDir = resolvedConfig?.build?.outDir;
2211
+ const sourceScan = await resolveViteSourceScanEntries(opts, runtimeState.twPatcher);
2212
+ sourceScanEntries = sourceScan?.entries;
2213
+ sourceScanMatcher = createViteSourceScanMatcher(sourceScanEntries);
2214
+ const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
2215
+ const nextScanSignature = createSourceCandidateScanSignature({
2216
+ inlineCandidates: sourceScan?.inlineCandidates,
2217
+ outDir,
2218
+ roots
2219
+ });
2220
+ if (isWatchBuild() && sourceCandidateScanSignature === nextScanSignature) {
2221
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2222
+ debug("reuse vite source candidate scan for watch rebuild");
2223
+ return;
1906
2224
  }
2225
+ sourceCandidateCollector.clear();
2226
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2227
+ await scanSourceCandidateRoots(roots, outDir);
2228
+ sourceCandidateScanSignature = nextScanSignature;
1907
2229
  }
1908
- if (shouldRefreshRuntime) await refreshRuntimeState(true);
1909
- if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
1910
- const postcssPlugins = config.css.postcss.plugins;
2230
+ },
2231
+ {
2232
+ name: `${require_precheck.vitePluginName}:post`,
2233
+ enforce: "post",
2234
+ config(config) {
2235
+ if (!shouldOwnTailwindGeneration) return;
2236
+ if (Array.isArray(config.plugins)) {
2237
+ const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
2238
+ if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
2239
+ }
2240
+ const root = config.root ? node_path.default.resolve(config.root) : node_process.default.cwd();
2241
+ const baseConfig = { resolve: { alias: [{
2242
+ find: /^tailwindcss$/,
2243
+ replacement: node_path.default.join(weappTailwindcssPackageDir, "generator-placeholder.css")
2244
+ }] } };
2245
+ if (config.css?.postcss !== void 0) return baseConfig;
2246
+ return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
2247
+ if (!postcssConfig) return baseConfig;
2248
+ debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
2249
+ return {
2250
+ ...baseConfig,
2251
+ css: { postcss: {
2252
+ ...postcssConfig.options,
2253
+ plugins: postcssConfig.plugins
2254
+ } }
2255
+ };
2256
+ });
2257
+ },
2258
+ async configResolved(config) {
2259
+ resolvedConfig = config;
1911
2260
  if (shouldOwnTailwindGeneration) {
1912
- const removed = removeTailwindPostcssPlugins(postcssPlugins);
1913
- if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2261
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2262
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2263
+ }
2264
+ const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
2265
+ let shouldRefreshRuntime = false;
2266
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2267
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2268
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2269
+ const previousBasedir = opts.tailwindcssBasedir;
2270
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
2271
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2272
+ shouldRefreshRuntime = true;
2273
+ }
1914
2274
  }
1915
- const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
1916
- if (idx > -1) {
1917
- postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
1918
- debug("remove postcss-html-transform plugin from vite config");
2275
+ if (!hasExplicitAppType && resolvedRoot) {
2276
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2277
+ if (nextAppType && opts.appType !== nextAppType) {
2278
+ const previousAppType = opts.appType;
2279
+ opts.appType = nextAppType;
2280
+ _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2281
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2282
+ shouldRefreshRuntime = true;
2283
+ }
2284
+ }
2285
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
2286
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2287
+ const postcssPlugins = config.css.postcss.plugins;
2288
+ if (shouldOwnTailwindGeneration) {
2289
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
2290
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2291
+ }
2292
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2293
+ if (idx > -1) {
2294
+ postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
2295
+ debug("remove postcss-html-transform plugin from vite config");
2296
+ }
1919
2297
  }
2298
+ },
2299
+ generateBundle: {
2300
+ order: "post",
2301
+ handler: generateBundleHook
2302
+ },
2303
+ outputOptions(options) {
2304
+ const plugins = options.plugins;
2305
+ return {
2306
+ ...options,
2307
+ plugins: Array.isArray(plugins) ? [...plugins, cssFinalizerOutputPlugin] : [cssFinalizerOutputPlugin]
2308
+ };
1920
2309
  }
1921
- },
1922
- generateBundle: {
1923
- order: "post",
1924
- handler: createGenerateBundleHook({
1925
- opts,
1926
- runtimeState,
1927
- ensureRuntimeClassSet,
1928
- ensureBundleRuntimeClassSet,
1929
- debug,
1930
- getResolvedConfig,
1931
- markCssAssetProcessed,
1932
- recordGeneratorCandidates
1933
- })
1934
- },
1935
- outputOptions(options) {
1936
- const plugins = options.plugins;
1937
- return {
1938
- ...options,
1939
- plugins: Array.isArray(plugins) ? [...plugins, cssFinalizerOutputPlugin] : [cssFinalizerOutputPlugin]
1940
- };
1941
2310
  }
1942
- }];
2311
+ ];
1943
2312
  if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
1944
2313
  return plugins;
1945
2314
  }
1946
2315
  //#endregion
1947
- Object.defineProperty(exports, "UnifiedViteWeappTailwindcssPlugin", {
2316
+ Object.defineProperty(exports, "WeappTailwindcss", {
1948
2317
  enumerable: true,
1949
2318
  get: function() {
1950
- return UnifiedViteWeappTailwindcssPlugin;
2319
+ return WeappTailwindcss;
1951
2320
  }
1952
2321
  });