weapp-tailwindcss 5.0.6 → 5.0.8

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 (103) hide show
  1. package/dist/{bundle-state-CdNXQl-o.mjs → bundle-state-5FtFktJr.mjs} +2 -1
  2. package/dist/{bundle-state-CFgzVHFP.js → bundle-state-cHwTyrOS.js} +2 -1
  3. package/dist/bundlers/gulp/index.d.ts +3 -4
  4. package/dist/bundlers/gulp/module-graph.d.ts +2 -0
  5. package/dist/bundlers/gulp/runtime-snapshot.d.ts +5 -0
  6. package/dist/bundlers/gulp/vinyl-transform.d.ts +3 -0
  7. package/dist/bundlers/shared/css-cleanup.d.ts +1 -1
  8. package/dist/bundlers/shared/css-source-trace.d.ts +20 -0
  9. package/dist/bundlers/shared/generator-css/directives/fallback.d.ts +11 -0
  10. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +56 -0
  11. package/dist/bundlers/shared/generator-css/local-imports.d.ts +7 -0
  12. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +1 -1
  13. package/dist/bundlers/shared/generator-css/types.d.ts +27 -0
  14. package/dist/bundlers/shared/generator-css/user-css.d.ts +26 -0
  15. package/dist/bundlers/shared/generator-css/validate.d.ts +5 -0
  16. package/dist/bundlers/shared/generator-css.d.ts +4 -32
  17. package/dist/bundlers/vite/css-finalizer.d.ts +3 -0
  18. package/dist/bundlers/vite/generate-bundle/css-config-directives.d.ts +2 -0
  19. package/dist/bundlers/vite/generate-bundle/css-output.d.ts +14 -0
  20. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +11 -0
  21. package/dist/bundlers/vite/generate-bundle/sfc-style-source.d.ts +9 -0
  22. package/dist/bundlers/vite/generate-bundle/style-matching.d.ts +5 -0
  23. package/dist/bundlers/vite/generate-bundle/subpackages.d.ts +7 -0
  24. package/dist/bundlers/vite/generate-bundle/types.d.ts +68 -0
  25. package/dist/bundlers/vite/generate-bundle.d.ts +4 -62
  26. package/dist/bundlers/vite/incremental-runtime-class-set/entries.d.ts +4 -0
  27. package/dist/bundlers/vite/incremental-runtime-class-set/escaped-candidates.d.ts +2 -0
  28. package/dist/bundlers/vite/incremental-runtime-class-set/v3-candidates.d.ts +13 -0
  29. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +1 -0
  30. package/dist/bundlers/vite/processed-css-assets/css-rules.d.ts +17 -0
  31. package/dist/bundlers/vite/processed-css-assets.d.ts +2 -0
  32. package/dist/bundlers/vite/source-candidates/scan-root.d.ts +10 -0
  33. package/dist/bundlers/vite/source-candidates/script.d.ts +7 -0
  34. package/dist/bundlers/vite/source-candidates/tailwind-v3-default-extractor.d.ts +1 -0
  35. package/dist/bundlers/vite/source-candidates.d.ts +8 -3
  36. package/dist/bundlers/vite/source-scan/css-entries.d.ts +20 -0
  37. package/dist/bundlers/vite/source-scan/dependencies.d.ts +2 -0
  38. package/dist/bundlers/vite/source-scan.d.ts +2 -12
  39. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/helpers.d.ts +48 -0
  40. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -20
  41. package/dist/cli.js +71 -69
  42. package/dist/cli.mjs +71 -69
  43. package/dist/core.js +1 -1
  44. package/dist/core.mjs +1 -1
  45. package/dist/{defaults-BPUuNYcD.js → defaults-Boc26eel.js} +1 -0
  46. package/dist/{defaults-8xrgzxFY.mjs → defaults-DH0ZQRhy.mjs} +1 -0
  47. package/dist/defaults.js +1 -1
  48. package/dist/defaults.mjs +1 -1
  49. package/dist/{generator-C56PJYxA.js → generator-C--TrAod.js} +1 -1
  50. package/dist/{generator-Bgn4m8An.mjs → generator-DnwUQOXB.mjs} +1 -1
  51. package/dist/generator.js +2 -2
  52. package/dist/generator.mjs +2 -2
  53. package/dist/gulp-5Tan5bHG.js +473 -0
  54. package/dist/gulp-B22YSGU_.mjs +463 -0
  55. package/dist/gulp.js +4 -414
  56. package/dist/gulp.mjs +1 -406
  57. package/dist/{incremental-runtime-class-set-Bmzdjlk0.js → hmr-timing-CscCNKb9.js} +1205 -449
  58. package/dist/{incremental-runtime-class-set-BEYHQkZc.mjs → hmr-timing-DK-mine6.mjs} +1169 -467
  59. package/dist/index.js +5 -5
  60. package/dist/index.mjs +5 -5
  61. package/dist/{postcss-BgINK7Nm.mjs → postcss-CjWuDZwL.mjs} +4 -4
  62. package/dist/{postcss-B7QNe78h.js → postcss-R5pDVHUy.js} +7 -7
  63. package/dist/postcss.js +1 -1
  64. package/dist/postcss.mjs +1 -1
  65. package/dist/{precheck-CyPbGn38.js → precheck-B8y6tDvG.js} +19 -5
  66. package/dist/{precheck-Copn2SqE.mjs → precheck-CcxTR7E_.mjs} +19 -5
  67. package/dist/presets.js +2 -2
  68. package/dist/presets.mjs +2 -2
  69. package/dist/tailwindcss/source-scan/inline-source.d.ts +7 -0
  70. package/dist/tailwindcss/source-scan.d.ts +2 -7
  71. package/dist/tailwindcss/v3-engine/generator/cache-key.d.ts +3 -0
  72. package/dist/tailwindcss/v3-engine/generator/content.d.ts +10 -0
  73. package/dist/tailwindcss/v3-engine/generator/runtime-ready.d.ts +2 -0
  74. package/dist/tailwindcss/v4-engine/generator/css-compat.d.ts +2 -0
  75. package/dist/tailwindcss/v4-engine/generator/rpx-candidates.d.ts +6 -0
  76. package/dist/tailwindcss/v4-engine/generator/scan-sources.d.ts +2 -0
  77. package/dist/tailwindcss/v4-engine/types.d.ts +1 -1
  78. package/dist/{tailwindcss-C0Zgo3Es.mjs → tailwindcss-0DaftXcU.mjs} +2 -2
  79. package/dist/{tailwindcss-Tw6CSVHL.js → tailwindcss-DbZ4o4m_.js} +2 -2
  80. package/dist/{transform-DgCFGtQR.mjs → transform-DRyWUN5X.mjs} +11 -2
  81. package/dist/{transform-95ivJthq.js → transform-DiW_u3eD.js} +11 -2
  82. package/dist/types/typedoc-tailwindcss-patch.d.ts +4 -2
  83. package/dist/types/user-defined-options/general.d.ts +5 -0
  84. package/dist/uni-app-x/component-local-style.d.ts +1 -0
  85. package/dist/uni-app-x/harmony.d.ts +1 -0
  86. package/dist/uni-app-x/style-asset/style-value.d.ts +16 -0
  87. package/dist/uni-app-x/style-asset.d.ts +20 -0
  88. package/dist/uni-app-x/transform.d.ts +1 -0
  89. package/dist/uni-app-x/vite.d.ts +1 -0
  90. package/dist/{v3-engine-Ji6AXPh2.mjs → v3-engine-ArQVHEau.mjs} +786 -699
  91. package/dist/{v3-engine-6FVAcrZl.js → v3-engine-DdlvXpID.js} +788 -701
  92. package/dist/{vite-Bw6LOXvf.js → vite-C_IUnDBy.js} +1797 -386
  93. package/dist/{vite-ChZ2cbn4.mjs → vite-_iUhzc4t.mjs} +1779 -369
  94. package/dist/vite.js +1 -1
  95. package/dist/vite.mjs +1 -1
  96. package/dist/weapp-tw-css-import-rewrite-loader.js +1148 -987
  97. package/dist/{webpack-CMJ7iqN7.mjs → webpack-CqnI4Ymw.mjs} +104 -37
  98. package/dist/{webpack-nn3P8_S_.js → webpack-KLoTb5Dr.js} +113 -45
  99. package/dist/webpack.js +1 -1
  100. package/dist/webpack.mjs +1 -1
  101. package/package.json +6 -5
  102. package/dist/source-candidates-BODCmzz5.mjs +0 -355
  103. package/dist/source-candidates-Caf2GDvx.js +0 -374
@@ -1,20 +1,19 @@
1
1
  const require_chunk = require("./chunk-emK7D4bc.js");
2
- const require_v3_engine = require("./v3-engine-6FVAcrZl.js");
3
- const require_generator = require("./generator-C56PJYxA.js");
4
- const require_precheck = require("./precheck-CyPbGn38.js");
2
+ const require_v3_engine = require("./v3-engine-DdlvXpID.js");
3
+ const require_generator = require("./generator-C--TrAod.js");
4
+ const require_precheck = require("./precheck-B8y6tDvG.js");
5
5
  const require_utils = require("./utils-Dolmt8EO.js");
6
- const require_tailwindcss = require("./tailwindcss-Tw6CSVHL.js");
7
- const require_incremental_runtime_class_set = require("./incremental-runtime-class-set-Bmzdjlk0.js");
8
- const require_source_candidates = require("./source-candidates-Caf2GDvx.js");
9
- const require_bundle_state = require("./bundle-state-CFgzVHFP.js");
6
+ const require_tailwindcss = require("./tailwindcss-DbZ4o4m_.js");
7
+ const require_hmr_timing = require("./hmr-timing-CscCNKb9.js");
8
+ const require_bundle_state = require("./bundle-state-cHwTyrOS.js");
10
9
  require("./logger-TlKT3xmR.js");
11
- let node_fs = require("node:fs");
12
- node_fs = require_chunk.__toESM(node_fs);
13
10
  let postcss = require("postcss");
14
11
  postcss = require_chunk.__toESM(postcss);
15
12
  let tailwindcss_patch = require("tailwindcss-patch");
16
13
  let node_process = require("node:process");
17
14
  node_process = require_chunk.__toESM(node_process);
15
+ let node_fs = require("node:fs");
16
+ node_fs = require_chunk.__toESM(node_fs);
18
17
  let node_path = require("node:path");
19
18
  node_path = require_chunk.__toESM(node_path);
20
19
  let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
@@ -23,9 +22,16 @@ let node_buffer = require("node:buffer");
23
22
  let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
24
23
  _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
25
24
  let comment_json = require("comment-json");
25
+ let postcss_selector_parser = require("postcss-selector-parser");
26
+ postcss_selector_parser = require_chunk.__toESM(postcss_selector_parser);
26
27
  let postcss_load_config = require("postcss-load-config");
27
28
  postcss_load_config = require_chunk.__toESM(postcss_load_config);
28
29
  let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
30
+ //#region src/uni-app-x/harmony.ts
31
+ function isUniAppXHarmonyOutDir(outDir) {
32
+ return typeof outDir === "string" && /(?:^|[/\\])\.?app-harmony(?:[/\\]|$)/.test(outDir);
33
+ }
34
+ //#endregion
29
35
  //#region src/bundlers/vite/query.ts
30
36
  function parseVueRequest(id) {
31
37
  const [filename = id, rawQuery] = id.split(`?`, 2);
@@ -45,6 +51,419 @@ function parseVueRequest(id) {
45
51
  };
46
52
  }
47
53
  //#endregion
54
+ //#region src/uni-app-x/style-asset/style-value.ts
55
+ const GEN_APP_STYLES_RE = /const\s+GenAppStyles\s*=\s*\[_uM\(\[([\s\S]*?)\]\)\]/;
56
+ const STYLE_ENTRY_RE = /\[\s*("((?:\\.|[^"\\])+)")\s*,\s*(_pS\(_uM\(\[[\s\S]*?\]\)\))\s*\]/g;
57
+ const STRING_LITERAL_RE = /(['"`])((?:\\.|(?!\1)[\s\S])*?)\1/g;
58
+ const SFC_STYLE_BLOCK_RE$2 = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
59
+ const STYLE_EXPORT_PREFIX_RE = /^\s*export\s+default\s+/;
60
+ const CLASS_SELECTOR_PREFIX_RE = /^\.((?:\\[^\n\r\f]|[\w-])+)(?=$|[.:#[])/;
61
+ function toCamelCase(prop) {
62
+ return prop.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
63
+ }
64
+ function normalizeValue(value) {
65
+ const trimmed = value.trim();
66
+ if (/^-?\d+(?:\.\d+)?px$/.test(trimmed)) return Number(trimmed.slice(0, -2));
67
+ return trimmed.replace(/\s*,\s*/g, ",");
68
+ }
69
+ function normalizeStyleValue(value) {
70
+ if (typeof value === "number") return value;
71
+ return normalizeValue(value);
72
+ }
73
+ function unescapeCssClassSelector(className) {
74
+ return className.replace(/\\([^\n\r\f0-9a-f])/gi, "$1");
75
+ }
76
+ function parseStyleExport(source) {
77
+ const json = source.replace(STYLE_EXPORT_PREFIX_RE, "").trim();
78
+ if (!json) return;
79
+ try {
80
+ return JSON.parse(json);
81
+ } catch {}
82
+ }
83
+ function parseStyleObject(source) {
84
+ try {
85
+ return JSON.parse(source);
86
+ } catch {}
87
+ }
88
+ function parseSourceMapSourcesContent(source) {
89
+ try {
90
+ const map = JSON.parse(source);
91
+ return Array.isArray(map.sourcesContent) ? map.sourcesContent.filter((item) => typeof item === "string") : [];
92
+ } catch {
93
+ return [];
94
+ }
95
+ }
96
+ function collectChunkMapSourcesContent(chunk) {
97
+ const map = chunk.map;
98
+ return Array.isArray(map?.sourcesContent) ? map.sourcesContent.filter((item) => typeof item === "string") : [];
99
+ }
100
+ function styleExportToUtsMap(styleExport) {
101
+ const classEntries = [];
102
+ for (const [className, styleStates] of Object.entries(styleExport)) {
103
+ const declarations = styleStates[""];
104
+ if (!declarations || Object.keys(declarations).length === 0) continue;
105
+ const declarationEntries = Object.entries(declarations).map(([prop, value]) => {
106
+ return `[${JSON.stringify(toCamelCase(prop))}, ${JSON.stringify(normalizeStyleValue(value))}]`;
107
+ });
108
+ if (declarationEntries.length === 0) continue;
109
+ classEntries.push(`[${JSON.stringify(className)}, _pS(_uM([${declarationEntries.join(", ")}]))]`);
110
+ }
111
+ if (classEntries.length === 0) return "[]";
112
+ return `[_uM([${classEntries.join(", ")}])]`;
113
+ }
114
+ function createUtsStyleArray(entries) {
115
+ if (entries.length === 0) return "[]";
116
+ return `[_uM([${entries.join(", ")}])]`;
117
+ }
118
+ function extractAppStyleEntries(source) {
119
+ const match = source.match(GEN_APP_STYLES_RE);
120
+ if (!match?.[1]) return;
121
+ const entries = /* @__PURE__ */ new Map();
122
+ for (const entry of match[1].matchAll(STYLE_ENTRY_RE)) {
123
+ const rawClassName = entry[1];
124
+ const className = entry[2];
125
+ const styleValue = entry[3];
126
+ if (!rawClassName || !className || !styleValue) continue;
127
+ entries.set(JSON.parse(rawClassName), `[${rawClassName}, ${styleValue}]`);
128
+ }
129
+ return entries.size > 0 ? entries : void 0;
130
+ }
131
+ function collectUsedClassNames(code, entries) {
132
+ const used = /* @__PURE__ */ new Set();
133
+ for (const literalMatch of code.matchAll(STRING_LITERAL_RE)) {
134
+ const literal = literalMatch[2];
135
+ if (!literal) continue;
136
+ for (const candidate of (0, tailwindcss_patch.splitCandidateTokens)(literal)) if (entries.has(candidate)) used.add(candidate);
137
+ }
138
+ return used;
139
+ }
140
+ function collectUsedStyleKeys(code, styleValue) {
141
+ return collectUsedClassNames(code, new Map(Object.keys(styleValue).map((className) => [className, className])));
142
+ }
143
+ function createUtsStyleArrayFromAppStyles(code, appSource) {
144
+ if (!appSource) return;
145
+ const entries = extractAppStyleEntries(appSource);
146
+ if (!entries) return;
147
+ const used = collectUsedClassNames(code, entries);
148
+ if (used.size === 0) return;
149
+ return createUtsStyleArray([...used].map((className) => entries.get(className)).filter(Boolean));
150
+ }
151
+ function cssToStyleExport(source) {
152
+ let root;
153
+ try {
154
+ root = postcss.default.parse(source);
155
+ } catch {
156
+ return;
157
+ }
158
+ const result = {};
159
+ root.walkRules((rule) => {
160
+ const selectors = rule.selectors ?? [];
161
+ for (const selector of selectors) {
162
+ const match = selector.trim().match(CLASS_SELECTOR_PREFIX_RE);
163
+ if (!match?.[1]) continue;
164
+ const declarations = {};
165
+ rule.walkDecls((decl) => {
166
+ declarations[toCamelCase(decl.prop)] = normalizeValue(decl.value);
167
+ });
168
+ if (Object.keys(declarations).length > 0) {
169
+ result[match[1]] = { "": declarations };
170
+ const className = unescapeCssClassSelector(match[1]);
171
+ result[className] = { "": declarations };
172
+ result[require_precheck.replaceWxml(className)] = { "": declarations };
173
+ }
174
+ }
175
+ });
176
+ return Object.keys(result).length > 0 ? result : void 0;
177
+ }
178
+ function cssSourceToStyleValue(source) {
179
+ return STYLE_EXPORT_PREFIX_RE.test(source) ? parseStyleExport(source) : cssToStyleExport(source);
180
+ }
181
+ function mergeStyleValues(...items) {
182
+ const result = {};
183
+ for (const item of items) {
184
+ if (!item) continue;
185
+ for (const [className, states] of Object.entries(item)) if (!result[className]) result[className] = states;
186
+ }
187
+ return Object.keys(result).length > 0 ? result : void 0;
188
+ }
189
+ function createStyleValueFromApplySources(sources, utilityStyles) {
190
+ if (!utilityStyles) return;
191
+ const result = {};
192
+ for (const source of sources) {
193
+ const styleSources = source.includes("<style") ? [...source.matchAll(SFC_STYLE_BLOCK_RE$2)].map((styleBlock) => styleBlock[1] ?? "") : [source];
194
+ for (const styleSource of styleSources) {
195
+ let root;
196
+ try {
197
+ root = postcss.default.parse(styleSource);
198
+ } catch {
199
+ continue;
200
+ }
201
+ root.walkRules((rule) => {
202
+ const applyRules = rule.nodes?.filter((node) => node.type === "atrule" && node.name === "apply") ?? [];
203
+ if (applyRules.length === 0) return;
204
+ const selectors = rule.selectors ?? [rule.selector];
205
+ for (const selector of selectors) {
206
+ const className = selector.trim().match(CLASS_SELECTOR_PREFIX_RE)?.[1];
207
+ if (!className) continue;
208
+ const declarations = {};
209
+ for (const applyRule of applyRules) for (const utility of (0, tailwindcss_patch.splitCandidateTokens)(applyRule.params)) {
210
+ const utilityDeclarations = utilityStyles[utility]?.[""] ?? utilityStyles[require_precheck.replaceWxml(utility)]?.[""];
211
+ if (utilityDeclarations) Object.assign(declarations, utilityDeclarations);
212
+ }
213
+ if (Object.keys(declarations).length > 0) {
214
+ const unescapedClassName = unescapeCssClassSelector(className);
215
+ result[className] = { "": declarations };
216
+ result[unescapedClassName] = { "": declarations };
217
+ result[require_precheck.replaceWxml(unescapedClassName)] = { "": declarations };
218
+ }
219
+ }
220
+ });
221
+ }
222
+ }
223
+ return Object.keys(result).length > 0 ? result : void 0;
224
+ }
225
+ function collectUniAppXHarmonyApplyStyleSourcesFromSource(source) {
226
+ return (source.includes("<style") ? [...source.matchAll(SFC_STYLE_BLOCK_RE$2)].map((styleBlock) => styleBlock[1] ?? "") : [source]).map((styleSource) => styleSource.trim()).filter((styleSource) => styleSource.length > 0 && styleSource.includes("@apply"));
227
+ }
228
+ function collectUniAppXHarmonyApplyUtilitiesFromSources(sources) {
229
+ const utilities = /* @__PURE__ */ new Set();
230
+ for (const source of sources) for (const styleSource of collectUniAppXHarmonyApplyStyleSourcesFromSource(source)) {
231
+ let root;
232
+ try {
233
+ root = postcss.default.parse(styleSource);
234
+ } catch {
235
+ continue;
236
+ }
237
+ root.walkAtRules("apply", (rule) => {
238
+ for (const utility of (0, tailwindcss_patch.splitCandidateTokens)(rule.params)) utilities.add(utility);
239
+ });
240
+ }
241
+ return utilities;
242
+ }
243
+ function createMergedStyleValue(code, localStyle, appStyle) {
244
+ const used = collectUsedStyleKeys(code, appStyle);
245
+ if (used.size === 0) return;
246
+ const merged = { ...localStyle ?? {} };
247
+ let changed = false;
248
+ for (const className of used) {
249
+ if (merged[className] || !appStyle[className]) continue;
250
+ merged[className] = appStyle[className];
251
+ changed = true;
252
+ }
253
+ return changed ? merged : void 0;
254
+ }
255
+ //#endregion
256
+ //#region src/uni-app-x/style-asset.ts
257
+ const GEN_STYLES_PLACEHOLDER_RE = /\/\*(Gen[A-Za-z0-9]+Styles)\*\/|const\s+(Gen[A-Za-z0-9]+Styles)\s*=\s*\[\]/;
258
+ const UVUE_TS_RE = /\.uvue\.ts$/;
259
+ const JS_RE = /\.js$/;
260
+ const APP_JS_RE = /(?:^|\/)App\.js$/;
261
+ const COMPONENT_JS_RE = /(?:^|\/)components\/.+\.js$/;
262
+ const HARMONY_BUNDLE_MARKER_FILES = new Set([
263
+ "import/app-service.ets",
264
+ "import/dynamic.ets",
265
+ "uni_modules/oh-package.json5"
266
+ ]);
267
+ const STYLE_DECL_RE = /const\s+(_style_\d+)\s*=\s*\{/g;
268
+ const EXPORT_SFC_RE = /_export_sfc\(_sfc_main\s*,\s*\[/;
269
+ const UNI_APP_X_STYLE_PLACEHOLDER_VERSION = "uni-app-x-style-placeholder-v2";
270
+ function createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, _applyUtilities) {
271
+ return applyStyleSources.join("\n");
272
+ }
273
+ function collectUniAppXHarmonyApplyUtilities(bundle) {
274
+ const utilities = /* @__PURE__ */ new Set();
275
+ const getBundleSource = createUniAppXBundleAssetSourceGetter(bundle);
276
+ for (const [file, item] of Object.entries(bundle)) {
277
+ if (item.type !== "chunk" || !file.endsWith(".js") || APP_JS_RE.test(file)) continue;
278
+ const mapSources = collectChunkMapSourcesContent(item).concat(resolveSourceMapFiles(file).flatMap((mapFile) => {
279
+ const source = getBundleSource(mapFile);
280
+ return source ? parseSourceMapSourcesContent(source) : [];
281
+ }));
282
+ for (const source of mapSources) for (const utility of collectUniAppXHarmonyApplyUtilitiesFromSources([source])) utilities.add(utility);
283
+ }
284
+ return utilities;
285
+ }
286
+ function collectUniAppXHarmonyApplyStyleSources(bundle) {
287
+ const sources = /* @__PURE__ */ new Set();
288
+ const getBundleSource = createUniAppXBundleAssetSourceGetter(bundle);
289
+ const addSource = (source) => {
290
+ for (const styleSource of collectUniAppXHarmonyApplyStyleSourcesFromSource(source)) sources.add(styleSource);
291
+ };
292
+ for (const [file, item] of Object.entries(bundle)) {
293
+ if (item.type === "asset" && file.endsWith(".uvue")) {
294
+ addSource(String(item.source));
295
+ continue;
296
+ }
297
+ if (item.type !== "chunk" || !file.endsWith(".js") || APP_JS_RE.test(file)) continue;
298
+ for (const sourceContent of collectChunkMapSourcesContent(item)) addSource(sourceContent);
299
+ for (const mapFile of resolveSourceMapFiles(file)) {
300
+ const source = getBundleSource(mapFile);
301
+ if (!source) continue;
302
+ for (const sourceContent of parseSourceMapSourcesContent(source)) addSource(sourceContent);
303
+ }
304
+ }
305
+ return [...sources];
306
+ }
307
+ function resolveStyleAssetFile(file) {
308
+ if (!UVUE_TS_RE.test(file)) return;
309
+ return file.replace(/\.uvue\.ts$/, ".uvue");
310
+ }
311
+ function resolveStylePlaceholderFallbackFiles(file) {
312
+ const styleAssetFile = resolveStyleAssetFile(file);
313
+ if (!styleAssetFile) return [];
314
+ const base = styleAssetFile.replace(/\.uvue$/, "");
315
+ return [
316
+ styleAssetFile,
317
+ `${base}.wxss`,
318
+ `${base}.css`
319
+ ];
320
+ }
321
+ function findBalancedObjectEnd(source, start) {
322
+ let depth = 0;
323
+ let quote;
324
+ let escaped = false;
325
+ for (let index = start; index < source.length; index++) {
326
+ const char = source[index];
327
+ if (quote) {
328
+ if (escaped) escaped = false;
329
+ else if (char === "\\") escaped = true;
330
+ else if (char === quote) quote = void 0;
331
+ continue;
332
+ }
333
+ if (char === "\"" || char === "'" || char === "`") {
334
+ quote = char;
335
+ continue;
336
+ }
337
+ if (char === "{") {
338
+ depth++;
339
+ continue;
340
+ }
341
+ if (char === "}") {
342
+ depth--;
343
+ if (depth === 0) return index + 1;
344
+ }
345
+ }
346
+ }
347
+ function findFirstStyleObjectDecl(source) {
348
+ STYLE_DECL_RE.lastIndex = 0;
349
+ const match = STYLE_DECL_RE.exec(source);
350
+ const varName = match?.[1];
351
+ if (!match || !varName) return;
352
+ const objectStart = source.indexOf("{", match.index);
353
+ if (objectStart < 0) return;
354
+ const objectEnd = findBalancedObjectEnd(source, objectStart);
355
+ if (!objectEnd) return;
356
+ return {
357
+ end: source[objectEnd] === ";" ? objectEnd + 1 : objectEnd,
358
+ objectEnd,
359
+ objectStart,
360
+ objectText: source.slice(objectStart, objectEnd),
361
+ start: match.index,
362
+ varName
363
+ };
364
+ }
365
+ function resolveCssFallbackFiles(file) {
366
+ const files = [
367
+ "main.wxss",
368
+ "main.css",
369
+ "app.wxss",
370
+ "app.css"
371
+ ];
372
+ if (file.startsWith("assets/") && file.endsWith(".js")) {
373
+ const withoutAssets = file.slice(7).replace(/\.js$/, "");
374
+ files.push(`${withoutAssets}.wxss`, `${withoutAssets}.css`);
375
+ }
376
+ return files;
377
+ }
378
+ function resolveSourceMapFiles(file) {
379
+ return [
380
+ `${file}.map`,
381
+ file.startsWith("assets/") ? `${file.slice(7)}.map` : void 0,
382
+ file.startsWith("assets/") ? void 0 : `assets/${file}.map`
383
+ ].filter((item) => typeof item === "string");
384
+ }
385
+ function createStyleValueFromBundleSources(file, _code, getBundleSource, options = {}) {
386
+ const cssStyles = mergeStyleValues(...[...options.cssSources ?? []].map((source) => source ? cssSourceToStyleValue(source) : void 0), ...resolveCssFallbackFiles(file).map((cssFile) => {
387
+ const source = getBundleSource?.(cssFile);
388
+ return source ? cssSourceToStyleValue(source) : void 0;
389
+ }));
390
+ return mergeStyleValues(cssStyles, createStyleValueFromApplySources([...options.mapSources ?? [], ...resolveSourceMapFiles(file).flatMap((mapFile) => {
391
+ const source = getBundleSource?.(mapFile);
392
+ return source ? parseSourceMapSourcesContent(source) : [];
393
+ })].filter((source) => typeof source === "string"), cssStyles));
394
+ }
395
+ function injectStyleOption(code, styleVarName) {
396
+ if (code.includes("[\"styles\"")) return code;
397
+ const exportMatch = code.match(EXPORT_SFC_RE);
398
+ if (!exportMatch || exportMatch.index === void 0) return code;
399
+ const fileOptionIndex = code.indexOf("[\"__file\"", exportMatch.index);
400
+ if (fileOptionIndex < 0) return code;
401
+ return `${code.slice(0, fileOptionIndex)}["styles", [${styleVarName}]], ${code.slice(fileOptionIndex)}`;
402
+ }
403
+ function injectUniAppXStylePlaceholder(file, code, getAssetSource) {
404
+ const match = code.match(GEN_STYLES_PLACEHOLDER_RE);
405
+ const stylesName = match?.[1] ?? match?.[2];
406
+ if (!stylesName) return code;
407
+ if (!resolveStyleAssetFile(file)) return code;
408
+ const appStyleArray = createUtsStyleArrayFromAppStyles(code, getAssetSource?.("App.uvue.ts"));
409
+ if (appStyleArray) return code.replace(GEN_STYLES_PLACEHOLDER_RE, `const ${stylesName} = ${appStyleArray}`);
410
+ const styleSource = resolveStylePlaceholderFallbackFiles(file).map((candidate) => getAssetSource?.(candidate)).find((source) => typeof source === "string" && source.length > 0);
411
+ if (!styleSource) return code;
412
+ const styleExport = cssSourceToStyleValue(styleSource);
413
+ if (!styleExport) return code;
414
+ return code.replace(GEN_STYLES_PLACEHOLDER_RE, `const ${stylesName} = ${styleExportToUtsMap(styleExport)}`);
415
+ }
416
+ function injectUniAppXHarmonyGlobalStyles(file, code, getBundleSource, options = {}) {
417
+ if (!JS_RE.test(file) || APP_JS_RE.test(file)) return code;
418
+ if (options.excludeComponents && COMPONENT_JS_RE.test(file)) return code;
419
+ const appSource = getBundleSource?.("assets/App.js") ?? getBundleSource?.("App.js");
420
+ const appStyleDecl = appSource ? findFirstStyleObjectDecl(appSource) : void 0;
421
+ const appStyle = appStyleDecl ? parseStyleObject(appStyleDecl.objectText) : void 0;
422
+ const localStyleDecl = findFirstStyleObjectDecl(code);
423
+ const localStyle = localStyleDecl ? parseStyleObject(localStyleDecl.objectText) : void 0;
424
+ const styleSource = mergeStyleValues(appStyle, createStyleValueFromBundleSources(file, code, getBundleSource, options));
425
+ if (!styleSource) return code;
426
+ const mergedStyle = createMergedStyleValue(code, localStyle, styleSource);
427
+ if (!mergedStyle) return code;
428
+ const nextStyleSource = JSON.stringify(mergedStyle);
429
+ if (localStyleDecl) return `${code.slice(0, localStyleDecl.objectStart)}${nextStyleSource}${code.slice(localStyleDecl.objectEnd)}`;
430
+ const exportMatch = code.match(EXPORT_SFC_RE);
431
+ if (!exportMatch || exportMatch.index === void 0) return code;
432
+ const styleVarName = "_style_wt";
433
+ return injectStyleOption(`${code.slice(0, exportMatch.index)}const ${styleVarName} = ${nextStyleSource};\n${code.slice(exportMatch.index)}`, styleVarName);
434
+ }
435
+ function injectUniAppXHarmonyBundleStyles(bundle, options = {}) {
436
+ const getBundleSource = createUniAppXBundleAssetSourceGetter(bundle);
437
+ let changed = false;
438
+ for (const [file, item] of Object.entries(bundle)) {
439
+ if (item.type !== "chunk" || !file.endsWith(".js")) continue;
440
+ const currentSource = item.code;
441
+ const nextSource = injectUniAppXHarmonyGlobalStyles(file, currentSource, getBundleSource, {
442
+ ...options,
443
+ mapSources: collectChunkMapSourcesContent(item)
444
+ });
445
+ if (nextSource !== currentSource) {
446
+ item.code = nextSource;
447
+ changed = true;
448
+ }
449
+ }
450
+ return changed;
451
+ }
452
+ function isUniAppXHarmonyBundle(bundle) {
453
+ for (const file of Object.keys(bundle)) if (HARMONY_BUNDLE_MARKER_FILES.has(file)) return true;
454
+ return false;
455
+ }
456
+ function createUniAppXBundleAssetSourceGetter(bundle) {
457
+ return (file) => {
458
+ const item = bundle[file] ?? Object.entries(bundle).find(([key, value]) => {
459
+ return (value.type === "asset" || value.type === "chunk") && (key === file || key.endsWith(`/${file}`));
460
+ })?.[1];
461
+ if (!item) return;
462
+ if (item.type === "asset") return String(item.source);
463
+ if (item.type === "chunk") return String(item.code);
464
+ };
465
+ }
466
+ //#endregion
48
467
  //#region src/uni-app-x/style-isolation.ts
49
468
  const manifestCache = /* @__PURE__ */ new Map();
50
469
  function resolveUniAppXStyleIsolationEnabled(root) {
@@ -66,7 +485,7 @@ function resolveUniAppXStyleIsolationEnabled(root) {
66
485
  //#region src/uni-app-x/vite.ts
67
486
  let transformUVuePromise;
68
487
  function loadTransformUVue() {
69
- transformUVuePromise ?? (transformUVuePromise = Promise.resolve().then(() => require("./transform-95ivJthq.js")).then((mod) => mod.transformUVue));
488
+ transformUVuePromise ?? (transformUVuePromise = Promise.resolve().then(() => require("./transform-DiW_u3eD.js")).then((mod) => mod.transformUVue));
70
489
  return transformUVuePromise;
71
490
  }
72
491
  const preprocessorLangs = new Set([
@@ -100,9 +519,21 @@ function isCssModuleExport(code) {
100
519
  function createUniAppXPlugins(options) {
101
520
  const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, generateCss, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
102
521
  const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(uniAppX);
103
- const isIosPlatform = providedIosPlatform ?? require_utils.resolveUniUtsPlatform().isAppIos;
522
+ const utsPlatform = require_utils.resolveUniUtsPlatform();
523
+ const isIosPlatform = providedIosPlatform ?? utsPlatform.isAppIos;
524
+ const isHarmonyPlatform = utsPlatform.isAppHarmony;
104
525
  const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
105
526
  let componentLocalStyleEnabled;
527
+ const harmonyApplyStyleSources = /* @__PURE__ */ new Set();
528
+ const harmonyApplyUtilities = /* @__PURE__ */ new Set();
529
+ function rememberHarmonyApplySource(code) {
530
+ const styleSources = collectUniAppXHarmonyApplyStyleSourcesFromSource(code);
531
+ if (styleSources.length === 0) return;
532
+ for (const styleSource of styleSources) {
533
+ harmonyApplyStyleSources.add(styleSource);
534
+ for (const utility of collectUniAppXHarmonyApplyUtilitiesFromSources([styleSource])) harmonyApplyUtilities.add(utility);
535
+ }
536
+ }
106
537
  function shouldEnableComponentLocalStyle() {
107
538
  if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
108
539
  componentLocalStyleEnabled = false;
@@ -117,11 +548,20 @@ function createUniAppXPlugins(options) {
117
548
  componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
118
549
  return componentLocalStyleEnabled;
119
550
  }
551
+ function shouldEnableHarmonyPageLocalStyle() {
552
+ return isHarmonyPlatform && resolvedUniAppXOptions.componentLocalStyles.enabled;
553
+ }
554
+ function isHarmonyBuildTarget() {
555
+ if (require_utils.resolveUniUtsPlatform().isAppHarmony) return true;
556
+ return isUniAppXHarmonyOutDir(getResolvedConfig()?.build?.outDir);
557
+ }
120
558
  async function transformStyle(code, id, query, hookContext) {
121
559
  const parsed = query ?? parseVueRequest(id).query;
122
560
  if (require_bundle_state.isCSSRequest(id) || parsed.vue && parsed.type === "style") {
123
561
  if (isCssModuleExport(code)) return;
124
- const generatedCss = require_v3_engine.hasTailwindSourceDirectives(code, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(code) ? await generateCss?.(id, code, hookContext) : void 0;
562
+ const shouldGenerateCss = require_v3_engine.hasTailwindSourceDirectives(code, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(code);
563
+ rememberHarmonyApplySource(code);
564
+ const generatedCss = shouldGenerateCss ? await generateCss?.(id, code, hookContext) : void 0;
125
565
  const styleCode = typeof generatedCss === "string" && generatedCss.trim().length > 0 ? generatedCss : code;
126
566
  const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
127
567
  let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
@@ -176,19 +616,21 @@ function createUniAppXPlugins(options) {
176
616
  },
177
617
  async transform(code, id) {
178
618
  if (!UVUE_NVUE_QUERY_RE.test(id)) return;
619
+ rememberHarmonyApplySource(code);
179
620
  const resolvedConfig = getResolvedConfig();
180
621
  const isServeCommand = resolvedConfig?.command === "serve";
181
622
  const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
182
623
  const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
183
624
  const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
184
625
  const transformUVue = await loadTransformUVue();
185
- const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
186
- customAttributesEntities,
187
- disabledDefaultTemplateHandler,
188
- enableComponentLocalStyle: shouldEnableComponentLocalStyle()
189
- } : void 0;
190
- if (extraOptions) return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
191
- if (shouldEnableComponentLocalStyle()) return transformUVue(code, id, jsHandler, currentRuntimeSet, { enableComponentLocalStyle: true });
626
+ const enableComponentLocalStyle = shouldEnableComponentLocalStyle();
627
+ const enablePageLocalStyle = shouldEnableHarmonyPageLocalStyle();
628
+ if (customAttributesEntities.length > 0 || disabledDefaultTemplateHandler || enableComponentLocalStyle || enablePageLocalStyle) return transformUVue(code, id, jsHandler, currentRuntimeSet, require_v3_engine.omitUndefined({
629
+ ...customAttributesEntities.length > 0 ? { customAttributesEntities } : {},
630
+ ...disabledDefaultTemplateHandler ? { disabledDefaultTemplateHandler } : {},
631
+ ...enableComponentLocalStyle ? { enableComponentLocalStyle } : {},
632
+ ...enablePageLocalStyle ? { enablePageLocalStyle } : {}
633
+ }));
192
634
  return transformUVue(code, id, jsHandler, currentRuntimeSet);
193
635
  },
194
636
  async handleHotUpdate(ctx) {
@@ -203,14 +645,52 @@ function createUniAppXPlugins(options) {
203
645
  await ensureRuntimeClassSet(true);
204
646
  }
205
647
  };
206
- return [...cssPlugins, nvuePlugin];
648
+ const stylePlaceholderPlugin = {
649
+ name: "weapp-tailwindcss:uni-app-x:style-placeholder",
650
+ enforce: "post",
651
+ generateBundle: {
652
+ order: "post",
653
+ async handler(_options, bundle) {
654
+ const currentUtsPlatform = require_utils.resolveUniUtsPlatform();
655
+ const canInferHarmonyTarget = !currentUtsPlatform.normalized || currentUtsPlatform.isApp;
656
+ const isHarmonyTarget = currentUtsPlatform.isAppHarmony || canInferHarmonyTarget && isHarmonyBuildTarget();
657
+ if (!currentUtsPlatform.isApp && !isHarmonyTarget) return;
658
+ const getAssetSource = createUniAppXBundleAssetSourceGetter(bundle);
659
+ if (isHarmonyTarget) {
660
+ const cssSources = [];
661
+ const applyStyleSources = [...harmonyApplyStyleSources, ...collectUniAppXHarmonyApplyStyleSources(bundle)];
662
+ const applyUtilities = new Set([...harmonyApplyUtilities, ...collectUniAppXHarmonyApplyUtilities(bundle)]);
663
+ if (applyStyleSources.length > 0 && applyUtilities.size > 0) {
664
+ const harmonyApplyCssFile = node_path.default.resolve(getResolvedConfig()?.root ?? node_process.default.cwd(), "uni-app-x-harmony-apply.css");
665
+ const generatedCss = await generateCss?.(harmonyApplyCssFile, createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities), this);
666
+ if (typeof generatedCss === "string" && generatedCss.trim().length > 0) cssSources.push(generatedCss);
667
+ }
668
+ injectUniAppXHarmonyBundleStyles(bundle, {
669
+ cssSources,
670
+ excludeComponents: shouldEnableComponentLocalStyle()
671
+ });
672
+ }
673
+ for (const [file, item] of Object.entries(bundle)) {
674
+ if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
675
+ const currentSource = String(item.source);
676
+ const nextSource = injectUniAppXStylePlaceholder(file, currentSource, getAssetSource);
677
+ if (nextSource !== currentSource) item.source = nextSource;
678
+ }
679
+ }
680
+ }
681
+ };
682
+ return [
683
+ ...cssPlugins,
684
+ nvuePlugin,
685
+ stylePlaceholderPlugin
686
+ ];
207
687
  }
208
688
  function createUniAppXAssetTask(file, originalSource, outDir, options) {
209
689
  return async () => {
210
- const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
690
+ const { cache, hashKey, createHandlerOptions, debug, getAssetSource, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
211
691
  const absoluteFile = require_bundle_state.toAbsoluteOutputPath(file, outDir);
212
692
  const rawSource = originalSource.source.toString();
213
- await require_incremental_runtime_class_set.processCachedTask({
693
+ await require_hmr_timing.processCachedTask({
214
694
  cache,
215
695
  cacheKey: file,
216
696
  hashKey,
@@ -230,10 +710,11 @@ function createUniAppXAssetTask(file, originalSource, outDir, options) {
230
710
  sourceType: "unambiguous"
231
711
  }
232
712
  }));
233
- onUpdate(file, currentSource, code);
713
+ const nextCode = injectUniAppXStylePlaceholder(file, code, getAssetSource);
714
+ onUpdate(file, currentSource, nextCode);
234
715
  debug("js handle: %s", file);
235
716
  applyLinkedResults(linked);
236
- return { result: code };
717
+ return { result: nextCode };
237
718
  }
238
719
  });
239
720
  };
@@ -309,6 +790,163 @@ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
309
790
  return new Set([...candidates, "container"]);
310
791
  }
311
792
  //#endregion
793
+ //#region src/bundlers/vite/generate-bundle/css-output.ts
794
+ const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
795
+ const CSS_SOURCE_OUTPUT_EXT_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/i;
796
+ const MINI_PROGRAM_STYLE_OUTPUT_EXT_RE = /\.(?:wx|ac|jx|tt|q|ty)ss$/i;
797
+ const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
798
+ function resolveReplayCssOutputFile(rootDir, file) {
799
+ const normalizedFile = require_bundle_state.normalizeOutputPathKey(node_path.default.isAbsolute(file) ? node_path.default.relative(rootDir, file) : file);
800
+ if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return require_bundle_state.normalizeOutputPathKey(node_path.default.basename(file));
801
+ return normalizedFile;
802
+ }
803
+ function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, preserveCssExtension = false) {
804
+ if (isWebGeneratorTarget || preserveCssExtension || opts.cssMatcher(file) || !SOURCE_STYLE_OUTPUT_EXT_RE.test(file) || !require_bundle_state.isCSSRequest(file)) return file;
805
+ return file.replace(SOURCE_STYLE_OUTPUT_EXT_RE, ".wxss");
806
+ }
807
+ function resolveViteCssPipelineOutputFile(file, _opts, rootDir, isWebGeneratorTarget = false, preserveCssExtension = false) {
808
+ const normalizedFile = resolveReplayCssOutputFile(rootDir, file);
809
+ if (isWebGeneratorTarget || preserveCssExtension || MINI_PROGRAM_STYLE_OUTPUT_EXT_RE.test(normalizedFile) || !CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedFile) || !require_bundle_state.isCSSRequest(normalizedFile)) return normalizedFile;
810
+ return normalizedFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".wxss");
811
+ }
812
+ function canProcessViteSourceStyleAsCss(source, file) {
813
+ if (SOURCE_STYLE_NON_CSS_SYNTAX_RE.test(source)) return false;
814
+ try {
815
+ postcss.default.parse(source, { from: file });
816
+ return true;
817
+ } catch {
818
+ return false;
819
+ }
820
+ }
821
+ function normalizeCssSourceForCompare(css) {
822
+ return css.trim();
823
+ }
824
+ function stripStyleFileExtension(file) {
825
+ const normalized = file.replace(/[?#].*$/, "");
826
+ const ext = node_path.default.extname(normalized);
827
+ return ext ? normalized.slice(0, -ext.length) : normalized;
828
+ }
829
+ function isAppOriginCssFile(file) {
830
+ return node_path.default.basename(stripStyleFileExtension(file)) === "app-origin";
831
+ }
832
+ function isMainAppCssFile(file) {
833
+ return node_path.default.basename(stripStyleFileExtension(file)) === "app";
834
+ }
835
+ function isMainStyleEntryCssFile(file) {
836
+ const basename = node_path.default.basename(stripStyleFileExtension(file));
837
+ return basename === "app" || basename === "main";
838
+ }
839
+ function isTailwindEntryCssFile(file) {
840
+ return node_path.default.basename(stripStyleFileExtension(file)) === "tailwind";
841
+ }
842
+ //#endregion
843
+ //#region src/bundlers/vite/generate-bundle/style-matching.ts
844
+ function isMatchingCssSourceFile(outputFile, cssSourceFile, outputRoot) {
845
+ return stripStyleFileExtension(node_path.default.resolve(outputRoot, outputFile)) === stripStyleFileExtension(node_path.default.resolve(cssSourceFile));
846
+ }
847
+ function collectStyleFileMatchBases(file, roots) {
848
+ const normalizedFile = file.replace(/[?#].*$/, "");
849
+ const bases = /* @__PURE__ */ new Set();
850
+ const addBase = (candidate) => {
851
+ const base = require_bundle_state.slash(stripStyleFileExtension(candidate));
852
+ if (base.length > 0) bases.add(base);
853
+ };
854
+ addBase(normalizedFile);
855
+ const resolvedRoots = roots.filter((root) => typeof root === "string" && root.length > 0).map((root) => node_path.default.resolve(root));
856
+ if (node_path.default.isAbsolute(normalizedFile)) for (const root of resolvedRoots) {
857
+ const relative = node_path.default.relative(root, normalizedFile);
858
+ if (relative && !relative.startsWith("..") && !node_path.default.isAbsolute(relative)) addBase(relative);
859
+ }
860
+ else for (const root of resolvedRoots) addBase(node_path.default.resolve(root, normalizedFile));
861
+ return bases;
862
+ }
863
+ function collectParentDirectories(file) {
864
+ const directories = [];
865
+ let current = node_path.default.dirname(node_path.default.resolve(file.replace(/[?#].*$/, "")));
866
+ while (true) {
867
+ directories.push(current);
868
+ const parent = node_path.default.dirname(current);
869
+ if (parent === current) break;
870
+ current = parent;
871
+ }
872
+ return directories;
873
+ }
874
+ function hasMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) {
875
+ return scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) > 0;
876
+ }
877
+ function scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) {
878
+ const outputBases = collectStyleFileMatchBases(outputFile, [outputRoot]);
879
+ const sourceBases = collectStyleFileMatchBases(sourceFile, [sourceRoot, ...collectParentDirectories(sourceFile)]);
880
+ let bestScore = 0;
881
+ const hasDirectorySegment = (value) => require_bundle_state.slash(value).includes("/");
882
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
883
+ else if (hasDirectorySegment(sourceBase) && outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
884
+ else if (hasDirectorySegment(outputBase) && sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
885
+ return bestScore;
886
+ }
887
+ //#endregion
888
+ //#region src/bundlers/vite/generate-bundle/css-config-directives.ts
889
+ function isPackageJsonImportRequest(request) {
890
+ return request.startsWith("#");
891
+ }
892
+ function normalizeMatchedCssSourcePath(file) {
893
+ if (!file || !node_path.default.isAbsolute(file)) return;
894
+ return node_path.default.resolve(file.replace(/[?#].*$/, ""));
895
+ }
896
+ function collectConfiguredTailwindV4CssSources(opts) {
897
+ const patcherCssSources = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssSources ?? [];
898
+ return [...opts.tailwindcss?.v4?.cssSources ?? [], ...patcherCssSources ?? []];
899
+ }
900
+ function collectConfiguredCssEntries(opts) {
901
+ const patcherCssEntries = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssEntries ?? [];
902
+ return [
903
+ ...opts.cssEntries ?? [],
904
+ ...opts.tailwindcss?.v4?.cssEntries ?? [],
905
+ ...patcherCssEntries ?? []
906
+ ].filter((entry) => typeof entry === "string" && entry.length > 0);
907
+ }
908
+ function collectCssConfigBaseCandidates(source, file, outputRoot, opts) {
909
+ const candidates = [];
910
+ const seen = /* @__PURE__ */ new Set();
911
+ const addCandidate = (candidate) => {
912
+ if (!candidate) return;
913
+ const normalized = node_path.default.resolve(candidate);
914
+ if (seen.has(normalized)) return;
915
+ seen.add(normalized);
916
+ candidates.push(normalized);
917
+ };
918
+ addCandidate(node_path.default.dirname(node_path.default.resolve(outputRoot, file.replace(/[?#].*$/, ""))));
919
+ const normalizedSource = normalizeCssSourceForCompare(source);
920
+ const patcherProjectRoot = typeof opts.tailwindcssPatcherOptions?.projectRoot === "string" ? opts.tailwindcssPatcherOptions.projectRoot : void 0;
921
+ const sourceBaseFallback = opts.tailwindcss?.v4?.base ?? patcherProjectRoot ?? opts.tailwindcssBasedir ?? outputRoot;
922
+ const sourceRoot = opts.tailwindcssBasedir ?? patcherProjectRoot;
923
+ const configuredCssEntries = collectConfiguredCssEntries(opts);
924
+ for (const cssEntry of configuredCssEntries) {
925
+ const resolvedCssEntry = node_path.default.resolve(cssEntry);
926
+ if (configuredCssEntries.length === 1 || isMatchingCssSourceFile(file, resolvedCssEntry, outputRoot) || hasMatchingStyleFileBase(file, resolvedCssEntry, outputRoot, sourceRoot)) addCandidate(node_path.default.dirname(resolvedCssEntry));
927
+ }
928
+ for (const cssSource of collectConfiguredTailwindV4CssSources(opts)) {
929
+ const cssSourceFile = normalizeMatchedCssSourcePath(cssSource.file);
930
+ const cssSourceCss = typeof cssSource.css === "string" ? normalizeCssSourceForCompare(cssSource.css) : void 0;
931
+ if (cssSourceFile && !isMatchingCssSourceFile(file, cssSourceFile, outputRoot) && cssSourceCss !== normalizedSource) continue;
932
+ addCandidate(cssSourceFile ? node_path.default.dirname(cssSourceFile) : void 0);
933
+ addCandidate(require_v3_engine.resolveTailwindV4CssSourceBase(cssSource, sourceBaseFallback));
934
+ }
935
+ return candidates;
936
+ }
937
+ function normalizeRelativeCssConfigDirectives(source, file, outputRoot, opts) {
938
+ if (!source.includes("@config")) return source;
939
+ const baseCandidates = collectCssConfigBaseCandidates(source, file, outputRoot, opts);
940
+ return source.replace(/@config\s+(["'])(.+?)\1\s*;?/g, (full, quote, request) => {
941
+ if (node_path.default.isAbsolute(request) || isPackageJsonImportRequest(request)) return full;
942
+ for (const base of baseCandidates) {
943
+ const configFile = node_path.default.resolve(base, request);
944
+ if ((0, node_fs.existsSync)(configFile)) return `@config ${quote}${require_bundle_state.slash(configFile)}${quote};`;
945
+ }
946
+ return full;
947
+ });
948
+ }
949
+ //#endregion
312
950
  //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
313
951
  function createCssHandlerOptionsCache(options) {
314
952
  const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
@@ -489,6 +1127,169 @@ function logBundleProcessPlan(options) {
489
1127
  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));
490
1128
  }
491
1129
  //#endregion
1130
+ //#region src/bundlers/vite/generate-bundle/sfc-style-source.ts
1131
+ const SFC_STYLE_SOURCE_EXTENSIONS = [
1132
+ ".vue",
1133
+ ".uvue",
1134
+ ".nvue",
1135
+ ".svelte",
1136
+ ".mpx"
1137
+ ];
1138
+ const SFC_STYLE_BLOCK_RE$1 = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
1139
+ function extractSfcStyleSources(source) {
1140
+ const styleSources = [];
1141
+ SFC_STYLE_BLOCK_RE$1.lastIndex = 0;
1142
+ let match = SFC_STYLE_BLOCK_RE$1.exec(source);
1143
+ while (match !== null) {
1144
+ styleSources.push(match[1] ?? "");
1145
+ match = SFC_STYLE_BLOCK_RE$1.exec(source);
1146
+ }
1147
+ return styleSources;
1148
+ }
1149
+ function hasSfcStyleSources(source) {
1150
+ return extractSfcStyleSources(source).length > 0;
1151
+ }
1152
+ function hasTailwindGenerationSource(source) {
1153
+ return require_v3_engine.hasTailwindSourceDirectives(source, { importFallback: true }) || require_v3_engine.hasTailwindRootDirectives(source, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(source);
1154
+ }
1155
+ async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, getSfcSource, debug) {
1156
+ const sourceFile = resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug);
1157
+ if (!sourceFile) {
1158
+ debug("sfc style source infer skipped: no source file for %s", outputFile);
1159
+ return;
1160
+ }
1161
+ const source = getSfcSource?.(sourceFile);
1162
+ if (source == null) {
1163
+ debug("sfc style source infer skipped: missing known source for %s -> %s", outputFile, sourceFile);
1164
+ return;
1165
+ }
1166
+ const rawSource = extractSfcStyleSources(source).join("\n");
1167
+ if (!rawSource || !hasTailwindGenerationSource(rawSource)) {
1168
+ debug("sfc style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
1169
+ return;
1170
+ }
1171
+ debug("sfc style source inferred: %s -> %s", outputFile, sourceFile);
1172
+ return {
1173
+ outputFile,
1174
+ rawSource,
1175
+ sourceFile
1176
+ };
1177
+ }
1178
+ function normalizeSfcSourceFileForCompare(file) {
1179
+ return require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1180
+ }
1181
+ function collectChunkModuleIds(output) {
1182
+ const moduleIds = Array.isArray(output.moduleIds) ? output.moduleIds : [];
1183
+ return [
1184
+ output.facadeModuleId,
1185
+ ...moduleIds,
1186
+ ...Object.keys(output.modules ?? {})
1187
+ ].filter((id, index, ids) => typeof id === "string" && id.length > 0 && ids.indexOf(id) === index);
1188
+ }
1189
+ function resolveSiblingJsChunkFile(outputFile) {
1190
+ const normalizedOutputFile = outputFile.replace(/[?#].*$/, "");
1191
+ if (MINI_PROGRAM_STYLE_OUTPUT_EXT_RE.test(normalizedOutputFile)) return normalizedOutputFile.replace(MINI_PROGRAM_STYLE_OUTPUT_EXT_RE, ".js");
1192
+ if (CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedOutputFile)) return normalizedOutputFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".js");
1193
+ }
1194
+ function normalizeSfcModuleId(id) {
1195
+ const file = id.replace(/[?#].*$/, "");
1196
+ if (!SFC_STYLE_SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension))) return;
1197
+ if (!node_path.default.isAbsolute(file)) return;
1198
+ return node_path.default.resolve(file);
1199
+ }
1200
+ function resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug) {
1201
+ const siblingJsFile = resolveSiblingJsChunkFile(outputFile);
1202
+ if (!siblingJsFile) {
1203
+ debug("sfc style sibling chunk skipped: no sibling js for %s", outputFile);
1204
+ return;
1205
+ }
1206
+ const normalizedSiblingJsFile = require_bundle_state.normalizeOutputPathKey(siblingJsFile);
1207
+ const siblingChunk = snapshot.entries.find((entry) => entry.type === "js" && entry.output.type === "chunk" && require_bundle_state.normalizeOutputPathKey(entry.file) === normalizedSiblingJsFile);
1208
+ if (!siblingChunk || siblingChunk.output.type !== "chunk") {
1209
+ debug("sfc style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
1210
+ return;
1211
+ }
1212
+ const sourceFiles = collectChunkModuleIds(siblingChunk.output).map(normalizeSfcModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
1213
+ if (sourceFiles.length === 0) {
1214
+ debug("sfc style sibling chunk skipped: no sfc modules for %s -> %s", outputFile, siblingJsFile);
1215
+ return;
1216
+ }
1217
+ const scoredSources = sourceFiles.map((sourceFile) => ({
1218
+ sourceFile,
1219
+ score: scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot)
1220
+ })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
1221
+ debug("sfc style sibling chunk candidates: %s -> %s %O", outputFile, siblingJsFile, scoredSources);
1222
+ const bestScore = scoredSources[0]?.score;
1223
+ if (!bestScore) return;
1224
+ const bestSources = scoredSources.filter((item) => item.score === bestScore);
1225
+ if (bestSources.length !== 1) {
1226
+ debug("sfc style sibling chunk skipped: ambiguous best sources for %s %O", outputFile, bestSources);
1227
+ return;
1228
+ }
1229
+ return bestSources[0]?.sourceFile;
1230
+ }
1231
+ //#endregion
1232
+ //#region src/bundlers/vite/generate-bundle/remembered-css.ts
1233
+ function createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash) {
1234
+ return `${cssRuntimeSignature}:${cssRuntimeAffectingHash}`;
1235
+ }
1236
+ function findRememberedCssSources(sources, outputFile, file, originalSource, outputRoot, sourceRoot) {
1237
+ if (!sources) return [];
1238
+ const rememberedSources = [...sources].map(([, remembered]) => remembered);
1239
+ const source = typeof originalSource.source === "string" ? originalSource.source : originalSource.source.toString();
1240
+ const markerFiles = new Set(require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(source).filter((block) => block.bundler === "vite" && typeof block.file === "string" && block.file.length > 0).map((block) => require_bundle_state.normalizeOutputPathKey(block.file)));
1241
+ if (markerFiles.size > 0) {
1242
+ const markerMatched = rememberedSources.filter((remembered) => markerFiles.has(require_bundle_state.normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, ""))));
1243
+ if (markerMatched.length > 0) return markerMatched;
1244
+ }
1245
+ const originalFiles = [
1246
+ file,
1247
+ originalSource.originalFileName,
1248
+ ...originalSource.originalFileNames ?? []
1249
+ ].filter((item) => typeof item === "string" && item.length > 0);
1250
+ const sourceMatched = rememberedSources.filter((remembered) => originalFiles.some((originalFile) => require_bundle_state.normalizeOutputPathKey(remembered.sourceFile) === require_bundle_state.normalizeOutputPathKey(originalFile)));
1251
+ if (sourceMatched.length > 0) return sourceMatched;
1252
+ const outputMatched = rememberedSources.filter((remembered) => require_bundle_state.normalizeOutputPathKey(remembered.outputFile) === require_bundle_state.normalizeOutputPathKey(outputFile));
1253
+ if (outputMatched.length > 0) return outputMatched;
1254
+ const shouldUseRememberedApplyFallback = !require_bundle_state.hasBundlerGeneratedCssMarker(source) && !hasTailwindGenerationSource(source);
1255
+ if (shouldUseRememberedApplyFallback && !rememberedSources.some((remembered) => require_v3_engine.hasTailwindApplyDirective(remembered.rawSource))) return [];
1256
+ const scoredMatches = rememberedSources.filter((remembered) => !shouldUseRememberedApplyFallback || require_v3_engine.hasTailwindApplyDirective(remembered.rawSource)).filter((remembered) => !(isMainAppCssFile(outputFile) && isAppOriginCssFile(remembered.outputFile))).map((remembered) => ({
1257
+ remembered,
1258
+ score: Math.max(scoreMatchingStyleFileBase(outputFile, remembered.sourceFile, outputRoot, sourceRoot), scoreMatchingStyleFileBase(outputFile, remembered.outputFile, outputRoot, sourceRoot))
1259
+ })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score);
1260
+ const bestScore = scoredMatches[0]?.score;
1261
+ return bestScore ? scoredMatches.filter((match) => match.score === bestScore).map((match) => match.remembered) : [];
1262
+ }
1263
+ function mergeRememberedCssSources(sources, outputFile) {
1264
+ if (sources.length <= 1) return sources[0];
1265
+ const seen = /* @__PURE__ */ new Set();
1266
+ const rawSources = [];
1267
+ for (const source of sources) {
1268
+ const key = `${source.sourceFile}\0${source.rawSource}`;
1269
+ if (seen.has(key)) continue;
1270
+ seen.add(key);
1271
+ rawSources.push(source.rawSource);
1272
+ }
1273
+ return {
1274
+ outputFile,
1275
+ rawSource: rawSources.join("\n"),
1276
+ sourceFile: sources[0]?.sourceFile ?? outputFile
1277
+ };
1278
+ }
1279
+ function collectRememberedCssReplayGroups(sources, opts, rootDir, isWebGeneratorTarget, preserveCssExtension) {
1280
+ const groups = /* @__PURE__ */ new Map();
1281
+ for (const [key, remembered] of sources ?? []) {
1282
+ const outputKey = require_bundle_state.normalizeOutputPathKey(resolveViteCssPipelineOutputFile(remembered.outputFile, opts, rootDir, isWebGeneratorTarget, preserveCssExtension));
1283
+ const group = groups.get(outputKey) ?? [];
1284
+ group.push({
1285
+ key,
1286
+ remembered
1287
+ });
1288
+ groups.set(outputKey, group);
1289
+ }
1290
+ return groups;
1291
+ }
1292
+ //#endregion
492
1293
  //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
493
1294
  function createReplayCssAsset(fileName, source) {
494
1295
  return {
@@ -567,6 +1368,75 @@ function hasRuntimeAffectingSourceChanges(changedByType) {
567
1368
  return changedByType.html.size > 0 || changedByType.js.size > 0;
568
1369
  }
569
1370
  //#endregion
1371
+ //#region src/bundlers/vite/generate-bundle/subpackages.ts
1372
+ function readBundleAssetSource(output) {
1373
+ if (output.type !== "asset") return;
1374
+ return typeof output.source === "string" ? output.source : output.source.toString();
1375
+ }
1376
+ function normalizePackageRoot(root) {
1377
+ return require_bundle_state.normalizeOutputPathKey(root).replace(/\/+$/, "");
1378
+ }
1379
+ function collectMiniProgramSubpackageRoots(bundle) {
1380
+ let hasAppJson = false;
1381
+ const roots = /* @__PURE__ */ new Set();
1382
+ for (const [file, output] of Object.entries(bundle)) {
1383
+ const outputFile = output.fileName || file;
1384
+ if (node_path.default.basename(outputFile) !== "app.json") continue;
1385
+ const source = readBundleAssetSource(output);
1386
+ if (!source) continue;
1387
+ hasAppJson = true;
1388
+ try {
1389
+ const appJson = JSON.parse(source);
1390
+ const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
1391
+ for (const subPackage of subPackages) {
1392
+ if (typeof subPackage.root !== "string" || subPackage.root.length === 0) continue;
1393
+ roots.add(normalizePackageRoot(subPackage.root));
1394
+ }
1395
+ } catch {}
1396
+ }
1397
+ return hasAppJson ? roots : void 0;
1398
+ }
1399
+ function isSubpackageOutputFile(file, subpackageRoots) {
1400
+ const normalizedFile = require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1401
+ for (const root of subpackageRoots) if (root.length > 0 && (normalizedFile === root || normalizedFile.startsWith(`${root}/`) || normalizedFile.endsWith(`/${root}`) || normalizedFile.includes(`/${root}/`))) return true;
1402
+ return false;
1403
+ }
1404
+ function resolveSubpackageSourceRootFromModuleId(moduleId, subpackageRoot) {
1405
+ const file = require_bundle_state.slash(node_path.default.resolve(moduleId.replace(/[?#].*$/, "")));
1406
+ const normalizedRoot = normalizePackageRoot(subpackageRoot);
1407
+ const rootSegment = `/${normalizedRoot}/`;
1408
+ const rootIndex = file.lastIndexOf(rootSegment);
1409
+ if (rootIndex >= 0) return file.slice(0, rootIndex + rootSegment.length - 1);
1410
+ const rootSuffix = `/${normalizedRoot}`;
1411
+ if (file.endsWith(rootSuffix)) return file;
1412
+ }
1413
+ function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, sourceBaseRoots) {
1414
+ const sourceRoots = /* @__PURE__ */ new Set();
1415
+ const sourceEntries = [];
1416
+ for (const entry of snapshot.entries) {
1417
+ if (entry.output.type !== "chunk" || !isSubpackageOutputFile(entry.file, subpackageRoots)) continue;
1418
+ const matchedSubpackageRoot = [...subpackageRoots].find((root) => isSubpackageOutputFile(entry.file, new Set([root])));
1419
+ if (!matchedSubpackageRoot) continue;
1420
+ for (const moduleId of collectChunkModuleIds(entry.output)) {
1421
+ if (!node_path.default.isAbsolute(moduleId.replace(/[?#].*$/, ""))) continue;
1422
+ const sourceRoot = resolveSubpackageSourceRootFromModuleId(moduleId, matchedSubpackageRoot);
1423
+ if (sourceRoot) sourceRoots.add(sourceRoot);
1424
+ }
1425
+ }
1426
+ sourceEntries.push(...[...sourceRoots].map((sourceRoot) => ({
1427
+ base: sourceRoot,
1428
+ negated: false,
1429
+ pattern: "**/*"
1430
+ })));
1431
+ const resolvedBaseRoots = sourceBaseRoots.filter((baseRoot) => typeof baseRoot === "string" && baseRoot.length > 0).map((baseRoot) => node_path.default.resolve(baseRoot)).filter((baseRoot, index, roots) => roots.indexOf(baseRoot) === index);
1432
+ for (const baseRoot of resolvedBaseRoots) for (const subpackageRoot of subpackageRoots) sourceEntries.push({
1433
+ base: baseRoot,
1434
+ negated: false,
1435
+ pattern: `**/${normalizePackageRoot(subpackageRoot)}/**`
1436
+ });
1437
+ return sourceEntries;
1438
+ }
1439
+ //#endregion
570
1440
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
571
1441
  let _lazyMatch = () => {
572
1442
  var __lib__ = (() => {
@@ -1013,11 +1883,372 @@ const mix = (del = delimiter) => {
1013
1883
  const posix = /* @__PURE__ */ mix(":");
1014
1884
  const win32 = /* @__PURE__ */ mix(";");
1015
1885
  //#endregion
1886
+ //#region src/bundlers/vite/processed-css-assets/css-rules.ts
1887
+ const MINI_PROGRAM_PREFLIGHT_SELECTOR_KEY = "view,text,::after,::before";
1888
+ const MINI_PROGRAM_PREFLIGHT_SELECTOR_KEYS = new Set([
1889
+ "view",
1890
+ "text",
1891
+ "::after",
1892
+ "::before"
1893
+ ]);
1894
+ const MINI_PROGRAM_THEME_SCOPE_SELECTOR_KEY = ":host,page,.tw-root,wx-root-portal-content";
1895
+ const MINI_PROGRAM_THEME_SCOPE_SELECTOR_KEYS = new Set([
1896
+ ":host",
1897
+ "page",
1898
+ ".tw-root",
1899
+ "wx-root-portal-content"
1900
+ ]);
1901
+ function normalizeCssForContainment(css) {
1902
+ return css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/::(before|after)\b/g, ":$1").replace(/\s+/g, " ").replace(/\s*([{}:;,>+~()])\s*/g, "$1").replace(/;\}/g, "}").trim();
1903
+ }
1904
+ function collectNormalizedCssNodes(css) {
1905
+ try {
1906
+ return (postcss.default.parse(css).nodes ?? []).filter((node) => node.type !== "comment").map((node) => normalizeCssForContainment(node.toString())).filter(Boolean);
1907
+ } catch {
1908
+ const normalizedCss = normalizeCssForContainment(css);
1909
+ return normalizedCss ? [normalizedCss] : [];
1910
+ }
1911
+ }
1912
+ function normalizeCssRuleKeyPart(value) {
1913
+ return value.replace(/::(before|after)\b/g, ":$1").replace(/\s+/g, " ").replace(/\s*([>+~(),])\s*/g, "$1").trim();
1914
+ }
1915
+ function getRuleAtRuleChain(rule) {
1916
+ const chain = [];
1917
+ let parent = rule.parent;
1918
+ while (parent && parent.type !== "root") {
1919
+ if (parent.type === "atrule") chain.unshift(`@${parent.name} ${normalizeCssRuleKeyPart(parent.params)}`);
1920
+ parent = parent.parent;
1921
+ }
1922
+ return chain;
1923
+ }
1924
+ function getCssRuleStructuralKey(rule) {
1925
+ const selector = normalizeCssRuleKeyPart(rule.selector);
1926
+ if (selector.length === 0) return;
1927
+ return [...getRuleAtRuleChain(rule), selector].join("|");
1928
+ }
1929
+ function getCssRuleStructuralKeyWithSelectorKey(rule, selectorKey) {
1930
+ return [...getRuleAtRuleChain(rule), selectorKey].join("|");
1931
+ }
1932
+ function getCssRuleContentKey(rule) {
1933
+ const structuralKey = getCssRuleStructuralKey(rule);
1934
+ if (!structuralKey) return;
1935
+ return [structuralKey, normalizeCssForContainment(rule.toString())].join("|");
1936
+ }
1937
+ function collectCssRuleContentKeys(css) {
1938
+ const keys = /* @__PURE__ */ new Set();
1939
+ try {
1940
+ postcss.default.parse(css).walkRules((rule) => {
1941
+ const key = getCssRuleContentKey(rule);
1942
+ if (key) keys.add(key);
1943
+ });
1944
+ } catch {}
1945
+ return keys;
1946
+ }
1947
+ function normalizeCssDeclarationKey(decl) {
1948
+ return [
1949
+ decl.prop.trim(),
1950
+ normalizeCssForContainment(decl.value),
1951
+ decl.important ? "!important" : ""
1952
+ ].join(":");
1953
+ }
1954
+ function collectCssRuleDeclarationKeys(rule) {
1955
+ const keys = /* @__PURE__ */ new Set();
1956
+ for (const node of rule.nodes ?? []) if (node.type === "decl") keys.add(normalizeCssDeclarationKey(node));
1957
+ return keys;
1958
+ }
1959
+ function collectCssRuleDeclarationProps(rule) {
1960
+ const props = /* @__PURE__ */ new Set();
1961
+ for (const node of rule.nodes ?? []) if (node.type === "decl") props.add(node.prop.trim());
1962
+ return props;
1963
+ }
1964
+ function collectCssRuleDeclarations(rule) {
1965
+ return (rule.nodes ?? []).filter((node) => node.type === "decl");
1966
+ }
1967
+ function collectCssRuleDeclarationKeyMap(css) {
1968
+ const map = /* @__PURE__ */ new Map();
1969
+ try {
1970
+ postcss.default.parse(css).walkRules((rule) => {
1971
+ const key = getCssRuleStructuralKey(rule);
1972
+ if (!key) return;
1973
+ const declarations = collectCssRuleDeclarationKeys(rule);
1974
+ if (declarations.size === 0) return;
1975
+ let existing = map.get(key);
1976
+ if (!existing) {
1977
+ existing = /* @__PURE__ */ new Set();
1978
+ map.set(key, existing);
1979
+ }
1980
+ for (const declaration of declarations) existing.add(declaration);
1981
+ });
1982
+ } catch {}
1983
+ return map;
1984
+ }
1985
+ function collectCssRuleDeclarationRecords(root, resolveRuleKey = getCssRuleStructuralKey) {
1986
+ const map = /* @__PURE__ */ new Map();
1987
+ root.walkRules((rule) => {
1988
+ const key = resolveRuleKey(rule);
1989
+ if (!key) return;
1990
+ const keys = collectCssRuleDeclarationKeys(rule);
1991
+ if (keys.size === 0) return;
1992
+ const records = map.get(key) ?? [];
1993
+ records.push({
1994
+ rule,
1995
+ keys,
1996
+ props: collectCssRuleDeclarationProps(rule)
1997
+ });
1998
+ map.set(key, records);
1999
+ });
2000
+ return map;
2001
+ }
2002
+ function normalizeSimpleMiniProgramSelectorNode(node) {
2003
+ if (node.type === "tag") {
2004
+ const value = node.value.toLowerCase();
2005
+ if (value === "view" || value === "text" || value === "page" || value === "wx-root-portal-content") return value;
2006
+ return;
2007
+ }
2008
+ if (node.type === "class") return node.value.toLowerCase() === "tw-root" ? ".tw-root" : void 0;
2009
+ if (node.type === "pseudo") {
2010
+ if (node.nodes && node.nodes.length > 0) return;
2011
+ const value = node.value.toLowerCase();
2012
+ if (value === ":before" || value === "::before") return "::before";
2013
+ if (value === ":after" || value === "::after") return "::after";
2014
+ if (value === ":host") return ":host";
2015
+ }
2016
+ }
2017
+ function normalizeSimpleMiniProgramSelector(selector) {
2018
+ if (selector.nodes.length !== 1) return;
2019
+ return normalizeSimpleMiniProgramSelectorNode(selector.nodes[0]);
2020
+ }
2021
+ function collectMiniProgramSelectorSet(selector) {
2022
+ try {
2023
+ const selectorSet = /* @__PURE__ */ new Set();
2024
+ const ast = (0, postcss_selector_parser.default)().astSync(selector);
2025
+ for (const child of ast.nodes) {
2026
+ const key = normalizeSimpleMiniProgramSelector(child);
2027
+ if (!key || selectorSet.has(key)) return;
2028
+ selectorSet.add(key);
2029
+ }
2030
+ return selectorSet;
2031
+ } catch {
2032
+ return;
2033
+ }
2034
+ }
2035
+ function isSameSelectorSet(actual, expected) {
2036
+ return actual?.size === expected.size && [...expected].every((key) => actual.has(key));
2037
+ }
2038
+ function getMiniProgramPreflightRuleStructuralKey(rule) {
2039
+ if (!isSameSelectorSet(collectMiniProgramSelectorSet(rule.selector), MINI_PROGRAM_PREFLIGHT_SELECTOR_KEYS)) return;
2040
+ return getCssRuleStructuralKeyWithSelectorKey(rule, MINI_PROGRAM_PREFLIGHT_SELECTOR_KEY);
2041
+ }
2042
+ function getMiniProgramThemeScopeRuleStructuralKey(rule) {
2043
+ if (!isSameSelectorSet(collectMiniProgramSelectorSet(rule.selector), MINI_PROGRAM_THEME_SCOPE_SELECTOR_KEYS)) return;
2044
+ return getCssRuleStructuralKeyWithSelectorKey(rule, MINI_PROGRAM_THEME_SCOPE_SELECTOR_KEY);
2045
+ }
2046
+ function mergeMiniProgramPreflightRuleDeclarations(baseCss, css) {
2047
+ try {
2048
+ const baseRoot = postcss.default.parse(baseCss);
2049
+ const root = postcss.default.parse(css);
2050
+ const baseRuleRecords = collectCssRuleDeclarationRecords(baseRoot, getMiniProgramPreflightRuleStructuralKey);
2051
+ let changedBase = false;
2052
+ let changedCss = false;
2053
+ root.walkRules((rule) => {
2054
+ const key = getMiniProgramPreflightRuleStructuralKey(rule);
2055
+ if (!key) return;
2056
+ const records = baseRuleRecords.get(key);
2057
+ const targetRecord = records?.[0];
2058
+ if (!targetRecord) return;
2059
+ const existingProps = new Set(records.flatMap((record) => [...record.props]));
2060
+ for (const decl of collectCssRuleDeclarations(rule)) {
2061
+ const prop = decl.prop.trim();
2062
+ if (existingProps.has(prop)) continue;
2063
+ targetRecord.rule.append(decl.clone());
2064
+ targetRecord.keys.add(normalizeCssDeclarationKey(decl));
2065
+ targetRecord.props.add(prop);
2066
+ existingProps.add(prop);
2067
+ changedBase = true;
2068
+ }
2069
+ rule.remove();
2070
+ changedCss = true;
2071
+ });
2072
+ if (!changedBase && !changedCss) return {
2073
+ baseCss,
2074
+ css,
2075
+ changed: false
2076
+ };
2077
+ removeEmptyAtRules(root);
2078
+ return {
2079
+ baseCss: changedBase ? baseRoot.toString() : baseCss,
2080
+ css: changedCss ? root.toString().trim() : css,
2081
+ changed: true
2082
+ };
2083
+ } catch {
2084
+ return {
2085
+ baseCss,
2086
+ css,
2087
+ changed: false
2088
+ };
2089
+ }
2090
+ }
2091
+ function mergeMiniProgramThemeScopeRuleDeclarations(baseCss, css) {
2092
+ try {
2093
+ const baseRoot = postcss.default.parse(baseCss);
2094
+ const root = postcss.default.parse(css);
2095
+ const baseRuleRecords = collectCssRuleDeclarationRecords(baseRoot, getMiniProgramThemeScopeRuleStructuralKey);
2096
+ let changedBase = false;
2097
+ let changedCss = false;
2098
+ root.walkRules((rule) => {
2099
+ const key = getMiniProgramThemeScopeRuleStructuralKey(rule);
2100
+ if (!key) return;
2101
+ const records = baseRuleRecords.get(key);
2102
+ const targetRecord = records?.[0];
2103
+ if (!targetRecord) return;
2104
+ const incomingDeclarations = collectCssRuleDeclarations(rule);
2105
+ if (incomingDeclarations.length === 0) return;
2106
+ const existingKeys = new Set(records.flatMap((record) => [...record.keys]));
2107
+ const existingProps = new Set(records.flatMap((record) => [...record.props]));
2108
+ if (incomingDeclarations.some((decl) => {
2109
+ const prop = decl.prop.trim();
2110
+ return existingProps.has(prop) && !existingKeys.has(normalizeCssDeclarationKey(decl));
2111
+ })) return;
2112
+ for (const decl of incomingDeclarations) {
2113
+ const declarationKey = normalizeCssDeclarationKey(decl);
2114
+ if (existingKeys.has(declarationKey)) continue;
2115
+ targetRecord.rule.append(decl.clone());
2116
+ targetRecord.keys.add(declarationKey);
2117
+ targetRecord.props.add(decl.prop.trim());
2118
+ existingKeys.add(declarationKey);
2119
+ existingProps.add(decl.prop.trim());
2120
+ changedBase = true;
2121
+ }
2122
+ rule.remove();
2123
+ changedCss = true;
2124
+ });
2125
+ if (!changedBase && !changedCss) return {
2126
+ baseCss,
2127
+ css,
2128
+ changed: false
2129
+ };
2130
+ removeEmptyAtRules(root);
2131
+ return {
2132
+ baseCss: changedBase ? baseRoot.toString() : baseCss,
2133
+ css: changedCss ? root.toString().trim() : css,
2134
+ changed: true
2135
+ };
2136
+ } catch {
2137
+ return {
2138
+ baseCss,
2139
+ css,
2140
+ changed: false
2141
+ };
2142
+ }
2143
+ }
2144
+ function isCssRuleCoveredByDeclarations(rule, baseRuleDeclarationKeys) {
2145
+ const key = getCssRuleStructuralKey(rule);
2146
+ if (!key) return false;
2147
+ const baseDeclarations = baseRuleDeclarationKeys.get(key);
2148
+ if (!baseDeclarations) return false;
2149
+ const declarations = collectCssRuleDeclarationKeys(rule);
2150
+ return declarations.size > 0 && [...declarations].every((declaration) => baseDeclarations.has(declaration));
2151
+ }
2152
+ function mergeCoveredCssRuleDeclarations(baseCss, css) {
2153
+ try {
2154
+ const baseRoot = postcss.default.parse(baseCss);
2155
+ const root = postcss.default.parse(css);
2156
+ const baseRuleRecords = collectCssRuleDeclarationRecords(baseRoot);
2157
+ let changedBase = false;
2158
+ let changedCss = false;
2159
+ root.walkRules((rule) => {
2160
+ const key = getCssRuleStructuralKey(rule);
2161
+ const records = key ? baseRuleRecords.get(key) : void 0;
2162
+ if (!records || records.length === 0) return;
2163
+ const incomingDeclarations = collectCssRuleDeclarations(rule);
2164
+ if (incomingDeclarations.length === 0) return;
2165
+ const baseKeys = new Set(records.flatMap((record) => [...record.keys]));
2166
+ if (incomingDeclarations.filter((decl) => baseKeys.has(normalizeCssDeclarationKey(decl))).length === 0) return;
2167
+ const missingDeclarations = incomingDeclarations.filter((decl) => !baseKeys.has(normalizeCssDeclarationKey(decl)));
2168
+ if (missingDeclarations.length === 0) {
2169
+ rule.remove();
2170
+ changedCss = true;
2171
+ return;
2172
+ }
2173
+ const baseProps = new Set(records.flatMap((record) => [...record.props]));
2174
+ if (missingDeclarations.filter((decl) => baseProps.has(decl.prop.trim())).length > 0) return;
2175
+ const targetRecord = records[0];
2176
+ if (!targetRecord) return;
2177
+ for (const decl of missingDeclarations) {
2178
+ targetRecord.rule.append(decl.clone());
2179
+ targetRecord.keys.add(normalizeCssDeclarationKey(decl));
2180
+ targetRecord.props.add(decl.prop.trim());
2181
+ }
2182
+ rule.remove();
2183
+ changedBase = true;
2184
+ changedCss = true;
2185
+ });
2186
+ if (!changedBase && !changedCss) return {
2187
+ baseCss,
2188
+ css,
2189
+ changed: false
2190
+ };
2191
+ removeEmptyAtRules(root);
2192
+ return {
2193
+ baseCss: changedBase ? baseRoot.toString() : baseCss,
2194
+ css: changedCss ? root.toString().trim() : css,
2195
+ changed: true
2196
+ };
2197
+ } catch {
2198
+ return {
2199
+ baseCss,
2200
+ css,
2201
+ changed: false
2202
+ };
2203
+ }
2204
+ }
2205
+ function removeEmptyAtRules(root) {
2206
+ root.walkAtRules((atRule) => {
2207
+ if (atRule.nodes && atRule.nodes.every((node) => node.type === "comment")) atRule.remove();
2208
+ });
2209
+ }
2210
+ function filterExistingCssRules(baseCss, css) {
2211
+ const baseRuleKeys = collectCssRuleContentKeys(baseCss);
2212
+ if (baseRuleKeys.size === 0) return css;
2213
+ try {
2214
+ const root = postcss.default.parse(css);
2215
+ const baseRuleDeclarationKeys = collectCssRuleDeclarationKeyMap(baseCss);
2216
+ let changed = false;
2217
+ root.walkRules((rule) => {
2218
+ const key = getCssRuleContentKey(rule);
2219
+ if (key && baseRuleKeys.has(key) || isCssRuleCoveredByDeclarations(rule, baseRuleDeclarationKeys)) {
2220
+ rule.remove();
2221
+ changed = true;
2222
+ }
2223
+ });
2224
+ if (!changed) return css;
2225
+ removeEmptyAtRules(root);
2226
+ return root.toString().trim();
2227
+ } catch {
2228
+ return css;
2229
+ }
2230
+ }
2231
+ function containsCssAfterMinify(baseCss, css) {
2232
+ if (baseCss.includes(css)) return true;
2233
+ const normalizedBaseCss = normalizeCssForContainment(baseCss);
2234
+ const normalizedCss = normalizeCssForContainment(css);
2235
+ if (normalizedCss.length > 0 && normalizedBaseCss.includes(normalizedCss)) return true;
2236
+ const normalizedNodes = collectNormalizedCssNodes(css);
2237
+ if (normalizedNodes.length > 0 && normalizedNodes.every((node) => normalizedBaseCss.includes(node))) return true;
2238
+ const baseRuleKeys = collectCssRuleContentKeys(baseCss);
2239
+ const ruleKeys = collectCssRuleContentKeys(css);
2240
+ return ruleKeys.size > 0 && [...ruleKeys].every((key) => baseRuleKeys.has(key));
2241
+ }
2242
+ //#endregion
1016
2243
  //#region src/bundlers/vite/processed-css-assets.ts
1017
2244
  const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
1018
2245
  function isCssOutputFile(file) {
1019
2246
  return CSS_OUTPUT_FILE_RE.test(file);
1020
2247
  }
2248
+ function isMainStyleAssetFile(file) {
2249
+ const basename = require_bundle_state.normalizeOutputPathKey(file.replace(/[?#].*$/, "")).replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss)$/i, "").split("/").pop();
2250
+ return basename === "app" || basename === "main";
2251
+ }
1021
2252
  function getAssetFile(bundleFile, asset) {
1022
2253
  return asset.fileName || bundleFile;
1023
2254
  }
@@ -1090,6 +2321,9 @@ function resolveViteProcessedCssAssetSource(file, rawSource, resolveViteProcesse
1090
2321
  const matchedCss = blocks.filter((block) => isMatchingGeneratedCssMarkerFile(file, block.file, resolveViteProcessedCssOutputFile)).map((block) => block.css);
1091
2322
  return matchedCss.length > 0 ? matchedCss.join("\n") : require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
1092
2323
  }
2324
+ function collectMatchingGeneratedCssMarkerFiles(file, rawSource, resolveViteProcessedCssOutputFile) {
2325
+ return require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(rawSource).filter((block) => block.bundler === "vite").filter((block) => isMatchingGeneratedCssMarkerFile(file, block.file, resolveViteProcessedCssOutputFile)).map((block) => block.file).filter((markerFile) => typeof markerFile === "string" && markerFile.length > 0);
2326
+ }
1093
2327
  function shouldInjectViteProcessedCssResult(opts, targetFile, sourceFile, options) {
1094
2328
  if (options.injectIntoMain === true) return true;
1095
2329
  if (options.injectIntoMain === false) return false;
@@ -1098,6 +2332,28 @@ function shouldInjectViteProcessedCssResult(opts, targetFile, sourceFile, option
1098
2332
  const sourceBaseName = sourceFileKey.replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss)$/i, "").split("/").pop();
1099
2333
  return sourceFileKey !== targetFileKey && (opts.mainCssChunkMatcher(sourceFile, opts.appType) || sourceBaseName === "app" || sourceBaseName === "main");
1100
2334
  }
2335
+ function isViteProcessedCssResultImported(record, importedStyleFiles) {
2336
+ const importedFileNames = new Set([...importedStyleFiles].map((file) => posix.posix.basename(file)));
2337
+ return importedStyleFiles.has(require_bundle_state.normalizeOutputPathKey(record.file)) || typeof record.outputFile === "string" && (importedStyleFiles.has(require_bundle_state.normalizeOutputPathKey(record.outputFile)) || importedFileNames.has(posix.posix.basename(require_bundle_state.normalizeOutputPathKey(record.outputFile))));
2338
+ }
2339
+ function removeCssCoveredByImportedViteResults(css, importedCssSources) {
2340
+ if (importedCssSources.length === 0) return css;
2341
+ const importedCss = importedCssSources.map((source) => require_bundle_state.stripBundlerGeneratedCssMarkers(source).trim()).filter(Boolean).join("\n");
2342
+ if (importedCss.length === 0) return css;
2343
+ return filterExistingCssRules(importedCss, css);
2344
+ }
2345
+ function collectImportedBundleCssSources(bundle, importedStyleFiles) {
2346
+ if (importedStyleFiles.size === 0) return [];
2347
+ const importedFileNames = new Set([...importedStyleFiles].map((file) => posix.posix.basename(file)));
2348
+ const importedSources = [];
2349
+ for (const [bundleFile, output] of Object.entries(bundle)) {
2350
+ if (output.type !== "asset") continue;
2351
+ const file = require_bundle_state.normalizeOutputPathKey(getAssetFile(bundleFile, output));
2352
+ if (!(importedStyleFiles.has(file) || !file.includes("/") && importedFileNames.has(posix.posix.basename(file)))) continue;
2353
+ importedSources.push(readAssetSource(output));
2354
+ }
2355
+ return importedSources;
2356
+ }
1101
2357
  function collectViteProcessedCssAssetResults(bundle, options) {
1102
2358
  let collected = 0;
1103
2359
  for (const [bundleFile, output] of Object.entries(bundle)) {
@@ -1110,8 +2366,18 @@ function collectViteProcessedCssAssetResults(bundle, options) {
1110
2366
  options.markCssAssetProcessed?.(output, file);
1111
2367
  options.recordCssAssetResult?.(file, nextCss);
1112
2368
  const resolvedOutputFile = options.resolveViteProcessedCssOutputFile?.(file) ?? file;
1113
- const shouldReplayIntoMainCss = options.opts != null && require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(file) && options.opts.mainCssChunkMatcher(resolvedOutputFile, options.opts.appType);
1114
- options.recordViteProcessedCssAssetResult?.(file, nextCss, { injectIntoMain: shouldReplayIntoMainCss || void 0 });
2369
+ const shouldReplayIntoMainCss = options.opts != null && isMainStyleAssetFile(file) && (require_bundle_state.normalizeOutputPathKey(resolvedOutputFile) !== require_bundle_state.normalizeOutputPathKey(file) || !options.opts.mainCssChunkMatcher(file, options.opts.appType));
2370
+ options.recordViteProcessedCssAssetResult?.(file, nextCss, {
2371
+ injectIntoMain: shouldReplayIntoMainCss || void 0,
2372
+ outputFile: resolvedOutputFile
2373
+ });
2374
+ for (const markerFile of collectMatchingGeneratedCssMarkerFiles(file, rawSource, options.resolveViteProcessedCssOutputFile)) {
2375
+ if (require_bundle_state.normalizeOutputPathKey(markerFile) === require_bundle_state.normalizeOutputPathKey(file)) continue;
2376
+ options.recordViteProcessedCssAssetResult?.(markerFile, nextCss, {
2377
+ injectIntoMain: shouldReplayIntoMainCss || void 0,
2378
+ outputFile: resolvedOutputFile
2379
+ });
2380
+ }
1115
2381
  options.debug?.("collect vite-processed css asset: %s bytes=%d", file, nextCss.length);
1116
2382
  collected++;
1117
2383
  }
@@ -1126,10 +2392,10 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
1126
2392
  } : {
1127
2393
  file,
1128
2394
  css: record.css,
1129
- injectIntoMain: record.injectIntoMain
2395
+ injectIntoMain: record.injectIntoMain,
2396
+ outputFile: record.outputFile
1130
2397
  };
1131
2398
  }).filter((record) => record.css.length > 0);
1132
- if (viteCssResults.length === 0) return 0;
1133
2399
  let injected = 0;
1134
2400
  for (const [bundleFile, output] of Object.entries(bundle)) {
1135
2401
  if (output.type !== "asset") continue;
@@ -1139,18 +2405,45 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
1139
2405
  const originalSource = readAssetSource(output);
1140
2406
  let nextCss = removeTailwindEntryDirectivesFromCss(originalSource);
1141
2407
  const importedStyleFiles = collectImportedStyleFiles(nextCss, file);
2408
+ const importedBundleCssSources = collectImportedBundleCssSources(bundle, importedStyleFiles);
2409
+ nextCss = removeCssCoveredByImportedViteResults(nextCss, importedBundleCssSources);
2410
+ const importedViteCssResults = viteCssResults.filter((record) => isViteProcessedCssResultImported(record, importedStyleFiles));
2411
+ const importedCssSources = [...importedBundleCssSources, ...importedViteCssResults.map((record) => record.css)];
2412
+ nextCss = removeCssCoveredByImportedViteResults(nextCss, importedViteCssResults.map((record) => record.css));
1142
2413
  for (const record of viteCssResults) {
1143
2414
  if (!shouldInjectViteProcessedCssResult(options.opts, mainFileKey, record.file, record)) continue;
1144
- if (importedStyleFiles.has(require_bundle_state.normalizeOutputPathKey(record.file))) continue;
1145
- const css = require_bundle_state.stripBundlerGeneratedCssMarkers(record.css).trim();
2415
+ if (isViteProcessedCssResultImported(record, importedStyleFiles)) continue;
2416
+ let css = require_bundle_state.stripBundlerGeneratedCssMarkers(record.css).trim();
2417
+ css = removeCssCoveredByImportedViteResults(css, importedCssSources).trim();
1146
2418
  if (css.length === 0) continue;
1147
- const mergedLayerCss = require_incremental_runtime_class_set.mergeMarkedUserLayerComponentsCss(nextCss, css);
2419
+ const mergedLayerCss = require_hmr_timing.mergeMarkedUserLayerComponentsCss(nextCss, css);
1148
2420
  if (mergedLayerCss.merged) {
1149
2421
  nextCss = mergedLayerCss.css;
1150
- continue;
2422
+ css = require_hmr_timing.extractMarkedUserLayerComponentsCss(css).rest.trim();
2423
+ if (css.length === 0) continue;
2424
+ }
2425
+ if (containsCssAfterMinify(nextCss, css)) continue;
2426
+ const mergedPreflightDeclarations = mergeMiniProgramPreflightRuleDeclarations(nextCss, css);
2427
+ if (mergedPreflightDeclarations.changed) {
2428
+ nextCss = mergedPreflightDeclarations.baseCss;
2429
+ css = mergedPreflightDeclarations.css.trim();
2430
+ if (css.length === 0) continue;
2431
+ }
2432
+ const mergedThemeScopeDeclarations = mergeMiniProgramThemeScopeRuleDeclarations(nextCss, css);
2433
+ if (mergedThemeScopeDeclarations.changed) {
2434
+ nextCss = mergedThemeScopeDeclarations.baseCss;
2435
+ css = mergedThemeScopeDeclarations.css.trim();
2436
+ if (css.length === 0) continue;
2437
+ }
2438
+ const mergedRuleDeclarations = mergeCoveredCssRuleDeclarations(nextCss, css);
2439
+ if (mergedRuleDeclarations.changed) {
2440
+ nextCss = mergedRuleDeclarations.baseCss;
2441
+ css = mergedRuleDeclarations.css.trim();
2442
+ if (css.length === 0) continue;
1151
2443
  }
1152
- if (nextCss.includes(css)) continue;
1153
- nextCss = appendCss(nextCss, css);
2444
+ const missingCss = filterExistingCssRules(nextCss, css);
2445
+ if (missingCss.length === 0 || containsCssAfterMinify(nextCss, missingCss)) continue;
2446
+ nextCss = appendCss(nextCss, missingCss);
1154
2447
  }
1155
2448
  if (nextCss === originalSource) continue;
1156
2449
  output.source = nextCss;
@@ -1159,81 +2452,30 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
1159
2452
  options.onUpdate?.(file, originalSource, nextCss);
1160
2453
  options.debug?.("inject vite-processed css into main css asset: %s bytes=%d", file, nextCss.length);
1161
2454
  injected++;
1162
- }
1163
- return injected;
1164
- }
1165
- //#endregion
1166
- //#region src/bundlers/vite/uni-app-x-css-options.ts
1167
- function resolveUniAppXNativeCssHandlerOptions(opts) {
1168
- if (opts.appType !== "uni-app-x" || !require_tailwindcss.isUniAppXEnabled(opts.uniAppX) || !require_utils.resolveUniUtsPlatform().isApp) return {};
1169
- return {
1170
- uniAppX: true,
1171
- uniAppXCssTarget: "uvue",
1172
- uniAppXUnsupported: require_tailwindcss.resolveUniAppXOptions(opts.uniAppX).uvueUnsupported
1173
- };
1174
- }
1175
- //#endregion
1176
- //#region src/bundlers/vite/generate-bundle.ts
1177
- function addSiblingCssFile(files, file) {
1178
- if (file.endsWith(".wxml")) files.add(file.replace(/\.wxml$/, ".wxss"));
1179
- else if (file.endsWith(".js")) files.add(file.replace(/\.js$/, ".wxss"));
1180
- }
1181
- function collectRuntimeLinkedCssFiles(snapshot) {
1182
- const files = /* @__PURE__ */ new Set();
1183
- for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file);
1184
- for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file);
1185
- return files;
1186
- }
1187
- function resolveReplayCssOutputFile(rootDir, file) {
1188
- const normalizedFile = require_bundle_state.normalizeOutputPathKey(node_path.default.isAbsolute(file) ? node_path.default.relative(rootDir, file) : file);
1189
- if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return require_bundle_state.normalizeOutputPathKey(node_path.default.basename(file));
1190
- return normalizedFile;
1191
- }
1192
- const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
1193
- const CSS_SOURCE_OUTPUT_EXT_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/i;
1194
- const MINI_PROGRAM_STYLE_OUTPUT_EXT_RE = /\.(?:wx|ac|jx|tt|q|ty)ss$/i;
1195
- const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
1196
- function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget) {
1197
- if (isWebGeneratorTarget || opts.cssMatcher(file) || !SOURCE_STYLE_OUTPUT_EXT_RE.test(file) || !require_bundle_state.isCSSRequest(file)) return file;
1198
- return file.replace(SOURCE_STYLE_OUTPUT_EXT_RE, ".wxss");
1199
- }
1200
- function resolveViteCssPipelineOutputFile(file, _opts, rootDir, isWebGeneratorTarget = false, preserveCssExtension = false) {
1201
- const normalizedFile = resolveReplayCssOutputFile(rootDir, file);
1202
- if (isWebGeneratorTarget || preserveCssExtension || MINI_PROGRAM_STYLE_OUTPUT_EXT_RE.test(normalizedFile) || !CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedFile) || !require_bundle_state.isCSSRequest(normalizedFile)) return normalizedFile;
1203
- return normalizedFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".wxss");
1204
- }
1205
- function canProcessViteSourceStyleAsCss(source, file) {
1206
- if (SOURCE_STYLE_NON_CSS_SYNTAX_RE.test(source)) return false;
1207
- try {
1208
- postcss.default.parse(source, { from: file });
1209
- return true;
1210
- } catch {
1211
- return false;
1212
- }
1213
- }
1214
- function isPackageJsonImportRequest(request) {
1215
- return request.startsWith("#");
1216
- }
1217
- function normalizeMatchedCssSourcePath(file) {
1218
- if (!file || !node_path.default.isAbsolute(file)) return;
1219
- return node_path.default.resolve(file.replace(/[?#].*$/, ""));
1220
- }
1221
- function stripStyleFileExtension(file) {
1222
- const normalized = file.replace(/[?#].*$/, "");
1223
- const ext = node_path.default.extname(normalized);
1224
- return ext ? normalized.slice(0, -ext.length) : normalized;
1225
- }
1226
- function isAppOriginCssFile(file) {
1227
- return node_path.default.basename(stripStyleFileExtension(file)) === "app-origin";
2455
+ }
2456
+ return injected;
1228
2457
  }
1229
- function isMainAppCssFile(file) {
1230
- return node_path.default.basename(stripStyleFileExtension(file)) === "app";
2458
+ //#endregion
2459
+ //#region src/bundlers/vite/uni-app-x-css-options.ts
2460
+ function resolveUniAppXNativeCssHandlerOptions(opts) {
2461
+ if (opts.appType !== "uni-app-x" || !require_tailwindcss.isUniAppXEnabled(opts.uniAppX) || !require_utils.resolveUniUtsPlatform().isApp) return {};
2462
+ return {
2463
+ uniAppX: true,
2464
+ uniAppXCssTarget: "uvue",
2465
+ uniAppXUnsupported: require_tailwindcss.resolveUniAppXOptions(opts.uniAppX).uvueUnsupported
2466
+ };
1231
2467
  }
1232
- function normalizeCssSourceForCompare(css) {
1233
- return css.trim();
2468
+ //#endregion
2469
+ //#region src/bundlers/vite/generate-bundle.ts
2470
+ function addSiblingCssFile(files, file) {
2471
+ if (file.endsWith(".wxml")) files.add(file.replace(/\.wxml$/, ".wxss"));
2472
+ else if (file.endsWith(".js")) files.add(file.replace(/\.js$/, ".wxss"));
1234
2473
  }
1235
- function createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash) {
1236
- return `${cssRuntimeSignature}:${cssRuntimeAffectingHash}`;
2474
+ function collectRuntimeLinkedCssFiles(snapshot) {
2475
+ const files = /* @__PURE__ */ new Set();
2476
+ for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file);
2477
+ for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file);
2478
+ return files;
1237
2479
  }
1238
2480
  async function createScopedGeneratorCandidateSignature(rawSource, sourceFile, fallbackSignature, getSourceCandidatesForEntries, options = {}) {
1239
2481
  if (!getSourceCandidatesForEntries || !rawSource.includes("@source")) return fallbackSignature;
@@ -1242,124 +2484,11 @@ async function createScopedGeneratorCandidateSignature(rawSource, sourceFile, fa
1242
2484
  const scopedSignature = createCandidateSignature(getSourceCandidatesForEntries(resolved.entries));
1243
2485
  return options.includeFallbackSignature === true ? `${scopedSignature}:${fallbackSignature}` : scopedSignature;
1244
2486
  }
1245
- function isMatchingCssSourceFile(outputFile, cssSourceFile, outputRoot) {
1246
- return stripStyleFileExtension(node_path.default.resolve(outputRoot, outputFile)) === stripStyleFileExtension(node_path.default.resolve(cssSourceFile));
1247
- }
1248
- function collectStyleFileMatchBases(file, roots) {
1249
- const normalizedFile = file.replace(/[?#].*$/, "");
1250
- const bases = /* @__PURE__ */ new Set();
1251
- const addBase = (candidate) => {
1252
- const base = require_bundle_state.slash(stripStyleFileExtension(candidate));
1253
- if (base.length > 0) bases.add(base);
1254
- };
1255
- addBase(normalizedFile);
1256
- const resolvedRoots = roots.filter((root) => typeof root === "string" && root.length > 0).map((root) => node_path.default.resolve(root));
1257
- if (node_path.default.isAbsolute(normalizedFile)) for (const root of resolvedRoots) {
1258
- const relative = node_path.default.relative(root, normalizedFile);
1259
- if (relative && !relative.startsWith("..") && !node_path.default.isAbsolute(relative)) addBase(relative);
1260
- }
1261
- else for (const root of resolvedRoots) addBase(node_path.default.resolve(root, normalizedFile));
1262
- return bases;
1263
- }
1264
- function collectParentDirectories(file) {
1265
- const directories = [];
1266
- let current = node_path.default.dirname(node_path.default.resolve(file.replace(/[?#].*$/, "")));
1267
- while (true) {
1268
- directories.push(current);
1269
- const parent = node_path.default.dirname(current);
1270
- if (parent === current) break;
1271
- current = parent;
1272
- }
1273
- return directories;
1274
- }
1275
- function hasMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) {
1276
- return scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) > 0;
1277
- }
1278
- function scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) {
1279
- const outputBases = collectStyleFileMatchBases(outputFile, [outputRoot]);
1280
- const sourceBases = collectStyleFileMatchBases(sourceFile, [sourceRoot, ...collectParentDirectories(sourceFile)]);
1281
- let bestScore = 0;
1282
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
1283
- else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
1284
- else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
1285
- return bestScore;
1286
- }
1287
- function findRememberedCssSource(sources, outputFile, file, originalSource, outputRoot, sourceRoot) {
1288
- if (!sources) return;
1289
- const rememberedSources = [...sources].map(([, remembered]) => remembered);
1290
- const originalFiles = [
1291
- file,
1292
- originalSource.originalFileName,
1293
- ...originalSource.originalFileNames ?? []
1294
- ].filter((item) => typeof item === "string" && item.length > 0);
1295
- const sourceMatched = rememberedSources.find((remembered) => originalFiles.some((originalFile) => require_bundle_state.normalizeOutputPathKey(remembered.sourceFile) === require_bundle_state.normalizeOutputPathKey(originalFile)));
1296
- if (sourceMatched) return sourceMatched;
1297
- const outputMatched = rememberedSources.find((remembered) => require_bundle_state.normalizeOutputPathKey(remembered.outputFile) === require_bundle_state.normalizeOutputPathKey(outputFile));
1298
- if (outputMatched) return outputMatched;
1299
- const scoredMatches = rememberedSources.filter((remembered) => !(isMainAppCssFile(outputFile) && isAppOriginCssFile(remembered.outputFile))).map((remembered) => ({
1300
- remembered,
1301
- score: Math.max(scoreMatchingStyleFileBase(outputFile, remembered.sourceFile, outputRoot, sourceRoot), scoreMatchingStyleFileBase(outputFile, remembered.outputFile, outputRoot, sourceRoot))
1302
- })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score);
1303
- const bestScore = scoredMatches[0]?.score;
1304
- return bestScore && scoredMatches.filter((match) => match.score === bestScore).length === 1 ? scoredMatches[0]?.remembered : void 0;
1305
- }
1306
- function collectConfiguredTailwindV4CssSources(opts) {
1307
- const patcherCssSources = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssSources ?? [];
1308
- return [...opts.tailwindcss?.v4?.cssSources ?? [], ...patcherCssSources ?? []];
1309
- }
1310
- function collectConfiguredCssEntries(opts) {
1311
- const patcherCssEntries = opts.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssEntries ?? [];
1312
- return [
1313
- ...opts.cssEntries ?? [],
1314
- ...opts.tailwindcss?.v4?.cssEntries ?? [],
1315
- ...patcherCssEntries ?? []
1316
- ].filter((entry) => typeof entry === "string" && entry.length > 0);
1317
- }
1318
- function collectCssConfigBaseCandidates(source, file, outputRoot, opts) {
1319
- const candidates = [];
1320
- const seen = /* @__PURE__ */ new Set();
1321
- const addCandidate = (candidate) => {
1322
- if (!candidate) return;
1323
- const normalized = node_path.default.resolve(candidate);
1324
- if (seen.has(normalized)) return;
1325
- seen.add(normalized);
1326
- candidates.push(normalized);
1327
- };
1328
- addCandidate(node_path.default.dirname(node_path.default.resolve(outputRoot, file.replace(/[?#].*$/, ""))));
1329
- const normalizedSource = normalizeCssSourceForCompare(source);
1330
- const patcherProjectRoot = typeof opts.tailwindcssPatcherOptions?.projectRoot === "string" ? opts.tailwindcssPatcherOptions.projectRoot : void 0;
1331
- const sourceBaseFallback = opts.tailwindcss?.v4?.base ?? patcherProjectRoot ?? opts.tailwindcssBasedir ?? outputRoot;
1332
- const sourceRoot = opts.tailwindcssBasedir ?? patcherProjectRoot;
1333
- const configuredCssEntries = collectConfiguredCssEntries(opts);
1334
- for (const cssEntry of configuredCssEntries) {
1335
- const resolvedCssEntry = node_path.default.resolve(cssEntry);
1336
- if (configuredCssEntries.length === 1 || isMatchingCssSourceFile(file, resolvedCssEntry, outputRoot) || hasMatchingStyleFileBase(file, resolvedCssEntry, outputRoot, sourceRoot)) addCandidate(node_path.default.dirname(resolvedCssEntry));
1337
- }
1338
- for (const cssSource of collectConfiguredTailwindV4CssSources(opts)) {
1339
- const cssSourceFile = normalizeMatchedCssSourcePath(cssSource.file);
1340
- const cssSourceCss = typeof cssSource.css === "string" ? normalizeCssSourceForCompare(cssSource.css) : void 0;
1341
- if (cssSourceFile && !isMatchingCssSourceFile(file, cssSourceFile, outputRoot) && cssSourceCss !== normalizedSource) continue;
1342
- addCandidate(cssSourceFile ? node_path.default.dirname(cssSourceFile) : void 0);
1343
- addCandidate(require_v3_engine.resolveTailwindV4CssSourceBase(cssSource, sourceBaseFallback));
1344
- }
1345
- return candidates;
1346
- }
1347
- function normalizeRelativeCssConfigDirectives(source, file, outputRoot, opts) {
1348
- if (!source.includes("@config")) return source;
1349
- const baseCandidates = collectCssConfigBaseCandidates(source, file, outputRoot, opts);
1350
- return source.replace(/@config\s+(["'])(.+?)\1\s*;?/g, (full, quote, request) => {
1351
- if (node_path.default.isAbsolute(request) || isPackageJsonImportRequest(request)) return full;
1352
- for (const base of baseCandidates) {
1353
- const configFile = node_path.default.resolve(base, request);
1354
- if ((0, node_fs.existsSync)(configFile)) return `@config ${quote}${require_bundle_state.slash(configFile)}${quote};`;
1355
- }
1356
- return full;
1357
- });
1358
- }
1359
2487
  function createGenerateBundleHook(context) {
1360
2488
  const state = require_bundle_state.createBundleBuildState();
1361
2489
  const lastCssResultByFile = /* @__PURE__ */ new Map();
1362
2490
  let currentOutDir;
2491
+ let currentSubpackageRoots;
1363
2492
  const cssHandlerOptions = createCssHandlerOptionsCache({
1364
2493
  getAppType: () => context.opts.appType,
1365
2494
  mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
@@ -1369,26 +2498,36 @@ function createGenerateBundleHook(context) {
1369
2498
  });
1370
2499
  return async function generateBundle(_opt, bundle) {
1371
2500
  const addWatchFile = (id) => this.addWatchFile?.(id);
1372
- const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, isCssAssetProcessed, isViteProcessedCssAsset, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getViteProcessedCssAssetResult, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberCssSource, refreshRememberedCssSource, getRememberedCssSources, getRememberedCssSignature, setRememberedCssSignature, recordGeneratorCandidates, hmrTimingRecorder } = context;
2501
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, isCssAssetProcessed, isViteProcessedCssAsset, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getViteProcessedCssAssetResult, getSourceCandidates, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberCssSource, refreshRememberedCssSource, getRememberedCssSources, getRememberedCssSignature, setRememberedCssSignature, getKnownSfcSource, recordGeneratorCandidates, hmrTimingRecorder } = context;
2502
+ const getBundlerSfcSource = (sourceFile) => {
2503
+ const code = this.getModuleInfo?.(sourceFile)?.code;
2504
+ return typeof code === "string" && hasSfcStyleSources(code) ? code : void 0;
2505
+ };
2506
+ const getSfcSource = (sourceFile) => getBundlerSfcSource(sourceFile) ?? getKnownSfcSource?.(sourceFile);
1373
2507
  const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
1374
2508
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1375
2509
  const isWebGeneratorTarget = generatorOptions.target === "web";
1376
- const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp;
2510
+ const resolvedConfig = getResolvedConfig();
2511
+ const uniUtsPlatform = require_utils.resolveUniUtsPlatform();
2512
+ const isNativeAppStyleTarget = uniUtsPlatform.isApp;
2513
+ const canInferHarmonyAppStyleTarget = !uniUtsPlatform.normalized || uniUtsPlatform.isApp;
2514
+ const isHarmonyAppStyleTarget = uniUtsPlatform.isAppHarmony || canInferHarmonyAppStyleTarget && (isUniAppXHarmonyBundle(bundle) || isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir));
2515
+ const shouldPreserveAppCssExtension = isNativeAppStyleTarget || isHarmonyAppStyleTarget;
1377
2516
  const shouldGenerateWebCssByGenerator = isWebGeneratorTarget && runtimeState.twPatcher.majorVersion === 3;
1378
2517
  const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
1379
- const resolvedConfig = getResolvedConfig();
1380
2518
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
1381
2519
  const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1382
2520
  await runtimeState.readyPromise;
1383
2521
  debug("start");
1384
2522
  onStart();
2523
+ const collectedBundlerGeneratedCssFiles = new Set(Object.entries(bundle).filter(([, output]) => output.type === "asset" && require_bundle_state.hasBundlerGeneratedCssMarker(output.source)).map(([file]) => file));
1385
2524
  collectViteProcessedCssAssetResults(bundle, {
1386
2525
  opts,
1387
2526
  isViteProcessedCssAsset,
1388
2527
  markCssAssetProcessed,
1389
2528
  recordCssAssetResult,
1390
2529
  recordViteProcessedCssAssetResult,
1391
- resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget),
2530
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension),
1392
2531
  debug
1393
2532
  });
1394
2533
  const hmrTimingStartedAt = performance.now();
@@ -1411,6 +2550,9 @@ function createGenerateBundleHook(context) {
1411
2550
  const debugCssDiff = node_process.default.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
1412
2551
  const disableV3OxideSourceRuntime = node_process.default.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1";
1413
2552
  const bundleFiles = Object.keys(bundle);
2553
+ const subpackageRoots = collectMiniProgramSubpackageRoots(bundle);
2554
+ if (subpackageRoots) currentSubpackageRoots = subpackageRoots;
2555
+ const isMainPackageStyleOutputFile = (file) => currentSubpackageRoots != null && !isSubpackageOutputFile(file, currentSubpackageRoots);
1414
2556
  const buildCommand = resolvedConfig?.command === "build";
1415
2557
  const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
1416
2558
  const hasOmittedKnownFiles = hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
@@ -1418,6 +2560,29 @@ function createGenerateBundleHook(context) {
1418
2560
  currentOutDir = outDir;
1419
2561
  const snapshotStart = performance.now();
1420
2562
  const snapshot = require_bundle_state.buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode, { hasOmittedKnownFiles });
2563
+ const subpackageSourceExcludeEntries = currentSubpackageRoots ? collectMiniProgramSubpackageSourceEntries(snapshot, currentSubpackageRoots, [
2564
+ rootDir,
2565
+ opts.tailwindcssBasedir,
2566
+ opts.tailwindcssPatcherOptions?.projectRoot
2567
+ ]) : [];
2568
+ const shouldExcludeSubpackageSourceCandidates = (outputFile, cssHandlerOptions) => cssHandlerOptions.isMainChunk === true && subpackageSourceExcludeEntries.length > 0 && isMainPackageStyleOutputFile(outputFile);
2569
+ const createScopedSourceCandidateGetter = (outputFile, cssHandlerOptions) => {
2570
+ if (!getSourceCandidatesForEntries) return;
2571
+ if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return getSourceCandidatesForEntries;
2572
+ return (entries, options) => getSourceCandidatesForEntries(entries, {
2573
+ ...options,
2574
+ excludeEntries: [...options?.excludeEntries ?? [], ...subpackageSourceExcludeEntries]
2575
+ });
2576
+ };
2577
+ const createScopedSourceCandidateSourceGetter = (outputFile, cssHandlerOptions) => {
2578
+ if (!getSourceCandidateSourcesForEntries) return;
2579
+ if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return getSourceCandidateSourcesForEntries;
2580
+ return (entries, options) => getSourceCandidateSourcesForEntries(entries, {
2581
+ ...options,
2582
+ excludeEntries: [...options?.excludeEntries ?? [], ...subpackageSourceExcludeEntries]
2583
+ });
2584
+ };
2585
+ const shouldInjectCssIntoMainFromOutput = (outputFile, sourceFile, outputCssHandlerOptions) => isMainStyleEntryCssFile(sourceFile) || isTailwindEntryCssFile(outputFile) || useIncrementalMode && (outputCssHandlerOptions.isMainChunk || isMainPackageStyleOutputFile(outputFile));
1421
2586
  recordTimingDetail("snapshot", snapshotStart);
1422
2587
  const useBundleRuntimeClassSet = !isWebGeneratorTarget && (useIncrementalMode || runtimeState.twPatcher.majorVersion === 4);
1423
2588
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
@@ -1432,6 +2597,12 @@ function createGenerateBundleHook(context) {
1432
2597
  await waitForSourceCandidateSyncs?.();
1433
2598
  recordTimingDetail("sourceCandidates.wait", sourceCandidateWaitStart);
1434
2599
  const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
2600
+ const createScopedGeneratorRuntime = (outputFile, cssHandlerOptions, runtime) => {
2601
+ if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return runtime;
2602
+ const filteredSourceCandidates = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions)?.(void 0);
2603
+ if (!filteredSourceCandidates) return runtime;
2604
+ return filteredSourceCandidates.size > 0 ? filteredSourceCandidates : runtime;
2605
+ };
1435
2606
  const jsEntries = snapshot.jsEntries;
1436
2607
  const getJsEntry = createJsEntryResolver(jsEntries);
1437
2608
  const moduleGraphOptions = require_bundle_state.createBundleModuleGraphOptions(outDir, jsEntries);
@@ -1440,10 +2611,11 @@ function createGenerateBundleHook(context) {
1440
2611
  const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !forceRuntimeRefreshByEnv && !disableV3OxideSourceRuntime;
1441
2612
  const runtimeStart = performance.now();
1442
2613
  const transformBaseRuntime = useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { transformOnly: true }) : void 0;
2614
+ const forceV4RuntimeRefreshBySource = runtimeState.twPatcher.majorVersion === 4 && forceRuntimeRefreshBySource;
1443
2615
  const runtime = isWebGeneratorTarget && !shouldGenerateWebCssByGenerator ? /* @__PURE__ */ new Set() : useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, {
1444
2616
  allowBaselineOnlyInitialSync: true,
1445
2617
  baseClassSet: sourceCandidates
1446
- }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
2618
+ }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv || forceV4RuntimeRefreshBySource, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1447
2619
  if (useV3OxideSourceRuntime) debug("[tailwindcss:v3] use oxide source candidates as runtime input, candidates=%d", sourceCandidates.size);
1448
2620
  const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1449
2621
  const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
@@ -1454,7 +2626,7 @@ function createGenerateBundleHook(context) {
1454
2626
  if (runtimeState.twPatcher.majorVersion === 3 && useV3OxideSourceRuntime && generatorRuntime.size > 0 && (state.iteration === 0 || !hasRuntimeAffectingChanges) && cssEntries.length <= 1) {
1455
2627
  const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
1456
2628
  if (mainCssEntry) {
1457
- const validatedRuntime = await require_incremental_runtime_class_set.validateCandidatesByGenerator({
2629
+ const validatedRuntime = await require_hmr_timing.validateCandidatesByGenerator({
1458
2630
  opts,
1459
2631
  runtimeState,
1460
2632
  candidates: generatorRuntime,
@@ -1513,7 +2685,7 @@ function createGenerateBundleHook(context) {
1513
2685
  }
1514
2686
  if (!processFiles.html.has(file)) continue;
1515
2687
  const rawSource = originalEntrySource;
1516
- tasks.push(timeTask("html", () => require_incremental_runtime_class_set.processCachedTask({
2688
+ tasks.push(timeTask("html", () => require_hmr_timing.processCachedTask({
1517
2689
  cache,
1518
2690
  cacheKey: file,
1519
2691
  hashKey: `${file}:html:${runtimeSignature}`,
@@ -1554,7 +2726,7 @@ function createGenerateBundleHook(context) {
1554
2726
  if (type === "css" && originalSource.type === "asset") {
1555
2727
  metrics.css.total++;
1556
2728
  const rawSource = normalizeRelativeCssConfigDirectives(originalEntrySource, file, outDir, opts);
1557
- const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget);
2729
+ const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, shouldPreserveAppCssExtension);
1558
2730
  if (outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file)) {
1559
2731
  delete bundle[file];
1560
2732
  debug("css skip raw source style asset: %s -> %s", file, outputFile);
@@ -1584,43 +2756,66 @@ function createGenerateBundleHook(context) {
1584
2756
  const viteProcessedCssAsset = isViteProcessedCssAsset?.(originalSource, file) === true || hasViteProcessedCssRecord;
1585
2757
  const cssAssetProcessed = isCssAssetProcessed?.(originalSource, file) === true;
1586
2758
  const alreadyProcessedCssAsset = viteProcessedCssAsset || cssAssetProcessed;
1587
- let rememberedCssSource = findRememberedCssSource(getRememberedCssSources?.(), outputFile, file, originalSource, outDir, opts.tailwindcssBasedir);
1588
- if (rememberedCssSource != null) rememberedCssSource = await refreshRememberedCssSource?.(rememberedCssSource) ?? rememberedCssSource;
2759
+ let rememberedCssSources = findRememberedCssSources(getRememberedCssSources?.(), outputFile, file, originalSource, outDir, opts.tailwindcssBasedir);
2760
+ if (rememberedCssSources.length > 0) rememberedCssSources = await Promise.all(rememberedCssSources.map(async (remembered) => await refreshRememberedCssSource?.(remembered) ?? remembered));
2761
+ const hasUsableRememberedTailwindSource = rememberedCssSources.some((remembered) => hasTailwindGenerationSource(remembered.rawSource) && require_bundle_state.normalizeOutputPathKey(remembered.sourceFile.replace(/[?#].*$/, "")) !== require_bundle_state.normalizeOutputPathKey(file));
2762
+ const inferredSfcStyleSource = await resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outDir, opts.tailwindcssBasedir, getSfcSource, debug);
2763
+ if (inferredSfcStyleSource) {
2764
+ const inferredSourceFile = normalizeSfcSourceFileForCompare(inferredSfcStyleSource.sourceFile);
2765
+ const rememberedSourcesBelongToInferredSfc = rememberedCssSources.length > 0 && rememberedCssSources.every((remembered) => normalizeSfcSourceFileForCompare(remembered.sourceFile) === inferredSourceFile);
2766
+ if (!hasUsableRememberedTailwindSource || rememberedSourcesBelongToInferredSfc) rememberedCssSources = [inferredSfcStyleSource];
2767
+ }
2768
+ const rememberedCssSource = mergeRememberedCssSources(rememberedCssSources, outputFile);
1589
2769
  const useRememberedCssSource = rememberedCssSource != null && require_bundle_state.normalizeOutputPathKey(rememberedCssSource.sourceFile) !== require_bundle_state.normalizeOutputPathKey(file);
1590
2770
  const vitePipelineCssAsset = viteProcessedCssAsset || useRememberedCssSource;
1591
2771
  const generatorRawSource = vitePipelineCssAsset ? rememberedCssSource?.rawSource ?? rawSource : rawSource;
1592
2772
  const hasRememberedApplySource = vitePipelineCssAsset && rememberedCssSource != null && require_v3_engine.hasTailwindApplyDirective(generatorRawSource);
1593
2773
  const hasDifferentRememberedCssSource = rememberedCssSource != null && normalizeCssSourceForCompare(rememberedCssSource.rawSource) !== normalizeCssSourceForCompare(rawSource);
1594
- const hasCurrentTailwindGenerationDirective = require_v3_engine.hasTailwindRootDirectives(rawSource, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(rawSource);
2774
+ const hasCurrentTailwindGenerationDirective = require_v3_engine.hasTailwindSourceDirectives(rawSource, { importFallback: true }) || require_v3_engine.hasTailwindRootDirectives(rawSource, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(rawSource);
1595
2775
  const hasRememberedApplyDirective = rememberedCssSource != null && require_v3_engine.hasTailwindApplyDirective(rememberedCssSource.rawSource);
1596
2776
  const hasStaleViteProcessedCssSource = vitePipelineCssAsset && hasDifferentRememberedCssSource && (hasCurrentTailwindGenerationDirective || hasRememberedApplyDirective);
1597
2777
  const generatorSourceFile = vitePipelineCssAsset ? rememberedCssSource?.sourceFile ?? file : file;
1598
2778
  const outputCssHandlerOptions = getCssHandlerOptions(outputFile);
1599
2779
  const cssHandlerOptions = vitePipelineCssAsset ? {
1600
2780
  ...getCssHandlerOptions(generatorSourceFile),
1601
- isMainChunk: outputCssHandlerOptions.isMainChunk || isAppOriginCssFile(file)
2781
+ isMainChunk: outputCssHandlerOptions.isMainChunk || isAppOriginCssFile(file) || isMainStyleEntryCssFile(generatorSourceFile)
1602
2782
  } : getCssHandlerOptions(file);
2783
+ const scopedSourceCandidateGetter = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions);
2784
+ const scopedSourceCandidateSourceGetter = createScopedSourceCandidateSourceGetter(outputFile, cssHandlerOptions);
2785
+ const sourceTraceTokenSources = scopedSourceCandidateSourceGetter ? require_hmr_timing.createCssTokenSourceMap(scopedSourceCandidateSourceGetter(void 0), opts) : void 0;
2786
+ const sourceTraceSignature = require_hmr_timing.createCssSourceTraceCacheSignature(sourceTraceTokenSources, opts);
2787
+ const scopedGeneratorRuntime = createScopedGeneratorRuntime(outputFile, cssHandlerOptions, generatorRuntime);
2788
+ const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
2789
+ opts,
2790
+ tokenSources: sourceTraceTokenSources
2791
+ });
2792
+ const shouldRegenerateMainPackageCssWithScopedCandidates = vitePipelineCssAsset && shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions);
1603
2793
  const generatorCssUserHandlerOptions = getCssUserHandlerOptions(generatorSourceFile);
1604
2794
  const cssRuntimeAffectingSignature = vitePipelineCssAsset ? require_bundle_state.createRuntimeAffectingSourceSignature(generatorRawSource, "css") : snapshot.runtimeAffectingSignatureByFile.get(file) ?? require_bundle_state.createRuntimeAffectingSourceSignature(generatorRawSource, "css");
1605
2795
  const cssRuntimeAffectingHash = vitePipelineCssAsset ? cache.computeHash(cssRuntimeAffectingSignature) : snapshot.runtimeAffectingHashByFile.get(file) ?? cache.computeHash(cssRuntimeAffectingSignature);
1606
2796
  const cssShareScope = createCssTransformShareScopeKey(opts, generatorSourceFile, generatorRawSource);
1607
2797
  const shouldRegenerateAppOriginCss = viteProcessedCssAsset && isAppOriginCssFile(file);
1608
- const shouldTrackGeneratorRuntime = hasStaleViteProcessedCssSource || shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file) || shouldRegenerateAppOriginCss);
1609
- const canRegenerateProcessedMainCss = cssHandlerOptions.isMainChunk && (getViteProcessedCssAssetResult?.(file)?.injectIntoMain === true || shouldRegenerateAppOriginCss);
1610
- if (alreadyProcessedCssAsset && !hasStaleViteProcessedCssSource && !hasRememberedApplySource && (!shouldTrackGeneratorRuntime || !canRegenerateProcessedMainCss)) {
2798
+ const shouldTrackGeneratorRuntime = hasStaleViteProcessedCssSource || shouldRegenerateMainPackageCssWithScopedCandidates || hasCurrentTailwindGenerationDirective || shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file) || shouldRegenerateAppOriginCss || hasRuntimeAffectingChanges && (alreadyProcessedCssAsset || vitePipelineCssAsset));
2799
+ const shouldPreserveCollectedViteCssAsset = !shouldRegenerateAppOriginCss && (collectedBundlerGeneratedCssFiles.has(file) || require_bundle_state.hasBundlerGeneratedCssMarker(rawSource));
2800
+ if (alreadyProcessedCssAsset && !hasStaleViteProcessedCssSource && !hasRememberedApplySource && !shouldRegenerateMainPackageCssWithScopedCandidates && (!shouldTrackGeneratorRuntime || shouldPreserveCollectedViteCssAsset)) {
1611
2801
  const nextCss = require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
1612
2802
  applyCssResult(nextCss);
1613
2803
  markCssAssetProcessed?.(originalSource, outputFile);
1614
2804
  recordCssAssetResult?.(outputFile, nextCss);
2805
+ const shouldInjectPreservedViteCssIntoMain = vitePipelineCssAsset && !isAppOriginCssFile(file) && shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions);
2806
+ recordViteProcessedCssAssetResult?.(outputFile, nextCss, {
2807
+ injectIntoMain: isAppOriginCssFile(file) ? false : shouldInjectPreservedViteCssIntoMain,
2808
+ outputFile
2809
+ });
1615
2810
  onUpdate(outputFile, rawSource, nextCss);
1616
2811
  debug("css skip vite-processed asset: %s", outputFile);
1617
2812
  continue;
1618
2813
  }
1619
- const trackedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? generatorCandidateSignature : "generator:stable";
1620
- const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? await createScopedGeneratorCandidateSignature(generatorRawSource, generatorSourceFile, trackedGeneratorCandidateSignature, getSourceCandidatesForEntries, { includeFallbackSignature: cssHandlerOptions.isMainChunk }) : trackedGeneratorCandidateSignature;
2814
+ const trackedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? createCandidateSignature(scopedGeneratorRuntime) : "generator:stable";
2815
+ const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? await createScopedGeneratorCandidateSignature(generatorRawSource, generatorSourceFile, trackedGeneratorCandidateSignature, scopedSourceCandidateGetter, { includeFallbackSignature: cssHandlerOptions.isMainChunk }) : trackedGeneratorCandidateSignature;
1621
2816
  const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
1622
2817
  const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash);
1623
- const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
2818
+ const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}:${sourceTraceSignature}`;
1624
2819
  if (!shouldTrackGeneratorRuntime) {
1625
2820
  const lastCss = lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file);
1626
2821
  if (lastCss != null) {
@@ -1631,16 +2826,16 @@ function createGenerateBundleHook(context) {
1631
2826
  continue;
1632
2827
  }
1633
2828
  }
1634
- tasks.push(timeTask("css", () => require_incremental_runtime_class_set.processCachedTask({
2829
+ tasks.push(timeTask("css", () => require_hmr_timing.processCachedTask({
1635
2830
  cache,
1636
2831
  cacheKey: file,
1637
2832
  hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1638
- hash: `${cssRuntimeAffectingHash}:${scopedGeneratorCandidateSignature}`,
2833
+ hash: `${cssRuntimeAffectingHash}:${scopedGeneratorCandidateSignature}:${sourceTraceSignature}`,
1639
2834
  applyResult(source) {
1640
2835
  applyCssResult(source);
1641
2836
  lastCssResultByFile.set(outputFile, source);
1642
2837
  markCssAssetProcessed?.(originalSource, outputFile);
1643
- rememberCssSource?.({
2838
+ if (rememberedCssSources.length <= 1) rememberCssSource?.({
1644
2839
  outputFile,
1645
2840
  rawSource: generatorRawSource,
1646
2841
  sourceFile: generatorSourceFile
@@ -1664,43 +2859,51 @@ function createGenerateBundleHook(context) {
1664
2859
  const runTransform = async () => {
1665
2860
  const start = performance.now();
1666
2861
  await runtimeState.readyPromise;
1667
- const previousCss = !vitePipelineCssAsset && useIncrementalMode && !hasRuntimeAffectingChanges && !snapshot.changedByType.css.has(file) ? lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file) : void 0;
1668
- const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
2862
+ const generated = await require_hmr_timing.generateCssByGenerator({
1669
2863
  opts,
1670
2864
  runtimeState,
1671
- runtime: generatorRuntime,
2865
+ runtime: scopedGeneratorRuntime,
1672
2866
  rawSource: generatorRawSource,
1673
2867
  file: generatorSourceFile,
1674
2868
  cssHandlerOptions,
1675
2869
  cssUserHandlerOptions: generatorCssUserHandlerOptions,
1676
- getSourceCandidatesForEntries,
2870
+ getSourceCandidatesForEntries: scopedSourceCandidateGetter,
1677
2871
  styleHandler,
1678
2872
  debug,
1679
- previousCss
2873
+ previousCss: !vitePipelineCssAsset && useIncrementalMode && !hasRuntimeAffectingChanges && !snapshot.changedByType.css.has(file) ? lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file) : void 0
1680
2874
  });
1681
2875
  if (generated) {
2876
+ const tracedCss = annotateCss(generated.css);
1682
2877
  registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
1683
- if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, generated.css));
1684
- debug("css generated result: %s bytes=%d", file, generated.css.length);
1685
- recordCssAssetResult?.(outputFile, generated.css);
1686
- if (vitePipelineCssAsset && cssHandlerOptions.isMainChunk) recordViteProcessedCssAssetResult?.(file, generated.css, { injectIntoMain: !isAppOriginCssFile(file) });
1687
- if (vitePipelineCssAsset) recordViteProcessedCssAssetResult?.(outputFile, generated.css, { injectIntoMain: false });
2878
+ if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
2879
+ debug("css generated result: %s bytes=%d", file, tracedCss.length);
2880
+ recordCssAssetResult?.(outputFile, tracedCss);
2881
+ const shouldInjectVitePipelineCssIntoMain = vitePipelineCssAsset && !isAppOriginCssFile(file) && shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions);
2882
+ recordViteProcessedCssAssetResult?.(outputFile, tracedCss, {
2883
+ injectIntoMain: isAppOriginCssFile(file) ? false : shouldInjectVitePipelineCssIntoMain,
2884
+ outputFile
2885
+ });
2886
+ if (vitePipelineCssAsset && shouldInjectVitePipelineCssIntoMain) recordViteProcessedCssAssetResult?.(file, tracedCss, {
2887
+ injectIntoMain: isAppOriginCssFile(file) ? false : shouldInjectVitePipelineCssIntoMain,
2888
+ outputFile
2889
+ });
1688
2890
  metrics.css.elapsed += measureElapsed(start);
1689
2891
  metrics.css.transformed++;
1690
2892
  debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, outputFile);
1691
- return generated.css;
2893
+ return tracedCss;
1692
2894
  }
1693
2895
  if (isWebGeneratorTarget) {
1694
2896
  metrics.css.elapsed += measureElapsed(start);
1695
2897
  metrics.css.transformed++;
1696
2898
  debug("css preserve web target: %s", outputFile);
1697
- return rawSource;
2899
+ return annotateCss(rawSource);
1698
2900
  }
1699
2901
  const { css } = await styleHandler(generatorRawSource, cssHandlerOptions);
1700
- if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, css));
2902
+ const tracedCss = annotateCss(css);
2903
+ if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, tracedCss));
1701
2904
  metrics.css.elapsed += measureElapsed(start);
1702
2905
  metrics.css.transformed++;
1703
- return css;
2906
+ return tracedCss;
1704
2907
  };
1705
2908
  const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1706
2909
  if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
@@ -1728,7 +2931,7 @@ function createGenerateBundleHook(context) {
1728
2931
  jsTaskFactories.push(async () => {
1729
2932
  await timeTask("js", async () => {
1730
2933
  const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1731
- await require_incremental_runtime_class_set.processCachedTask({
2934
+ await require_hmr_timing.processCachedTask({
1732
2935
  cache,
1733
2936
  cacheKey: file,
1734
2937
  hashKey: `${file}:js`,
@@ -1773,9 +2976,10 @@ function createGenerateBundleHook(context) {
1773
2976
  const factory = createUniAppXAssetTask(file, originalSource, outDir, {
1774
2977
  cache,
1775
2978
  hashKey: `${file}:js`,
1776
- hashSalt: createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0),
2979
+ hashSalt: createJsHashSalt(runtimeSignature, [UNI_APP_X_STYLE_PLACEHOLDER_VERSION, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0].filter(Boolean).join(":")),
1777
2980
  createHandlerOptions,
1778
2981
  debug,
2982
+ getAssetSource: createUniAppXBundleAssetSourceGetter(bundle),
1779
2983
  jsHandler,
1780
2984
  onUpdate,
1781
2985
  runtimeSet: transformRuntime,
@@ -1812,61 +3016,146 @@ function createGenerateBundleHook(context) {
1812
3016
  });
1813
3017
  }
1814
3018
  }
1815
- if (useIncrementalMode || isNativeAppStyleTarget) for (const [key, rememberedEntry] of getRememberedCssSources?.() ?? []) {
1816
- const { outputFile: rememberedOutputFile, rawSource, sourceFile } = await refreshRememberedCssSource?.(rememberedEntry) ?? rememberedEntry;
1817
- const outputFile = resolveViteCssPipelineOutputFile(rememberedOutputFile, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget);
1818
- const cssHandlerOptions = getCssHandlerOptions(outputFile);
1819
- const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(createCssRuntimeSignature(runtimeSignature, await createScopedGeneratorCandidateSignature(rawSource, sourceFile, generatorCandidateSignature, getSourceCandidatesForEntries, { includeFallbackSignature: cssHandlerOptions.isMainChunk })), cache.computeHash(require_bundle_state.createRuntimeAffectingSourceSignature(rawSource, "css")));
1820
- if (bundleFiles.includes(outputFile) || bundleFiles.includes(sourceFile) || getRememberedCssSignature?.(key) === rememberedCssRuntimeSignature) continue;
1821
- tasks.push(timeTask("css.replay", async () => {
1822
- const start = performance.now();
1823
- const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
3019
+ if (useIncrementalMode || isNativeAppStyleTarget) {
3020
+ const rememberedReplayGroups = collectRememberedCssReplayGroups(getRememberedCssSources?.(), opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension);
3021
+ for (const [outputFile, rememberedGroup] of rememberedReplayGroups) {
3022
+ const refreshedRememberedGroup = await Promise.all(rememberedGroup.map(async (item) => ({
3023
+ key: item.key,
3024
+ remembered: await refreshRememberedCssSource?.(item.remembered) ?? item.remembered
3025
+ })));
3026
+ const rememberedCssSource = mergeRememberedCssSources(refreshedRememberedGroup.map((item) => item.remembered), outputFile);
3027
+ if (!rememberedCssSource) continue;
3028
+ const { rawSource, sourceFile } = rememberedCssSource;
3029
+ const outputCssHandlerOptions = getCssHandlerOptions(outputFile);
3030
+ const cssHandlerOptions = {
3031
+ ...getCssHandlerOptions(sourceFile),
3032
+ isMainChunk: outputCssHandlerOptions.isMainChunk || isMainStyleEntryCssFile(sourceFile)
3033
+ };
3034
+ const scopedSourceCandidateGetter = createScopedSourceCandidateGetter(outputFile, cssHandlerOptions);
3035
+ const scopedSourceCandidateSourceGetter = createScopedSourceCandidateSourceGetter(outputFile, cssHandlerOptions);
3036
+ const sourceTraceTokenSources = scopedSourceCandidateSourceGetter ? require_hmr_timing.createCssTokenSourceMap(scopedSourceCandidateSourceGetter(void 0), opts) : void 0;
3037
+ const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
1824
3038
  opts,
1825
- runtimeState,
1826
- runtime: generatorRuntime,
1827
- rawSource,
1828
- file: sourceFile,
1829
- cssHandlerOptions,
1830
- cssUserHandlerOptions: getCssUserHandlerOptions(outputFile),
1831
- getSourceCandidatesForEntries,
1832
- styleHandler,
1833
- debug
1834
- });
1835
- const css = generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css;
1836
- setRememberedCssSignature?.(key, rememberedCssRuntimeSignature);
1837
- if (generated) {
1838
- registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
1839
- recordCssAssetResult?.(outputFile, generated.css);
1840
- recordViteProcessedCssAssetResult?.(sourceFile, generated.css, { injectIntoMain: cssHandlerOptions.isMainChunk });
1841
- debug("css replay generated result: %s bytes=%d", outputFile, css.length);
1842
- }
1843
- const replayAsset = createReplayCssAsset(outputFile, css);
1844
- if (typeof this.emitFile === "function") this.emitFile({
1845
- type: "asset",
1846
- fileName: outputFile,
1847
- source: css
3039
+ tokenSources: sourceTraceTokenSources
1848
3040
  });
1849
- else bundle[outputFile] = replayAsset;
1850
- markCssAssetProcessed?.(replayAsset, outputFile);
1851
- metrics.css.elapsed += measureElapsed(start);
1852
- metrics.css.transformed++;
1853
- onUpdate(outputFile, rawSource, css);
1854
- debug("css replay handle: %s", outputFile);
1855
- }));
3041
+ const scopedGeneratorRuntime = createScopedGeneratorRuntime(outputFile, cssHandlerOptions, generatorRuntime);
3042
+ const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(createCssRuntimeSignature(createCandidateSignature(scopedGeneratorRuntime), await createScopedGeneratorCandidateSignature(rawSource, sourceFile, createCandidateSignature(scopedGeneratorRuntime), scopedSourceCandidateGetter, { includeFallbackSignature: cssHandlerOptions.isMainChunk })), cache.computeHash(require_bundle_state.createRuntimeAffectingSourceSignature(rawSource, "css")));
3043
+ const rememberedKeys = refreshedRememberedGroup.map((item) => item.key);
3044
+ const allRememberedSignaturesFresh = rememberedKeys.length > 0 && rememberedKeys.every((key) => getRememberedCssSignature?.(key) === rememberedCssRuntimeSignature);
3045
+ if (bundleFiles.includes(outputFile) || bundleFiles.includes(sourceFile) || allRememberedSignaturesFresh) continue;
3046
+ tasks.push(timeTask("css.replay", async () => {
3047
+ const start = performance.now();
3048
+ const generated = await require_hmr_timing.generateCssByGenerator({
3049
+ opts,
3050
+ runtimeState,
3051
+ runtime: scopedGeneratorRuntime,
3052
+ rawSource,
3053
+ file: sourceFile,
3054
+ cssHandlerOptions,
3055
+ cssUserHandlerOptions: getCssUserHandlerOptions(sourceFile),
3056
+ getSourceCandidatesForEntries: scopedSourceCandidateGetter,
3057
+ styleHandler,
3058
+ debug
3059
+ });
3060
+ const css = annotateCss(generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css);
3061
+ for (const key of rememberedKeys) setRememberedCssSignature?.(key, rememberedCssRuntimeSignature);
3062
+ if (generated) {
3063
+ registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
3064
+ recordCssAssetResult?.(outputFile, css);
3065
+ const shouldInjectReplayCssIntoMain = shouldInjectCssIntoMainFromOutput(outputFile, sourceFile, outputCssHandlerOptions);
3066
+ recordViteProcessedCssAssetResult?.(sourceFile, css, {
3067
+ injectIntoMain: isAppOriginCssFile(outputFile) ? false : shouldInjectReplayCssIntoMain,
3068
+ outputFile
3069
+ });
3070
+ debug("css replay generated result: %s bytes=%d", outputFile, css.length);
3071
+ }
3072
+ const replayAsset = createReplayCssAsset(outputFile, css);
3073
+ if (typeof this.emitFile === "function") this.emitFile({
3074
+ type: "asset",
3075
+ fileName: outputFile,
3076
+ source: css
3077
+ });
3078
+ else bundle[outputFile] = replayAsset;
3079
+ markCssAssetProcessed?.(replayAsset, outputFile);
3080
+ metrics.css.elapsed += measureElapsed(start);
3081
+ metrics.css.transformed++;
3082
+ onUpdate(outputFile, rawSource, css);
3083
+ debug("css replay handle: %s", outputFile);
3084
+ }));
3085
+ }
1856
3086
  }
1857
3087
  require_bundle_state.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1858
3088
  const tasksStart = performance.now();
1859
3089
  await Promise.all(tasks);
1860
3090
  recordTimingDetail("tasks", tasksStart);
1861
3091
  for (const apply of pendingLinkedUpdates) apply();
1862
- injectViteProcessedCssIntoMainCssAssets(bundle, {
1863
- opts,
1864
- getViteProcessedCssAssetResults,
1865
- markCssAssetProcessed,
1866
- recordCssAssetResult,
1867
- debug,
1868
- onUpdate
1869
- });
3092
+ const applyStyleSources = collectUniAppXHarmonyApplyStyleSources(bundle);
3093
+ if (opts.appType === "uni-app-x" || isNativeAppStyleTarget || isHarmonyAppStyleTarget) {
3094
+ const getAssetSource = createUniAppXBundleAssetSourceGetter(bundle);
3095
+ const viteProcessedCssSources = [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css);
3096
+ const applyUtilities = collectUniAppXHarmonyApplyUtilities(bundle);
3097
+ const shouldInjectHarmonyBundleStyles = isHarmonyAppStyleTarget;
3098
+ if (shouldInjectHarmonyBundleStyles) {
3099
+ if (applyUtilities.size > 0 && applyStyleSources.length > 0) {
3100
+ const outputFile = "uni-app-x-harmony-apply.css";
3101
+ const cssHandlerOptions = getCssHandlerOptions(outputFile);
3102
+ const generated = await require_hmr_timing.generateCssByGenerator({
3103
+ opts,
3104
+ runtimeState,
3105
+ runtime: new Set([...generatorRuntime, ...applyUtilities]),
3106
+ rawSource: createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities),
3107
+ file: outputFile,
3108
+ cssHandlerOptions,
3109
+ cssUserHandlerOptions: {
3110
+ ...cssHandlerOptions,
3111
+ isMainChunk: false
3112
+ },
3113
+ getSourceCandidatesForEntries,
3114
+ styleHandler,
3115
+ debug
3116
+ });
3117
+ if (generated?.css) viteProcessedCssSources.push(require_hmr_timing.annotateCssSourceTrace(generated.css, {
3118
+ opts,
3119
+ tokenSources: getSourceCandidateSourcesForEntries ? require_hmr_timing.createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts) : void 0
3120
+ }));
3121
+ }
3122
+ }
3123
+ if (shouldInjectHarmonyBundleStyles && injectUniAppXHarmonyBundleStyles(bundle, { cssSources: viteProcessedCssSources })) debug("uni-app-x harmony bundle styles inject");
3124
+ for (const [file, item] of Object.entries(bundle)) {
3125
+ if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
3126
+ const currentSource = String(item.source);
3127
+ const nextSource = injectUniAppXStylePlaceholder(file, currentSource, getAssetSource);
3128
+ if (nextSource !== currentSource) {
3129
+ item.source = nextSource;
3130
+ onUpdate(file, currentSource, nextSource);
3131
+ debug("uni-app-x style placeholder inject: %s", file);
3132
+ }
3133
+ }
3134
+ }
3135
+ const syncViteProcessedCssIntoMainCssAssets = () => {
3136
+ collectViteProcessedCssAssetResults(bundle, {
3137
+ opts,
3138
+ isViteProcessedCssAsset,
3139
+ markCssAssetProcessed,
3140
+ recordCssAssetResult,
3141
+ recordViteProcessedCssAssetResult,
3142
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension),
3143
+ debug
3144
+ });
3145
+ return injectViteProcessedCssIntoMainCssAssets(bundle, {
3146
+ opts,
3147
+ getViteProcessedCssAssetResults,
3148
+ markCssAssetProcessed,
3149
+ recordCssAssetResult,
3150
+ debug,
3151
+ onUpdate
3152
+ });
3153
+ };
3154
+ syncViteProcessedCssIntoMainCssAssets();
3155
+ if (isHarmonyAppStyleTarget && applyStyleSources.length > 0) {
3156
+ if (injectUniAppXHarmonyBundleStyles(bundle, { cssSources: [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css) })) debug("uni-app-x harmony bundle styles inject after css assets");
3157
+ syncViteProcessedCssIntoMainCssAssets();
3158
+ }
1870
3159
  const stateUpdateStart = performance.now();
1871
3160
  require_bundle_state.updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1872
3161
  state.generatorCandidateSignature = generatorCandidateSignature;
@@ -1917,6 +3206,9 @@ function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
1917
3206
  function shouldFinalizeProcessedCssAsset(opts, file) {
1918
3207
  return opts.mainCssChunkMatcher(file, opts.appType);
1919
3208
  }
3209
+ function collectViteProcessedCssSources(getViteProcessedCssAssetResults) {
3210
+ return [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css);
3211
+ }
1920
3212
  function createViteCssFinalizerOutputPlugin(context) {
1921
3213
  return {
1922
3214
  name: "weapp-tailwindcss:adaptor:css-finalizer",
@@ -1924,29 +3216,34 @@ function createViteCssFinalizerOutputPlugin(context) {
1924
3216
  generateBundle: {
1925
3217
  order: "post",
1926
3218
  async handler(_options, bundle) {
1927
- const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
3219
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
1928
3220
  const resolvedConfig = getResolvedConfig();
1929
- if (resolvedConfig?.command !== "build") return;
1930
3221
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1931
3222
  const isWebGeneratorTarget = generatorOptions.target === "web";
1932
- const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp;
1933
- const rootDir = resolvedConfig.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
1934
- collectViteProcessedCssAssetResults(bundle, {
3223
+ const uniUtsPlatform = require_utils.resolveUniUtsPlatform();
3224
+ const canInferHarmonyAppStyleTarget = !uniUtsPlatform.normalized || uniUtsPlatform.isApp;
3225
+ const isHarmonyAppStyleTarget = uniUtsPlatform.isAppHarmony || canInferHarmonyAppStyleTarget && (isUniAppXHarmonyBundle(bundle) || isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir));
3226
+ const isNativeAppStyleTarget = uniUtsPlatform.isApp || isHarmonyAppStyleTarget;
3227
+ if (resolvedConfig?.command !== "build" && !isNativeAppStyleTarget) return;
3228
+ const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
3229
+ const sourceTraceTokenSources = getSourceCandidateSourcesForEntries ? require_hmr_timing.createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts) : void 0;
3230
+ const annotateCss = (css) => require_hmr_timing.annotateCssSourceTrace(css, {
1935
3231
  opts,
1936
- isViteProcessedCssAsset,
1937
- markCssAssetProcessed,
1938
- recordCssAssetResult,
1939
- recordViteProcessedCssAssetResult,
1940
- resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget),
1941
- debug
3232
+ tokenSources: sourceTraceTokenSources
1942
3233
  });
1943
- const isCssOutputAssetEntry = (entry) => {
1944
- const [, output] = entry;
1945
- return output.type === "asset" && opts.cssMatcher(output.fileName) && !isCssAssetProcessed(output, output.fileName);
3234
+ const collectViteProcessedCssAssets = () => {
3235
+ collectViteProcessedCssAssetResults(bundle, {
3236
+ opts,
3237
+ isViteProcessedCssAsset,
3238
+ markCssAssetProcessed,
3239
+ recordCssAssetResult,
3240
+ recordViteProcessedCssAssetResult,
3241
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget),
3242
+ debug
3243
+ });
1946
3244
  };
1947
- const entries = Object.entries(bundle).filter(isCssOutputAssetEntry);
1948
- if (entries.length === 0) {
1949
- injectViteProcessedCssIntoMainCssAssets(bundle, {
3245
+ const injectViteProcessedCssIntoMainCss = () => {
3246
+ return injectViteProcessedCssIntoMainCssAssets(bundle, {
1950
3247
  opts,
1951
3248
  getViteProcessedCssAssetResults,
1952
3249
  markCssAssetProcessed,
@@ -1954,6 +3251,46 @@ function createViteCssFinalizerOutputPlugin(context) {
1954
3251
  debug,
1955
3252
  onUpdate: opts.onUpdate
1956
3253
  });
3254
+ };
3255
+ collectViteProcessedCssAssets();
3256
+ const createHarmonyBundleStyleSources = async (runtime) => {
3257
+ const cssSources = collectViteProcessedCssSources(getViteProcessedCssAssetResults);
3258
+ const applyUtilities = collectUniAppXHarmonyApplyUtilities(bundle);
3259
+ const applyStyleSources = collectUniAppXHarmonyApplyStyleSources(bundle);
3260
+ if (applyUtilities.size === 0 || applyStyleSources.length === 0) return cssSources;
3261
+ const harmonyRuntime = new Set([...runtime, ...applyUtilities]);
3262
+ const harmonyCssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, "uni-app-x-harmony-apply.css");
3263
+ const generated = await require_hmr_timing.generateCssByGenerator({
3264
+ opts,
3265
+ runtimeState,
3266
+ runtime: harmonyRuntime,
3267
+ rawSource: createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities),
3268
+ file: "uni-app-x-harmony-apply.css",
3269
+ cssHandlerOptions: harmonyCssHandlerOptions,
3270
+ cssUserHandlerOptions: {
3271
+ ...harmonyCssHandlerOptions,
3272
+ isMainChunk: false
3273
+ },
3274
+ getSourceCandidatesForEntries,
3275
+ styleHandler: opts.styleHandler,
3276
+ debug
3277
+ });
3278
+ if (generated?.css) cssSources.push(annotateCss(generated.css));
3279
+ return cssSources;
3280
+ };
3281
+ const injectHarmonyBundleStyles = async (runtime) => {
3282
+ if (!isHarmonyAppStyleTarget) return;
3283
+ if (injectUniAppXHarmonyBundleStyles(bundle, { cssSources: await createHarmonyBundleStyleSources(runtime) })) debug("uni-app-x harmony bundle styles inject");
3284
+ };
3285
+ const isCssOutputAssetEntry = (entry) => {
3286
+ const [, output] = entry;
3287
+ return output.type === "asset" && opts.cssMatcher(output.fileName) && !isCssAssetProcessed(output, output.fileName);
3288
+ };
3289
+ const entries = Object.entries(bundle).filter(isCssOutputAssetEntry);
3290
+ if (entries.length === 0) {
3291
+ await injectHarmonyBundleStyles(getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet());
3292
+ collectViteProcessedCssAssets();
3293
+ injectViteProcessedCssIntoMainCss();
1957
3294
  return;
1958
3295
  }
1959
3296
  await runtimeState.readyPromise;
@@ -1965,7 +3302,7 @@ function createViteCssFinalizerOutputPlugin(context) {
1965
3302
  const file = output.fileName || bundleFile;
1966
3303
  const rawSource = output.source.toString();
1967
3304
  if (isViteProcessedCssAsset?.(output, file)) {
1968
- const nextCss = require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
3305
+ const nextCss = annotateCss(require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource));
1969
3306
  output.source = nextCss;
1970
3307
  markCssAssetProcessed(output, file);
1971
3308
  recordCssAssetResult?.(file, nextCss);
@@ -1986,7 +3323,7 @@ function createViteCssFinalizerOutputPlugin(context) {
1986
3323
  ...generatorCssHandlerOptions,
1987
3324
  isMainChunk: false
1988
3325
  } : cssUserHandlerOptions;
1989
- const generated = shouldGenerateCssByGenerator(opts, file, generatorRawSource, processed) ? await require_incremental_runtime_class_set.generateCssByGenerator({
3326
+ const generated = shouldGenerateCssByGenerator(opts, file, generatorRawSource, processed) ? await require_hmr_timing.generateCssByGenerator({
1990
3327
  opts,
1991
3328
  runtimeState,
1992
3329
  runtime: generatorRuntime,
@@ -1998,7 +3335,7 @@ function createViteCssFinalizerOutputPlugin(context) {
1998
3335
  styleHandler: opts.styleHandler,
1999
3336
  debug
2000
3337
  }) : void 0;
2001
- const nextCss = generated?.css ?? (generatorOptions.target === "web" ? rawSource : (await opts.styleHandler(rawSource, cssHandlerOptions)).css);
3338
+ const nextCss = annotateCss(generated?.css ?? (generatorOptions.target === "web" ? rawSource : (await opts.styleHandler(rawSource, cssHandlerOptions)).css));
2002
3339
  if (generated) {
2003
3340
  registerGeneratorDependencies(this, generated.dependencies);
2004
3341
  debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
@@ -2010,14 +3347,9 @@ function createViteCssFinalizerOutputPlugin(context) {
2010
3347
  opts.onUpdate(file, rawSource, nextCss);
2011
3348
  debug("css finalizer handle: %s", file);
2012
3349
  }));
2013
- injectViteProcessedCssIntoMainCssAssets(bundle, {
2014
- opts,
2015
- getViteProcessedCssAssetResults,
2016
- markCssAssetProcessed,
2017
- recordCssAssetResult,
2018
- debug,
2019
- onUpdate: opts.onUpdate
2020
- });
3350
+ await injectHarmonyBundleStyles(generatorRuntime);
3351
+ collectViteProcessedCssAssets();
3352
+ injectViteProcessedCssIntoMainCss();
2021
3353
  }
2022
3354
  }
2023
3355
  };
@@ -2269,8 +3601,14 @@ function createViteRuntimeClassSet(options) {
2269
3601
  readyPromise: require_precheck.createTailwindRuntimeReadyPromise(initialTwPatcher),
2270
3602
  refreshTailwindcssPatcher
2271
3603
  };
2272
- const bundleRuntimeClassSetManager = require_incremental_runtime_class_set.createBundleRuntimeClassSetManager({ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues });
2273
- const transformRuntimeClassSetManager = require_incremental_runtime_class_set.createBundleRuntimeClassSetManager({ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues });
3604
+ const bundleRuntimeClassSetManager = require_hmr_timing.createBundleRuntimeClassSetManager({
3605
+ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
3606
+ escapeMap: opts.escapeMap
3607
+ });
3608
+ const transformRuntimeClassSetManager = require_hmr_timing.createBundleRuntimeClassSetManager({
3609
+ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
3610
+ escapeMap: opts.escapeMap
3611
+ });
2274
3612
  let runtimeSet;
2275
3613
  let runtimeSetPromise;
2276
3614
  let runtimeRefreshSignature;
@@ -2498,6 +3836,7 @@ const weappTailwindcssPackageDir = require_bundle_state.resolvePackageDir("weapp
2498
3836
  const weappTailwindcssDirPosix = require_bundle_state.slash(weappTailwindcssPackageDir);
2499
3837
  const sourceCandidateScanSnapshotCache = /* @__PURE__ */ new Map();
2500
3838
  const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
3839
+ const SFC_COMPONENT_FILE_RE = /\.(?:vue|uvue|nvue|svelte|mpx)$/i;
2501
3840
  function normalizeSignaturePath(value) {
2502
3841
  return require_bundle_state.slash(node_path.default.resolve(value));
2503
3842
  }
@@ -2529,6 +3868,10 @@ function stripSourceHash(sourceFile) {
2529
3868
  const hashIndex = sourceFile.indexOf("#");
2530
3869
  return hashIndex === -1 ? sourceFile : sourceFile.slice(0, hashIndex);
2531
3870
  }
3871
+ function isMainStyleEntryFile(file) {
3872
+ const name = node_path.default.basename(require_bundle_state.stripRequestQuery((0, _weapp_tailwindcss_shared.cleanUrl)(file))).replace(/\.[^.]+$/, "");
3873
+ return name === "app" || name === "main";
3874
+ }
2532
3875
  function normalizeCssSourceIdentity(sourceFile) {
2533
3876
  const cleanSourceFile = stripSourceHash(sourceFile);
2534
3877
  const { filename, query } = parseVueRequest(cleanSourceFile);
@@ -2627,8 +3970,8 @@ function WeappTailwindcss(options = {}) {
2627
3970
  const customAttributesEntities = require_precheck.toCustomAttributesEntities(customAttributes);
2628
3971
  let resolvedConfig;
2629
3972
  let recordedGeneratorCandidates;
2630
- const sourceCandidateExtractor = tailwindcssMajorVersion === 3 ? require_source_candidates.createTailwindV3DefaultExtractor() : void 0;
2631
- const sourceCandidateCollector = require_source_candidates.createSourceCandidateCollector({
3973
+ const sourceCandidateExtractor = tailwindcssMajorVersion === 3 ? require_hmr_timing.createTailwindV3DefaultExtractor() : void 0;
3974
+ const sourceCandidateCollector = require_hmr_timing.createSourceCandidateCollector({
2632
3975
  bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
2633
3976
  extractor: sourceCandidateExtractor
2634
3977
  });
@@ -2647,6 +3990,7 @@ function WeappTailwindcss(options = {}) {
2647
3990
  const viteProcessedCssAssetResults = /* @__PURE__ */ new Map();
2648
3991
  const rememberedCssSources = /* @__PURE__ */ new Map();
2649
3992
  const rememberedCssSignatureByFile = /* @__PURE__ */ new Map();
3993
+ const knownSfcSources = /* @__PURE__ */ new Map();
2650
3994
  const tailwindRootCssModuleIds = /* @__PURE__ */ new Set();
2651
3995
  const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
2652
3996
  opts,
@@ -2657,7 +4001,7 @@ function WeappTailwindcss(options = {}) {
2657
4001
  disabledDefaultTemplateHandler,
2658
4002
  debug
2659
4003
  });
2660
- const hmrTimingRecorder = require_incremental_runtime_class_set.createHmrTimingRecorder("vite");
4004
+ const hmrTimingRecorder = require_hmr_timing.createHmrTimingRecorder("vite");
2661
4005
  refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2662
4006
  onLoad();
2663
4007
  const getResolvedConfig = () => resolvedConfig;
@@ -2680,6 +4024,7 @@ function WeappTailwindcss(options = {}) {
2680
4024
  };
2681
4025
  const getSourceCandidates = () => sourceCandidateCollector.values();
2682
4026
  const getSourceCandidatesForEntries = (entries) => sourceCandidateCollector.valuesForEntries(entries);
4027
+ const getSourceCandidateSourcesForEntries = (entries, options) => sourceCandidateCollector.sourcesForEntries(entries, options);
2683
4028
  const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
2684
4029
  const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || node_process.default.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || node_process.default.env["WEAPP_TW_HMR_TIMING"] === "1";
2685
4030
  const hasSourceCandidateScanState = () => sourceCandidateScanSignature !== void 0;
@@ -2785,21 +4130,20 @@ function WeappTailwindcss(options = {}) {
2785
4130
  while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2786
4131
  };
2787
4132
  const syncChangedSourceCandidateFile = (id) => {
2788
- if (!shouldOwnTailwindGeneration || !require_source_candidates.isSourceCandidateRequest(id)) return Promise.resolve();
4133
+ if (!shouldOwnTailwindGeneration || !require_hmr_timing.isSourceCandidateRequest(id)) return Promise.resolve();
2789
4134
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2790
- const refreshRememberedCssSourceTask = refreshRememberedCssSourceByCurrentFile(file);
2791
4135
  if (isSourceScanDependency(file)) invalidateSourceCandidateScan();
2792
4136
  if (sourceScanMatcher && !sourceScanMatcher(file)) {
2793
4137
  sourceCandidateCollector.remove(file);
2794
4138
  cacheCurrentSourceCandidateScan();
2795
- return refreshRememberedCssSourceTask;
4139
+ return refreshRememberedCssSourceByCurrentFile(file);
2796
4140
  }
2797
4141
  if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2798
4142
  cacheCurrentSourceCandidateScan();
2799
- return refreshRememberedCssSourceTask;
4143
+ return refreshRememberedCssSourceByCurrentFile(file);
2800
4144
  }
2801
4145
  const existingTask = pendingSourceCandidateSyncByFile.get(file);
2802
- if (existingTask) return Promise.all([refreshRememberedCssSourceTask, existingTask]).then(() => void 0);
4146
+ if (existingTask) return existingTask.then(() => refreshRememberedCssSourceByCurrentFile(file)).then(() => void 0);
2803
4147
  const task = sourceCandidateCollector.syncCurrentFile(id).catch((error) => {
2804
4148
  debug("source candidate watch sync failed: %s %O", id, error);
2805
4149
  }).then(() => {
@@ -2810,18 +4154,37 @@ function WeappTailwindcss(options = {}) {
2810
4154
  });
2811
4155
  pendingSourceCandidateSyncs.add(task);
2812
4156
  pendingSourceCandidateSyncByFile.set(file, task);
2813
- return Promise.all([refreshRememberedCssSourceTask, task]).then(() => void 0);
4157
+ return task.then(() => refreshRememberedCssSourceByCurrentFile(file)).then(() => void 0);
2814
4158
  };
2815
4159
  const shouldCollectTransformedSourceCandidates = (id) => {
2816
4160
  if (id.search(/[?#]/) < 0) return true;
2817
4161
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2818
- return !/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file);
4162
+ return !SFC_COMPONENT_FILE_RE.test(file);
4163
+ };
4164
+ const hasSfcStyleBlocks = (source) => {
4165
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
4166
+ return SFC_STYLE_BLOCK_RE.test(source);
4167
+ };
4168
+ const normalizeKnownSfcSourceKey = (file) => require_bundle_state.normalizeOutputPathKey(node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file)));
4169
+ const rememberKnownSfcSource = (id, code) => {
4170
+ if (id.search(/[?#]/) >= 0) return;
4171
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
4172
+ if (!SFC_COMPONENT_FILE_RE.test(file)) return;
4173
+ if (!hasSfcStyleBlocks(code)) return;
4174
+ knownSfcSources.set(normalizeKnownSfcSourceKey(file), code);
4175
+ };
4176
+ const getKnownSfcSource = (file) => {
4177
+ const scanSource = sourceCandidateCollector.source(file);
4178
+ if (scanSource && hasSfcStyleBlocks(scanSource)) return scanSource;
4179
+ return knownSfcSources.get(normalizeKnownSfcSourceKey(file));
2819
4180
  };
2820
4181
  const rememberCssSource = (entry, cssRuntimeSignature) => {
2821
- const key = require_bundle_state.normalizeOutputPathKey(entry.outputFile);
4182
+ const outputKey = require_bundle_state.normalizeOutputPathKey(entry.outputFile);
4183
+ const normalizedSourceFile = normalizeCssSourceIdentity(entry.sourceFile);
4184
+ const previousOutputEntry = rememberedCssSources.get(outputKey);
4185
+ const key = previousOutputEntry != null && normalizeCssSourceIdentity(previousOutputEntry.sourceFile) !== normalizedSourceFile ? `${outputKey}\0${normalizedSourceFile}` : outputKey;
2822
4186
  const previous = rememberedCssSources.get(key);
2823
4187
  rememberedCssSources.set(key, entry);
2824
- const normalizedSourceFile = normalizeCssSourceIdentity(entry.sourceFile);
2825
4188
  for (const [rememberedKey, remembered] of rememberedCssSources) {
2826
4189
  if (rememberedKey === key || normalizeCssSourceIdentity(remembered.sourceFile) !== normalizedSourceFile) continue;
2827
4190
  rememberedCssSources.set(rememberedKey, {
@@ -2863,41 +4226,57 @@ function WeappTailwindcss(options = {}) {
2863
4226
  match = SFC_STYLE_BLOCK_RE.exec(source);
2864
4227
  }
2865
4228
  };
4229
+ const extractSfcStyleSource = (source, index) => {
4230
+ if (index !== void 0) return extractSfcStyleBlock(source, index);
4231
+ const styleSources = [];
4232
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
4233
+ let match = SFC_STYLE_BLOCK_RE.exec(source);
4234
+ while (match !== null) {
4235
+ styleSources.push(match[1] ?? "");
4236
+ match = SFC_STYLE_BLOCK_RE.exec(source);
4237
+ }
4238
+ return styleSources.length > 0 ? styleSources.join("\n") : void 0;
4239
+ };
4240
+ const resolveCachedStyleSource = (sourceFile) => {
4241
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(sourceFile));
4242
+ if (SFC_COMPONENT_FILE_RE.test(file)) return getKnownSfcSource(file);
4243
+ if (require_bundle_state.isSourceStyleRequest(file)) return sourceCandidateCollector.source(file);
4244
+ };
2866
4245
  const refreshRememberedCssSourceByCurrentFile = async (sourceFile) => {
2867
4246
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(sourceFile);
2868
4247
  const normalizedSourceFile = require_bundle_state.normalizeOutputPathKey(file);
2869
4248
  const matchedRememberedSources = [...rememberedCssSources.values()].filter((remembered) => require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery((0, _weapp_tailwindcss_shared.cleanUrl)(remembered.sourceFile))) === normalizedSourceFile);
2870
4249
  if (matchedRememberedSources.length === 0) return;
2871
- try {
2872
- const source = await (0, node_fs_promises.readFile)(file, "utf8");
2873
- if (/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file)) {
2874
- for (const remembered of matchedRememberedSources) {
2875
- const { query } = parseVueRequest(remembered.sourceFile);
2876
- const styleSource = extractSfcStyleBlock(source, query.type === "style" ? query.index : void 0);
2877
- if (styleSource !== void 0) refreshRememberedCssSourceBySourceFile(remembered.sourceFile, styleSource);
2878
- }
2879
- return;
4250
+ const source = resolveCachedStyleSource(file);
4251
+ if (source == null) {
4252
+ debug("refresh remembered css source skipped: missing cached source for %s", file);
4253
+ return;
4254
+ }
4255
+ if (SFC_COMPONENT_FILE_RE.test(file)) {
4256
+ for (const remembered of matchedRememberedSources) {
4257
+ const { query } = parseVueRequest(remembered.sourceFile);
4258
+ const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
4259
+ if (styleSource !== void 0) refreshRememberedCssSourceBySourceFile(remembered.sourceFile, styleSource);
2880
4260
  }
2881
- if (require_bundle_state.isSourceStyleRequest(file)) refreshRememberedCssSourceBySourceFile(file, source);
2882
- } catch (error) {
2883
- debug("refresh remembered css source failed: %s %O", file, error);
4261
+ return;
2884
4262
  }
4263
+ if (require_bundle_state.isSourceStyleRequest(file)) refreshRememberedCssSourceBySourceFile(file, source);
2885
4264
  };
2886
4265
  const refreshRememberedCssSource = async (remembered) => {
2887
4266
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(remembered.sourceFile));
2888
4267
  const rememberedKey = [...rememberedCssSources.entries()].find(([, entry]) => entry === remembered)?.[0];
2889
4268
  if (!rememberedKey || !node_path.default.isAbsolute(file)) return;
2890
- try {
2891
- const source = await (0, node_fs_promises.readFile)(file, "utf8");
2892
- if (/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file)) {
2893
- const { query } = parseVueRequest(remembered.sourceFile);
2894
- const styleSource = extractSfcStyleBlock(source, query.type === "style" ? query.index : void 0);
2895
- return styleSource === void 0 ? void 0 : refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, styleSource);
2896
- }
2897
- if (require_bundle_state.isSourceStyleRequest(file)) return refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, source);
2898
- } catch (error) {
2899
- debug("refresh remembered css source before bundle replay failed: %s %O", file, error);
4269
+ const source = resolveCachedStyleSource(file);
4270
+ if (source == null) {
4271
+ debug("refresh remembered css source before bundle replay skipped: missing cached source for %s", file);
4272
+ return;
2900
4273
  }
4274
+ if (SFC_COMPONENT_FILE_RE.test(file)) {
4275
+ const { query } = parseVueRequest(remembered.sourceFile);
4276
+ const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
4277
+ return styleSource === void 0 ? void 0 : refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, styleSource);
4278
+ }
4279
+ if (require_bundle_state.isSourceStyleRequest(file)) return refreshRememberedCssSourceEntry(rememberedKey, remembered, remembered.sourceFile, source);
2901
4280
  };
2902
4281
  const getRememberedCssSources = () => rememberedCssSources;
2903
4282
  const getRememberedCssSourceEntry = (file) => rememberedCssSources.get(require_bundle_state.normalizeOutputPathKey(file));
@@ -2909,9 +4288,12 @@ function WeappTailwindcss(options = {}) {
2909
4288
  viteGeneratedCssByFile.set(file, css);
2910
4289
  };
2911
4290
  const recordViteProcessedCssAssetResult = (file, css, options = {}) => {
2912
- viteProcessedCssAssetResults.set(require_bundle_state.normalizeOutputPathKey(file), {
4291
+ const key = require_bundle_state.normalizeOutputPathKey(file);
4292
+ const previous = viteProcessedCssAssetResults.get(key);
4293
+ viteProcessedCssAssetResults.set(key, {
2913
4294
  css,
2914
- injectIntoMain: options.injectIntoMain
4295
+ injectIntoMain: options.injectIntoMain ?? previous?.injectIntoMain,
4296
+ outputFile: options.outputFile ?? previous?.outputFile
2915
4297
  });
2916
4298
  };
2917
4299
  const getViteProcessedCssAssetResults = () => viteProcessedCssAssetResults.entries();
@@ -2966,6 +4348,10 @@ function WeappTailwindcss(options = {}) {
2966
4348
  const isUniViteProject = () => {
2967
4349
  return resolvedConfig?.plugins?.some((plugin) => plugin.name.includes("uni")) ?? false;
2968
4350
  };
4351
+ const isHarmonyAppBuildTarget = () => {
4352
+ if (require_utils.resolveUniUtsPlatform().isAppHarmony) return true;
4353
+ return isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir);
4354
+ };
2969
4355
  const sendSupplementalCssHotUpdates = (ctx, cssModules) => {
2970
4356
  const updates = cssModules.filter((mod) => !includesHotModule(ctx.modules, mod)).map((mod) => {
2971
4357
  const hotUrl = resolveModuleHotUrl(mod);
@@ -3019,32 +4405,50 @@ function WeappTailwindcss(options = {}) {
3019
4405
  await waitForSourceCandidateSyncs();
3020
4406
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3021
4407
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
3022
- const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp;
4408
+ const isHarmonyAppStyleTarget = isHarmonyAppBuildTarget();
4409
+ const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp || isHarmonyAppStyleTarget;
3023
4410
  const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, generatorOptions.target === "web", isNativeAppStyleTarget);
3024
4411
  const runtime = getRecordedGeneratorCandidates() ?? getSourceCandidates() ?? await ensureRuntimeClassSet();
3025
- const cssHandlerOptions = transformCssHandlerOptions.getCssHandlerOptions(outputFile);
3026
- const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
4412
+ const outputCssHandlerOptions = transformCssHandlerOptions.getCssHandlerOptions(outputFile);
4413
+ const cssHandlerOptions = {
4414
+ ...transformCssHandlerOptions.getCssHandlerOptions(file),
4415
+ isMainChunk: outputCssHandlerOptions.isMainChunk || isMainStyleEntryFile(file)
4416
+ };
4417
+ const shouldDeferEmptyScopedCssSource = !(opts.appType === "uni-app-x" && !cssHandlerOptions.isMainChunk && require_v3_engine.hasTailwindApplyDirective(code));
4418
+ const generated = await require_hmr_timing.generateCssByGenerator({
3027
4419
  opts,
3028
4420
  runtimeState,
3029
4421
  runtime,
3030
4422
  rawSource: code,
3031
4423
  file,
3032
4424
  cssHandlerOptions,
3033
- cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(outputFile),
4425
+ cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(file),
3034
4426
  getSourceCandidatesForEntries,
3035
4427
  styleHandler,
3036
4428
  debug,
3037
4429
  previousCss: viteGeneratedCssByFile.get(file),
3038
- deferEmptyScopedCssSource: true
4430
+ deferEmptyScopedCssSource: shouldDeferEmptyScopedCssSource
3039
4431
  });
3040
4432
  if (!generated) return;
4433
+ const tracedCss = require_hmr_timing.annotateCssSourceTrace(generated.css, {
4434
+ opts,
4435
+ tokenSources: require_hmr_timing.createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts)
4436
+ });
3041
4437
  for (const dependency of generated.dependencies) hookContext?.addWatchFile?.(dependency);
3042
- viteGeneratedCssByFile.set(file, generated.css);
3043
- if (generated.css.includes("weapp-tailwindcss layer components start")) recordViteProcessedCssAssetResult(file, generated.css, { injectIntoMain: cssHandlerOptions.isMainChunk });
4438
+ viteGeneratedCssByFile.set(file, tracedCss);
4439
+ const shouldInjectGeneratedCssIntoMain = isMainStyleEntryFile(file) || mainCssChunkMatcher(outputFile, opts.appType);
4440
+ recordViteProcessedCssAssetResult(file, tracedCss, {
4441
+ injectIntoMain: shouldInjectGeneratedCssIntoMain,
4442
+ outputFile
4443
+ });
4444
+ if (tracedCss.includes("weapp-tailwindcss layer components start")) recordViteProcessedCssAssetResult(file, tracedCss, {
4445
+ injectIntoMain: shouldInjectGeneratedCssIntoMain,
4446
+ outputFile
4447
+ });
3044
4448
  if (isNativeAppStyleTarget && outputFile.endsWith(".css")) hookContext?.emitFile?.({
3045
4449
  type: "asset",
3046
4450
  fileName: outputFile,
3047
- source: generated.css
4451
+ source: tracedCss
3048
4452
  });
3049
4453
  markViteProcessedCssSource(file);
3050
4454
  rememberTailwindRootCssModule(id);
@@ -3054,8 +4458,8 @@ function WeappTailwindcss(options = {}) {
3054
4458
  rawSource: code,
3055
4459
  sourceFile: id
3056
4460
  });
3057
- debug("css generated for vite postcss pipeline: %s bytes=%d", file, generated.css.length);
3058
- return `${require_bundle_state.createBundlerGeneratedCssMarker("vite", normalizeViteProcessedCssFile(file))}\n${generated.css}`;
4461
+ debug("css generated for vite postcss pipeline: %s bytes=%d", file, tracedCss.length);
4462
+ return `${require_bundle_state.createBundlerGeneratedCssMarker("vite", normalizeViteProcessedCssFile(file))}\n${tracedCss}`;
3059
4463
  };
3060
4464
  const rewritePlugins = createRewriteCssImportsPlugins({
3061
4465
  getAppType: () => opts.appType,
@@ -3085,12 +4489,14 @@ function WeappTailwindcss(options = {}) {
3085
4489
  getViteProcessedCssAssetResult,
3086
4490
  getSourceCandidates,
3087
4491
  getSourceCandidatesForEntries,
4492
+ getSourceCandidateSourcesForEntries,
3088
4493
  waitForSourceCandidateSyncs,
3089
4494
  rememberCssSource,
3090
4495
  refreshRememberedCssSource,
3091
4496
  getRememberedCssSources,
3092
4497
  getRememberedCssSignature,
3093
4498
  setRememberedCssSignature,
4499
+ getKnownSfcSource,
3094
4500
  recordGeneratorCandidates,
3095
4501
  hmrTimingRecorder
3096
4502
  });
@@ -3109,6 +4515,7 @@ function WeappTailwindcss(options = {}) {
3109
4515
  getRecordedGeneratorCandidates,
3110
4516
  getSourceCandidates,
3111
4517
  getSourceCandidatesForEntries,
4518
+ getSourceCandidateSourcesForEntries,
3112
4519
  waitForSourceCandidateSyncs,
3113
4520
  rememberMainCssSource: (file, rawSource) => rememberCssSource({
3114
4521
  outputFile: file,
@@ -3142,7 +4549,8 @@ function WeappTailwindcss(options = {}) {
3142
4549
  name: `${require_precheck.vitePluginName}:source-candidates`,
3143
4550
  enforce: "pre",
3144
4551
  async transform(code, id) {
3145
- if (!shouldOwnTailwindGeneration || !require_source_candidates.isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
4552
+ if (shouldOwnTailwindGeneration) rememberKnownSfcSource(id, code);
4553
+ if (!shouldOwnTailwindGeneration || !require_hmr_timing.isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
3146
4554
  return hmrTimingRecorder.measure("sourceCandidates.transform", async () => {
3147
4555
  invalidateRecordedGeneratorCandidates();
3148
4556
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
@@ -3161,7 +4569,7 @@ function WeappTailwindcss(options = {}) {
3161
4569
  },
3162
4570
  async watchChange(id, change) {
3163
4571
  await hmrTimingRecorder.measure("sourceCandidates.watchChange", async () => {
3164
- if (shouldOwnTailwindGeneration && require_source_candidates.isSourceCandidateRequest(id)) invalidateRecordedGeneratorCandidates();
4572
+ if (shouldOwnTailwindGeneration && require_hmr_timing.isSourceCandidateRequest(id)) invalidateRecordedGeneratorCandidates();
3165
4573
  if (isSourceScanDependency(id)) invalidateSourceCandidateScan();
3166
4574
  if (change.event === "delete") {
3167
4575
  sourceCandidateCollector.remove(id);
@@ -3173,7 +4581,7 @@ function WeappTailwindcss(options = {}) {
3173
4581
  },
3174
4582
  async handleHotUpdate(ctx) {
3175
4583
  return hmrTimingRecorder.measure("sourceCandidates.handleHotUpdate", async () => {
3176
- const isSourceCandidateHotUpdate = shouldOwnTailwindGeneration && require_source_candidates.isSourceCandidateRequest(ctx.file);
4584
+ const isSourceCandidateHotUpdate = shouldOwnTailwindGeneration && require_hmr_timing.isSourceCandidateRequest(ctx.file);
3177
4585
  await syncChangedSourceCandidateFile(ctx.file);
3178
4586
  if (isSourceCandidateHotUpdate) invalidateRecordedGeneratorCandidates();
3179
4587
  const cssModules = resolveHotTailwindCssModules(ctx);
@@ -3267,11 +4675,14 @@ function WeappTailwindcss(options = {}) {
3267
4675
  }
3268
4676
  }, { emit: false });
3269
4677
  },
3270
- generateBundle: generateBundleHook
3271
- },
3272
- cssFinalizerOutputPlugin
4678
+ generateBundle: {
4679
+ order: "post",
4680
+ handler: generateBundleHook
4681
+ }
4682
+ }
3273
4683
  ];
3274
4684
  if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
4685
+ plugins.push(cssFinalizerOutputPlugin);
3275
4686
  return plugins;
3276
4687
  }
3277
4688
  //#endregion