weapp-tailwindcss 4.12.0 → 5.0.0-next.2

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 (313) hide show
  1. package/dist/babel/index.d.ts +3 -0
  2. package/dist/bundlers/gulp/index.d.ts +7 -0
  3. package/dist/bundlers/shared/cache.d.ts +16 -0
  4. package/dist/bundlers/shared/css-cleanup.d.ts +4 -0
  5. package/dist/bundlers/shared/css-imports.d.ts +8 -0
  6. package/dist/bundlers/shared/generator-candidates.d.ts +5 -0
  7. package/dist/bundlers/shared/generator-css.d.ts +43 -0
  8. package/dist/bundlers/shared/module-graph.d.ts +5 -0
  9. package/dist/bundlers/shared/run-tasks.d.ts +2 -0
  10. package/dist/bundlers/vite/bundle-entries.d.ts +14 -0
  11. package/dist/bundlers/vite/bundle-state.d.ts +43 -0
  12. package/dist/bundlers/vite/css-finalizer.d.ts +22 -0
  13. package/dist/bundlers/vite/generate-bundle.d.ts +33 -0
  14. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +21 -0
  15. package/dist/bundlers/vite/index.d.ts +3 -0
  16. package/dist/bundlers/vite/js-precheck.d.ts +1 -0
  17. package/dist/bundlers/vite/query.d.ts +15 -0
  18. package/dist/bundlers/vite/resolve-app-type.d.ts +2 -0
  19. package/dist/bundlers/vite/rewrite-css-imports.d.ts +11 -0
  20. package/dist/bundlers/vite/runtime-affecting-signature.d.ts +2 -0
  21. package/dist/bundlers/vite/source-candidates.d.ts +15 -0
  22. package/dist/bundlers/vite/utils.d.ts +9 -0
  23. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +20 -0
  24. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-assets.d.ts +14 -0
  25. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-loaders.d.ts +15 -0
  26. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4.d.ts +9 -0
  27. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +17 -0
  28. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +19 -0
  29. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +9 -0
  30. package/dist/bundlers/webpack/index.d.ts +1 -0
  31. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +12 -0
  32. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +11 -0
  33. package/dist/bundlers/webpack/shared/css-imports.d.ts +6 -0
  34. package/dist/bundlers/webpack/shared/loader-anchors.d.ts +8 -0
  35. package/dist/cache/index.d.ts +38 -0
  36. package/dist/cache/md5.d.ts +1 -0
  37. package/dist/chunk-8l464Juk.js +28 -0
  38. package/dist/cli/config.d.ts +5 -0
  39. package/dist/cli/context.d.ts +16 -0
  40. package/dist/cli/doctor/constants.d.ts +7 -0
  41. package/dist/cli/doctor/types.d.ts +31 -0
  42. package/dist/cli/doctor.d.ts +4 -0
  43. package/dist/cli/helpers/options/format.d.ts +2 -0
  44. package/dist/cli/helpers/options/parse.d.ts +3 -0
  45. package/dist/cli/helpers/options/resolve.d.ts +1 -0
  46. package/dist/cli/helpers/options.d.ts +3 -0
  47. package/dist/cli/helpers/patch-cwd.d.ts +1 -0
  48. package/dist/cli/helpers.d.ts +5 -0
  49. package/dist/cli/mount-options/patch-status.d.ts +2 -0
  50. package/dist/cli/mount-options.d.ts +2 -0
  51. package/dist/cli/patch-options.d.ts +6 -0
  52. package/dist/cli/tokens.d.ts +4 -0
  53. package/dist/cli/types.d.ts +17 -0
  54. package/dist/cli/vscode-entry.d.ts +14 -0
  55. package/dist/cli/workspace/package-dirs.d.ts +3 -0
  56. package/dist/cli/workspace/patch-package.d.ts +3 -0
  57. package/dist/cli/workspace/patch-utils.d.ts +3 -0
  58. package/dist/cli/workspace/types.d.ts +11 -0
  59. package/dist/cli/workspace/workspace-globs.d.ts +2 -0
  60. package/dist/cli/workspace/workspace-io.d.ts +1 -0
  61. package/dist/cli/workspace/workspace-lock.d.ts +1 -0
  62. package/dist/cli/workspace.d.ts +2 -0
  63. package/dist/cli.d.ts +1 -2
  64. package/dist/cli.js +2425 -3524
  65. package/dist/cli.mjs +2402 -3505
  66. package/dist/constants-B-_T5UnW.mjs +44 -0
  67. package/dist/constants-p1dyh1x1.js +73 -0
  68. package/dist/constants.d.ts +13 -0
  69. package/dist/context/compiler-context-cache.d.ts +3 -0
  70. package/dist/context/custom-attributes.d.ts +2 -0
  71. package/dist/context/handlers.d.ts +6 -0
  72. package/dist/context/index.d.ts +7 -0
  73. package/dist/context/logger.d.ts +4 -0
  74. package/dist/context/tailwindcss/basedir.d.ts +1 -0
  75. package/dist/context/tailwindcss/rax.d.ts +2 -0
  76. package/dist/context/tailwindcss.d.ts +4 -0
  77. package/dist/context/workspace.d.ts +3 -0
  78. package/dist/core.d.ts +5 -21
  79. package/dist/core.js +138 -180
  80. package/dist/core.mjs +135 -180
  81. package/dist/css-imports-BbrbluP9.js +177 -0
  82. package/dist/css-imports-CSdPq_Sc.mjs +128 -0
  83. package/dist/css-macro/constants.d.ts +14 -0
  84. package/dist/css-macro/index.d.ts +15 -0
  85. package/dist/css-macro/postcss.d.ts +3 -7
  86. package/dist/css-macro/postcss.js +44 -58
  87. package/dist/css-macro/postcss.mjs +44 -56
  88. package/dist/css-macro.d.ts +1 -20
  89. package/dist/css-macro.js +37 -50
  90. package/dist/css-macro.mjs +33 -47
  91. package/dist/debug/index.d.ts +5 -0
  92. package/dist/defaults.d.ts +2 -11
  93. package/dist/defaults.js +132 -8
  94. package/dist/defaults.mjs +128 -7
  95. package/dist/escape.js +31 -54
  96. package/dist/escape.mjs +18 -25
  97. package/dist/experimental/index.d.ts +2 -0
  98. package/dist/experimental/oxc/ast-utils.d.ts +30 -0
  99. package/dist/experimental/oxc/index.d.ts +2 -0
  100. package/dist/experimental/oxc/module-specifiers.d.ts +2 -0
  101. package/dist/experimental/shared/cache.d.ts +3 -0
  102. package/dist/experimental/shared/transform.d.ts +3 -0
  103. package/dist/experimental/shared.d.ts +8 -0
  104. package/dist/experimental/swc/ast-utils.d.ts +30 -0
  105. package/dist/experimental/swc/index.d.ts +2 -0
  106. package/dist/experimental/swc/module-specifiers.d.ts +2 -0
  107. package/dist/generator/index.d.ts +11 -0
  108. package/dist/generator/options.d.ts +17 -0
  109. package/dist/generator/types.d.ts +20 -0
  110. package/dist/generator-Y-Ikv4Fu.mjs +1177 -0
  111. package/dist/generator-css-B5ejWUMv.mjs +1098 -0
  112. package/dist/generator-css-D3OdPRiS.js +1125 -0
  113. package/dist/generator-mmhXzZnv.js +1276 -0
  114. package/dist/generator.d.ts +1 -0
  115. package/dist/generator.js +19 -0
  116. package/dist/generator.mjs +2 -0
  117. package/dist/gulp.d.ts +4 -24
  118. package/dist/gulp.js +271 -13
  119. package/dist/gulp.mjs +263 -13
  120. package/dist/index.d.ts +8 -15
  121. package/dist/index.js +12 -24
  122. package/dist/index.mjs +6 -24
  123. package/dist/js/JsTokenUpdater.d.ts +14 -0
  124. package/dist/js/ModuleGraph.d.ts +18 -0
  125. package/dist/js/NodePathWalker.d.ts +33 -0
  126. package/dist/js/babel/parse.d.ts +9 -0
  127. package/dist/js/babel/process.d.ts +4 -0
  128. package/dist/js/babel.d.ts +13 -0
  129. package/dist/js/class-context.d.ts +3 -0
  130. package/dist/js/evalTransforms.d.ts +7 -0
  131. package/dist/js/handlers.d.ts +5 -0
  132. package/dist/js/index.d.ts +4 -0
  133. package/dist/js/module-graph/ignored-exports.d.ts +18 -0
  134. package/dist/js/module-graph/types.d.ts +17 -0
  135. package/dist/js/node-path-walker/export-handlers.d.ts +12 -0
  136. package/dist/js/node-path-walker/import-tokens.d.ts +24 -0
  137. package/dist/js/precheck.d.ts +2 -0
  138. package/dist/js/sourceAnalysis.d.ts +17 -0
  139. package/dist/js/syntax.d.ts +10 -0
  140. package/dist/js/taggedTemplateIgnore.d.ts +13 -0
  141. package/dist/js/types.d.ts +11 -0
  142. package/dist/lightningcss/index.d.ts +8 -0
  143. package/dist/lightningcss/style-handler/options.d.ts +3 -0
  144. package/dist/lightningcss/style-handler/selector-transform.d.ts +10 -0
  145. package/dist/lightningcss/style-handler/selector-utils.d.ts +10 -0
  146. package/dist/lightningcss/style-handler.d.ts +17 -0
  147. package/dist/loader-anchors-CNkWT8hx.js +273 -0
  148. package/dist/loader-anchors-TrU7EUr7.mjs +205 -0
  149. package/dist/logger/index.d.ts +2 -0
  150. package/dist/logger-BZ45DZJT.js +1003 -0
  151. package/dist/logger-BoVx1Dbt.mjs +935 -0
  152. package/dist/patcher-options-6gJN2EXy.js +115 -0
  153. package/dist/patcher-options-DQfR5xxT.mjs +92 -0
  154. package/dist/postcss-html-transform.d.ts +3 -3
  155. package/dist/postcss-html-transform.js +7 -10
  156. package/dist/postcss-html-transform.mjs +3 -6
  157. package/dist/postcss.d.ts +15 -0
  158. package/dist/postcss.js +280 -0
  159. package/dist/postcss.mjs +270 -0
  160. package/dist/presets/hbuilderx.d.ts +4 -0
  161. package/dist/presets/index.d.ts +3 -0
  162. package/dist/presets/shared.d.ts +10 -0
  163. package/dist/presets/taro.d.ts +4 -0
  164. package/dist/presets/uni-app-x.d.ts +16 -0
  165. package/dist/presets/uni-app.d.ts +4 -0
  166. package/dist/presets.d.ts +1 -76
  167. package/dist/presets.js +115 -163
  168. package/dist/presets.mjs +107 -163
  169. package/dist/recorder-gYSNLfOP.js +2878 -0
  170. package/dist/recorder-zsgatmkB.mjs +2763 -0
  171. package/dist/reset/index.d.ts +2 -0
  172. package/dist/reset.d.ts +1 -4
  173. package/dist/reset.js +19 -8
  174. package/dist/reset.mjs +2 -8
  175. package/dist/shared/classname-transform.d.ts +14 -0
  176. package/dist/shared/mpx.d.ts +7 -0
  177. package/dist/shared/tailwindcss-css-redirect.d.ts +1 -0
  178. package/dist/tailwindcss/index.d.ts +11 -0
  179. package/dist/tailwindcss/miniprogram.d.ts +1 -0
  180. package/dist/tailwindcss/patcher-options.d.ts +56 -0
  181. package/dist/tailwindcss/patcher-resolve.d.ts +4 -0
  182. package/dist/tailwindcss/patcher.d.ts +13 -0
  183. package/dist/tailwindcss/recorder.d.ts +13 -0
  184. package/dist/tailwindcss/remove-unsupported-css.d.ts +2 -0
  185. package/dist/tailwindcss/runtime/cache.d.ts +11 -0
  186. package/dist/tailwindcss/runtime-logs.d.ts +3 -0
  187. package/dist/tailwindcss/runtime.d.ts +29 -0
  188. package/dist/tailwindcss/targets/paths.d.ts +13 -0
  189. package/dist/tailwindcss/targets/record-io.d.ts +5 -0
  190. package/dist/tailwindcss/targets/recorder.d.ts +3 -0
  191. package/dist/tailwindcss/targets/types.d.ts +35 -0
  192. package/dist/tailwindcss/targets.d.ts +6 -0
  193. package/dist/tailwindcss/v3-engine/generator.d.ts +2 -0
  194. package/dist/tailwindcss/v3-engine/index.d.ts +4 -0
  195. package/dist/tailwindcss/v3-engine/miniprogram.d.ts +4 -0
  196. package/dist/tailwindcss/v3-engine/source.d.ts +5 -0
  197. package/dist/tailwindcss/v3-engine/types.d.ts +55 -0
  198. package/dist/tailwindcss/v4/config.d.ts +5 -0
  199. package/dist/tailwindcss/v4/css-entries.d.ts +7 -0
  200. package/dist/tailwindcss/v4/index.d.ts +2 -0
  201. package/dist/tailwindcss/v4/multi-patcher.d.ts +2 -0
  202. package/dist/tailwindcss/v4/patcher-options.d.ts +24 -0
  203. package/dist/tailwindcss/v4/patcher.d.ts +14 -0
  204. package/dist/tailwindcss/v4-engine/candidates.d.ts +2 -0
  205. package/dist/tailwindcss/v4-engine/design-system.d.ts +1 -0
  206. package/dist/tailwindcss/v4-engine/generator.d.ts +2 -0
  207. package/dist/tailwindcss/v4-engine/index.d.ts +5 -0
  208. package/dist/tailwindcss/v4-engine/miniprogram.d.ts +5 -0
  209. package/dist/tailwindcss/v4-engine/source.d.ts +7 -0
  210. package/dist/tailwindcss/v4-engine/tailwind-v3-compatibility.d.ts +1 -0
  211. package/dist/tailwindcss/v4-engine/tailwind-v3-default-colors.d.ts +1 -0
  212. package/dist/tailwindcss/v4-engine/tailwind-v4-default-colors.d.ts +1 -0
  213. package/dist/tailwindcss/v4-engine/types.d.ts +19 -0
  214. package/dist/typedoc.export.d.ts +5 -0
  215. package/dist/types/base.d.ts +1 -0
  216. package/dist/types/disabled-options.d.ts +4 -0
  217. package/dist/types/index.d.ts +104 -0
  218. package/dist/types/shared.d.ts +7 -0
  219. package/dist/types/user-defined-options/general.d.ts +31 -0
  220. package/dist/types/user-defined-options/important.d.ts +37 -0
  221. package/dist/types/user-defined-options/index.d.ts +11 -0
  222. package/dist/types/user-defined-options/lifecycle.d.ts +6 -0
  223. package/dist/types/user-defined-options/matcher.d.ts +9 -0
  224. package/dist/types.d.ts +1 -150
  225. package/dist/types.js +0 -1
  226. package/dist/types.mjs +1 -1
  227. package/dist/uni-app-x/component-local-style.d.ts +19 -0
  228. package/dist/uni-app-x/index.d.ts +2 -0
  229. package/dist/uni-app-x/options.d.ts +12 -0
  230. package/dist/uni-app-x/style-isolation.d.ts +2 -0
  231. package/dist/uni-app-x/transform.d.ts +9 -0
  232. package/dist/uni-app-x/vite.d.ts +36 -0
  233. package/dist/utils/decode.d.ts +2 -0
  234. package/dist/utils/disabled.d.ts +6 -0
  235. package/dist/utils/hbuilderx.d.ts +5 -0
  236. package/dist/utils/index.d.ts +7 -0
  237. package/dist/utils/nameMatcher.d.ts +4 -0
  238. package/dist/utils/resolve-package.d.ts +1 -0
  239. package/dist/utils/uni-platform.d.ts +11 -0
  240. package/dist/utils-7DUGTFED.mjs +48 -0
  241. package/dist/utils-DmC9_In3.js +61 -0
  242. package/dist/vite-BC9U7ahn.js +2199 -0
  243. package/dist/vite-CrlzCNqz.mjs +2186 -0
  244. package/dist/vite.d.ts +4 -17
  245. package/dist/vite.js +5 -14
  246. package/dist/vite.mjs +2 -14
  247. package/dist/weapp-tw-css-import-rewrite-loader.js +59 -92
  248. package/dist/weapp-tw-runtime-classset-loader.js +31 -50
  249. package/dist/webpack-Bu6M-Hbw.mjs +441 -0
  250. package/dist/webpack-DD7A6V0u.js +456 -0
  251. package/dist/webpack.d.ts +4 -25
  252. package/dist/webpack.js +6 -17
  253. package/dist/webpack.mjs +2 -17
  254. package/dist/webpack4.d.ts +4 -26
  255. package/dist/webpack4.js +375 -481
  256. package/dist/webpack4.mjs +366 -482
  257. package/dist/wxml/Tokenizer.d.ts +15 -0
  258. package/dist/wxml/custom-attributes.d.ts +4 -0
  259. package/dist/wxml/index.d.ts +2 -0
  260. package/dist/wxml/shared.d.ts +2 -0
  261. package/dist/wxml/tokenizer/types.d.ts +18 -0
  262. package/dist/wxml/utils/codegen/legacy-rewriter.d.ts +2 -0
  263. package/dist/wxml/utils/codegen/legacy-visitor.d.ts +8 -0
  264. package/dist/wxml/utils/codegen.d.ts +2 -0
  265. package/dist/wxml/utils/custom-template.d.ts +3 -0
  266. package/dist/wxml/utils/fragment-helpers.d.ts +6 -0
  267. package/dist/wxml/utils/fragment-updater.d.ts +4 -0
  268. package/dist/wxml/utils/template-fragments.d.ts +3 -0
  269. package/dist/wxml/utils.d.ts +8 -0
  270. package/dist/wxml/whitespace.d.ts +2 -0
  271. package/generator-placeholder.css +1 -0
  272. package/package.json +19 -8
  273. package/dist/chunk-24AGZQVR.js +0 -183
  274. package/dist/chunk-3VQKDHGP.mjs +0 -179
  275. package/dist/chunk-4AFQP74Z.js +0 -24
  276. package/dist/chunk-57SOQCAU.mjs +0 -582
  277. package/dist/chunk-5ZYHNDEK.mjs +0 -2439
  278. package/dist/chunk-76S2EME4.mjs +0 -34
  279. package/dist/chunk-A5PB4KZT.js +0 -138
  280. package/dist/chunk-DUHYLR2R.js +0 -276
  281. package/dist/chunk-DYLQ6UOI.js +0 -71
  282. package/dist/chunk-E7I5TW5K.js +0 -52
  283. package/dist/chunk-FS2NOOEB.js +0 -292
  284. package/dist/chunk-HVNGIKLS.js +0 -3930
  285. package/dist/chunk-JZQBZHN5.js +0 -579
  286. package/dist/chunk-KGTVD4EP.mjs +0 -3930
  287. package/dist/chunk-NNOQDMUP.mjs +0 -10
  288. package/dist/chunk-OF6MFURR.js +0 -34
  289. package/dist/chunk-OFB2KBRP.js +0 -2442
  290. package/dist/chunk-OOHJLO5M.mjs +0 -71
  291. package/dist/chunk-PCDYXXSK.mjs +0 -1515
  292. package/dist/chunk-RKISS72P.js +0 -7
  293. package/dist/chunk-RRQZL7FQ.mjs +0 -292
  294. package/dist/chunk-XAKAD2CR.mjs +0 -138
  295. package/dist/chunk-XZP3MREK.mjs +0 -276
  296. package/dist/chunk-ZAA5ZG3D.js +0 -1518
  297. package/dist/chunk-ZCH4YINE.mjs +0 -52
  298. package/dist/cli.d.mts +0 -2
  299. package/dist/core.d.mts +0 -26
  300. package/dist/css-macro/postcss.d.mts +0 -7
  301. package/dist/css-macro.d.mts +0 -18
  302. package/dist/defaults.d.mts +0 -11
  303. package/dist/gulp.d.mts +0 -24
  304. package/dist/index-BXrmQelt.d.mts +0 -672
  305. package/dist/index-BXrmQelt.d.ts +0 -672
  306. package/dist/index.d.mts +0 -15
  307. package/dist/postcss-html-transform.d.mts +0 -2
  308. package/dist/presets.d.mts +0 -76
  309. package/dist/reset.d.mts +0 -1
  310. package/dist/types.d.mts +0 -150
  311. package/dist/vite.d.mts +0 -17
  312. package/dist/webpack.d.mts +0 -25
  313. package/dist/webpack4.d.mts +0 -26
@@ -0,0 +1,2199 @@
1
+ const require_chunk = require("./chunk-8l464Juk.js");
2
+ const require_generator = require("./generator-mmhXzZnv.js");
3
+ const require_patcher_options = require("./patcher-options-6gJN2EXy.js");
4
+ const require_recorder = require("./recorder-gYSNLfOP.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-D3OdPRiS.js");
8
+ const require_css_imports = require("./css-imports-BbrbluP9.js");
9
+ let node_path = require("node:path");
10
+ node_path = require_chunk.__toESM(node_path);
11
+ let node_process = require("node:process");
12
+ node_process = require_chunk.__toESM(node_process);
13
+ let tailwindcss_patch = require("tailwindcss-patch");
14
+ let node_buffer = require("node:buffer");
15
+ let node_fs = require("node:fs");
16
+ node_fs = require_chunk.__toESM(node_fs);
17
+ let node_fs_promises = require("node:fs/promises");
18
+ let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
19
+ let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
20
+ let magic_string = require("magic-string");
21
+ magic_string = require_chunk.__toESM(magic_string);
22
+ let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
23
+ let htmlparser2 = require("htmlparser2");
24
+ let fast_glob = require("fast-glob");
25
+ fast_glob = require_chunk.__toESM(fast_glob);
26
+ let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
27
+ _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
28
+ let postcss_load_config = require("postcss-load-config");
29
+ postcss_load_config = require_chunk.__toESM(postcss_load_config);
30
+ let _vue_compiler_dom = require("@vue/compiler-dom");
31
+ let _vue_compiler_sfc = require("@vue/compiler-sfc");
32
+ let comment_json = require("comment-json");
33
+ //#region src/uni-app-x/component-local-style.ts
34
+ const EXPRESSION_WRAPPER_PREFIX = "(\n";
35
+ const EXPRESSION_WRAPPER_SUFFIX = "\n)";
36
+ const COMPONENT_RE = /(?:^|[/\\])components(?:[/\\].+)?\.(?:uvue|nvue)$/;
37
+ function createStableHash(input) {
38
+ let hash = 2166136261;
39
+ for (let i = 0; i < input.length; i++) {
40
+ hash ^= input.charCodeAt(i);
41
+ hash = Math.imul(hash, 16777619);
42
+ }
43
+ return (hash >>> 0).toString(36);
44
+ }
45
+ function extractLiteralValue(path) {
46
+ const allowDoubleQuotes = path.isTemplateElement();
47
+ if (path.isStringLiteral()) return {
48
+ allowDoubleQuotes,
49
+ literal: path.node.value,
50
+ offset: 1
51
+ };
52
+ return {
53
+ allowDoubleQuotes,
54
+ literal: typeof path.node.value === "string" ? path.node.value : path.node.value.raw,
55
+ offset: 0
56
+ };
57
+ }
58
+ function createAlias(fileId, utility, index) {
59
+ return `wtu-${createStableHash(`${fileId}:${utility}`)}-${index.toString(36)}`;
60
+ }
61
+ function isRuntimeCandidate(candidate, runtimeSet) {
62
+ if (!runtimeSet || runtimeSet.size === 0) return false;
63
+ return runtimeSet.has(candidate) || runtimeSet.has(require_recorder.replaceWxml(candidate));
64
+ }
65
+ function shouldEnableComponentLocalStyle(id) {
66
+ return COMPONENT_RE.test(id);
67
+ }
68
+ var UniAppXComponentLocalStyleCollector = class {
69
+ constructor(fileId, runtimeSet) {
70
+ this.fileId = fileId;
71
+ this.runtimeSet = runtimeSet;
72
+ this.aliasByUtility = /* @__PURE__ */ new Map();
73
+ this.aliasByLookup = /* @__PURE__ */ new Map();
74
+ }
75
+ ensureAlias(utility) {
76
+ const cached = this.aliasByUtility.get(utility);
77
+ if (cached) return cached;
78
+ const alias = createAlias(this.fileId, utility, this.aliasByUtility.size);
79
+ this.aliasByUtility.set(utility, alias);
80
+ this.aliasByLookup.set(utility, alias);
81
+ this.aliasByLookup.set(require_recorder.replaceWxml(utility), alias);
82
+ return alias;
83
+ }
84
+ rewriteLiteral(literal, shouldInclude) {
85
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal);
86
+ if (candidates.length === 0) return literal;
87
+ let rewritten = literal;
88
+ for (const candidate of candidates) {
89
+ if (!shouldInclude(candidate)) continue;
90
+ rewritten = rewritten.replace(candidate, this.ensureAlias(candidate));
91
+ }
92
+ return rewritten;
93
+ }
94
+ collectAndRewriteStaticClass(literal) {
95
+ return this.rewriteLiteral(literal, (candidate) => isRuntimeCandidate(candidate, this.runtimeSet));
96
+ }
97
+ collectRuntimeClasses(rawSource, options = {}) {
98
+ const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
99
+ try {
100
+ const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
101
+ plugins: ["typescript"],
102
+ sourceType: options.wrapExpression ? "module" : "unambiguous"
103
+ }), {}, void 0, false);
104
+ for (const path of analysis.targetPaths) {
105
+ const { literal, allowDoubleQuotes } = extractLiteralValue(path);
106
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
107
+ const classContext = options.wrapExpression || require_recorder.isClassContextLiteralPath(path);
108
+ for (const candidate of candidates) {
109
+ if (!candidate || !classContext && !isRuntimeCandidate(candidate, this.runtimeSet)) continue;
110
+ if (isRuntimeCandidate(candidate, this.runtimeSet)) this.ensureAlias(candidate);
111
+ }
112
+ }
113
+ } catch {}
114
+ }
115
+ rewriteTransformedCode(rawSource, options = {}) {
116
+ if (this.aliasByLookup.size === 0) return rawSource;
117
+ const wrapped = options.wrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
118
+ try {
119
+ const analysis = require_recorder.analyzeSource(require_recorder.babelParse(wrapped, {
120
+ plugins: ["typescript"],
121
+ sourceType: options.wrapExpression ? "module" : "unambiguous"
122
+ }), {}, void 0, false);
123
+ if (analysis.targetPaths.length === 0) return rawSource;
124
+ const updater = new require_recorder.JsTokenUpdater();
125
+ for (const path of analysis.targetPaths) {
126
+ const { literal, allowDoubleQuotes, offset } = extractLiteralValue(path);
127
+ const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
128
+ if (candidates.length === 0) continue;
129
+ let rewritten = literal;
130
+ let mutated = false;
131
+ for (const candidate of candidates) {
132
+ const alias = this.aliasByLookup.get(candidate);
133
+ if (!alias) continue;
134
+ const replaced = rewritten.replace(candidate, alias);
135
+ if (replaced !== rewritten) {
136
+ rewritten = replaced;
137
+ mutated = true;
138
+ }
139
+ }
140
+ if (!mutated || typeof path.node.start !== "number" || typeof path.node.end !== "number") continue;
141
+ updater.addToken({
142
+ start: path.node.start + offset,
143
+ end: path.node.end - offset,
144
+ value: rewritten,
145
+ path
146
+ });
147
+ }
148
+ if (updater.length === 0) return rawSource;
149
+ const ms = new magic_string.default(wrapped);
150
+ updater.updateMagicString(ms);
151
+ if (options.wrapExpression) {
152
+ ms.remove(0, 2);
153
+ ms.remove(wrapped.length - 2, wrapped.length);
154
+ }
155
+ return ms.toString();
156
+ } catch {
157
+ return rawSource;
158
+ }
159
+ }
160
+ hasStyles() {
161
+ return this.aliasByUtility.size > 0;
162
+ }
163
+ toStyleBlock() {
164
+ if (!this.hasStyles()) return "";
165
+ const lines = ["<style scoped>"];
166
+ for (const [utility, alias] of this.aliasByUtility) {
167
+ lines.push(`.${alias} {`);
168
+ lines.push(` @apply ${utility};`);
169
+ lines.push("}");
170
+ }
171
+ lines.push("</style>");
172
+ return `${lines.join("\n")}\n`;
173
+ }
174
+ };
175
+ //#endregion
176
+ //#region src/uni-app-x/transform.ts
177
+ function traverse(node, visitor) {
178
+ visitor(node);
179
+ if (Array.isArray(node.children)) {
180
+ for (const child of node.children) if (child && typeof child === "object" && "type" in child) traverse(child, visitor);
181
+ }
182
+ }
183
+ function updateStaticAttribute(ms, prop, content = prop.value?.content) {
184
+ if (!prop.value) return;
185
+ const start = prop.value.loc.start.offset + 1;
186
+ const end = prop.value.loc.end.offset - 1;
187
+ if (start < end) ms.update(start, end, require_recorder.replaceWxml(content ?? ""));
188
+ }
189
+ function updateStaticAttributeWithLocalStyle(ms, prop, collector, content = prop.value?.content) {
190
+ if (!prop.value) return;
191
+ const start = prop.value.loc.start.offset + 1;
192
+ const end = prop.value.loc.end.offset - 1;
193
+ if (start < end) ms.update(start, end, collector.collectAndRewriteStaticClass(content ?? ""));
194
+ }
195
+ function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
196
+ if (prop.exp?.type !== _vue_compiler_dom.NodeTypes.SIMPLE_EXPRESSION) return;
197
+ const expression = prop.exp.content;
198
+ const start = prop.exp.loc.start.offset;
199
+ const end = prop.exp.loc.end.offset;
200
+ if (start >= end) return;
201
+ const generated = require_recorder.generateCode(expression, {
202
+ jsHandler,
203
+ runtimeSet,
204
+ wrapExpression: true
205
+ });
206
+ ms.update(start, end, generated);
207
+ }
208
+ function updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, collector, runtimeSet) {
209
+ if (prop.exp?.type !== _vue_compiler_dom.NodeTypes.SIMPLE_EXPRESSION) return;
210
+ const expression = prop.exp.content;
211
+ const start = prop.exp.loc.start.offset;
212
+ const end = prop.exp.loc.end.offset;
213
+ if (start >= end) return;
214
+ collector.collectRuntimeClasses(expression, { wrapExpression: true });
215
+ const generated = require_recorder.generateCode(expression, {
216
+ jsHandler,
217
+ runtimeSet,
218
+ wrapExpression: true
219
+ });
220
+ ms.update(start, end, collector.rewriteTransformedCode(generated, { wrapExpression: true }));
221
+ }
222
+ function shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute) {
223
+ const lowerName = attrName.toLowerCase();
224
+ const shouldHandleDefault = !disabledDefaultTemplateHandler && lowerName === "class";
225
+ const shouldHandleCustom = matchCustomAttribute?.(tag, attrName) ?? false;
226
+ return {
227
+ shouldHandleDefault,
228
+ shouldHandleCustom,
229
+ shouldHandle: shouldHandleDefault || shouldHandleCustom
230
+ };
231
+ }
232
+ const defaultCreateJsHandlerOptions = { babelParserOptions: { plugins: ["typescript"] } };
233
+ const UVUE_NVUE_RE$1 = /\.(?:uvue|nvue)(?:\?.*)?$/;
234
+ function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
235
+ if (!UVUE_NVUE_RE$1.test(id)) return;
236
+ const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
237
+ const matchCustomAttribute = require_recorder.createAttributeMatcher(customAttributesEntities);
238
+ const ms = new magic_string.default(code);
239
+ const { descriptor, errors } = (0, _vue_compiler_sfc.parse)(code);
240
+ const localStyleCollector = options.enableComponentLocalStyle && shouldEnableComponentLocalStyle(id) ? new UniAppXComponentLocalStyleCollector(id, runtimeSet) : void 0;
241
+ if (errors.length === 0) {
242
+ if (descriptor.template?.ast) traverse(descriptor.template.ast, (node) => {
243
+ if (node.type !== _vue_compiler_dom.NodeTypes.ELEMENT) return;
244
+ const tag = node.tag;
245
+ for (const prop of node.props) if (prop.type === _vue_compiler_dom.NodeTypes.ATTRIBUTE) {
246
+ const { shouldHandle, shouldHandleDefault } = shouldHandleAttribute(tag, prop.name, disabledDefaultTemplateHandler, matchCustomAttribute);
247
+ if (!shouldHandle) continue;
248
+ if (shouldHandleDefault && localStyleCollector) updateStaticAttributeWithLocalStyle(ms, prop, localStyleCollector);
249
+ else updateStaticAttribute(ms, prop);
250
+ if (shouldHandleDefault) continue;
251
+ } else if (prop.type === _vue_compiler_dom.NodeTypes.DIRECTIVE && prop.name === "bind" && prop.arg?.type === _vue_compiler_dom.NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
252
+ const attrName = prop.arg.content;
253
+ const { shouldHandle } = shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute);
254
+ if (!shouldHandle) continue;
255
+ if (attrName.toLowerCase() === "class" && localStyleCollector) updateDirectiveExpressionWithLocalStyle(ms, prop, jsHandler, localStyleCollector, runtimeSet);
256
+ else updateDirectiveExpression(ms, prop, jsHandler, runtimeSet);
257
+ }
258
+ });
259
+ if (descriptor.script) {
260
+ localStyleCollector?.collectRuntimeClasses(descriptor.script.content);
261
+ const { code } = jsHandler(descriptor.script.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
262
+ ms.update(descriptor.script.loc.start.offset, descriptor.script.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
263
+ }
264
+ if (descriptor.scriptSetup) {
265
+ localStyleCollector?.collectRuntimeClasses(descriptor.scriptSetup.content);
266
+ const { code } = jsHandler(descriptor.scriptSetup.content, runtimeSet ?? /* @__PURE__ */ new Set(), defaultCreateJsHandlerOptions);
267
+ ms.update(descriptor.scriptSetup.loc.start.offset, descriptor.scriptSetup.loc.end.offset, localStyleCollector ? localStyleCollector.rewriteTransformedCode(code) : code);
268
+ }
269
+ if (localStyleCollector?.hasStyles()) ms.append(`\n${localStyleCollector.toStyleBlock()}`);
270
+ }
271
+ const result = {
272
+ code: ms.toString(),
273
+ map: null
274
+ };
275
+ Object.defineProperty(result, "map", {
276
+ configurable: true,
277
+ enumerable: true,
278
+ get() {
279
+ return ms.generateMap();
280
+ }
281
+ });
282
+ return result;
283
+ }
284
+ //#endregion
285
+ //#region src/bundlers/vite/query.ts
286
+ function parseVueRequest(id) {
287
+ const [filename, rawQuery] = id.split(`?`, 2);
288
+ const searchParams = new URLSearchParams(rawQuery);
289
+ const query = Object.fromEntries(searchParams);
290
+ if (query.vue != null) query.vue = true;
291
+ if (query.index != null) query.index = Number(query.index);
292
+ if (query.raw != null) query.raw = true;
293
+ if (query.url != null) query.url = true;
294
+ if (query.scoped != null) query.scoped = true;
295
+ const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
296
+ const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
297
+ if (langType) query.lang = langType;
298
+ return {
299
+ filename,
300
+ query
301
+ };
302
+ }
303
+ //#endregion
304
+ //#region src/bundlers/vite/utils.ts
305
+ function slash(p) {
306
+ return (0, _weapp_tailwindcss_shared.ensurePosix)(p);
307
+ }
308
+ const isWindows = node_process.default.platform === "win32";
309
+ const cssLangRE = new RegExp(`\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`);
310
+ function isCSSRequest(request) {
311
+ return cssLangRE.test(request);
312
+ }
313
+ function normalizePath(id) {
314
+ return node_path.default.posix.normalize(isWindows ? (0, _weapp_tailwindcss_shared.ensurePosix)(id) : id);
315
+ }
316
+ async function formatPostcssSourceMap(rawMap, file) {
317
+ const inputFileDir = node_path.default.dirname(file);
318
+ const sources = rawMap.sources.map((source) => {
319
+ const cleanSource = (0, _weapp_tailwindcss_shared.cleanUrl)(decodeURIComponent(source));
320
+ if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
321
+ return normalizePath(node_path.default.resolve(inputFileDir, cleanSource));
322
+ });
323
+ return {
324
+ file,
325
+ mappings: rawMap.mappings,
326
+ names: rawMap.names,
327
+ sources,
328
+ sourcesContent: rawMap.sourcesContent,
329
+ version: rawMap.version
330
+ };
331
+ }
332
+ //#endregion
333
+ //#region src/uni-app-x/style-isolation.ts
334
+ const manifestCache = /* @__PURE__ */ new Map();
335
+ function resolveUniAppXStyleIsolationEnabled(root) {
336
+ if (!root) return false;
337
+ const normalizedRoot = node_path.default.resolve(root);
338
+ const cached = manifestCache.get(normalizedRoot);
339
+ if (cached !== void 0) return cached;
340
+ const manifestPath = node_path.default.join(normalizedRoot, "manifest.json");
341
+ let enabled = false;
342
+ try {
343
+ enabled = `${(0, comment_json.parse)(node_fs.default.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
344
+ } catch {
345
+ enabled = false;
346
+ }
347
+ manifestCache.set(normalizedRoot, enabled);
348
+ return enabled;
349
+ }
350
+ //#endregion
351
+ //#region src/uni-app-x/vite.ts
352
+ const preprocessorLangs = new Set([
353
+ "scss",
354
+ "sass",
355
+ "less",
356
+ "styl",
357
+ "stylus"
358
+ ]);
359
+ const INLINE_LANG_RE = /lang\.([a-z]+)/i;
360
+ const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
361
+ const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
362
+ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
363
+ function isPreprocessorRequest(id, lang) {
364
+ const normalizedLang = lang?.toLowerCase();
365
+ if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
366
+ const inlineLangMatch = id.match(INLINE_LANG_RE);
367
+ if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) return true;
368
+ return PREPROCESSOR_EXT_RE.test(id);
369
+ }
370
+ function resolveUniAppXCssTarget(id) {
371
+ return UVUE_NVUE_RE.test((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ? "uvue" : void 0;
372
+ }
373
+ function resolveUniAppXJsTransformEnabled$1(uniAppX) {
374
+ return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
375
+ }
376
+ function createUniAppXPlugins(options) {
377
+ const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
378
+ const resolvedUniAppXOptions = require_logger.resolveUniAppXOptions(uniAppX);
379
+ const isIosPlatform = providedIosPlatform ?? require_utils.resolveUniUtsPlatform().isAppIos;
380
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
381
+ let componentLocalStyleEnabled;
382
+ function shouldEnableComponentLocalStyle() {
383
+ if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
384
+ componentLocalStyleEnabled = false;
385
+ return false;
386
+ }
387
+ if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
388
+ componentLocalStyleEnabled = true;
389
+ return true;
390
+ }
391
+ if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
392
+ const root = getResolvedConfig()?.root;
393
+ componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
394
+ return componentLocalStyleEnabled;
395
+ }
396
+ async function transformStyle(code, id, query) {
397
+ const parsed = query ?? parseVueRequest(id).query;
398
+ if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
399
+ const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
400
+ let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
401
+ if (!styleHandlerOptions) {
402
+ styleHandlerOptions = {
403
+ isMainChunk: mainCssChunkMatcher(id, appType),
404
+ uniAppXCssTarget: resolveUniAppXCssTarget(id),
405
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
406
+ postcssOptions: { options: {
407
+ from: id,
408
+ map: {
409
+ inline: false,
410
+ annotation: false,
411
+ sourcesContent: true
412
+ }
413
+ } }
414
+ };
415
+ cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
416
+ }
417
+ const postcssResult = await styleHandler(code, styleHandlerOptions);
418
+ const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
419
+ for (const warning of warnings) _weapp_tailwindcss_logger.logger.warn(warning.toString());
420
+ const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), (0, _weapp_tailwindcss_shared.cleanUrl)(id));
421
+ return {
422
+ code: postcssResult.css,
423
+ map: postcssMap
424
+ };
425
+ }
426
+ }
427
+ const cssPlugins = [{
428
+ name: "weapp-tailwindcss:uni-app-x:css",
429
+ async transform(code, id) {
430
+ await runtimeState.patchPromise;
431
+ return transformStyle(code, id);
432
+ }
433
+ }, {
434
+ name: "weapp-tailwindcss:uni-app-x:css:pre",
435
+ enforce: "pre",
436
+ async transform(code, id) {
437
+ await runtimeState.patchPromise;
438
+ const { query } = parseVueRequest(id);
439
+ const lang = query.lang;
440
+ if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
441
+ return transformStyle(code, id, query);
442
+ }
443
+ }];
444
+ const nvuePlugin = {
445
+ name: "weapp-tailwindcss:uni-app-x:nvue",
446
+ enforce: "pre",
447
+ async buildStart() {
448
+ await ensureRuntimeClassSet(true);
449
+ },
450
+ async transform(code, id) {
451
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
452
+ const resolvedConfig = getResolvedConfig();
453
+ const isServeCommand = resolvedConfig?.command === "serve";
454
+ const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
455
+ const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
456
+ const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
457
+ const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
458
+ customAttributesEntities,
459
+ disabledDefaultTemplateHandler,
460
+ enableComponentLocalStyle: shouldEnableComponentLocalStyle()
461
+ } : void 0;
462
+ if (extraOptions) return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
463
+ if (shouldEnableComponentLocalStyle()) return transformUVue(code, id, jsHandler, currentRuntimeSet, { enableComponentLocalStyle: true });
464
+ return transformUVue(code, id, jsHandler, currentRuntimeSet);
465
+ },
466
+ async handleHotUpdate(ctx) {
467
+ if (getResolvedConfig()?.command !== "serve") return;
468
+ if (!UVUE_NVUE_RE.test(ctx.file)) return;
469
+ await ensureRuntimeClassSet(true);
470
+ },
471
+ async watchChange(id) {
472
+ const resolvedConfig = getResolvedConfig();
473
+ if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
474
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
475
+ await ensureRuntimeClassSet(true);
476
+ }
477
+ };
478
+ return [...cssPlugins, nvuePlugin];
479
+ }
480
+ function createUniAppXAssetTask(file, originalSource, outDir, options) {
481
+ return async () => {
482
+ const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
483
+ const absoluteFile = require_css_imports.toAbsoluteOutputPath(file, outDir);
484
+ const rawSource = originalSource.source.toString();
485
+ await require_generator_css.processCachedTask({
486
+ cache,
487
+ cacheKey: file,
488
+ hashKey,
489
+ rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
490
+ applyResult(source) {
491
+ originalSource.source = source;
492
+ },
493
+ onCacheHit() {
494
+ debug("js cache hit: %s", file);
495
+ },
496
+ async transform() {
497
+ const currentSource = originalSource.source.toString();
498
+ const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
499
+ uniAppX: resolveUniAppXJsTransformEnabled$1(options.uniAppX),
500
+ babelParserOptions: {
501
+ plugins: ["typescript"],
502
+ sourceType: "unambiguous"
503
+ }
504
+ }));
505
+ onUpdate(file, currentSource, code);
506
+ debug("js handle: %s", file);
507
+ applyLinkedResults(linked);
508
+ return { result: code };
509
+ }
510
+ });
511
+ };
512
+ }
513
+ //#endregion
514
+ //#region src/bundlers/vite/css-finalizer.ts
515
+ function createCssHandlerOptions(opts, majorVersion, file) {
516
+ return {
517
+ isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
518
+ postcssOptions: { options: { from: file } },
519
+ majorVersion
520
+ };
521
+ }
522
+ function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
523
+ if (require_generator_css.hasTailwindGeneratedCssMarkers(rawSource) || require_generator_css.hasTailwindSourceDirectives(rawSource)) return true;
524
+ return processed && shouldFinalizeProcessedCssAsset(opts, file);
525
+ }
526
+ function shouldFinalizeProcessedCssAsset(opts, file) {
527
+ return require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType);
528
+ }
529
+ function createViteCssFinalizerOutputPlugin(context) {
530
+ return {
531
+ name: "weapp-tailwindcss:adaptor:css-finalizer",
532
+ generateBundle: {
533
+ order: "post",
534
+ async handler(_options, bundle) {
535
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource } = context;
536
+ if (getResolvedConfig()?.command !== "build") return;
537
+ const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
538
+ if (entries.length === 0) return;
539
+ await runtimeState.patchPromise;
540
+ await waitForSourceCandidateSyncs?.();
541
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
542
+ const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
543
+ const collectedGeneratorCandidates = new Set([...runtime, ...getSourceCandidates?.() ?? []]);
544
+ const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
545
+ await Promise.all(entries.map(async ([bundleFile, output]) => {
546
+ const file = output.fileName || bundleFile;
547
+ const rawSource = output.source.toString();
548
+ const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, file);
549
+ const cssUserHandlerOptions = {
550
+ ...cssHandlerOptions,
551
+ isMainChunk: false
552
+ };
553
+ const generated = shouldGenerateCssByGenerator(opts, file, rawSource, isCssAssetProcessed(output, file)) ? await require_generator_css.generateCssByGenerator({
554
+ opts,
555
+ runtimeState,
556
+ runtime: generatorRuntime,
557
+ rawSource,
558
+ file,
559
+ cssHandlerOptions,
560
+ cssUserHandlerOptions,
561
+ styleHandler: opts.styleHandler,
562
+ debug
563
+ }) : void 0;
564
+ const nextCss = generated?.css ?? (await opts.styleHandler(rawSource, cssHandlerOptions)).css;
565
+ if (generated) {
566
+ debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
567
+ recordCssAssetResult?.(file, nextCss);
568
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource);
569
+ }
570
+ output.source = nextCss;
571
+ markCssAssetProcessed(output, file);
572
+ opts.onUpdate(file, rawSource, nextCss);
573
+ debug("css finalizer handle: %s", file);
574
+ }));
575
+ }
576
+ }
577
+ };
578
+ }
579
+ //#endregion
580
+ //#region src/bundlers/vite/bundle-entries.ts
581
+ function readOutputEntry(entry) {
582
+ if (entry.output.type === "chunk") return entry.output.code;
583
+ const source = entry.output.source;
584
+ if (typeof source === "string") return source;
585
+ if (source instanceof Uint8Array) return node_buffer.Buffer.from(source).toString();
586
+ const fallbackSource = source;
587
+ if (fallbackSource == null) return;
588
+ if (typeof fallbackSource.toString === "function") return fallbackSource.toString();
589
+ }
590
+ function isJavaScriptEntry(entry) {
591
+ if (entry.output.type === "chunk") return true;
592
+ return entry.fileName.endsWith(".js");
593
+ }
594
+ function createBundleModuleGraphOptions(outputDir, entries) {
595
+ const normalizedEntries = /* @__PURE__ */ new Map();
596
+ for (const [id, entry] of entries) normalizedEntries.set(require_css_imports.normalizeOutputPathKey(id), entry);
597
+ const getEntry = (id) => entries.get(id) ?? normalizedEntries.get(require_css_imports.normalizeOutputPathKey(id));
598
+ return {
599
+ resolve(specifier, importer) {
600
+ return require_css_imports.resolveOutputSpecifier(specifier, importer, outputDir, (candidate) => Boolean(getEntry(candidate)));
601
+ },
602
+ load(id) {
603
+ const entry = getEntry(id);
604
+ if (!entry) return;
605
+ return readOutputEntry(entry);
606
+ },
607
+ filter(id) {
608
+ return Boolean(getEntry(id));
609
+ }
610
+ };
611
+ }
612
+ function applyLinkedResults(linked, entries, onLinkedUpdate, onApplied) {
613
+ if (!linked) return;
614
+ const normalizedEntries = /* @__PURE__ */ new Map();
615
+ for (const [entryId, entry] of entries) normalizedEntries.set(require_css_imports.normalizeOutputPathKey(entryId), entry);
616
+ for (const [id, { code }] of Object.entries(linked)) {
617
+ const entry = entries.get(id) ?? normalizedEntries.get(require_css_imports.normalizeOutputPathKey(id));
618
+ if (!entry) continue;
619
+ const previous = readOutputEntry(entry);
620
+ if (previous == null || previous === code) continue;
621
+ if (entry.output.type === "chunk") entry.output.code = code;
622
+ else entry.output.source = code;
623
+ onApplied?.(entry, code);
624
+ onLinkedUpdate(entry.fileName, previous, code);
625
+ }
626
+ }
627
+ //#endregion
628
+ //#region src/bundlers/vite/runtime-affecting-signature.ts
629
+ const CSS_BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
630
+ const CSS_AROUND_PUNCTUATION_RE = /\s*([{}:;,>+~()])\s*/g;
631
+ const CSS_TRAILING_DECLARATION_SEMICOLON_RE = /;\}/g;
632
+ const CSS_WHITESPACE_RE = /\s+/g;
633
+ function createHtmlRuntimeAffectingSignature(source) {
634
+ try {
635
+ const parts = [];
636
+ const parser = new htmlparser2.Parser({
637
+ onattribute(name, value) {
638
+ parts.push(`a:${name}=${value}`);
639
+ },
640
+ oncomment(data) {
641
+ parts.push(`c:${data}`);
642
+ },
643
+ ontext(data) {
644
+ const value = data.trim();
645
+ if (value.length > 0) parts.push(`t:${value}`);
646
+ }
647
+ }, { xmlMode: true });
648
+ parser.write(source);
649
+ parser.end();
650
+ return parts.join("\n");
651
+ } catch {
652
+ return source;
653
+ }
654
+ }
655
+ function createJsRuntimeAffectingSignature(source) {
656
+ try {
657
+ const ast = require_recorder.babelParse(source, {
658
+ cache: true,
659
+ cacheKey: "vite-runtime-affecting:unambiguous",
660
+ plugins: ["jsx", "typescript"],
661
+ sourceType: "unambiguous"
662
+ });
663
+ const parts = [];
664
+ require_recorder.traverse(ast, {
665
+ noScope: true,
666
+ StringLiteral(path) {
667
+ parts.push(`s:${path.node.value}`);
668
+ },
669
+ TemplateElement(path) {
670
+ parts.push(`t:${path.node.value.raw}`);
671
+ },
672
+ JSXText(path) {
673
+ const value = path.node.value.trim();
674
+ if (value.length > 0) parts.push(`x:${value}`);
675
+ }
676
+ });
677
+ const comments = ast.comments;
678
+ if (Array.isArray(comments)) {
679
+ for (const comment of comments) if (typeof comment?.value === "string" && comment.value.length > 0) parts.push(`c:${comment.value}`);
680
+ }
681
+ return parts.join("\n");
682
+ } catch {
683
+ return source;
684
+ }
685
+ }
686
+ function createCssRuntimeAffectingSignature(source) {
687
+ return source.replace(CSS_BLOCK_COMMENT_RE, "").replace(CSS_AROUND_PUNCTUATION_RE, "$1").replace(CSS_TRAILING_DECLARATION_SEMICOLON_RE, "}").replace(CSS_WHITESPACE_RE, " ").trim();
688
+ }
689
+ function createRuntimeAffectingSourceSignature(source, type) {
690
+ if (type === "html") return createHtmlRuntimeAffectingSignature(source);
691
+ if (type === "js") return createJsRuntimeAffectingSignature(source);
692
+ if (type === "css") return createCssRuntimeAffectingSignature(source);
693
+ return source;
694
+ }
695
+ //#endregion
696
+ //#region src/bundlers/vite/bundle-state.ts
697
+ function createBundleBuildState() {
698
+ return {
699
+ iteration: 0,
700
+ sourceHashByFile: /* @__PURE__ */ new Map(),
701
+ runtimeAffectingSignatureByFile: /* @__PURE__ */ new Map(),
702
+ runtimeAffectingHashByFile: /* @__PURE__ */ new Map(),
703
+ linkedByEntry: /* @__PURE__ */ new Map(),
704
+ dependentsByLinkedFile: /* @__PURE__ */ new Map()
705
+ };
706
+ }
707
+ function createChangedByType() {
708
+ return {
709
+ html: /* @__PURE__ */ new Set(),
710
+ js: /* @__PURE__ */ new Set(),
711
+ css: /* @__PURE__ */ new Set(),
712
+ other: /* @__PURE__ */ new Set()
713
+ };
714
+ }
715
+ function createProcessFiles() {
716
+ return {
717
+ html: /* @__PURE__ */ new Set(),
718
+ js: /* @__PURE__ */ new Set(),
719
+ css: /* @__PURE__ */ new Set()
720
+ };
721
+ }
722
+ function readEntrySource(output) {
723
+ if (output.type === "chunk") return output.code;
724
+ return output.source.toString();
725
+ }
726
+ function classifyBundleEntry(file, opts) {
727
+ if (opts.cssMatcher(file)) return "css";
728
+ if (opts.htmlMatcher(file)) return "html";
729
+ if (opts.jsMatcher(file) || opts.wxsMatcher(file)) return "js";
730
+ return "other";
731
+ }
732
+ function collectJsEntries(fileName, output, outDir, store) {
733
+ const entry = {
734
+ fileName,
735
+ output
736
+ };
737
+ if (!isJavaScriptEntry(entry)) return;
738
+ const absolute = require_css_imports.toAbsoluteOutputPath(fileName, outDir);
739
+ store.set(absolute, entry);
740
+ }
741
+ function markProcessFile(type, file, processFiles) {
742
+ if (type === "html" || type === "js" || type === "css") processFiles[type].add(file);
743
+ }
744
+ function buildBundleSnapshot(bundle, opts, outDir, state, forceAll = false) {
745
+ const sourceHashByFile = /* @__PURE__ */ new Map();
746
+ const runtimeAffectingSignatureByFile = /* @__PURE__ */ new Map();
747
+ const runtimeAffectingHashByFile = /* @__PURE__ */ new Map();
748
+ const changedByType = createChangedByType();
749
+ const runtimeAffectingChangedByType = createChangedByType();
750
+ const processFiles = createProcessFiles();
751
+ const linkedImpactsByEntry = /* @__PURE__ */ new Map();
752
+ const jsEntries = /* @__PURE__ */ new Map();
753
+ const entries = [];
754
+ const firstRun = state.linkedByEntry.size === 0;
755
+ for (const [file, output] of Object.entries(bundle)) {
756
+ const type = classifyBundleEntry(file, opts);
757
+ const source = readEntrySource(output);
758
+ const hash = opts.cache.computeHash(source);
759
+ sourceHashByFile.set(file, hash);
760
+ const previousHash = state.sourceHashByFile.get(file);
761
+ const changed = previousHash == null || previousHash !== hash;
762
+ const previousRuntimeAffectingSignature = state.runtimeAffectingSignatureByFile.get(file);
763
+ const previousRuntimeAffectingHash = state.runtimeAffectingHashByFile.get(file);
764
+ const canReuseRuntimeAffectingSignature = !changed && previousRuntimeAffectingSignature != null && previousRuntimeAffectingHash != null;
765
+ const runtimeAffectingSignature = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingSignature : createRuntimeAffectingSourceSignature(source, type);
766
+ const runtimeAffectingHash = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingHash : opts.cache.computeHash(runtimeAffectingSignature);
767
+ runtimeAffectingSignatureByFile.set(file, runtimeAffectingSignature);
768
+ runtimeAffectingHashByFile.set(file, runtimeAffectingHash);
769
+ if (changed) changedByType[type].add(file);
770
+ if (previousRuntimeAffectingHash == null || previousRuntimeAffectingHash !== runtimeAffectingHash) runtimeAffectingChangedByType[type].add(file);
771
+ if (forceAll || firstRun) markProcessFile(type, file, processFiles);
772
+ else if (type === "html") processFiles.html.add(file);
773
+ else if (changed && (type === "js" || type === "css")) processFiles[type].add(file);
774
+ collectJsEntries(file, output, outDir, jsEntries);
775
+ entries.push({
776
+ file,
777
+ output,
778
+ source,
779
+ type
780
+ });
781
+ }
782
+ if (!forceAll && !firstRun) for (const changedFile of changedByType.js) {
783
+ const dependents = state.dependentsByLinkedFile.get(changedFile);
784
+ if (!dependents) continue;
785
+ for (const entryFile of dependents) {
786
+ processFiles.js.add(entryFile);
787
+ let impacts = linkedImpactsByEntry.get(entryFile);
788
+ if (!impacts) {
789
+ impacts = /* @__PURE__ */ new Set();
790
+ linkedImpactsByEntry.set(entryFile, impacts);
791
+ }
792
+ impacts.add(changedFile);
793
+ }
794
+ }
795
+ return {
796
+ entries,
797
+ jsEntries,
798
+ sourceHashByFile,
799
+ runtimeAffectingSignatureByFile,
800
+ runtimeAffectingHashByFile,
801
+ changedByType,
802
+ runtimeAffectingChangedByType,
803
+ processFiles,
804
+ linkedImpactsByEntry
805
+ };
806
+ }
807
+ function invertLinkedByEntry(linkedByEntry) {
808
+ const dependentsByLinkedFile = /* @__PURE__ */ new Map();
809
+ for (const [entryFile, linkedFiles] of linkedByEntry.entries()) for (const linkedFile of linkedFiles) {
810
+ let dependents = dependentsByLinkedFile.get(linkedFile);
811
+ if (!dependents) {
812
+ dependents = /* @__PURE__ */ new Set();
813
+ dependentsByLinkedFile.set(linkedFile, dependents);
814
+ }
815
+ dependents.add(entryFile);
816
+ }
817
+ return dependentsByLinkedFile;
818
+ }
819
+ function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
820
+ const incremental = options.incremental === true;
821
+ state.iteration += 1;
822
+ state.sourceHashByFile = incremental ? new Map([...state.sourceHashByFile, ...snapshot.sourceHashByFile]) : snapshot.sourceHashByFile;
823
+ state.runtimeAffectingSignatureByFile = incremental ? new Map([...state.runtimeAffectingSignatureByFile, ...snapshot.runtimeAffectingSignatureByFile]) : snapshot.runtimeAffectingSignatureByFile;
824
+ state.runtimeAffectingHashByFile = incremental ? new Map([...state.runtimeAffectingHashByFile, ...snapshot.runtimeAffectingHashByFile]) : snapshot.runtimeAffectingHashByFile;
825
+ state.linkedByEntry = incremental ? new Map([...state.linkedByEntry, ...linkedByEntry]) : linkedByEntry;
826
+ state.dependentsByLinkedFile = invertLinkedByEntry(state.linkedByEntry);
827
+ }
828
+ //#endregion
829
+ //#region src/bundlers/vite/generate-bundle.ts
830
+ function formatDebugFileList(files, limit = 8) {
831
+ if (files.size === 0) return "-";
832
+ const sorted = [...files].sort();
833
+ if (sorted.length <= limit) return sorted.join(",");
834
+ return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
835
+ }
836
+ function createEmptyMetric() {
837
+ return {
838
+ total: 0,
839
+ transformed: 0,
840
+ cacheHits: 0,
841
+ elapsed: 0
842
+ };
843
+ }
844
+ function createEmptyMetrics() {
845
+ return {
846
+ runtimeSet: 0,
847
+ html: createEmptyMetric(),
848
+ js: createEmptyMetric(),
849
+ css: createEmptyMetric()
850
+ };
851
+ }
852
+ function measureElapsed(start) {
853
+ return performance.now() - start;
854
+ }
855
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
856
+ return uniAppX === void 0 ? true : require_logger.isUniAppXEnabled(uniAppX);
857
+ }
858
+ function formatCacheHitRate(metric) {
859
+ if (metric.total === 0) return "0.00%";
860
+ return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
861
+ }
862
+ function formatMs(value) {
863
+ return value.toFixed(2);
864
+ }
865
+ function summarizeStringDiff(previous, next) {
866
+ if (previous === next) return "same";
867
+ const previousLength = previous.length;
868
+ const nextLength = next.length;
869
+ const minLength = Math.min(previousLength, nextLength);
870
+ let prefixLength = 0;
871
+ while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
872
+ let previousSuffixCursor = previousLength - 1;
873
+ let nextSuffixCursor = nextLength - 1;
874
+ while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
875
+ previousSuffixCursor -= 1;
876
+ nextSuffixCursor -= 1;
877
+ }
878
+ const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
879
+ const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
880
+ return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
881
+ }
882
+ function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
883
+ const changedLinkedFiles = linkedImpactsByEntry.get(entry);
884
+ if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
885
+ return [...changedLinkedFiles].sort().map((file) => {
886
+ return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
887
+ }).join(",");
888
+ }
889
+ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
890
+ if (!linkedImpactSignature) return runtimeSignature;
891
+ return `${runtimeSignature}:linked:${linkedImpactSignature}`;
892
+ }
893
+ function createStableTextSignature(input) {
894
+ let hash = 2166136261;
895
+ for (let i = 0; i < input.length; i++) {
896
+ hash ^= input.charCodeAt(i);
897
+ hash = Math.imul(hash, 16777619);
898
+ }
899
+ return (hash >>> 0).toString(36);
900
+ }
901
+ function createCandidateSignature(candidates) {
902
+ if (candidates.size === 0) return "empty";
903
+ return createStableTextSignature([...candidates].sort().join("\n"));
904
+ }
905
+ function getSnapshotHash(snapshotMap, file, fallback) {
906
+ return snapshotMap.get(file) ?? fallback;
907
+ }
908
+ function hasRuntimeAffectingSourceChanges(changedByType) {
909
+ return changedByType.html.size > 0 || changedByType.js.size > 0;
910
+ }
911
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
912
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
913
+ const CSS_IMPORT_RE = /@import\b/i;
914
+ function isPathIndependentCssUrl(value) {
915
+ const normalized = value.trim();
916
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
917
+ }
918
+ function hasPathDependentCssUrl(rawSource) {
919
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
920
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
921
+ while (match !== null) {
922
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
923
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
924
+ }
925
+ return false;
926
+ }
927
+ function createCssTransformShareScope(file, rawSource) {
928
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_css_imports.normalizeOutputPathKey(node_path.default.dirname(file))}`;
929
+ return "global";
930
+ }
931
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
932
+ if (require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_css_imports.normalizeOutputPathKey(file)}`;
933
+ return createCssTransformShareScope(file, rawSource);
934
+ }
935
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
936
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
937
+ }
938
+ function createReplayCssAsset(fileName, source) {
939
+ return {
940
+ type: "asset",
941
+ fileName,
942
+ name: void 0,
943
+ source,
944
+ needsCodeReference: false,
945
+ names: [],
946
+ originalFileName: null,
947
+ originalFileNames: []
948
+ };
949
+ }
950
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
951
+ const currentFileSet = new Set(currentBundleFiles);
952
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
953
+ return false;
954
+ }
955
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
956
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
957
+ function isArbitraryValueCandidate(candidate) {
958
+ return candidate.includes("[") && candidate.includes("]");
959
+ }
960
+ function collectUnescapedDynamicCandidates(source) {
961
+ const matches = /* @__PURE__ */ new Set();
962
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
963
+ QUOTED_LITERAL_RE.lastIndex = 0;
964
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
965
+ while (quoted !== null) {
966
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
967
+ for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, true)) {
968
+ const normalized = candidate.trim();
969
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
970
+ matches.add(normalized);
971
+ }
972
+ quoted = QUOTED_LITERAL_RE.exec(expression);
973
+ }
974
+ }
975
+ return [...matches];
976
+ }
977
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
978
+ if (candidates.has("container")) return candidates;
979
+ if (!sourceCandidates.has("container")) return candidates;
980
+ return new Set([...candidates, "container"]);
981
+ }
982
+ function createGenerateBundleHook(context) {
983
+ const state = createBundleBuildState();
984
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
985
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
986
+ return async function generateBundle(_opt, bundle) {
987
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
988
+ const { appType, cache, mainCssChunkMatcher, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
989
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
990
+ const getCssHandlerOptions = (file) => {
991
+ const majorVersion = runtimeState.twPatcher.majorVersion;
992
+ const isMainChunk = mainCssChunkMatcher(file, appType);
993
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
994
+ const cached = cssHandlerOptionsCache.get(cacheKey);
995
+ if (cached) return cached;
996
+ const created = {
997
+ isMainChunk,
998
+ postcssOptions: { options: { from: file } },
999
+ majorVersion
1000
+ };
1001
+ cssHandlerOptionsCache.set(cacheKey, created);
1002
+ return created;
1003
+ };
1004
+ const getCssUserHandlerOptions = (file) => {
1005
+ const cacheKey = `${runtimeState.twPatcher.majorVersion ?? "unknown"}:${file}`;
1006
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
1007
+ if (cached) return cached;
1008
+ const created = {
1009
+ ...getCssHandlerOptions(file),
1010
+ isMainChunk: false
1011
+ };
1012
+ cssUserHandlerOptionsCache.set(cacheKey, created);
1013
+ return created;
1014
+ };
1015
+ await runtimeState.patchPromise;
1016
+ debug("start");
1017
+ onStart();
1018
+ const metrics = createEmptyMetrics();
1019
+ const forceRuntimeRefreshByEnv = node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1020
+ const disableDirtyOptimization = node_process.default.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
1021
+ const disableJsPrecheck = node_process.default.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
1022
+ const debugCssDiff = node_process.default.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
1023
+ const resolvedConfig = getResolvedConfig();
1024
+ const bundleFiles = Object.keys(bundle);
1025
+ const useIncrementalMode = !(resolvedConfig?.command === "build") || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1026
+ const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
1027
+ const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1028
+ const snapshot = buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
1029
+ const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
1030
+ const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1031
+ const processFiles = snapshot.processFiles;
1032
+ if (useIncrementalMode) {
1033
+ 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));
1034
+ 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));
1035
+ } 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));
1036
+ const jsEntries = snapshot.jsEntries;
1037
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
1038
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_css_imports.normalizeOutputPathKey(id), entry);
1039
+ const getJsEntry = (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_css_imports.normalizeOutputPathKey(id));
1040
+ const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
1041
+ const runtimeStart = performance.now();
1042
+ const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1043
+ const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1044
+ await waitForSourceCandidateSyncs?.();
1045
+ const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1046
+ const collectedGeneratorCandidates = generatorOptions.mode === "force" ? new Set(sourceCandidates) : new Set([...runtime, ...sourceCandidates]);
1047
+ const generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
1048
+ const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1049
+ recordGeneratorCandidates?.(generatorRuntime);
1050
+ const defaultTemplateHandlerOptions = { runtimeSet: runtime };
1051
+ metrics.runtimeSet = measureElapsed(runtimeStart);
1052
+ if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1053
+ debug("get runtimeSet, class count: %d", runtime.size);
1054
+ const runtimeSignature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1055
+ const handleLinkedUpdate = (fileName, previous, next) => {
1056
+ onUpdate(fileName, previous, next);
1057
+ debug("js linked handle: %s", fileName);
1058
+ };
1059
+ const pendingLinkedUpdates = [];
1060
+ const scheduleLinkedApply = (entry, code) => {
1061
+ pendingLinkedUpdates.push(() => {
1062
+ if (entry.output.type === "chunk") entry.output.code = code;
1063
+ else entry.output.source = code;
1064
+ });
1065
+ };
1066
+ const applyLinkedUpdates = (linked) => {
1067
+ applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1068
+ };
1069
+ const createHandlerOptions = (absoluteFilename, extra) => ({
1070
+ ...extra,
1071
+ filename: absoluteFilename,
1072
+ tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
1073
+ moduleGraph: moduleGraphOptions,
1074
+ babelParserOptions: {
1075
+ ...extra?.babelParserOptions ?? {},
1076
+ sourceFilename: absoluteFilename
1077
+ }
1078
+ });
1079
+ const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1080
+ const sharedCssResultCache = /* @__PURE__ */ new Map();
1081
+ const tasks = [];
1082
+ const jsTaskFactories = [];
1083
+ for (const entry of snapshot.entries) {
1084
+ const { file, output: originalSource, source: originalEntrySource, type } = entry;
1085
+ if (type === "html" && originalSource.type === "asset") {
1086
+ metrics.html.total++;
1087
+ if (!processFiles.html.has(file)) continue;
1088
+ const rawSource = originalEntrySource;
1089
+ tasks.push(require_generator_css.processCachedTask({
1090
+ cache,
1091
+ cacheKey: file,
1092
+ hashKey: `${file}:html:${runtimeSignature}`,
1093
+ hash: getSnapshotHash(snapshot.sourceHashByFile, file, rawSource),
1094
+ applyResult(source) {
1095
+ originalSource.source = source;
1096
+ },
1097
+ onCacheHit() {
1098
+ metrics.html.cacheHits++;
1099
+ debug("html cache hit: %s", file);
1100
+ },
1101
+ async transform() {
1102
+ const start = performance.now();
1103
+ let transformed = await templateHandler(rawSource, defaultTemplateHandlerOptions);
1104
+ let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1105
+ if (unresolvedDynamicCandidates.length > 0) {
1106
+ _weapp_tailwindcss_logger.logger.warn("检测到 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
1107
+ transformed = await templateHandler(rawSource, { runtimeSet: await context.ensureRuntimeClassSet(true) });
1108
+ unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1109
+ if (unresolvedDynamicCandidates.length > 0) _weapp_tailwindcss_logger.logger.warn("WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
1110
+ }
1111
+ metrics.html.elapsed += measureElapsed(start);
1112
+ metrics.html.transformed++;
1113
+ onUpdate(file, rawSource, transformed);
1114
+ debug("html handle: %s", file);
1115
+ return { result: transformed };
1116
+ }
1117
+ }));
1118
+ continue;
1119
+ }
1120
+ if (type === "css" && originalSource.type === "asset") {
1121
+ metrics.css.total++;
1122
+ const rawSource = originalEntrySource;
1123
+ const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1124
+ const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
1125
+ const cssHandlerOptions = getCssHandlerOptions(file);
1126
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1127
+ const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1128
+ tasks.push(require_generator_css.processCachedTask({
1129
+ cache,
1130
+ cacheKey: file,
1131
+ hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1132
+ hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${generatorCandidateSignature}`,
1133
+ applyResult(source) {
1134
+ originalSource.source = source;
1135
+ markCssAssetProcessed?.(originalSource, file);
1136
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource, cssRuntimeSignature);
1137
+ },
1138
+ onCacheHit() {
1139
+ metrics.css.cacheHits++;
1140
+ debug("css cache hit: %s", file);
1141
+ },
1142
+ async transform() {
1143
+ if (cssSharedCacheKey) {
1144
+ const sharedCssTask = sharedCssResultCache.get(cssSharedCacheKey);
1145
+ if (sharedCssTask != null) {
1146
+ metrics.css.cacheHits++;
1147
+ debug("css shared hit: %s", file);
1148
+ const sharedCss = await sharedCssTask;
1149
+ onUpdate(file, rawSource, sharedCss);
1150
+ return { result: sharedCss };
1151
+ }
1152
+ }
1153
+ const runTransform = async () => {
1154
+ const start = performance.now();
1155
+ await runtimeState.patchPromise;
1156
+ const generated = await require_generator_css.generateCssByGenerator({
1157
+ opts,
1158
+ runtimeState,
1159
+ runtime: generatorRuntime,
1160
+ rawSource,
1161
+ file,
1162
+ cssHandlerOptions,
1163
+ cssUserHandlerOptions: getCssUserHandlerOptions(file),
1164
+ styleHandler,
1165
+ debug
1166
+ });
1167
+ if (generated) {
1168
+ if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, generated.css));
1169
+ debug("css generated result: %s bytes=%d", file, generated.css.length);
1170
+ recordCssAssetResult?.(file, generated.css);
1171
+ metrics.css.elapsed += measureElapsed(start);
1172
+ metrics.css.transformed++;
1173
+ debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, file);
1174
+ return generated.css;
1175
+ }
1176
+ const { css } = await styleHandler(rawSource, getCssHandlerOptions(file));
1177
+ if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, css));
1178
+ metrics.css.elapsed += measureElapsed(start);
1179
+ metrics.css.transformed++;
1180
+ return css;
1181
+ };
1182
+ const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1183
+ if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1184
+ const css = await cssTask;
1185
+ onUpdate(file, rawSource, css);
1186
+ debug("css handle: %s", file);
1187
+ return { result: css };
1188
+ }
1189
+ }));
1190
+ continue;
1191
+ }
1192
+ if (type !== "js") continue;
1193
+ metrics.js.total++;
1194
+ const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
1195
+ if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
1196
+ if (originalSource.type === "chunk") {
1197
+ const absoluteFile = node_path.default.resolve(outDir, file);
1198
+ const initialRawSource = originalEntrySource;
1199
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1200
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1201
+ jsTaskFactories.push(async () => {
1202
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1203
+ await require_generator_css.processCachedTask({
1204
+ cache,
1205
+ cacheKey: file,
1206
+ hashKey: `${file}:js`,
1207
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1208
+ applyResult(source) {
1209
+ originalSource.code = source;
1210
+ },
1211
+ onCacheHit() {
1212
+ metrics.js.cacheHits++;
1213
+ debug("js cache hit: %s", file);
1214
+ },
1215
+ async transform() {
1216
+ const start = performance.now();
1217
+ const rawSource = originalSource.code;
1218
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1219
+ const handlerOptions = createHandlerOptions(absoluteFile);
1220
+ if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(rawSource, handlerOptions)) {
1221
+ metrics.js.elapsed += measureElapsed(start);
1222
+ metrics.js.transformed++;
1223
+ return { result: rawSource };
1224
+ }
1225
+ const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1226
+ metrics.js.elapsed += measureElapsed(start);
1227
+ metrics.js.transformed++;
1228
+ onUpdate(file, rawSource, code);
1229
+ debug("js handle: %s", file);
1230
+ if (linked) for (const id of Object.keys(linked)) {
1231
+ const linkedEntry = getJsEntry(id);
1232
+ if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1233
+ }
1234
+ applyLinkedUpdates(linked);
1235
+ return { result: code };
1236
+ }
1237
+ });
1238
+ });
1239
+ } else if (uniAppX && originalSource.type === "asset") {
1240
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1241
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1242
+ const baseApplyLinkedUpdates = applyLinkedUpdates;
1243
+ const wrappedApplyLinkedUpdates = (linked) => {
1244
+ if (linked) for (const id of Object.keys(linked)) {
1245
+ const linkedEntry = getJsEntry(id);
1246
+ if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1247
+ }
1248
+ baseApplyLinkedUpdates(linked);
1249
+ };
1250
+ const factory = createUniAppXAssetTask(file, originalSource, outDir, {
1251
+ cache,
1252
+ hashKey: `${file}:js`,
1253
+ hashSalt: createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0),
1254
+ createHandlerOptions,
1255
+ debug,
1256
+ jsHandler,
1257
+ onUpdate,
1258
+ runtimeSet: runtime,
1259
+ applyLinkedResults: wrappedApplyLinkedUpdates,
1260
+ uniAppX
1261
+ });
1262
+ jsTaskFactories.push(async () => {
1263
+ const start = performance.now();
1264
+ if (!shouldTransformJs) {
1265
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1266
+ await factory();
1267
+ metrics.js.elapsed += measureElapsed(start);
1268
+ metrics.js.transformed++;
1269
+ return;
1270
+ }
1271
+ const currentSource = originalEntrySource;
1272
+ const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
1273
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1274
+ babelParserOptions: {
1275
+ plugins: ["typescript"],
1276
+ sourceType: "unambiguous"
1277
+ }
1278
+ });
1279
+ if (!disableJsPrecheck && require_recorder.shouldSkipJsTransform(currentSource, precheckOptions)) {
1280
+ metrics.js.elapsed += measureElapsed(start);
1281
+ metrics.js.transformed++;
1282
+ return;
1283
+ }
1284
+ await factory();
1285
+ metrics.js.elapsed += measureElapsed(start);
1286
+ metrics.js.transformed++;
1287
+ });
1288
+ }
1289
+ }
1290
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1291
+ if (useIncrementalMode && generatorOptions.mode === "force") for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1292
+ if (bundleFiles.includes(file) || getRememberedMainCssSignature?.(file) === cssRuntimeSignature) continue;
1293
+ tasks.push((async () => {
1294
+ const start = performance.now();
1295
+ const cssHandlerOptions = getCssHandlerOptions(file);
1296
+ const generated = await require_generator_css.generateCssByGenerator({
1297
+ opts,
1298
+ runtimeState,
1299
+ runtime: generatorRuntime,
1300
+ rawSource,
1301
+ file,
1302
+ cssHandlerOptions,
1303
+ cssUserHandlerOptions: getCssUserHandlerOptions(file),
1304
+ styleHandler,
1305
+ debug
1306
+ });
1307
+ const css = generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css;
1308
+ setRememberedMainCssSignature?.(file, cssRuntimeSignature);
1309
+ if (generated) {
1310
+ recordCssAssetResult?.(file, generated.css);
1311
+ debug("css replay generated result: %s bytes=%d", file, css.length);
1312
+ }
1313
+ const replayAsset = createReplayCssAsset(file, css);
1314
+ if (typeof this.emitFile === "function") this.emitFile({
1315
+ type: "asset",
1316
+ fileName: file,
1317
+ source: css
1318
+ });
1319
+ else bundle[file] = replayAsset;
1320
+ markCssAssetProcessed?.(replayAsset, file);
1321
+ metrics.css.elapsed += measureElapsed(start);
1322
+ metrics.css.transformed++;
1323
+ onUpdate(file, rawSource, css);
1324
+ debug("css replay handle: %s", file);
1325
+ })());
1326
+ }
1327
+ require_css_imports.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1328
+ await Promise.all(tasks);
1329
+ for (const apply of pendingLinkedUpdates) apply();
1330
+ updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1331
+ 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));
1332
+ onEnd();
1333
+ debug("end");
1334
+ };
1335
+ }
1336
+ //#endregion
1337
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
1338
+ const debug$1 = require_recorder.createDebug("[vite:runtime-set] ");
1339
+ const EXTENSION_DOT_PREFIX_RE = /^\./;
1340
+ function createExtractOptions(context, source) {
1341
+ return {
1342
+ cwd: context.projectRoot,
1343
+ base: context.base,
1344
+ baseFallbacks: context.baseFallbacks,
1345
+ css: context.css,
1346
+ content: source,
1347
+ extension: "html"
1348
+ };
1349
+ }
1350
+ function createRuntimeEntries(snapshot) {
1351
+ return snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js");
1352
+ }
1353
+ function collectChangedRuntimeFiles(snapshot) {
1354
+ return new Set([...snapshot.runtimeAffectingChangedByType.html, ...snapshot.runtimeAffectingChangedByType.js]);
1355
+ }
1356
+ function resolveEntryExtension(entry) {
1357
+ const ext = entry.file.split(/[?#]/, 1)[0]?.split(".").pop()?.replace(EXTENSION_DOT_PREFIX_RE, "") ?? "";
1358
+ if (ext.length > 0) return ext;
1359
+ return entry.type === "html" ? "html" : "js";
1360
+ }
1361
+ function createCandidateValidationSource(candidates) {
1362
+ return [...new Set(candidates)].sort().join("\n");
1363
+ }
1364
+ function removeCandidateSet$1(candidateCountByClass, runtimeSet, candidates) {
1365
+ for (const className of candidates) {
1366
+ const count = candidateCountByClass.get(className);
1367
+ if (count == null) continue;
1368
+ if (count <= 1) {
1369
+ candidateCountByClass.delete(className);
1370
+ runtimeSet.delete(className);
1371
+ continue;
1372
+ }
1373
+ candidateCountByClass.set(className, count - 1);
1374
+ }
1375
+ }
1376
+ function addCandidateSet$1(candidateCountByClass, runtimeSet, candidates) {
1377
+ for (const className of candidates) {
1378
+ const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
1379
+ candidateCountByClass.set(className, nextCount);
1380
+ runtimeSet.add(className);
1381
+ }
1382
+ }
1383
+ function createBundleRuntimeClassSetManager(options = {}) {
1384
+ const customExtractCandidates = options.extractCandidates;
1385
+ const extractCandidates = customExtractCandidates ?? tailwindcss_patch.extractValidCandidates;
1386
+ const extractRawCandidates = options.extractRawCandidates ?? tailwindcss_patch.extractRawCandidatesWithPositions;
1387
+ const runtimeSet = /* @__PURE__ */ new Set();
1388
+ const candidateCountByClass = /* @__PURE__ */ new Map();
1389
+ const candidatesByFile = /* @__PURE__ */ new Map();
1390
+ const candidateValidityCache = /* @__PURE__ */ new Map();
1391
+ let runtimeSignature;
1392
+ let validationContext;
1393
+ let designSystemPromise;
1394
+ async function reset() {
1395
+ runtimeSet.clear();
1396
+ candidateCountByClass.clear();
1397
+ candidatesByFile.clear();
1398
+ candidateValidityCache.clear();
1399
+ runtimeSignature = void 0;
1400
+ validationContext = void 0;
1401
+ designSystemPromise = void 0;
1402
+ }
1403
+ async function resolveValidationContextCached(patcher) {
1404
+ if (!validationContext) validationContext = await require_generator.resolveTailwindV4SourceFromPatcher(patcher);
1405
+ return validationContext;
1406
+ }
1407
+ async function loadDesignSystem(context) {
1408
+ if (!designSystemPromise) designSystemPromise = (0, tailwindcss_patch.loadTailwindV4DesignSystem)(context);
1409
+ return designSystemPromise;
1410
+ }
1411
+ function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
1412
+ const parsedCandidates = [...unknownCandidates].filter((candidate) => designSystem.parseCandidate(candidate).length > 0);
1413
+ const cssByCandidate = parsedCandidates.length > 0 ? designSystem.candidatesToCss(parsedCandidates) : [];
1414
+ const validCandidates = /* @__PURE__ */ new Set();
1415
+ for (let index = 0; index < parsedCandidates.length; index += 1) {
1416
+ const candidate = parsedCandidates[index];
1417
+ const css = cssByCandidate[index];
1418
+ if (candidate && typeof css === "string" && css.trim().length > 0) validCandidates.add(candidate);
1419
+ }
1420
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1421
+ }
1422
+ async function validateUnknownCandidates(patcher, unknownCandidates) {
1423
+ if (unknownCandidates.size === 0) return;
1424
+ const context = await resolveValidationContextCached(patcher);
1425
+ if (!customExtractCandidates) try {
1426
+ populateCandidateValidityCacheFromDesignSystem(await loadDesignSystem(context), unknownCandidates);
1427
+ return;
1428
+ } catch (error) {
1429
+ debug$1("incremental design-system validation failed: %O", error);
1430
+ designSystemPromise = void 0;
1431
+ throw error;
1432
+ }
1433
+ const source = createCandidateValidationSource(unknownCandidates);
1434
+ const validCandidates = new Set(await extractCandidates(createExtractOptions(context, source)));
1435
+ for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1436
+ }
1437
+ async function extractEntryRawCandidates(entry) {
1438
+ const matches = await extractRawCandidates(entry.source, resolveEntryExtension(entry));
1439
+ const candidates = /* @__PURE__ */ new Set();
1440
+ for (const match of matches) {
1441
+ const candidate = match?.rawCandidate;
1442
+ if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
1443
+ }
1444
+ return candidates;
1445
+ }
1446
+ async function sync(patcher, snapshot) {
1447
+ const nextSignature = require_logger.getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1448
+ const runtimeEntries = createRuntimeEntries(snapshot);
1449
+ const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1450
+ const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
1451
+ const fullRebuild = runtimeSignature !== nextSignature || candidatesByFile.size === 0;
1452
+ if (runtimeSignature !== nextSignature) {
1453
+ debug$1("runtime signature changed, reset incremental runtime set: %s", nextSignature);
1454
+ await reset();
1455
+ }
1456
+ runtimeSignature = nextSignature;
1457
+ for (const [file, previousCandidates] of candidatesByFile) {
1458
+ if (currentRuntimeFiles.has(file)) continue;
1459
+ removeCandidateSet$1(candidateCountByClass, runtimeSet, previousCandidates);
1460
+ candidatesByFile.delete(file);
1461
+ }
1462
+ const changedRuntimeFiles = fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
1463
+ if (changedRuntimeFiles.length === 0) return new Set(runtimeSet);
1464
+ const rawCandidatesByFile = /* @__PURE__ */ new Map();
1465
+ const unknownCandidates = /* @__PURE__ */ new Set();
1466
+ await Promise.all(changedRuntimeFiles.map(async (file) => {
1467
+ const entry = runtimeEntriesByFile.get(file);
1468
+ if (!entry) return;
1469
+ const candidates = await extractEntryRawCandidates(entry);
1470
+ rawCandidatesByFile.set(file, candidates);
1471
+ for (const candidate of candidates) if (!candidateValidityCache.has(candidate)) unknownCandidates.add(candidate);
1472
+ }));
1473
+ await validateUnknownCandidates(patcher, unknownCandidates);
1474
+ let rawCandidateCount = 0;
1475
+ for (const file of changedRuntimeFiles) {
1476
+ const nextRawCandidates = rawCandidatesByFile.get(file);
1477
+ const previousCandidates = candidatesByFile.get(file);
1478
+ if (previousCandidates) removeCandidateSet$1(candidateCountByClass, runtimeSet, previousCandidates);
1479
+ if (!nextRawCandidates || nextRawCandidates.size === 0) {
1480
+ candidatesByFile.delete(file);
1481
+ continue;
1482
+ }
1483
+ rawCandidateCount += nextRawCandidates.size;
1484
+ const nextCandidates = new Set([...nextRawCandidates].filter((candidate) => candidateValidityCache.get(candidate) === true));
1485
+ if (nextCandidates.size === 0) {
1486
+ candidatesByFile.delete(file);
1487
+ continue;
1488
+ }
1489
+ addCandidateSet$1(candidateCountByClass, runtimeSet, nextCandidates);
1490
+ candidatesByFile.set(file, nextCandidates);
1491
+ }
1492
+ 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);
1493
+ return new Set(runtimeSet);
1494
+ }
1495
+ return {
1496
+ sync,
1497
+ reset
1498
+ };
1499
+ }
1500
+ //#endregion
1501
+ //#region src/bundlers/vite/resolve-app-type.ts
1502
+ const PACKAGE_JSON_FILE$1 = "package.json";
1503
+ const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1504
+ const TARO_SCRIPT_RE = /\btaro\b/u;
1505
+ const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1506
+ function resolveDependencyNames(pkg) {
1507
+ return new Set([
1508
+ ...Object.keys(pkg.dependencies ?? {}),
1509
+ ...Object.keys(pkg.devDependencies ?? {}),
1510
+ ...Object.keys(pkg.peerDependencies ?? {}),
1511
+ ...Object.keys(pkg.optionalDependencies ?? {})
1512
+ ]);
1513
+ }
1514
+ function hasScriptMatch(pkg, pattern) {
1515
+ return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1516
+ }
1517
+ function resolveAppTypeFromPackageJson(pkg) {
1518
+ const dependencyNames = resolveDependencyNames(pkg);
1519
+ if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1520
+ if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1521
+ if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1522
+ if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1523
+ if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1524
+ }
1525
+ function tryReadUniAppManifest(root) {
1526
+ const manifestPath = node_path.default.join(root, "manifest.json");
1527
+ if (!(0, node_fs.existsSync)(manifestPath)) return;
1528
+ try {
1529
+ return JSON.parse((0, node_fs.readFileSync)(manifestPath, "utf8"));
1530
+ } catch {}
1531
+ }
1532
+ function tryReadPackageJson(root) {
1533
+ const packageJsonPath = node_path.default.join(root, PACKAGE_JSON_FILE$1);
1534
+ if (!(0, node_fs.existsSync)(packageJsonPath)) return;
1535
+ try {
1536
+ return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8"));
1537
+ } catch {}
1538
+ }
1539
+ function resolveAppTypeFromMarkers(root) {
1540
+ for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if ((0, node_fs.existsSync)(node_path.default.join(root, relativePath))) return appType;
1541
+ }
1542
+ function resolveImplicitAppTypeFromViteRoot(root) {
1543
+ const resolvedRoot = node_path.default.resolve(root);
1544
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return;
1545
+ const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1546
+ if (markerDetected) return markerDetected;
1547
+ let current = resolvedRoot;
1548
+ while (true) {
1549
+ const manifest = tryReadUniAppManifest(current);
1550
+ if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1551
+ const pkg = tryReadPackageJson(current);
1552
+ if (pkg) {
1553
+ const detected = resolveAppTypeFromPackageJson(pkg);
1554
+ if (detected) return detected;
1555
+ }
1556
+ const parent = node_path.default.dirname(current);
1557
+ if (parent === current) break;
1558
+ current = parent;
1559
+ }
1560
+ }
1561
+ //#endregion
1562
+ //#region src/bundlers/vite/rewrite-css-imports.ts
1563
+ function joinPosixPath(base, subpath) {
1564
+ if (base.endsWith("/")) return `${base}${subpath}`;
1565
+ return `${base}/${subpath}`;
1566
+ }
1567
+ function isCssLikeImporter(importer) {
1568
+ if (!importer) return false;
1569
+ const normalized = (0, _weapp_tailwindcss_shared.cleanUrl)(importer);
1570
+ return isCSSRequest(normalized) || normalized.endsWith("/*");
1571
+ }
1572
+ function createRewriteCssImportsPlugins(options) {
1573
+ if (!options.shouldRewrite) return [];
1574
+ const { appType, getAppType, rootImport, weappTailwindcssDirPosix } = options;
1575
+ const resolveAppType = () => getAppType?.() ?? appType;
1576
+ return [{
1577
+ name: `${require_recorder.vitePluginName}:rewrite-css-imports`,
1578
+ enforce: "pre",
1579
+ resolveId: {
1580
+ order: "pre",
1581
+ handler(id, importer) {
1582
+ const replacement = require_css_imports.resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1583
+ join: joinPosixPath,
1584
+ appType: resolveAppType(),
1585
+ rootImport
1586
+ });
1587
+ if (!replacement) return null;
1588
+ if (importer && !isCssLikeImporter(importer)) return null;
1589
+ return replacement;
1590
+ }
1591
+ },
1592
+ transform: {
1593
+ order: "pre",
1594
+ handler(code, id) {
1595
+ if (!isCSSRequest(id)) return null;
1596
+ const rewritten = require_css_imports.rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1597
+ join: joinPosixPath,
1598
+ appType: resolveAppType(),
1599
+ rootImport
1600
+ });
1601
+ if (!rewritten) return null;
1602
+ return {
1603
+ code: rewritten,
1604
+ map: null
1605
+ };
1606
+ }
1607
+ }
1608
+ }];
1609
+ }
1610
+ //#endregion
1611
+ //#region src/bundlers/vite/source-candidates.ts
1612
+ const CLEAN_URL_RE = /[?#].*$/;
1613
+ const SOURCE_CANDIDATE_EXTENSIONS = [
1614
+ "js",
1615
+ "jsx",
1616
+ "mjs",
1617
+ "cjs",
1618
+ "ts",
1619
+ "tsx",
1620
+ "mts",
1621
+ "cts",
1622
+ "vue",
1623
+ "uvue",
1624
+ "nvue",
1625
+ "svelte",
1626
+ "mpx",
1627
+ "html",
1628
+ "wxml",
1629
+ "axml",
1630
+ "jxml",
1631
+ "ksml",
1632
+ "ttml",
1633
+ "qml",
1634
+ "tyml",
1635
+ "xhsml",
1636
+ "swan",
1637
+ "css",
1638
+ "wxss",
1639
+ "acss",
1640
+ "jxss",
1641
+ "ttss",
1642
+ "qss",
1643
+ "tyss",
1644
+ "scss",
1645
+ "sass",
1646
+ "less",
1647
+ "styl",
1648
+ "stylus"
1649
+ ];
1650
+ 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?)$/;
1651
+ const CSS_SOURCE_CANDIDATE_EXTENSION_RE = /^(?:css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|styl|stylus)$/;
1652
+ const SOURCE_CANDIDATE_GLOB = `**/*.{${SOURCE_CANDIDATE_EXTENSIONS.join(",")}}`;
1653
+ const DEFAULT_SCAN_IGNORE = ["**/node_modules/**", "**/.git/**"];
1654
+ function cleanUrl(id) {
1655
+ return id.replace(CLEAN_URL_RE, "");
1656
+ }
1657
+ function toPosixPath(value) {
1658
+ return value.split(node_path.default.sep).join("/");
1659
+ }
1660
+ function resolveOutDirIgnorePattern(root, outDir) {
1661
+ if (!outDir) return;
1662
+ const relative = node_path.default.relative(root, node_path.default.resolve(root, outDir));
1663
+ if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) return;
1664
+ return `${toPosixPath(relative)}/**`;
1665
+ }
1666
+ function resolveSourceCandidateExtension(id) {
1667
+ const normalized = cleanUrl(id);
1668
+ return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
1669
+ }
1670
+ function isSourceCandidateRequest(id) {
1671
+ return SOURCE_CANDIDATE_EXTENSION_RE.test(cleanUrl(id));
1672
+ }
1673
+ function removeCandidateSet(candidateCount, candidates) {
1674
+ for (const candidate of candidates) {
1675
+ const count = candidateCount.get(candidate);
1676
+ if (count == null) continue;
1677
+ if (count <= 1) {
1678
+ candidateCount.delete(candidate);
1679
+ continue;
1680
+ }
1681
+ candidateCount.set(candidate, count - 1);
1682
+ }
1683
+ }
1684
+ function addCandidateSet(candidateCount, candidates) {
1685
+ for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
1686
+ }
1687
+ const CSS_APPLY_RE = /@apply\s+([^;{}]+)/g;
1688
+ const CSS_APPLY_IMPORTANT = "!important";
1689
+ function extractCssApplyCandidates(source) {
1690
+ const candidates = /* @__PURE__ */ new Set();
1691
+ CSS_APPLY_RE.lastIndex = 0;
1692
+ let match = CSS_APPLY_RE.exec(source);
1693
+ while (match !== null) {
1694
+ const params = match[1] ?? "";
1695
+ for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(params, true)) {
1696
+ const normalized = candidate.trim();
1697
+ if (normalized && normalized !== CSS_APPLY_IMPORTANT) candidates.add(normalized);
1698
+ }
1699
+ match = CSS_APPLY_RE.exec(source);
1700
+ }
1701
+ return candidates;
1702
+ }
1703
+ function createSourceCandidateCollector() {
1704
+ const candidatesById = /* @__PURE__ */ new Map();
1705
+ const candidateCount = /* @__PURE__ */ new Map();
1706
+ async function sync(id, source) {
1707
+ const normalizedId = cleanUrl(id);
1708
+ const extension = resolveSourceCandidateExtension(normalizedId);
1709
+ const nextCandidates = /* @__PURE__ */ new Set();
1710
+ if (CSS_SOURCE_CANDIDATE_EXTENSION_RE.test(extension)) for (const candidate of extractCssApplyCandidates(source)) nextCandidates.add(candidate);
1711
+ else {
1712
+ const matches = await (0, tailwindcss_patch.extractRawCandidatesWithPositions)(source, extension);
1713
+ for (const match of matches) {
1714
+ const candidate = match.rawCandidate;
1715
+ if (typeof candidate === "string" && candidate.length > 0) nextCandidates.add(candidate);
1716
+ }
1717
+ }
1718
+ remove(normalizedId);
1719
+ if (nextCandidates.size === 0) return;
1720
+ candidatesById.set(normalizedId, nextCandidates);
1721
+ addCandidateSet(candidateCount, nextCandidates);
1722
+ }
1723
+ async function syncFile(id) {
1724
+ const normalizedId = cleanUrl(id);
1725
+ await sync(normalizedId, await (0, node_fs_promises.readFile)(normalizedId, "utf8"));
1726
+ }
1727
+ async function scanRoot({ root, outDir }) {
1728
+ const resolvedRoot = node_path.default.resolve(root);
1729
+ const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, outDir);
1730
+ const files = await (0, fast_glob.default)(SOURCE_CANDIDATE_GLOB, {
1731
+ absolute: true,
1732
+ cwd: resolvedRoot,
1733
+ ignore: outDirIgnore ? [...DEFAULT_SCAN_IGNORE, outDirIgnore] : DEFAULT_SCAN_IGNORE,
1734
+ onlyFiles: true,
1735
+ unique: true
1736
+ });
1737
+ await Promise.all(files.map((file) => syncFile(file)));
1738
+ }
1739
+ function remove(id) {
1740
+ const normalizedId = cleanUrl(id);
1741
+ const previousCandidates = candidatesById.get(normalizedId);
1742
+ if (!previousCandidates) return;
1743
+ removeCandidateSet(candidateCount, previousCandidates);
1744
+ candidatesById.delete(normalizedId);
1745
+ }
1746
+ function values() {
1747
+ return new Set(candidateCount.keys());
1748
+ }
1749
+ function clear() {
1750
+ candidatesById.clear();
1751
+ candidateCount.clear();
1752
+ }
1753
+ return {
1754
+ sync,
1755
+ syncFile,
1756
+ scanRoot,
1757
+ remove,
1758
+ values,
1759
+ clear
1760
+ };
1761
+ }
1762
+ //#endregion
1763
+ //#region src/bundlers/vite/index.ts
1764
+ const debug = require_recorder.createDebug();
1765
+ const weappTailwindcssPackageDir = require_css_imports.resolvePackageDir("weapp-tailwindcss");
1766
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1767
+ const PACKAGE_JSON_FILE = "package.json";
1768
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1769
+ function getPostcssPluginName(plugin) {
1770
+ if (!plugin) return;
1771
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1772
+ return getPostcssPluginName(plugin());
1773
+ } catch {
1774
+ return;
1775
+ }
1776
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1777
+ const { postcssPlugin } = plugin;
1778
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1779
+ }
1780
+ function isTailwindPostcssPlugin(plugin) {
1781
+ const name = getPostcssPluginName(plugin);
1782
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1783
+ }
1784
+ function removeTailwindPostcssPlugins(plugins) {
1785
+ let removed = 0;
1786
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1787
+ plugins.splice(i, 1);
1788
+ removed++;
1789
+ }
1790
+ return removed;
1791
+ }
1792
+ async function resolveFilteredPostcssConfig(root) {
1793
+ try {
1794
+ const loaded = await (0, postcss_load_config.default)({}, root);
1795
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1796
+ const removed = removeTailwindPostcssPlugins(plugins);
1797
+ if (removed === 0) return;
1798
+ return {
1799
+ options: loaded.options,
1800
+ plugins,
1801
+ removed
1802
+ };
1803
+ } catch (error) {
1804
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1805
+ throw error;
1806
+ }
1807
+ }
1808
+ function isTailwindVitePlugin(plugin) {
1809
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1810
+ const { name } = plugin;
1811
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1812
+ }
1813
+ function removeTailwindVitePlugins(plugins) {
1814
+ let removed = 0;
1815
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1816
+ plugins.splice(i, 1);
1817
+ removed++;
1818
+ }
1819
+ return removed;
1820
+ }
1821
+ function disableTailwindVitePlugin(plugin) {
1822
+ if (!isTailwindVitePlugin(plugin)) return false;
1823
+ const mutablePlugin = plugin;
1824
+ for (const hook of [
1825
+ "configResolved",
1826
+ "configureServer",
1827
+ "transform",
1828
+ "hotUpdate",
1829
+ "handleHotUpdate"
1830
+ ]) delete mutablePlugin[hook];
1831
+ return true;
1832
+ }
1833
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1834
+ let removed = 0;
1835
+ for (let i = plugins.length - 1; i >= 0; i--) {
1836
+ const plugin = plugins[i];
1837
+ if (Array.isArray(plugin)) {
1838
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1839
+ if (plugin.length === 0) plugins.splice(i, 1);
1840
+ continue;
1841
+ }
1842
+ if (disableTailwindVitePlugin(plugin)) {
1843
+ plugins.splice(i, 1);
1844
+ removed++;
1845
+ }
1846
+ }
1847
+ return removed;
1848
+ }
1849
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1850
+ const resolvedRoot = node_path.default.resolve(root);
1851
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
1852
+ const searchRoots = [];
1853
+ let current = resolvedRoot;
1854
+ while (true) {
1855
+ searchRoots.push(current);
1856
+ const parent = node_path.default.dirname(current);
1857
+ if (parent === current) break;
1858
+ current = parent;
1859
+ }
1860
+ const tailwindConfigPath = require_logger.findTailwindConfig(searchRoots);
1861
+ if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
1862
+ const packageRoot = require_logger.findNearestPackageRoot(resolvedRoot);
1863
+ if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1864
+ return resolvedRoot;
1865
+ }
1866
+ /**
1867
+ * @name UnifiedViteWeappTailwindcssPlugin
1868
+ * @description uni-app vite / uni-app-x 版本插件
1869
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1870
+ */
1871
+ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1872
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1873
+ const rewriteCssImportsSpecified = Object.hasOwn(options, "rewriteCssImports");
1874
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1875
+ const opts = require_recorder.getCompilerContext(options);
1876
+ const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1877
+ const uniAppXEnabled = require_logger.isUniAppXEnabled(uniAppX);
1878
+ const disabledOptions = require_css_imports.resolveDisabledOptions(disabled);
1879
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1880
+ const shouldOwnTailwindGeneration = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force";
1881
+ const shouldRewriteCssImports = opts.rewriteCssImports !== false && !disabledOptions.rewriteCssImports && (rewriteCssImportsSpecified || tailwindcssMajorVersion >= 4);
1882
+ const rewritePlugins = createRewriteCssImportsPlugins({
1883
+ getAppType: () => opts.appType,
1884
+ rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
1885
+ shouldRewrite: shouldRewriteCssImports,
1886
+ weappTailwindcssDirPosix
1887
+ });
1888
+ if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1889
+ const customAttributesEntities = require_recorder.toCustomAttributesEntities(customAttributes);
1890
+ const patchRecorderState = require_recorder.setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1891
+ source: "runtime",
1892
+ cwd: opts.tailwindcssBasedir ?? node_process.default.cwd()
1893
+ });
1894
+ const runtimeState = {
1895
+ twPatcher: initialTwPatcher,
1896
+ patchPromise: patchRecorderState.patchPromise,
1897
+ refreshTailwindcssPatcher,
1898
+ onPatchCompleted: patchRecorderState.onPatchCompleted
1899
+ };
1900
+ let runtimeSet;
1901
+ let runtimeSetPromise;
1902
+ let resolvedConfig;
1903
+ let runtimeRefreshSignature;
1904
+ let runtimeRefreshOptionsKey;
1905
+ let recordedGeneratorCandidates;
1906
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1907
+ const sourceCandidateCollector = createSourceCandidateCollector();
1908
+ const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1909
+ const processedCssAssets = /* @__PURE__ */ new WeakSet();
1910
+ const processedCssAssetFiles = /* @__PURE__ */ new Set();
1911
+ const rememberedMainCssSources = /* @__PURE__ */ new Map();
1912
+ const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
1913
+ function resolveRuntimeRefreshOptions() {
1914
+ const configPath = require_patcher_options.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1915
+ const signature = require_logger.getRuntimeClassSetSignature(runtimeState.twPatcher);
1916
+ const optionsKey = JSON.stringify({
1917
+ appType: opts.appType,
1918
+ uniAppX: uniAppXEnabled,
1919
+ customAttributesEntities,
1920
+ disabledDefaultTemplateHandler,
1921
+ configPath,
1922
+ rewriteCssImports: shouldRewriteCssImports
1923
+ });
1924
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1925
+ runtimeRefreshSignature = signature;
1926
+ runtimeRefreshOptionsKey = optionsKey;
1927
+ return {
1928
+ changed,
1929
+ signature,
1930
+ optionsKey
1931
+ };
1932
+ }
1933
+ async function refreshRuntimeState(force) {
1934
+ const invalidation = resolveRuntimeRefreshOptions();
1935
+ const refreshed = await require_recorder.refreshTailwindRuntimeState(runtimeState, {
1936
+ force: force || invalidation.changed,
1937
+ clearCache: force || invalidation.changed
1938
+ });
1939
+ if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1940
+ if (refreshed) {
1941
+ runtimeSet = void 0;
1942
+ runtimeSetPromise = void 0;
1943
+ }
1944
+ }
1945
+ async function ensureRuntimeClassSet(force = false) {
1946
+ const forceRuntimeRefresh = force || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1947
+ await refreshRuntimeState(force);
1948
+ await runtimeState.patchPromise;
1949
+ if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1950
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
1951
+ const invalidation = resolveRuntimeRefreshOptions();
1952
+ runtimeSetPromise = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1953
+ force: forceRuntimeRefresh || invalidation.changed,
1954
+ skipRefresh: forceRuntimeRefresh,
1955
+ clearCache: forceRuntimeRefresh || invalidation.changed
1956
+ });
1957
+ }
1958
+ const task = runtimeSetPromise;
1959
+ try {
1960
+ runtimeSet = await task;
1961
+ return runtimeSet;
1962
+ } finally {
1963
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1964
+ }
1965
+ }
1966
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1967
+ const forceRuntimeRefresh = forceRefresh || node_process.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1968
+ const invalidation = resolveRuntimeRefreshOptions();
1969
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1970
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1971
+ await refreshRuntimeState(shouldRefreshPatcher);
1972
+ await runtimeState.patchPromise;
1973
+ if (shouldRefreshPatcher) {
1974
+ runtimeSet = void 0;
1975
+ runtimeSetPromise = void 0;
1976
+ await bundleRuntimeClassSetManager.reset();
1977
+ }
1978
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1979
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1980
+ runtimeSet = nextRuntimeSet;
1981
+ return nextRuntimeSet;
1982
+ } catch (error) {
1983
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1984
+ await bundleRuntimeClassSetManager.reset();
1985
+ }
1986
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1987
+ const task = require_recorder.collectRuntimeClassSet(runtimeState.twPatcher, {
1988
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1989
+ skipRefresh: forceRuntimeRefresh,
1990
+ clearCache: forceRuntimeRefresh || invalidation.changed
1991
+ });
1992
+ runtimeSetPromise = task;
1993
+ try {
1994
+ runtimeSet = await task;
1995
+ return runtimeSet;
1996
+ } finally {
1997
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1998
+ }
1999
+ }
2000
+ onLoad();
2001
+ const getResolvedConfig = () => resolvedConfig;
2002
+ const markCssAssetProcessed = (asset, file) => {
2003
+ processedCssAssets.add(asset);
2004
+ if (file) processedCssAssetFiles.add(require_css_imports.normalizeOutputPathKey(file));
2005
+ };
2006
+ const isCssAssetProcessed = (asset, file) => {
2007
+ return processedCssAssets.has(asset) || (file ? processedCssAssetFiles.has(require_css_imports.normalizeOutputPathKey(file)) : false);
2008
+ };
2009
+ const recordGeneratorCandidates = (candidates) => {
2010
+ recordedGeneratorCandidates = new Set(candidates);
2011
+ };
2012
+ const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2013
+ const getSourceCandidates = () => sourceCandidateCollector.values();
2014
+ const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
2015
+ const waitForSourceCandidateSyncs = async () => {
2016
+ while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2017
+ };
2018
+ const syncChangedSourceCandidateFile = (id) => {
2019
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return Promise.resolve();
2020
+ const task = sourceCandidateCollector.syncFile(id).catch((error) => {
2021
+ debug("source candidate watch sync failed: %s %O", id, error);
2022
+ }).finally(() => {
2023
+ pendingSourceCandidateSyncs.delete(task);
2024
+ });
2025
+ pendingSourceCandidateSyncs.add(task);
2026
+ return task;
2027
+ };
2028
+ const rememberMainCssSource = (file, rawSource, cssRuntimeSignature) => {
2029
+ rememberedMainCssSources.set(file, rawSource);
2030
+ if (cssRuntimeSignature) rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2031
+ };
2032
+ const getRememberedMainCssSources = () => rememberedMainCssSources;
2033
+ const getRememberedMainCssSignature = (file) => rememberedMainCssSignatureByFile.get(file);
2034
+ const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2035
+ rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2036
+ };
2037
+ const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2038
+ opts,
2039
+ runtimeState,
2040
+ ensureRuntimeClassSet,
2041
+ debug,
2042
+ getResolvedConfig,
2043
+ markCssAssetProcessed,
2044
+ isCssAssetProcessed,
2045
+ getRecordedGeneratorCandidates,
2046
+ getSourceCandidates,
2047
+ waitForSourceCandidateSyncs,
2048
+ rememberMainCssSource
2049
+ });
2050
+ const isIosPlatform = require_utils.resolveUniUtsPlatform().isAppIos;
2051
+ const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
2052
+ appType: opts.appType ?? "uni-app-x",
2053
+ customAttributesEntities,
2054
+ disabledDefaultTemplateHandler,
2055
+ isIosPlatform,
2056
+ mainCssChunkMatcher,
2057
+ runtimeState,
2058
+ styleHandler,
2059
+ jsHandler,
2060
+ ensureRuntimeClassSet,
2061
+ getResolvedConfig,
2062
+ uniAppX
2063
+ }) : void 0;
2064
+ const plugins = [
2065
+ ...rewritePlugins,
2066
+ {
2067
+ name: `${require_recorder.vitePluginName}:source-candidates`,
2068
+ enforce: "pre",
2069
+ async transform(code, id) {
2070
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return;
2071
+ await sourceCandidateCollector.sync(id, code);
2072
+ },
2073
+ async watchChange(id, change) {
2074
+ if (change.event === "delete") {
2075
+ sourceCandidateCollector.remove(id);
2076
+ return;
2077
+ }
2078
+ await syncChangedSourceCandidateFile(id);
2079
+ },
2080
+ async handleHotUpdate(ctx) {
2081
+ await syncChangedSourceCandidateFile(ctx.file);
2082
+ },
2083
+ async buildStart() {
2084
+ if (!shouldOwnTailwindGeneration) return;
2085
+ if (resolvedConfig?.command === "build" && !isWatchBuild()) sourceCandidateCollector.clear();
2086
+ const root = resolvedConfig?.root ?? node_process.default.cwd();
2087
+ const outDir = resolvedConfig?.build?.outDir;
2088
+ await sourceCandidateCollector.scanRoot({
2089
+ root,
2090
+ outDir
2091
+ });
2092
+ }
2093
+ },
2094
+ {
2095
+ name: `${require_recorder.vitePluginName}:post`,
2096
+ enforce: "post",
2097
+ config(config) {
2098
+ if (!shouldOwnTailwindGeneration) return;
2099
+ if (Array.isArray(config.plugins)) {
2100
+ const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
2101
+ if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
2102
+ }
2103
+ const root = config.root ? node_path.default.resolve(config.root) : node_process.default.cwd();
2104
+ const baseConfig = { resolve: { alias: [{
2105
+ find: /^tailwindcss$/,
2106
+ replacement: node_path.default.join(weappTailwindcssPackageDir, "generator-placeholder.css")
2107
+ }] } };
2108
+ if (config.css?.postcss !== void 0) return baseConfig;
2109
+ return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
2110
+ if (!postcssConfig) return baseConfig;
2111
+ debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
2112
+ return {
2113
+ ...baseConfig,
2114
+ css: { postcss: {
2115
+ ...postcssConfig.options,
2116
+ plugins: postcssConfig.plugins
2117
+ } }
2118
+ };
2119
+ });
2120
+ },
2121
+ async configResolved(config) {
2122
+ resolvedConfig = config;
2123
+ if (shouldOwnTailwindGeneration) {
2124
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2125
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2126
+ }
2127
+ const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
2128
+ let shouldRefreshRuntime = false;
2129
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2130
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2131
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2132
+ const previousBasedir = opts.tailwindcssBasedir;
2133
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
2134
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2135
+ shouldRefreshRuntime = true;
2136
+ }
2137
+ }
2138
+ if (!hasExplicitAppType && resolvedRoot) {
2139
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2140
+ if (nextAppType && opts.appType !== nextAppType) {
2141
+ const previousAppType = opts.appType;
2142
+ opts.appType = nextAppType;
2143
+ _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2144
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2145
+ shouldRefreshRuntime = true;
2146
+ }
2147
+ }
2148
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
2149
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2150
+ const postcssPlugins = config.css.postcss.plugins;
2151
+ if (shouldOwnTailwindGeneration) {
2152
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
2153
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2154
+ }
2155
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2156
+ if (idx > -1) {
2157
+ postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
2158
+ debug("remove postcss-html-transform plugin from vite config");
2159
+ }
2160
+ }
2161
+ },
2162
+ generateBundle: {
2163
+ order: "post",
2164
+ handler: createGenerateBundleHook({
2165
+ opts,
2166
+ runtimeState,
2167
+ ensureRuntimeClassSet,
2168
+ ensureBundleRuntimeClassSet,
2169
+ debug,
2170
+ getResolvedConfig,
2171
+ markCssAssetProcessed,
2172
+ getSourceCandidates,
2173
+ waitForSourceCandidateSyncs,
2174
+ rememberMainCssSource,
2175
+ getRememberedMainCssSources,
2176
+ getRememberedMainCssSignature,
2177
+ setRememberedMainCssSignature,
2178
+ recordGeneratorCandidates
2179
+ })
2180
+ },
2181
+ outputOptions(options) {
2182
+ const plugins = options.plugins;
2183
+ return {
2184
+ ...options,
2185
+ plugins: Array.isArray(plugins) ? [...plugins, cssFinalizerOutputPlugin] : [cssFinalizerOutputPlugin]
2186
+ };
2187
+ }
2188
+ }
2189
+ ];
2190
+ if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
2191
+ return plugins;
2192
+ }
2193
+ //#endregion
2194
+ Object.defineProperty(exports, "UnifiedViteWeappTailwindcssPlugin", {
2195
+ enumerable: true,
2196
+ get: function() {
2197
+ return UnifiedViteWeappTailwindcssPlugin;
2198
+ }
2199
+ });