weapp-tailwindcss 5.0.0-next.2 → 5.0.0-next.21

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