weapp-tailwindcss 5.0.0-next.9 → 5.0.1

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