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