weapp-tailwindcss 5.0.3 → 5.0.5

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 (57) hide show
  1. package/README.en.md +9 -0
  2. package/README.md +5 -133
  3. package/dist/{auto-dPpsm6FB.js → auto-Cvy0zWpS.js} +1 -1
  4. package/dist/{bundle-state-CW1X7QIy.js → bundle-state-Cso_ceUo.js} +8 -2
  5. package/dist/{bundle-state-s5HwfrmR.mjs → bundle-state-DEyxCR4f.mjs} +2 -2
  6. package/dist/bundlers/shared/generator-css/directives.d.ts +1 -0
  7. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +1 -0
  8. package/dist/bundlers/vite/generate-bundle.d.ts +3 -1
  9. package/dist/bundlers/vite/rewrite-css-imports.d.ts +8 -0
  10. package/dist/bundlers/vite/serve-css-generation.d.ts +5 -0
  11. package/dist/bundlers/vite/uni-app-x-css-options.d.ts +2 -0
  12. package/dist/{chunk-C5U5_Hdc.js → chunk-emK7D4bc.js} +0 -7
  13. package/dist/core.js +1 -1
  14. package/dist/core.mjs +1 -1
  15. package/dist/css-macro.js +3 -3
  16. package/dist/{defaults-zKUH2mDe.js → defaults-BPUuNYcD.js} +1 -1
  17. package/dist/defaults.js +1 -1
  18. package/dist/{generator-Bd1LntD3.js → generator-AD-eX8Tr.js} +2 -2
  19. package/dist/{generator-DRHWC1t-.mjs → generator-DVWLNO0n.mjs} +1 -1
  20. package/dist/generator.js +2 -2
  21. package/dist/generator.mjs +2 -2
  22. package/dist/gulp.js +6 -6
  23. package/dist/gulp.mjs +5 -5
  24. package/dist/{incremental-runtime-class-set-BdCWIuPW.js → incremental-runtime-class-set-vOetpdWs.js} +195 -43
  25. package/dist/{incremental-runtime-class-set-BcAFhVvu.mjs → incremental-runtime-class-set-xf49kky6.mjs} +194 -42
  26. package/dist/index.js +4 -4
  27. package/dist/index.mjs +4 -4
  28. package/dist/{postcss-DfnqZ4Bm.js → postcss-Cbi6RFpf.js} +57 -10
  29. package/dist/{postcss-CJrmfXvi.mjs → postcss-hSUxK7oR.mjs} +55 -8
  30. package/dist/postcss-html-transform.js +1 -1
  31. package/dist/postcss.js +1 -1
  32. package/dist/postcss.mjs +1 -1
  33. package/dist/{precheck-h6TNzFbF.mjs → precheck-Bsn_LMmo.mjs} +19 -33
  34. package/dist/{precheck-8Ik4q0yI.js → precheck-b8Y8qZg0.js} +17 -31
  35. package/dist/presets.js +9 -5
  36. package/dist/presets.mjs +7 -3
  37. package/dist/reset.js +1 -1
  38. package/dist/{source-candidates-D7b-Jzsx.mjs → source-candidates-BsWYoIPN.mjs} +1 -1
  39. package/dist/{source-candidates-DQxvGPSw.js → source-candidates-o2ZrKWzu.js} +2 -2
  40. package/dist/{tailwindcss-D5RogwtV.mjs → tailwindcss-AWaPVF2B.mjs} +1 -1
  41. package/dist/{tailwindcss-jvoYizzX.js → tailwindcss-CpQ6X4l6.js} +3 -3
  42. package/dist/{vite-DT-VUrl0.js → transform-BkGtbxb1.js} +245 -10127
  43. package/dist/{vite-yCeZWm7n.mjs → transform-DumSZmTh.mjs} +263 -10128
  44. package/dist/uni-app-x/vite.d.ts +3 -0
  45. package/dist/{utils-D7Ygohep.js → utils-Dolmt8EO.js} +1 -1
  46. package/dist/{v3-engine-CmIF_gsq.js → v3-engine-CM0TRa8V.js} +29 -5
  47. package/dist/{v3-engine-BCUGX3gX.mjs → v3-engine-Cczrkzqt.mjs} +22 -4
  48. package/dist/vite-CTuHPC91.js +3283 -0
  49. package/dist/vite-DLXDMHON.mjs +3270 -0
  50. package/dist/vite.js +1 -1
  51. package/dist/vite.mjs +1 -1
  52. package/dist/weapp-tw-css-import-rewrite-loader.js +201 -42
  53. package/dist/{webpack-BFMJqCH9.js → webpack-BBHJYKqB.js} +8 -9
  54. package/dist/{webpack-E0gT72EX.mjs → webpack-DJFw08SK.mjs} +6 -7
  55. package/dist/webpack.js +1 -1
  56. package/dist/webpack.mjs +1 -1
  57. package/package.json +3 -4
@@ -0,0 +1,3283 @@
1
+ const require_chunk = require("./chunk-emK7D4bc.js");
2
+ const require_v3_engine = require("./v3-engine-CM0TRa8V.js");
3
+ const require_generator = require("./generator-AD-eX8Tr.js");
4
+ const require_precheck = require("./precheck-b8Y8qZg0.js");
5
+ const require_utils = require("./utils-Dolmt8EO.js");
6
+ const require_tailwindcss = require("./tailwindcss-CpQ6X4l6.js");
7
+ const require_incremental_runtime_class_set = require("./incremental-runtime-class-set-vOetpdWs.js");
8
+ const require_source_candidates = require("./source-candidates-o2ZrKWzu.js");
9
+ const require_bundle_state = require("./bundle-state-Cso_ceUo.js");
10
+ require("./logger-TlKT3xmR.js");
11
+ let node_fs = require("node:fs");
12
+ node_fs = require_chunk.__toESM(node_fs);
13
+ let postcss = require("postcss");
14
+ postcss = require_chunk.__toESM(postcss);
15
+ let tailwindcss_patch = require("tailwindcss-patch");
16
+ let node_process = require("node:process");
17
+ node_process = require_chunk.__toESM(node_process);
18
+ let node_path = require("node:path");
19
+ node_path = require_chunk.__toESM(node_path);
20
+ let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
21
+ let node_fs_promises = require("node:fs/promises");
22
+ let node_buffer = require("node:buffer");
23
+ let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
24
+ _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
25
+ let comment_json = require("comment-json");
26
+ let postcss_load_config = require("postcss-load-config");
27
+ postcss_load_config = require_chunk.__toESM(postcss_load_config);
28
+ let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
29
+ //#region src/bundlers/vite/query.ts
30
+ function parseVueRequest(id) {
31
+ const [filename = id, rawQuery] = id.split(`?`, 2);
32
+ const searchParams = new URLSearchParams(rawQuery);
33
+ const query = Object.fromEntries(searchParams);
34
+ if (query.vue != null) query.vue = true;
35
+ if (query.index != null) query.index = Number(query.index);
36
+ if (query.raw != null) query.raw = true;
37
+ if (query.url != null) query.url = true;
38
+ if (query.scoped != null) query.scoped = true;
39
+ const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
40
+ const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
41
+ if (langType) query.lang = langType;
42
+ return {
43
+ filename,
44
+ query
45
+ };
46
+ }
47
+ //#endregion
48
+ //#region src/uni-app-x/style-isolation.ts
49
+ const manifestCache = /* @__PURE__ */ new Map();
50
+ function resolveUniAppXStyleIsolationEnabled(root) {
51
+ if (!root) return false;
52
+ const normalizedRoot = node_path.default.resolve(root);
53
+ const cached = manifestCache.get(normalizedRoot);
54
+ if (cached !== void 0) return cached;
55
+ const manifestPath = node_path.default.join(normalizedRoot, "manifest.json");
56
+ let enabled = false;
57
+ try {
58
+ enabled = `${(0, comment_json.parse)(node_fs.default.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
59
+ } catch {
60
+ enabled = false;
61
+ }
62
+ manifestCache.set(normalizedRoot, enabled);
63
+ return enabled;
64
+ }
65
+ //#endregion
66
+ //#region src/uni-app-x/vite.ts
67
+ let transformUVuePromise;
68
+ function loadTransformUVue() {
69
+ transformUVuePromise ?? (transformUVuePromise = Promise.resolve().then(() => require("./transform-BkGtbxb1.js")).then((mod) => mod.transformUVue));
70
+ return transformUVuePromise;
71
+ }
72
+ const preprocessorLangs = new Set([
73
+ "scss",
74
+ "sass",
75
+ "less",
76
+ "styl",
77
+ "stylus"
78
+ ]);
79
+ const INLINE_LANG_RE = /lang\.([a-z]+)/i;
80
+ const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
81
+ const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
82
+ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
83
+ const CSS_MODULE_EXPORT_RE = /^\s*export\s+default\s+(?:\{|\w|\[\])/;
84
+ function isPreprocessorRequest(id, lang) {
85
+ const normalizedLang = lang?.toLowerCase();
86
+ if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
87
+ const inlineLang = id.match(INLINE_LANG_RE)?.[1];
88
+ if (inlineLang && preprocessorLangs.has(inlineLang.toLowerCase())) return true;
89
+ return PREPROCESSOR_EXT_RE.test(id);
90
+ }
91
+ function resolveUniAppXCssTarget(id) {
92
+ return UVUE_NVUE_RE.test((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ? "uvue" : void 0;
93
+ }
94
+ function resolveUniAppXJsTransformEnabled$1(uniAppX) {
95
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
96
+ }
97
+ function isCssModuleExport(code) {
98
+ return CSS_MODULE_EXPORT_RE.test(code);
99
+ }
100
+ function createUniAppXPlugins(options) {
101
+ const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, generateCss, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
102
+ const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(uniAppX);
103
+ const isIosPlatform = providedIosPlatform ?? require_utils.resolveUniUtsPlatform().isAppIos;
104
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
105
+ let componentLocalStyleEnabled;
106
+ function shouldEnableComponentLocalStyle() {
107
+ if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
108
+ componentLocalStyleEnabled = false;
109
+ return false;
110
+ }
111
+ if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
112
+ componentLocalStyleEnabled = true;
113
+ return true;
114
+ }
115
+ if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
116
+ const root = getResolvedConfig()?.root;
117
+ componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
118
+ return componentLocalStyleEnabled;
119
+ }
120
+ async function transformStyle(code, id, query, hookContext) {
121
+ const parsed = query ?? parseVueRequest(id).query;
122
+ if (require_bundle_state.isCSSRequest(id) || parsed.vue && parsed.type === "style") {
123
+ 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;
125
+ const styleCode = typeof generatedCss === "string" && generatedCss.trim().length > 0 ? generatedCss : code;
126
+ const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
127
+ let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
128
+ if (!styleHandlerOptions) {
129
+ styleHandlerOptions = require_v3_engine.omitUndefined({
130
+ isMainChunk: mainCssChunkMatcher(id, appType),
131
+ uniAppXCssTarget: resolveUniAppXCssTarget(id),
132
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
133
+ postcssOptions: { options: {
134
+ from: id,
135
+ map: {
136
+ inline: false,
137
+ annotation: false,
138
+ sourcesContent: true
139
+ }
140
+ } }
141
+ });
142
+ cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
143
+ }
144
+ const postcssResult = await styleHandler(styleCode, styleHandlerOptions);
145
+ const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
146
+ for (const warning of warnings) _weapp_tailwindcss_logger.logger.warn(warning.toString());
147
+ const postcssMap = await require_bundle_state.formatPostcssSourceMap(postcssResult.map.toJSON(), require_bundle_state.normalizePath((0, _weapp_tailwindcss_shared.cleanUrl)(id)));
148
+ return {
149
+ code: postcssResult.css,
150
+ map: postcssMap
151
+ };
152
+ }
153
+ }
154
+ const cssPlugins = [{
155
+ name: "weapp-tailwindcss:uni-app-x:css",
156
+ async transform(code, id) {
157
+ await runtimeState.readyPromise;
158
+ return transformStyle(code, id, void 0, this);
159
+ }
160
+ }, {
161
+ name: "weapp-tailwindcss:uni-app-x:css:pre",
162
+ enforce: "pre",
163
+ async transform(code, id) {
164
+ await runtimeState.readyPromise;
165
+ const { query } = parseVueRequest(id);
166
+ const lang = query.lang;
167
+ if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
168
+ return transformStyle(code, id, query, this);
169
+ }
170
+ }];
171
+ const nvuePlugin = {
172
+ name: "weapp-tailwindcss:uni-app-x:nvue",
173
+ enforce: "pre",
174
+ async buildStart() {
175
+ await ensureRuntimeClassSet(true);
176
+ },
177
+ async transform(code, id) {
178
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
179
+ const resolvedConfig = getResolvedConfig();
180
+ const isServeCommand = resolvedConfig?.command === "serve";
181
+ const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
182
+ const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
183
+ const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
184
+ 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 });
192
+ return transformUVue(code, id, jsHandler, currentRuntimeSet);
193
+ },
194
+ async handleHotUpdate(ctx) {
195
+ if (getResolvedConfig()?.command !== "serve") return;
196
+ if (!UVUE_NVUE_RE.test(ctx.file)) return;
197
+ await ensureRuntimeClassSet(true);
198
+ },
199
+ async watchChange(id) {
200
+ const resolvedConfig = getResolvedConfig();
201
+ if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
202
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
203
+ await ensureRuntimeClassSet(true);
204
+ }
205
+ };
206
+ return [...cssPlugins, nvuePlugin];
207
+ }
208
+ function createUniAppXAssetTask(file, originalSource, outDir, options) {
209
+ return async () => {
210
+ const { cache, hashKey, createHandlerOptions, debug, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
211
+ const absoluteFile = require_bundle_state.toAbsoluteOutputPath(file, outDir);
212
+ const rawSource = originalSource.source.toString();
213
+ await require_incremental_runtime_class_set.processCachedTask({
214
+ cache,
215
+ cacheKey: file,
216
+ hashKey,
217
+ rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
218
+ applyResult(source) {
219
+ originalSource.source = source;
220
+ },
221
+ onCacheHit() {
222
+ debug("js cache hit: %s", file);
223
+ },
224
+ async transform() {
225
+ const currentSource = originalSource.source.toString();
226
+ const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
227
+ uniAppX: resolveUniAppXJsTransformEnabled$1(options.uniAppX),
228
+ babelParserOptions: {
229
+ plugins: ["typescript"],
230
+ sourceType: "unambiguous"
231
+ }
232
+ }));
233
+ onUpdate(file, currentSource, code);
234
+ debug("js handle: %s", file);
235
+ applyLinkedResults(linked);
236
+ return { result: code };
237
+ }
238
+ });
239
+ };
240
+ }
241
+ //#endregion
242
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
243
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
244
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
245
+ const CLASS_ATTRIBUTE_RE = /\bclass\s*=\s*/g;
246
+ const MUSTACHE_OPEN = "{{";
247
+ const MUSTACHE_CLOSE = "}}";
248
+ function isUrlLikeCandidate(candidate) {
249
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
250
+ }
251
+ function isArbitraryValueCandidate(candidate) {
252
+ return candidate.includes("[") && candidate.includes("]") && !isUrlLikeCandidate(candidate.trim());
253
+ }
254
+ function collectClassAttributeValues(source) {
255
+ const values = [];
256
+ CLASS_ATTRIBUTE_RE.lastIndex = 0;
257
+ let matched = CLASS_ATTRIBUTE_RE.exec(source);
258
+ while (matched !== null) {
259
+ const quoteIndex = CLASS_ATTRIBUTE_RE.lastIndex;
260
+ const quote = source[quoteIndex];
261
+ if (quote !== "\"" && quote !== "'") {
262
+ matched = CLASS_ATTRIBUTE_RE.exec(source);
263
+ continue;
264
+ }
265
+ let expressionDepth = 0;
266
+ for (let index = quoteIndex + 1; index < source.length; index++) {
267
+ if (source.startsWith(MUSTACHE_OPEN, index)) {
268
+ expressionDepth++;
269
+ index += 1;
270
+ continue;
271
+ }
272
+ if (expressionDepth > 0 && source.startsWith(MUSTACHE_CLOSE, index)) {
273
+ expressionDepth--;
274
+ index += 1;
275
+ continue;
276
+ }
277
+ if (expressionDepth === 0 && source[index] === quote) {
278
+ values.push(source.slice(quoteIndex + 1, index));
279
+ CLASS_ATTRIBUTE_RE.lastIndex = index + 1;
280
+ break;
281
+ }
282
+ }
283
+ matched = CLASS_ATTRIBUTE_RE.exec(source);
284
+ }
285
+ return values;
286
+ }
287
+ function collectUnescapedDynamicCandidates(source, allowedCandidates) {
288
+ const matches = /* @__PURE__ */ new Set();
289
+ const shouldFilterByAllowedCandidates = allowedCandidates !== void 0 && allowedCandidates.size > 0;
290
+ for (const classValue of collectClassAttributeValues(source)) for (const expression of classValue.match(MUSTACHE_EXPRESSION_RE) ?? []) {
291
+ QUOTED_LITERAL_RE.lastIndex = 0;
292
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
293
+ while (quoted !== null) {
294
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
295
+ for (const candidate of (0, tailwindcss_patch.splitCandidateTokens)(literal)) {
296
+ const normalized = candidate.trim();
297
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
298
+ if (shouldFilterByAllowedCandidates && !allowedCandidates.has(normalized)) continue;
299
+ matches.add(normalized);
300
+ }
301
+ quoted = QUOTED_LITERAL_RE.exec(expression);
302
+ }
303
+ }
304
+ return [...matches];
305
+ }
306
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
307
+ if (candidates.has("container")) return candidates;
308
+ if (!sourceCandidates.has("container")) return candidates;
309
+ return new Set([...candidates, "container"]);
310
+ }
311
+ //#endregion
312
+ //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
313
+ function createCssHandlerOptionsCache(options) {
314
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
315
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
316
+ const getCssHandlerOptions = (file) => {
317
+ const majorVersion = options.getMajorVersion();
318
+ const appType = options.getAppType();
319
+ const isMainChunk = options.mainCssChunkMatcher(file, appType);
320
+ const outputRoot = options.getOutputRoot?.();
321
+ const from = outputRoot ? node_path.default.resolve(outputRoot, file) : file;
322
+ const extraOptions = options.getExtraOptions?.(file) ?? {};
323
+ const cacheKey = `${majorVersion ?? "unknown"}:${appType ?? "unknown"}:${isMainChunk ? "1" : "0"}:${outputRoot ?? ""}:${file}:${JSON.stringify(extraOptions)}`;
324
+ const cached = cssHandlerOptionsCache.get(cacheKey);
325
+ if (cached) return cached;
326
+ const created = {
327
+ ...extraOptions,
328
+ isMainChunk,
329
+ postcssOptions: { options: { from } },
330
+ majorVersion,
331
+ sourceOptions: { outputRoot }
332
+ };
333
+ cssHandlerOptionsCache.set(cacheKey, created);
334
+ return created;
335
+ };
336
+ const getCssUserHandlerOptions = (file) => {
337
+ const majorVersion = options.getMajorVersion();
338
+ const outputRoot = options.getOutputRoot?.();
339
+ const cacheKey = `${majorVersion ?? "unknown"}:${outputRoot ?? ""}:${file}`;
340
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
341
+ if (cached) return cached;
342
+ const created = {
343
+ ...getCssHandlerOptions(file),
344
+ isMainChunk: false
345
+ };
346
+ cssUserHandlerOptionsCache.set(cacheKey, created);
347
+ return created;
348
+ };
349
+ return {
350
+ getCssHandlerOptions,
351
+ getCssUserHandlerOptions
352
+ };
353
+ }
354
+ //#endregion
355
+ //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
356
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
357
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
358
+ const CSS_IMPORT_RE = /@import\b/i;
359
+ function isPathIndependentCssUrl(value) {
360
+ const normalized = value.trim();
361
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
362
+ }
363
+ function hasPathDependentCssUrl(rawSource) {
364
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
365
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
366
+ while (match !== null) {
367
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
368
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
369
+ }
370
+ return false;
371
+ }
372
+ function createCssTransformShareScope(file, rawSource) {
373
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${require_bundle_state.normalizeOutputPathKey(node_path.default.dirname(file))}`;
374
+ return "global";
375
+ }
376
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
377
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_bundle_state.normalizeOutputPathKey(file)}`;
378
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
379
+ if (require_v3_engine.hasTailwindGeneratedCssMarkers(rawSource) || require_v3_engine.hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback }) || opts.twPatcher.majorVersion === 3 && (opts.cssEntries?.length ?? 0) > 1 && rawSource.includes("@tailwind")) return `source:${require_bundle_state.normalizeOutputPathKey(file)}`;
380
+ return createCssTransformShareScope(file, rawSource);
381
+ }
382
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
383
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
384
+ }
385
+ //#endregion
386
+ //#region src/bundlers/vite/generate-bundle/dirty-state.ts
387
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
388
+ const currentFileSet = new Set(currentBundleFiles);
389
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
390
+ return false;
391
+ }
392
+ //#endregion
393
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
394
+ function createJsEntryResolver(jsEntries) {
395
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
396
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(require_bundle_state.normalizeOutputPathKey(id), entry);
397
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(require_bundle_state.normalizeOutputPathKey(id));
398
+ }
399
+ //#endregion
400
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
401
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
402
+ return uniAppX === void 0 ? true : require_tailwindcss.isUniAppXEnabled(uniAppX);
403
+ }
404
+ function createJsHandlerOptionsFactory(options) {
405
+ return (absoluteFilename, extra) => ({
406
+ ...extra,
407
+ filename: absoluteFilename,
408
+ tailwindcssMajorVersion: options.getMajorVersion(),
409
+ moduleGraph: options.moduleGraph,
410
+ babelParserOptions: {
411
+ ...extra?.babelParserOptions ?? {},
412
+ sourceFilename: absoluteFilename
413
+ }
414
+ });
415
+ }
416
+ //#endregion
417
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
418
+ function createLinkedUpdateHelpers(options) {
419
+ const pendingLinkedUpdates = [];
420
+ const handleLinkedUpdate = (fileName, previous, next) => {
421
+ options.onUpdate(fileName, previous, next);
422
+ options.debug("js linked handle: %s", fileName);
423
+ };
424
+ const scheduleLinkedApply = (entry, code) => {
425
+ pendingLinkedUpdates.push(() => {
426
+ if (entry.output.type === "chunk") entry.output.code = code;
427
+ else entry.output.source = code;
428
+ });
429
+ };
430
+ const applyLinkedUpdates = (linked) => {
431
+ require_bundle_state.applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
432
+ };
433
+ return {
434
+ applyLinkedUpdates,
435
+ pendingLinkedUpdates
436
+ };
437
+ }
438
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
439
+ if (!linked || !linkedSet) return;
440
+ for (const id of Object.keys(linked)) {
441
+ const linkedEntry = getJsEntry(id);
442
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
443
+ }
444
+ }
445
+ //#endregion
446
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
447
+ function formatDebugFileList(files, limit = 8) {
448
+ if (files.size === 0) return "-";
449
+ const sorted = [...files].sort();
450
+ if (sorted.length <= limit) return sorted.join(",");
451
+ return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
452
+ }
453
+ function createEmptyMetric() {
454
+ return {
455
+ total: 0,
456
+ transformed: 0,
457
+ cacheHits: 0,
458
+ elapsed: 0
459
+ };
460
+ }
461
+ function createEmptyMetrics() {
462
+ return {
463
+ runtimeSet: 0,
464
+ html: createEmptyMetric(),
465
+ js: createEmptyMetric(),
466
+ css: createEmptyMetric()
467
+ };
468
+ }
469
+ function measureElapsed(start) {
470
+ return performance.now() - start;
471
+ }
472
+ function formatCacheHitRate(metric) {
473
+ if (metric.total === 0) return "0.00%";
474
+ return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
475
+ }
476
+ function formatMs(value) {
477
+ return value.toFixed(2);
478
+ }
479
+ //#endregion
480
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
481
+ function logBundleProcessPlan(options) {
482
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
483
+ const { processFiles } = snapshot;
484
+ if (useIncrementalMode) {
485
+ debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", iteration, snapshot.changedByType.html.size, formatDebugFileList(snapshot.changedByType.html), snapshot.changedByType.js.size, formatDebugFileList(snapshot.changedByType.js), snapshot.changedByType.css.size, formatDebugFileList(snapshot.changedByType.css), snapshot.changedByType.other.size, formatDebugFileList(snapshot.changedByType.other));
486
+ debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", iteration, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
487
+ return;
488
+ }
489
+ 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
+ }
491
+ //#endregion
492
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
493
+ function createReplayCssAsset(fileName, source) {
494
+ return {
495
+ type: "asset",
496
+ fileName,
497
+ name: void 0,
498
+ source,
499
+ needsCodeReference: false,
500
+ names: [],
501
+ originalFileName: null,
502
+ originalFileNames: []
503
+ };
504
+ }
505
+ function isAddWatchFileInvalidRollupPhaseError$1(error) {
506
+ const candidate = error;
507
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
508
+ }
509
+ function registerGeneratorDependencies$1(ctx, dependencies) {
510
+ if (typeof ctx.addWatchFile !== "function") return;
511
+ for (const dependency of dependencies ?? []) try {
512
+ ctx.addWatchFile(dependency);
513
+ } catch (error) {
514
+ if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
515
+ _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
516
+ continue;
517
+ }
518
+ throw error;
519
+ }
520
+ }
521
+ //#endregion
522
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
523
+ function summarizeStringDiff(previous, next) {
524
+ if (previous === next) return "same";
525
+ const previousLength = previous.length;
526
+ const nextLength = next.length;
527
+ const minLength = Math.min(previousLength, nextLength);
528
+ let prefixLength = 0;
529
+ while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1;
530
+ let previousSuffixCursor = previousLength - 1;
531
+ let nextSuffixCursor = nextLength - 1;
532
+ while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
533
+ previousSuffixCursor -= 1;
534
+ nextSuffixCursor -= 1;
535
+ }
536
+ const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
537
+ const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
538
+ return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
539
+ }
540
+ function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
541
+ const changedLinkedFiles = linkedImpactsByEntry.get(entry);
542
+ if (!changedLinkedFiles || changedLinkedFiles.size === 0) return;
543
+ return [...changedLinkedFiles].sort().map((file) => {
544
+ return `${file}:${sourceHashByFile.get(file) ?? "missing"}`;
545
+ }).join(",");
546
+ }
547
+ function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
548
+ if (!linkedImpactSignature) return runtimeSignature;
549
+ return `${runtimeSignature}:linked:${linkedImpactSignature}`;
550
+ }
551
+ function createStableTextSignature(input) {
552
+ let hash = 2166136261;
553
+ for (let i = 0; i < input.length; i++) {
554
+ hash ^= input.charCodeAt(i);
555
+ hash = Math.imul(hash, 16777619);
556
+ }
557
+ return (hash >>> 0).toString(36);
558
+ }
559
+ function createCandidateSignature(candidates) {
560
+ if (candidates.size === 0) return "empty";
561
+ return createStableTextSignature([...candidates].sort().join("\n"));
562
+ }
563
+ function getSnapshotHash(snapshotMap, file, fallback) {
564
+ return snapshotMap.get(file) ?? fallback;
565
+ }
566
+ function hasRuntimeAffectingSourceChanges(changedByType) {
567
+ return changedByType.html.size > 0 || changedByType.js.size > 0;
568
+ }
569
+ //#endregion
570
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
571
+ let _lazyMatch = () => {
572
+ var __lib__ = (() => {
573
+ var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
574
+ for (var n in e) m(r, n, {
575
+ get: e[n],
576
+ enumerable: true
577
+ });
578
+ }, H = (r, e, n, a) => {
579
+ if (e && typeof e == "object" || typeof e == "function") for (let t of G(e)) !T.call(r, t) && t !== n && m(r, t, {
580
+ get: () => e[t],
581
+ enumerable: !(a = V(e, t)) || a.enumerable
582
+ });
583
+ return r;
584
+ }, J = (r) => H(m({}, "__esModule", { value: true }), r), w = {};
585
+ q(w, { default: () => re });
586
+ var A = (r) => Array.isArray(r), d = (r) => typeof r == "function", Q = (r) => r.length === 0, W = (r) => typeof r == "number", K = (r) => typeof r == "object" && r !== null, X = (r) => r instanceof RegExp, b = (r) => typeof r == "string", h = (r) => r === void 0, Y = (r) => {
587
+ const e = /* @__PURE__ */ new Map();
588
+ return (n) => {
589
+ const a = e.get(n);
590
+ if (a) return a;
591
+ const t = r(n);
592
+ return e.set(n, t), t;
593
+ };
594
+ }, rr = (r, e, n = {}) => {
595
+ const a = {
596
+ cache: {},
597
+ input: r,
598
+ index: 0,
599
+ indexMax: 0,
600
+ options: n,
601
+ output: []
602
+ };
603
+ if (v(e)(a) && a.index === r.length) return a.output;
604
+ throw new Error(`Failed to parse at index ${a.indexMax}`);
605
+ }, i = (r, e) => A(r) ? er(r, e) : b(r) ? ar(r, e) : nr(r, e), er = (r, e) => {
606
+ const n = {};
607
+ for (const a of r) {
608
+ if (a.length !== 1) throw new Error(`Invalid character: "${a}"`);
609
+ const t = a.charCodeAt(0);
610
+ n[t] = true;
611
+ }
612
+ return (a) => {
613
+ const t = a.index, o = a.input;
614
+ for (; a.index < o.length && o.charCodeAt(a.index) in n;) a.index += 1;
615
+ const u = a.index;
616
+ if (u > t) {
617
+ if (!h(e) && !a.options.silent) {
618
+ const s = a.input.slice(t, u), c = d(e) ? e(s, o, String(t)) : e;
619
+ h(c) || a.output.push(c);
620
+ }
621
+ a.indexMax = Math.max(a.indexMax, a.index);
622
+ }
623
+ return true;
624
+ };
625
+ }, nr = (r, e) => {
626
+ const n = r.source, a = r.flags.replace(/y|$/, "y"), t = new RegExp(n, a);
627
+ return g((o) => {
628
+ t.lastIndex = o.index;
629
+ const u = t.exec(o.input);
630
+ if (u) {
631
+ if (!h(e) && !o.options.silent) {
632
+ const s = d(e) ? e(...u, o.input, String(o.index)) : e;
633
+ h(s) || o.output.push(s);
634
+ }
635
+ return o.index += u[0].length, o.indexMax = Math.max(o.indexMax, o.index), true;
636
+ } else return false;
637
+ });
638
+ }, ar = (r, e) => (n) => {
639
+ if (n.input.startsWith(r, n.index)) {
640
+ if (!h(e) && !n.options.silent) {
641
+ const t = d(e) ? e(r, n.input, String(n.index)) : e;
642
+ h(t) || n.output.push(t);
643
+ }
644
+ return n.index += r.length, n.indexMax = Math.max(n.indexMax, n.index), true;
645
+ } else return false;
646
+ }, C = (r, e, n, a) => {
647
+ const t = v(r);
648
+ return g(_(M((o) => {
649
+ let u = 0;
650
+ for (; u < n;) {
651
+ const s = o.index;
652
+ if (!t(o) || (u += 1, o.index === s)) break;
653
+ }
654
+ return u >= e;
655
+ })));
656
+ }, tr = (r, e) => C(r, 0, 1), f = (r, e) => C(r, 0, Infinity), x = (r, e) => {
657
+ const n = r.map(v);
658
+ return g(_(M((a) => {
659
+ for (let t = 0, o = n.length; t < o; t++) if (!n[t](a)) return false;
660
+ return true;
661
+ })));
662
+ }, l = (r, e) => {
663
+ const n = r.map(v);
664
+ return g(_((a) => {
665
+ for (let t = 0, o = n.length; t < o; t++) if (n[t](a)) return true;
666
+ return false;
667
+ }));
668
+ }, M = (r, e = false) => {
669
+ const n = v(r);
670
+ return (a) => {
671
+ const t = a.index, o = a.output.length, u = n(a);
672
+ return (!u || e) && (a.index = t, a.output.length !== o && (a.output.length = o)), u;
673
+ };
674
+ }, _ = (r, e) => {
675
+ return v(r);
676
+ }, g = (() => {
677
+ let r = 0;
678
+ return (e) => {
679
+ const n = v(e), a = r += 1;
680
+ return (t) => {
681
+ var o;
682
+ if (t.options.memoization === false) return n(t);
683
+ const u = t.index, s = (o = t.cache)[a] || (o[a] = /* @__PURE__ */ new Map()), c = s.get(u);
684
+ if (c === false) return false;
685
+ if (W(c)) return t.index = c, true;
686
+ if (c) return t.index = c.index, c.output?.length && t.output.push(...c.output), true;
687
+ {
688
+ const Z = t.output.length;
689
+ if (n(t)) {
690
+ const D = t.index, U = t.output.length;
691
+ if (U > Z) {
692
+ const ee = t.output.slice(Z, U);
693
+ s.set(u, {
694
+ index: D,
695
+ output: ee
696
+ });
697
+ } else s.set(u, D);
698
+ return true;
699
+ } else return s.set(u, false), false;
700
+ }
701
+ };
702
+ };
703
+ })(), E = (r) => {
704
+ let e;
705
+ return (n) => (e || (e = v(r())), e(n));
706
+ }, v = Y((r) => {
707
+ if (d(r)) return Q(r) ? E(r) : r;
708
+ if (b(r) || X(r)) return i(r);
709
+ if (A(r)) return x(r);
710
+ if (K(r)) return l(Object.values(r));
711
+ throw new Error("Invalid rule");
712
+ }), P = "abcdefghijklmnopqrstuvwxyz", ir = (r) => {
713
+ let e = "";
714
+ for (; r > 0;) e = P[(r - 1) % 26] + e, r = Math.floor((r - 1) / 26);
715
+ return e;
716
+ }, O = (r) => {
717
+ let e = 0;
718
+ for (let n = 0, a = r.length; n < a; n++) e = e * 26 + P.indexOf(r[n]) + 1;
719
+ return e;
720
+ }, S = (r, e) => {
721
+ if (e < r) return S(e, r);
722
+ const n = [];
723
+ for (; r <= e;) n.push(r++);
724
+ return n;
725
+ }, or = (r, e, n) => S(r, e).map((a) => String(a).padStart(n, "0")), R = (r, e) => S(O(r), O(e)).map(ir), p = (r) => r, z = (r) => ur((e) => rr(e, r, { memoization: false }).join("")), ur = (r) => {
726
+ const e = {};
727
+ return (n) => e[n] ?? (e[n] = r(n));
728
+ }, sr = i(/^\*\*\/\*$/, ".*"), cr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]+)$/, (r, e, n) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}`), lr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]*)\{([ a-zA-Z0-9._-]+(?:,[ a-zA-Z0-9._-]+)*)\}$/, (r, e, n, a) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}(?:${a.replaceAll(",", "|").replaceAll(".", "\\.")})`), y = i(/\\./, p), pr = i(/[$.*+?^(){}[\]\|]/, (r) => `\\${r}`), vr = i(/./, p), fr = l([i(/^(?:!!)*!(.*)$/, (r, e) => `(?!^${L(e)}$).*?`), i(/^(!!)+/, "")]), j = l([
729
+ i(/\/(\*\*\/)+/, "(?:/.+/|/)"),
730
+ i(/^(\*\*\/)+/, "(?:^|.*/)"),
731
+ i(/\/(\*\*)$/, "(?:/.*|$)"),
732
+ i(/\*\*/, ".*")
733
+ ]), N = l([i(/\*\/(?!\*\*\/)/, "[^/]*/"), i(/\*/, "[^/]*")]), k = i("?", "[^/]"), $r = i("[", p), wr = i("]", p), Ar = i(/[!^]/, "^/"), br = i(/[a-z]-[a-z]|[0-9]-[0-9]/i, p), Er = l([
734
+ y,
735
+ i(/[$.*+?^(){}[\|]/, (r) => `\\${r}`),
736
+ br,
737
+ i(/[^\]]/, p)
738
+ ]), B = x([
739
+ $r,
740
+ tr(Ar),
741
+ f(Er),
742
+ wr
743
+ ]), Pr = i("{", "(?:"), Or = i("}", ")"), I = x([
744
+ Pr,
745
+ l([
746
+ i(/(\d+)\.\.(\d+)/, (r, e, n) => or(+e, +n, Math.min(e.length, n.length)).join("|")),
747
+ i(/([a-z]+)\.\.([a-z]+)/, (r, e, n) => R(e, n).join("|")),
748
+ i(/([A-Z]+)\.\.([A-Z]+)/, (r, e, n) => R(e.toLowerCase(), n.toLowerCase()).join("|").toUpperCase())
749
+ ]),
750
+ Or
751
+ ]), kr = i("{", "(?:"), Br = i("}", ")"), Ir = i(",", "|"), Fr = i(/[$.*+?^(){[\]\|]/, (r) => `\\${r}`), Lr = i(/[^}]/, p), F = x([
752
+ kr,
753
+ f(l([
754
+ j,
755
+ N,
756
+ k,
757
+ B,
758
+ I,
759
+ E(() => F),
760
+ y,
761
+ Fr,
762
+ Ir,
763
+ Lr
764
+ ])),
765
+ Br
766
+ ]), L = z(f(l([
767
+ sr,
768
+ cr,
769
+ lr,
770
+ fr,
771
+ j,
772
+ N,
773
+ k,
774
+ B,
775
+ I,
776
+ F,
777
+ y,
778
+ pr,
779
+ vr
780
+ ]))), Tr = i(/\\./, p), qr = i(/./, p), Yr = z(f(l([
781
+ Tr,
782
+ i(/\*\*\*+/, "*"),
783
+ i(/([^/{[(!])\*\*/, (r, e) => `${e}*`),
784
+ i(/(^|.)\*\*(?=[^*/)\]}])/, (r, e) => `${e}*`),
785
+ qr
786
+ ]))), $ = (r, e) => {
787
+ const n = Array.isArray(r) ? r : [r];
788
+ if (!n.length) return false;
789
+ const a = n.map($.compile), t = n.every((s) => /(\/(?:\*\*)?|\[\/\])$/.test(s)), o = e.replace(/[\\\/]+/g, "/").replace(/\/$/, t ? "/" : "");
790
+ return a.some((s) => s.test(o));
791
+ };
792
+ $.compile = (r) => new RegExp(`^${L(Yr(r))}$`, "s");
793
+ var re = $;
794
+ return J(w);
795
+ })();
796
+ return __lib__.default || __lib__;
797
+ };
798
+ let _match;
799
+ const zeptomatch = (path, pattern) => {
800
+ if (!_match) {
801
+ _match = _lazyMatch();
802
+ _lazyMatch = null;
803
+ }
804
+ return _match(path, pattern);
805
+ };
806
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
807
+ function normalizeWindowsPath(input = "") {
808
+ if (!input) return input;
809
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
810
+ }
811
+ const _UNC_REGEX = /^[/\\]{2}/;
812
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
813
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
814
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
815
+ const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
816
+ const _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
817
+ const normalize = function(path) {
818
+ if (path.length === 0) return ".";
819
+ path = normalizeWindowsPath(path);
820
+ const isUNCPath = path.match(_UNC_REGEX);
821
+ const isPathAbsolute = isAbsolute(path);
822
+ const trailingSeparator = path[path.length - 1] === "/";
823
+ path = normalizeString(path, !isPathAbsolute);
824
+ if (path.length === 0) {
825
+ if (isPathAbsolute) return "/";
826
+ return trailingSeparator ? "./" : ".";
827
+ }
828
+ if (trailingSeparator) path += "/";
829
+ if (_DRIVE_LETTER_RE.test(path)) path += "/";
830
+ if (isUNCPath) {
831
+ if (!isPathAbsolute) return `//./${path}`;
832
+ return `//${path}`;
833
+ }
834
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
835
+ };
836
+ const join = function(...segments) {
837
+ let path = "";
838
+ for (const seg of segments) {
839
+ if (!seg) continue;
840
+ if (path.length > 0) {
841
+ const pathTrailing = path[path.length - 1] === "/";
842
+ const segLeading = seg[0] === "/";
843
+ if (pathTrailing && segLeading) path += seg.slice(1);
844
+ else path += pathTrailing || segLeading ? seg : `/${seg}`;
845
+ } else path += seg;
846
+ }
847
+ return normalize(path);
848
+ };
849
+ function cwd() {
850
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
851
+ return "/";
852
+ }
853
+ const resolve = function(...arguments_) {
854
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
855
+ let resolvedPath = "";
856
+ let resolvedAbsolute = false;
857
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
858
+ const path = index >= 0 ? arguments_[index] : cwd();
859
+ if (!path || path.length === 0) continue;
860
+ resolvedPath = `${path}/${resolvedPath}`;
861
+ resolvedAbsolute = isAbsolute(path);
862
+ }
863
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
864
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
865
+ return resolvedPath.length > 0 ? resolvedPath : ".";
866
+ };
867
+ function normalizeString(path, allowAboveRoot) {
868
+ let res = "";
869
+ let lastSegmentLength = 0;
870
+ let lastSlash = -1;
871
+ let dots = 0;
872
+ let char = null;
873
+ for (let index = 0; index <= path.length; ++index) {
874
+ if (index < path.length) char = path[index];
875
+ else if (char === "/") break;
876
+ else char = "/";
877
+ if (char === "/") {
878
+ if (lastSlash === index - 1 || dots === 1);
879
+ else if (dots === 2) {
880
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
881
+ if (res.length > 2) {
882
+ const lastSlashIndex = res.lastIndexOf("/");
883
+ if (lastSlashIndex === -1) {
884
+ res = "";
885
+ lastSegmentLength = 0;
886
+ } else {
887
+ res = res.slice(0, lastSlashIndex);
888
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
889
+ }
890
+ lastSlash = index;
891
+ dots = 0;
892
+ continue;
893
+ } else if (res.length > 0) {
894
+ res = "";
895
+ lastSegmentLength = 0;
896
+ lastSlash = index;
897
+ dots = 0;
898
+ continue;
899
+ }
900
+ }
901
+ if (allowAboveRoot) {
902
+ res += res.length > 0 ? "/.." : "..";
903
+ lastSegmentLength = 2;
904
+ }
905
+ } else {
906
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
907
+ else res = path.slice(lastSlash + 1, index);
908
+ lastSegmentLength = index - lastSlash - 1;
909
+ }
910
+ lastSlash = index;
911
+ dots = 0;
912
+ } else if (char === "." && dots !== -1) ++dots;
913
+ else dots = -1;
914
+ }
915
+ return res;
916
+ }
917
+ const isAbsolute = function(p) {
918
+ return _IS_ABSOLUTE_RE.test(p);
919
+ };
920
+ const toNamespacedPath = function(p) {
921
+ return normalizeWindowsPath(p);
922
+ };
923
+ const extname = function(p) {
924
+ if (p === "..") return "";
925
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
926
+ return match && match[1] || "";
927
+ };
928
+ const relative = function(from, to) {
929
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
930
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
931
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
932
+ const _fromCopy = [..._from];
933
+ for (const segment of _fromCopy) {
934
+ if (_to[0] !== segment) break;
935
+ _from.shift();
936
+ _to.shift();
937
+ }
938
+ return [..._from.map(() => ".."), ..._to].join("/");
939
+ };
940
+ const dirname = function(p) {
941
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
942
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
943
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
944
+ };
945
+ const format = function(p) {
946
+ const ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "";
947
+ const segments = [
948
+ p.root,
949
+ p.dir,
950
+ p.base ?? (p.name ?? "") + ext
951
+ ].filter(Boolean);
952
+ return normalizeWindowsPath(p.root ? resolve(...segments) : segments.join("/"));
953
+ };
954
+ const basename = function(p, extension) {
955
+ const segments = normalizeWindowsPath(p).split("/");
956
+ let lastSegment = "";
957
+ for (let i = segments.length - 1; i >= 0; i--) {
958
+ const val = segments[i];
959
+ if (val) {
960
+ lastSegment = val;
961
+ break;
962
+ }
963
+ }
964
+ return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
965
+ };
966
+ const parse = function(p) {
967
+ const root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "";
968
+ const base = basename(p);
969
+ const extension = extname(base);
970
+ return {
971
+ root,
972
+ dir: dirname(p),
973
+ base,
974
+ ext: extension,
975
+ name: base.slice(0, base.length - extension.length)
976
+ };
977
+ };
978
+ const matchesGlob = (path, pattern) => {
979
+ return zeptomatch(pattern, normalize(path));
980
+ };
981
+ const _path = {
982
+ __proto__: null,
983
+ basename,
984
+ dirname,
985
+ extname,
986
+ format,
987
+ isAbsolute,
988
+ join,
989
+ matchesGlob,
990
+ normalize,
991
+ normalizeString,
992
+ parse,
993
+ relative,
994
+ resolve,
995
+ sep: "/",
996
+ toNamespacedPath
997
+ };
998
+ //#endregion
999
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/index.mjs
1000
+ const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
1001
+ const _platforms = {
1002
+ posix: void 0,
1003
+ win32: void 0
1004
+ };
1005
+ const mix = (del = delimiter) => {
1006
+ return new Proxy(_path, { get(_, prop) {
1007
+ if (prop === "delimiter") return del;
1008
+ if (prop === "posix") return posix;
1009
+ if (prop === "win32") return win32;
1010
+ return _platforms[prop] || _path[prop];
1011
+ } });
1012
+ };
1013
+ const posix = /* @__PURE__ */ mix(":");
1014
+ const win32 = /* @__PURE__ */ mix(";");
1015
+ //#endregion
1016
+ //#region src/bundlers/vite/processed-css-assets.ts
1017
+ const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
1018
+ function isCssOutputFile(file) {
1019
+ return CSS_OUTPUT_FILE_RE.test(file);
1020
+ }
1021
+ function getAssetFile(bundleFile, asset) {
1022
+ return asset.fileName || bundleFile;
1023
+ }
1024
+ function readAssetSource(asset) {
1025
+ return typeof asset.source === "string" ? asset.source : asset.source.toString();
1026
+ }
1027
+ function appendCss(baseCss, css) {
1028
+ if (baseCss.length === 0) return css;
1029
+ if (css.length === 0) return baseCss;
1030
+ return `${baseCss}\n${css}`;
1031
+ }
1032
+ function removeTailwindSourceMediaWrappers(css) {
1033
+ if (!css.includes("@media source(")) return css;
1034
+ try {
1035
+ const root = postcss.default.parse(css);
1036
+ let changed = false;
1037
+ root.walkAtRules("media", (atRule) => {
1038
+ if (!atRule.params.startsWith("source(")) return;
1039
+ if (atRule.nodes && atRule.nodes.length > 0) atRule.replaceWith(...atRule.nodes);
1040
+ else atRule.remove();
1041
+ changed = true;
1042
+ });
1043
+ root.walkAtRules((atRule) => {
1044
+ if (atRule.nodes && atRule.nodes.length === 0) {
1045
+ atRule.remove();
1046
+ changed = true;
1047
+ }
1048
+ });
1049
+ return changed ? root.toString() : css;
1050
+ } catch {
1051
+ return css.replace(/@media\s+source\([^)]*\)\s*\{\s*\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\/?\s*\}/gi, "").replace(/@media\s+source\([^)]*\)\s*\{\s*\}/gi, "");
1052
+ }
1053
+ }
1054
+ function removeTailwindEntryDirectivesFromCss(css) {
1055
+ return require_v3_engine.removeTailwindSourceDirectives(removeTailwindSourceMediaWrappers(css));
1056
+ }
1057
+ function stripStyleExtension(file) {
1058
+ return file.replace(/[?#].*$/, "").replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss|scss|sass|less|styl|stylus|pcss|postcss)$/i, "");
1059
+ }
1060
+ function isStyleImportRequest(request) {
1061
+ return typeof request === "string" && request.length > 0 && !/^(?:https?:)?\/\//i.test(request) && /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i.test(request);
1062
+ }
1063
+ function resolveImportedStyleFile(targetFile, request) {
1064
+ if (!isStyleImportRequest(request)) return;
1065
+ const cleanRequest = request.replace(/[?#].*$/, "");
1066
+ if (cleanRequest.startsWith("/")) return require_bundle_state.normalizeOutputPathKey(cleanRequest.slice(1));
1067
+ const targetDir = posix.posix.dirname(require_bundle_state.normalizeOutputPathKey(targetFile));
1068
+ return require_bundle_state.normalizeOutputPathKey(posix.posix.join(targetDir === "." ? "" : targetDir, cleanRequest));
1069
+ }
1070
+ function collectImportedStyleFiles(css, targetFile) {
1071
+ const imports = /* @__PURE__ */ new Set();
1072
+ try {
1073
+ postcss.default.parse(css).walkAtRules("import", (atRule) => {
1074
+ const importedFile = resolveImportedStyleFile(targetFile, require_v3_engine.parseImportRequest(atRule.params));
1075
+ if (importedFile) imports.add(importedFile);
1076
+ });
1077
+ } catch {}
1078
+ return imports;
1079
+ }
1080
+ function normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile) {
1081
+ return resolveViteProcessedCssOutputFile?.(markerFile) ?? markerFile;
1082
+ }
1083
+ function isMatchingGeneratedCssMarkerFile(targetFile, markerFile, resolveViteProcessedCssOutputFile) {
1084
+ if (!markerFile) return false;
1085
+ return require_bundle_state.normalizeOutputPathKey(stripStyleExtension(targetFile)) === require_bundle_state.normalizeOutputPathKey(stripStyleExtension(normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile)));
1086
+ }
1087
+ function resolveViteProcessedCssAssetSource(file, rawSource, resolveViteProcessedCssOutputFile) {
1088
+ const blocks = require_bundle_state.parseBundlerGeneratedCssMarkerBlocks(rawSource).filter((block) => block.bundler === "vite");
1089
+ if (blocks.length <= 1) return require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
1090
+ const matchedCss = blocks.filter((block) => isMatchingGeneratedCssMarkerFile(file, block.file, resolveViteProcessedCssOutputFile)).map((block) => block.css);
1091
+ return matchedCss.length > 0 ? matchedCss.join("\n") : require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
1092
+ }
1093
+ function shouldInjectViteProcessedCssResult(opts, targetFile, sourceFile, options) {
1094
+ if (options.injectIntoMain === true) return true;
1095
+ if (options.injectIntoMain === false) return false;
1096
+ const targetFileKey = require_bundle_state.normalizeOutputPathKey(targetFile);
1097
+ const sourceFileKey = require_bundle_state.normalizeOutputPathKey(sourceFile);
1098
+ const sourceBaseName = sourceFileKey.replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss)$/i, "").split("/").pop();
1099
+ return sourceFileKey !== targetFileKey && (opts.mainCssChunkMatcher(sourceFile, opts.appType) || sourceBaseName === "app" || sourceBaseName === "main");
1100
+ }
1101
+ function collectViteProcessedCssAssetResults(bundle, options) {
1102
+ let collected = 0;
1103
+ for (const [bundleFile, output] of Object.entries(bundle)) {
1104
+ if (output.type !== "asset") continue;
1105
+ const file = getAssetFile(bundleFile, output);
1106
+ if (!isCssOutputFile(file) || !options.isViteProcessedCssAsset?.(output, file)) continue;
1107
+ const rawSource = readAssetSource(output);
1108
+ const nextCss = resolveViteProcessedCssAssetSource(file, rawSource, options.resolveViteProcessedCssOutputFile);
1109
+ if (nextCss !== rawSource) output.source = nextCss;
1110
+ options.markCssAssetProcessed?.(output, file);
1111
+ options.recordCssAssetResult?.(file, nextCss);
1112
+ 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 });
1115
+ options.debug?.("collect vite-processed css asset: %s bytes=%d", file, nextCss.length);
1116
+ collected++;
1117
+ }
1118
+ return collected;
1119
+ }
1120
+ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
1121
+ const viteCssResults = [...options.getViteProcessedCssAssetResults?.() ?? []].map(([file, record]) => {
1122
+ return typeof record === "string" ? {
1123
+ file,
1124
+ css: record,
1125
+ injectIntoMain: void 0
1126
+ } : {
1127
+ file,
1128
+ css: record.css,
1129
+ injectIntoMain: record.injectIntoMain
1130
+ };
1131
+ }).filter((record) => record.css.length > 0);
1132
+ if (viteCssResults.length === 0) return 0;
1133
+ let injected = 0;
1134
+ for (const [bundleFile, output] of Object.entries(bundle)) {
1135
+ if (output.type !== "asset") continue;
1136
+ const file = getAssetFile(bundleFile, output);
1137
+ if (!options.opts.cssMatcher(file) || !options.opts.mainCssChunkMatcher(file, options.opts.appType)) continue;
1138
+ const mainFileKey = require_bundle_state.normalizeOutputPathKey(file);
1139
+ const originalSource = readAssetSource(output);
1140
+ let nextCss = removeTailwindEntryDirectivesFromCss(originalSource);
1141
+ const importedStyleFiles = collectImportedStyleFiles(nextCss, file);
1142
+ for (const record of viteCssResults) {
1143
+ 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();
1146
+ if (css.length === 0) continue;
1147
+ const mergedLayerCss = require_incremental_runtime_class_set.mergeMarkedUserLayerComponentsCss(nextCss, css);
1148
+ if (mergedLayerCss.merged) {
1149
+ nextCss = mergedLayerCss.css;
1150
+ continue;
1151
+ }
1152
+ if (nextCss.includes(css)) continue;
1153
+ nextCss = appendCss(nextCss, css);
1154
+ }
1155
+ if (nextCss === originalSource) continue;
1156
+ output.source = nextCss;
1157
+ options.markCssAssetProcessed?.(output, file);
1158
+ options.recordCssAssetResult?.(file, nextCss);
1159
+ options.onUpdate?.(file, originalSource, nextCss);
1160
+ options.debug?.("inject vite-processed css into main css asset: %s bytes=%d", file, nextCss.length);
1161
+ 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";
1228
+ }
1229
+ function isMainAppCssFile(file) {
1230
+ return node_path.default.basename(stripStyleFileExtension(file)) === "app";
1231
+ }
1232
+ function normalizeCssSourceForCompare(css) {
1233
+ return css.trim();
1234
+ }
1235
+ function createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash) {
1236
+ return `${cssRuntimeSignature}:${cssRuntimeAffectingHash}`;
1237
+ }
1238
+ async function createScopedGeneratorCandidateSignature(rawSource, sourceFile, fallbackSignature, getSourceCandidatesForEntries, options = {}) {
1239
+ if (!getSourceCandidatesForEntries || !rawSource.includes("@source")) return fallbackSignature;
1240
+ const resolved = await require_v3_engine.resolveTailwindV4EntriesFromCssCached(rawSource, node_path.default.dirname(node_path.default.resolve(sourceFile.replace(/[?#].*$/, ""))));
1241
+ if (resolved?.entries === void 0) return fallbackSignature;
1242
+ const scopedSignature = createCandidateSignature(getSourceCandidatesForEntries(resolved.entries));
1243
+ return options.includeFallbackSignature === true ? `${scopedSignature}:${fallbackSignature}` : scopedSignature;
1244
+ }
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
+ function createGenerateBundleHook(context) {
1360
+ const state = require_bundle_state.createBundleBuildState();
1361
+ const lastCssResultByFile = /* @__PURE__ */ new Map();
1362
+ let currentOutDir;
1363
+ const cssHandlerOptions = createCssHandlerOptionsCache({
1364
+ getAppType: () => context.opts.appType,
1365
+ mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
1366
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion,
1367
+ getOutputRoot: () => currentOutDir,
1368
+ getExtraOptions: () => resolveUniAppXNativeCssHandlerOptions(context.opts)
1369
+ });
1370
+ return async function generateBundle(_opt, bundle) {
1371
+ 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;
1373
+ const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
1374
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1375
+ const isWebGeneratorTarget = generatorOptions.target === "web";
1376
+ const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp;
1377
+ const shouldGenerateWebCssByGenerator = isWebGeneratorTarget && runtimeState.twPatcher.majorVersion === 3;
1378
+ const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
1379
+ const resolvedConfig = getResolvedConfig();
1380
+ const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
1381
+ const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1382
+ await runtimeState.readyPromise;
1383
+ debug("start");
1384
+ onStart();
1385
+ collectViteProcessedCssAssetResults(bundle, {
1386
+ opts,
1387
+ isViteProcessedCssAsset,
1388
+ markCssAssetProcessed,
1389
+ recordCssAssetResult,
1390
+ recordViteProcessedCssAssetResult,
1391
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget),
1392
+ debug
1393
+ });
1394
+ const hmrTimingStartedAt = performance.now();
1395
+ const timingDetails = {};
1396
+ const recordTimingDetail = (name, startedAt) => {
1397
+ timingDetails[name] = (timingDetails[name] ?? 0) + Math.max(0, performance.now() - startedAt);
1398
+ };
1399
+ const timeTask = async (name, task) => {
1400
+ const start = performance.now();
1401
+ try {
1402
+ await task();
1403
+ } finally {
1404
+ recordTimingDetail(`tasks.${name}`, start);
1405
+ }
1406
+ };
1407
+ const metrics = createEmptyMetrics();
1408
+ const forceRuntimeRefreshByEnv = node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1409
+ const disableDirtyOptimization = node_process.default.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1";
1410
+ const disableJsPrecheck = node_process.default.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1";
1411
+ const debugCssDiff = node_process.default.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
1412
+ const disableV3OxideSourceRuntime = node_process.default.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1";
1413
+ const bundleFiles = Object.keys(bundle);
1414
+ const buildCommand = resolvedConfig?.command === "build";
1415
+ const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
1416
+ const hasOmittedKnownFiles = hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1417
+ const useIncrementalMode = !buildCommand || hasPreviousBundleState || hasOmittedKnownFiles;
1418
+ currentOutDir = outDir;
1419
+ const snapshotStart = performance.now();
1420
+ const snapshot = require_bundle_state.buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode, { hasOmittedKnownFiles });
1421
+ recordTimingDetail("snapshot", snapshotStart);
1422
+ const useBundleRuntimeClassSet = !isWebGeneratorTarget && (useIncrementalMode || runtimeState.twPatcher.majorVersion === 4);
1423
+ const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1424
+ const processFiles = snapshot.processFiles;
1425
+ logBundleProcessPlan({
1426
+ debug,
1427
+ snapshot,
1428
+ useIncrementalMode,
1429
+ iteration: state.iteration + 1
1430
+ });
1431
+ const sourceCandidateWaitStart = performance.now();
1432
+ await waitForSourceCandidateSyncs?.();
1433
+ recordTimingDetail("sourceCandidates.wait", sourceCandidateWaitStart);
1434
+ const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1435
+ const jsEntries = snapshot.jsEntries;
1436
+ const getJsEntry = createJsEntryResolver(jsEntries);
1437
+ const moduleGraphOptions = require_bundle_state.createBundleModuleGraphOptions(outDir, jsEntries);
1438
+ const hasCssAssetEntry = snapshot.entries.some((entry) => entry.type === "css" && entry.output.type === "asset");
1439
+ const hasRuntimeAffectingChanges = hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1440
+ const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !forceRuntimeRefreshByEnv && !disableV3OxideSourceRuntime;
1441
+ const runtimeStart = performance.now();
1442
+ const transformBaseRuntime = useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { transformOnly: true }) : void 0;
1443
+ const runtime = isWebGeneratorTarget && !shouldGenerateWebCssByGenerator ? /* @__PURE__ */ new Set() : useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, {
1444
+ allowBaselineOnlyInitialSync: true,
1445
+ baseClassSet: sourceCandidates
1446
+ }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1447
+ if (useV3OxideSourceRuntime) debug("[tailwindcss:v3] use oxide source candidates as runtime input, candidates=%d", sourceCandidates.size);
1448
+ const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1449
+ const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
1450
+ const filteredGeneratorCandidates = shouldFilterTailwindV4MiniProgramCandidates ? require_v3_engine.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
1451
+ let transformRuntime = transformBaseRuntime ?? runtime;
1452
+ let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, runtimeState.twPatcher.majorVersion === 3 && hasRuntimeAffectingChanges && transformBaseRuntime ? new Set([...filteredGeneratorCandidates, ...transformBaseRuntime]) : filteredGeneratorCandidates);
1453
+ const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
1454
+ if (runtimeState.twPatcher.majorVersion === 3 && useV3OxideSourceRuntime && generatorRuntime.size > 0 && (state.iteration === 0 || !hasRuntimeAffectingChanges) && cssEntries.length <= 1) {
1455
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
1456
+ if (mainCssEntry) {
1457
+ const validatedRuntime = await require_incremental_runtime_class_set.validateCandidatesByGenerator({
1458
+ opts,
1459
+ runtimeState,
1460
+ candidates: generatorRuntime,
1461
+ rawSource: mainCssEntry.source,
1462
+ file: mainCssEntry.file,
1463
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
1464
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
1465
+ styleHandler,
1466
+ debug
1467
+ });
1468
+ if (validatedRuntime.size > 0) {
1469
+ generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, validatedRuntime);
1470
+ transformRuntime = generatorRuntime;
1471
+ } else {
1472
+ generatorRuntime = validatedRuntime;
1473
+ transformRuntime = validatedRuntime;
1474
+ }
1475
+ }
1476
+ }
1477
+ const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1478
+ const generatorCandidatesChanged = state.generatorCandidateSignature !== generatorCandidateSignature;
1479
+ const runtimeLinkedCssFiles = collectRuntimeLinkedCssFiles(snapshot);
1480
+ recordGeneratorCandidates?.(generatorRuntime);
1481
+ const dynamicRetryCandidates = new Set([
1482
+ ...sourceCandidates,
1483
+ ...generatorRuntime,
1484
+ ...transformRuntime
1485
+ ]);
1486
+ const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
1487
+ metrics.runtimeSet = measureElapsed(runtimeStart);
1488
+ timingDetails["runtime"] = metrics.runtimeSet;
1489
+ if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1490
+ debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
1491
+ const runtimeSignature = require_v3_engine.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1492
+ const shouldProcessTailwindGeneration = !useIncrementalMode || hasRuntimeAffectingChanges || generatorCandidatesChanged || snapshot.processFiles.css.size > 0;
1493
+ const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
1494
+ jsEntries,
1495
+ onUpdate,
1496
+ debug
1497
+ });
1498
+ const createHandlerOptions = createJsHandlerOptionsFactory({
1499
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
1500
+ moduleGraph: moduleGraphOptions
1501
+ });
1502
+ const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1503
+ const sharedCssResultCache = /* @__PURE__ */ new Map();
1504
+ const tasks = [];
1505
+ const jsTaskFactories = [];
1506
+ for (const entry of snapshot.entries) {
1507
+ const { file, output: originalSource, source: originalEntrySource, type } = entry;
1508
+ if (type === "html" && originalSource.type === "asset") {
1509
+ metrics.html.total++;
1510
+ if (isWebGeneratorTarget) {
1511
+ debug("html skip web target: %s", file);
1512
+ continue;
1513
+ }
1514
+ if (!processFiles.html.has(file)) continue;
1515
+ const rawSource = originalEntrySource;
1516
+ tasks.push(timeTask("html", () => require_incremental_runtime_class_set.processCachedTask({
1517
+ cache,
1518
+ cacheKey: file,
1519
+ hashKey: `${file}:html:${runtimeSignature}`,
1520
+ hash: getSnapshotHash(snapshot.sourceHashByFile, file, rawSource),
1521
+ applyResult(source) {
1522
+ originalSource.source = source;
1523
+ },
1524
+ onCacheHit() {
1525
+ metrics.html.cacheHits++;
1526
+ debug("html cache hit: %s", file);
1527
+ },
1528
+ async transform() {
1529
+ const start = performance.now();
1530
+ let transformed = await templateHandler(rawSource, defaultTemplateHandlerOptions);
1531
+ let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1532
+ let retryRuntimeSet;
1533
+ if (unresolvedDynamicCandidates.length > 0) {
1534
+ const fullRuntimeSet = await context.ensureRuntimeClassSet(true);
1535
+ const allowedRetryCandidates = fullRuntimeSet.size === 0 ? unresolvedDynamicCandidates : unresolvedDynamicCandidates.filter((candidate) => dynamicRetryCandidates.has(candidate) || fullRuntimeSet.has(candidate));
1536
+ retryRuntimeSet = new Set([...fullRuntimeSet, ...allowedRetryCandidates]);
1537
+ unresolvedDynamicCandidates = unresolvedDynamicCandidates.filter((candidate) => retryRuntimeSet?.has(candidate) === true);
1538
+ }
1539
+ if (retryRuntimeSet && unresolvedDynamicCandidates.length > 0) {
1540
+ _weapp_tailwindcss_logger.logger.warn("检测到已提取 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
1541
+ transformed = await templateHandler(rawSource, { runtimeSet: retryRuntimeSet });
1542
+ unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed, retryRuntimeSet);
1543
+ if (unresolvedDynamicCandidates.length > 0) _weapp_tailwindcss_logger.logger.warn("已提取 WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
1544
+ }
1545
+ metrics.html.elapsed += measureElapsed(start);
1546
+ metrics.html.transformed++;
1547
+ onUpdate(file, rawSource, transformed);
1548
+ debug("html handle: %s", file);
1549
+ return { result: transformed };
1550
+ }
1551
+ })));
1552
+ continue;
1553
+ }
1554
+ if (type === "css" && originalSource.type === "asset") {
1555
+ metrics.css.total++;
1556
+ const rawSource = normalizeRelativeCssConfigDirectives(originalEntrySource, file, outDir, opts);
1557
+ const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget);
1558
+ if (outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file)) {
1559
+ delete bundle[file];
1560
+ debug("css skip raw source style asset: %s -> %s", file, outputFile);
1561
+ continue;
1562
+ }
1563
+ const applyCssResult = (source) => {
1564
+ if (outputFile !== file) {
1565
+ delete bundle[file];
1566
+ if (typeof this.emitFile === "function") this.emitFile({
1567
+ type: "asset",
1568
+ fileName: outputFile,
1569
+ source
1570
+ });
1571
+ else bundle[outputFile] = createReplayCssAsset(outputFile, source);
1572
+ originalSource.fileName = outputFile;
1573
+ }
1574
+ originalSource.source = source;
1575
+ };
1576
+ if (isWebGeneratorTarget && !shouldGenerateWebCssByGenerator) {
1577
+ applyCssResult(rawSource);
1578
+ markCssAssetProcessed?.(originalSource, outputFile);
1579
+ onUpdate(outputFile, rawSource, rawSource);
1580
+ debug("css skip web target: %s", outputFile);
1581
+ continue;
1582
+ }
1583
+ const hasViteProcessedCssRecord = getViteProcessedCssAssetResult?.(file) != null;
1584
+ const viteProcessedCssAsset = isViteProcessedCssAsset?.(originalSource, file) === true || hasViteProcessedCssRecord;
1585
+ const cssAssetProcessed = isCssAssetProcessed?.(originalSource, file) === true;
1586
+ const alreadyProcessedCssAsset = viteProcessedCssAsset || cssAssetProcessed;
1587
+ let rememberedCssSource = findRememberedCssSource(getRememberedCssSources?.(), outputFile, file, originalSource, outDir, opts.tailwindcssBasedir);
1588
+ if (rememberedCssSource != null) rememberedCssSource = await refreshRememberedCssSource?.(rememberedCssSource) ?? rememberedCssSource;
1589
+ const useRememberedCssSource = rememberedCssSource != null && require_bundle_state.normalizeOutputPathKey(rememberedCssSource.sourceFile) !== require_bundle_state.normalizeOutputPathKey(file);
1590
+ const vitePipelineCssAsset = viteProcessedCssAsset || useRememberedCssSource;
1591
+ const generatorRawSource = vitePipelineCssAsset ? rememberedCssSource?.rawSource ?? rawSource : rawSource;
1592
+ const hasRememberedApplySource = vitePipelineCssAsset && rememberedCssSource != null && require_v3_engine.hasTailwindApplyDirective(generatorRawSource);
1593
+ const hasDifferentRememberedCssSource = rememberedCssSource != null && normalizeCssSourceForCompare(rememberedCssSource.rawSource) !== normalizeCssSourceForCompare(rawSource);
1594
+ const hasCurrentTailwindGenerationDirective = require_v3_engine.hasTailwindRootDirectives(rawSource, { importFallback: true }) || require_v3_engine.hasTailwindApplyDirective(rawSource);
1595
+ const hasRememberedApplyDirective = rememberedCssSource != null && require_v3_engine.hasTailwindApplyDirective(rememberedCssSource.rawSource);
1596
+ const hasStaleViteProcessedCssSource = vitePipelineCssAsset && hasDifferentRememberedCssSource && (hasCurrentTailwindGenerationDirective || hasRememberedApplyDirective);
1597
+ const generatorSourceFile = vitePipelineCssAsset ? rememberedCssSource?.sourceFile ?? file : file;
1598
+ const outputCssHandlerOptions = getCssHandlerOptions(outputFile);
1599
+ const cssHandlerOptions = vitePipelineCssAsset ? {
1600
+ ...getCssHandlerOptions(generatorSourceFile),
1601
+ isMainChunk: outputCssHandlerOptions.isMainChunk || isAppOriginCssFile(file)
1602
+ } : getCssHandlerOptions(file);
1603
+ const generatorCssUserHandlerOptions = getCssUserHandlerOptions(generatorSourceFile);
1604
+ const cssRuntimeAffectingSignature = vitePipelineCssAsset ? require_bundle_state.createRuntimeAffectingSourceSignature(generatorRawSource, "css") : snapshot.runtimeAffectingSignatureByFile.get(file) ?? require_bundle_state.createRuntimeAffectingSourceSignature(generatorRawSource, "css");
1605
+ const cssRuntimeAffectingHash = vitePipelineCssAsset ? cache.computeHash(cssRuntimeAffectingSignature) : snapshot.runtimeAffectingHashByFile.get(file) ?? cache.computeHash(cssRuntimeAffectingSignature);
1606
+ const cssShareScope = createCssTransformShareScopeKey(opts, generatorSourceFile, generatorRawSource);
1607
+ 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)) {
1611
+ const nextCss = require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
1612
+ applyCssResult(nextCss);
1613
+ markCssAssetProcessed?.(originalSource, outputFile);
1614
+ recordCssAssetResult?.(outputFile, nextCss);
1615
+ onUpdate(outputFile, rawSource, nextCss);
1616
+ debug("css skip vite-processed asset: %s", outputFile);
1617
+ continue;
1618
+ }
1619
+ const trackedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? generatorCandidateSignature : "generator:stable";
1620
+ const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? await createScopedGeneratorCandidateSignature(generatorRawSource, generatorSourceFile, trackedGeneratorCandidateSignature, getSourceCandidatesForEntries, { includeFallbackSignature: cssHandlerOptions.isMainChunk }) : trackedGeneratorCandidateSignature;
1621
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
1622
+ const rememberedCssRuntimeSignature = createRememberedCssRuntimeSignature(cssRuntimeSignature, cssRuntimeAffectingHash);
1623
+ const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1624
+ if (!shouldTrackGeneratorRuntime) {
1625
+ const lastCss = lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file);
1626
+ if (lastCss != null) {
1627
+ applyCssResult(lastCss);
1628
+ markCssAssetProcessed?.(originalSource, outputFile);
1629
+ metrics.css.cacheHits++;
1630
+ debug("css replay last result: %s", outputFile);
1631
+ continue;
1632
+ }
1633
+ }
1634
+ tasks.push(timeTask("css", () => require_incremental_runtime_class_set.processCachedTask({
1635
+ cache,
1636
+ cacheKey: file,
1637
+ hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1638
+ hash: `${cssRuntimeAffectingHash}:${scopedGeneratorCandidateSignature}`,
1639
+ applyResult(source) {
1640
+ applyCssResult(source);
1641
+ lastCssResultByFile.set(outputFile, source);
1642
+ markCssAssetProcessed?.(originalSource, outputFile);
1643
+ rememberCssSource?.({
1644
+ outputFile,
1645
+ rawSource: generatorRawSource,
1646
+ sourceFile: generatorSourceFile
1647
+ }, rememberedCssRuntimeSignature);
1648
+ },
1649
+ onCacheHit() {
1650
+ metrics.css.cacheHits++;
1651
+ debug("css cache hit: %s", file);
1652
+ },
1653
+ async transform() {
1654
+ if (cssSharedCacheKey) {
1655
+ const sharedCssTask = sharedCssResultCache.get(cssSharedCacheKey);
1656
+ if (sharedCssTask != null) {
1657
+ metrics.css.cacheHits++;
1658
+ debug("css shared hit: %s", file);
1659
+ const sharedCss = await sharedCssTask;
1660
+ onUpdate(file, rawSource, sharedCss);
1661
+ return { result: sharedCss };
1662
+ }
1663
+ }
1664
+ const runTransform = async () => {
1665
+ const start = performance.now();
1666
+ 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({
1669
+ opts,
1670
+ runtimeState,
1671
+ runtime: generatorRuntime,
1672
+ rawSource: generatorRawSource,
1673
+ file: generatorSourceFile,
1674
+ cssHandlerOptions,
1675
+ cssUserHandlerOptions: generatorCssUserHandlerOptions,
1676
+ getSourceCandidatesForEntries,
1677
+ styleHandler,
1678
+ debug,
1679
+ previousCss
1680
+ });
1681
+ if (generated) {
1682
+ 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 });
1688
+ metrics.css.elapsed += measureElapsed(start);
1689
+ metrics.css.transformed++;
1690
+ debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, outputFile);
1691
+ return generated.css;
1692
+ }
1693
+ if (isWebGeneratorTarget) {
1694
+ metrics.css.elapsed += measureElapsed(start);
1695
+ metrics.css.transformed++;
1696
+ debug("css preserve web target: %s", outputFile);
1697
+ return rawSource;
1698
+ }
1699
+ const { css } = await styleHandler(generatorRawSource, cssHandlerOptions);
1700
+ if (debugCssDiff) debug("css diff %s: %s", generatorSourceFile, summarizeStringDiff(generatorRawSource, css));
1701
+ metrics.css.elapsed += measureElapsed(start);
1702
+ metrics.css.transformed++;
1703
+ return css;
1704
+ };
1705
+ const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1706
+ if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1707
+ const css = await cssTask;
1708
+ onUpdate(outputFile, rawSource, css);
1709
+ debug("css handle: %s", outputFile);
1710
+ return { result: css };
1711
+ }
1712
+ })));
1713
+ continue;
1714
+ }
1715
+ if (type !== "js") continue;
1716
+ metrics.js.total++;
1717
+ if (isWebGeneratorTarget) {
1718
+ debug("js skip web target: %s", file);
1719
+ continue;
1720
+ }
1721
+ const shouldTransformJs = !useIncrementalMode || processFiles.js.has(file);
1722
+ if (!shouldTransformJs) debug("js skip transform (clean), replay cache: %s", file);
1723
+ if (originalSource.type === "chunk") {
1724
+ const absoluteFile = node_path.default.resolve(outDir, file);
1725
+ const initialRawSource = originalEntrySource;
1726
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1727
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1728
+ jsTaskFactories.push(async () => {
1729
+ await timeTask("js", async () => {
1730
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1731
+ await require_incremental_runtime_class_set.processCachedTask({
1732
+ cache,
1733
+ cacheKey: file,
1734
+ hashKey: `${file}:js`,
1735
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1736
+ applyResult(source) {
1737
+ originalSource.code = source;
1738
+ },
1739
+ onCacheHit() {
1740
+ metrics.js.cacheHits++;
1741
+ debug("js cache hit: %s", file);
1742
+ },
1743
+ async transform() {
1744
+ const start = performance.now();
1745
+ const rawSource = originalSource.code;
1746
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1747
+ const handlerOptions = createHandlerOptions(absoluteFile);
1748
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
1749
+ metrics.js.elapsed += measureElapsed(start);
1750
+ metrics.js.transformed++;
1751
+ return { result: rawSource };
1752
+ }
1753
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1754
+ metrics.js.elapsed += measureElapsed(start);
1755
+ metrics.js.transformed++;
1756
+ onUpdate(file, rawSource, code);
1757
+ debug("js handle: %s", file);
1758
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1759
+ applyLinkedUpdates(linked);
1760
+ return { result: code };
1761
+ }
1762
+ });
1763
+ });
1764
+ });
1765
+ } else if (uniAppX && originalSource.type === "asset") {
1766
+ const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1767
+ if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1768
+ const baseApplyLinkedUpdates = applyLinkedUpdates;
1769
+ const wrappedApplyLinkedUpdates = (linked) => {
1770
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1771
+ baseApplyLinkedUpdates(linked);
1772
+ };
1773
+ const factory = createUniAppXAssetTask(file, originalSource, outDir, {
1774
+ cache,
1775
+ hashKey: `${file}:js`,
1776
+ hashSalt: createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0),
1777
+ createHandlerOptions,
1778
+ debug,
1779
+ jsHandler,
1780
+ onUpdate,
1781
+ runtimeSet: transformRuntime,
1782
+ applyLinkedResults: wrappedApplyLinkedUpdates,
1783
+ uniAppX
1784
+ });
1785
+ jsTaskFactories.push(async () => {
1786
+ await timeTask("js", async () => {
1787
+ const start = performance.now();
1788
+ if (!shouldTransformJs) {
1789
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1790
+ await factory();
1791
+ metrics.js.elapsed += measureElapsed(start);
1792
+ metrics.js.transformed++;
1793
+ return;
1794
+ }
1795
+ const currentSource = originalEntrySource;
1796
+ const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
1797
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1798
+ babelParserOptions: {
1799
+ plugins: ["typescript"],
1800
+ sourceType: "unambiguous"
1801
+ }
1802
+ });
1803
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
1804
+ metrics.js.elapsed += measureElapsed(start);
1805
+ metrics.js.transformed++;
1806
+ return;
1807
+ }
1808
+ await factory();
1809
+ metrics.js.elapsed += measureElapsed(start);
1810
+ metrics.js.transformed++;
1811
+ });
1812
+ });
1813
+ }
1814
+ }
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({
1824
+ 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
1848
+ });
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
+ }));
1856
+ }
1857
+ require_bundle_state.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1858
+ const tasksStart = performance.now();
1859
+ await Promise.all(tasks);
1860
+ recordTimingDetail("tasks", tasksStart);
1861
+ for (const apply of pendingLinkedUpdates) apply();
1862
+ injectViteProcessedCssIntoMainCssAssets(bundle, {
1863
+ opts,
1864
+ getViteProcessedCssAssetResults,
1865
+ markCssAssetProcessed,
1866
+ recordCssAssetResult,
1867
+ debug,
1868
+ onUpdate
1869
+ });
1870
+ const stateUpdateStart = performance.now();
1871
+ require_bundle_state.updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1872
+ state.generatorCandidateSignature = generatorCandidateSignature;
1873
+ recordTimingDetail("state.update", stateUpdateStart);
1874
+ debug("metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)", useIncrementalMode ? state.iteration : 0, formatMs(metrics.runtimeSet), metrics.html.total, metrics.html.transformed, metrics.html.cacheHits, formatCacheHitRate(metrics.html), formatMs(metrics.html.elapsed), metrics.js.total, metrics.js.transformed, metrics.js.cacheHits, formatCacheHitRate(metrics.js), formatMs(metrics.js.elapsed), metrics.css.total, metrics.css.transformed, metrics.css.cacheHits, formatCacheHitRate(metrics.css), formatMs(metrics.css.elapsed));
1875
+ if (hmrTimingRecorder) {
1876
+ hmrTimingRecorder.record("generateBundle", performance.now() - hmrTimingStartedAt, timingDetails);
1877
+ hmrTimingRecorder.emitTotal();
1878
+ }
1879
+ onEnd();
1880
+ debug("end");
1881
+ };
1882
+ }
1883
+ //#endregion
1884
+ //#region src/bundlers/vite/css-finalizer.ts
1885
+ function isAddWatchFileInvalidRollupPhaseError(error) {
1886
+ const candidate = error;
1887
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
1888
+ }
1889
+ function registerGeneratorDependencies(ctx, dependencies) {
1890
+ if (typeof ctx.addWatchFile !== "function") return;
1891
+ for (const dependency of dependencies ?? []) try {
1892
+ ctx.addWatchFile(dependency);
1893
+ } catch (error) {
1894
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
1895
+ _weapp_tailwindcss_logger.logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
1896
+ continue;
1897
+ }
1898
+ throw error;
1899
+ }
1900
+ }
1901
+ function createCssHandlerOptions(opts, majorVersion, file) {
1902
+ return {
1903
+ ...resolveUniAppXNativeCssHandlerOptions(opts),
1904
+ isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
1905
+ postcssOptions: { options: { from: file } },
1906
+ ...majorVersion === void 0 ? {} : { majorVersion }
1907
+ };
1908
+ }
1909
+ function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
1910
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1911
+ if (require_v3_engine.hasLocalCssImport(rawSource)) return false;
1912
+ if (require_v3_engine.hasTailwindGeneratedCssMarkers(rawSource)) return true;
1913
+ if (require_v3_engine.hasTailwindRootDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return true;
1914
+ if (opts.twPatcher.majorVersion === 3) return false;
1915
+ return processed && require_v3_engine.hasTailwindApplyDirective(rawSource) && shouldFinalizeProcessedCssAsset(opts, file);
1916
+ }
1917
+ function shouldFinalizeProcessedCssAsset(opts, file) {
1918
+ return opts.mainCssChunkMatcher(file, opts.appType);
1919
+ }
1920
+ function createViteCssFinalizerOutputPlugin(context) {
1921
+ return {
1922
+ name: "weapp-tailwindcss:adaptor:css-finalizer",
1923
+ enforce: "post",
1924
+ generateBundle: {
1925
+ order: "post",
1926
+ async handler(_options, bundle) {
1927
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
1928
+ const resolvedConfig = getResolvedConfig();
1929
+ if (resolvedConfig?.command !== "build") return;
1930
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1931
+ 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, {
1935
+ opts,
1936
+ isViteProcessedCssAsset,
1937
+ markCssAssetProcessed,
1938
+ recordCssAssetResult,
1939
+ recordViteProcessedCssAssetResult,
1940
+ resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget),
1941
+ debug
1942
+ });
1943
+ const isCssOutputAssetEntry = (entry) => {
1944
+ const [, output] = entry;
1945
+ return output.type === "asset" && opts.cssMatcher(output.fileName) && !isCssAssetProcessed(output, output.fileName);
1946
+ };
1947
+ const entries = Object.entries(bundle).filter(isCssOutputAssetEntry);
1948
+ if (entries.length === 0) {
1949
+ injectViteProcessedCssIntoMainCssAssets(bundle, {
1950
+ opts,
1951
+ getViteProcessedCssAssetResults,
1952
+ markCssAssetProcessed,
1953
+ recordCssAssetResult,
1954
+ debug,
1955
+ onUpdate: opts.onUpdate
1956
+ });
1957
+ return;
1958
+ }
1959
+ await runtimeState.readyPromise;
1960
+ await waitForSourceCandidateSyncs?.();
1961
+ const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
1962
+ const collectedGeneratorCandidates = new Set([...runtime, ...getSourceCandidates?.() ?? []]);
1963
+ const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? require_v3_engine.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
1964
+ await Promise.all(entries.map(async ([bundleFile, output]) => {
1965
+ const file = output.fileName || bundleFile;
1966
+ const rawSource = output.source.toString();
1967
+ if (isViteProcessedCssAsset?.(output, file)) {
1968
+ const nextCss = require_bundle_state.stripBundlerGeneratedCssMarkers(rawSource);
1969
+ output.source = nextCss;
1970
+ markCssAssetProcessed(output, file);
1971
+ recordCssAssetResult?.(file, nextCss);
1972
+ debug("css finalizer skip vite-processed css: %s", file);
1973
+ return;
1974
+ }
1975
+ const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, file);
1976
+ const cssUserHandlerOptions = {
1977
+ ...cssHandlerOptions,
1978
+ isMainChunk: false
1979
+ };
1980
+ const processed = isCssAssetProcessed(output, file);
1981
+ const rememberedMainCssSource = processed && cssHandlerOptions.isMainChunk ? getRememberedMainCssSource?.(file) : void 0;
1982
+ const generatorRawSource = rememberedMainCssSource?.rawSource ?? rawSource;
1983
+ const generatorSourceFile = rememberedMainCssSource?.sourceFile ?? file;
1984
+ const generatorCssHandlerOptions = rememberedMainCssSource ? createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, generatorSourceFile) : cssHandlerOptions;
1985
+ const generatorCssUserHandlerOptions = rememberedMainCssSource ? {
1986
+ ...generatorCssHandlerOptions,
1987
+ isMainChunk: false
1988
+ } : cssUserHandlerOptions;
1989
+ const generated = shouldGenerateCssByGenerator(opts, file, generatorRawSource, processed) ? await require_incremental_runtime_class_set.generateCssByGenerator({
1990
+ opts,
1991
+ runtimeState,
1992
+ runtime: generatorRuntime,
1993
+ rawSource: generatorRawSource,
1994
+ file: generatorSourceFile,
1995
+ cssHandlerOptions: generatorCssHandlerOptions,
1996
+ cssUserHandlerOptions: generatorCssUserHandlerOptions,
1997
+ getSourceCandidatesForEntries,
1998
+ styleHandler: opts.styleHandler,
1999
+ debug
2000
+ }) : void 0;
2001
+ const nextCss = generated?.css ?? (generatorOptions.target === "web" ? rawSource : (await opts.styleHandler(rawSource, cssHandlerOptions)).css);
2002
+ if (generated) {
2003
+ registerGeneratorDependencies(this, generated.dependencies);
2004
+ debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
2005
+ recordCssAssetResult?.(file, nextCss);
2006
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, generatorRawSource);
2007
+ }
2008
+ output.source = nextCss;
2009
+ markCssAssetProcessed(output, file);
2010
+ opts.onUpdate(file, rawSource, nextCss);
2011
+ debug("css finalizer handle: %s", file);
2012
+ }));
2013
+ injectViteProcessedCssIntoMainCssAssets(bundle, {
2014
+ opts,
2015
+ getViteProcessedCssAssetResults,
2016
+ markCssAssetProcessed,
2017
+ recordCssAssetResult,
2018
+ debug,
2019
+ onUpdate: opts.onUpdate
2020
+ });
2021
+ }
2022
+ }
2023
+ };
2024
+ }
2025
+ //#endregion
2026
+ //#region src/bundlers/vite/official-tailwind-plugins.ts
2027
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
2028
+ function getPostcssPluginName(plugin) {
2029
+ if (!plugin) return;
2030
+ if (typeof plugin === "function" && "postcss" in plugin) try {
2031
+ return getPostcssPluginName(plugin());
2032
+ } catch {
2033
+ return;
2034
+ }
2035
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
2036
+ const { postcssPlugin } = plugin;
2037
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
2038
+ }
2039
+ function isTailwindPostcssPlugin(plugin) {
2040
+ const name = getPostcssPluginName(plugin);
2041
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
2042
+ }
2043
+ function removeTailwindPostcssPlugins(plugins) {
2044
+ let removed = 0;
2045
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
2046
+ plugins.splice(i, 1);
2047
+ removed++;
2048
+ }
2049
+ return removed;
2050
+ }
2051
+ function isTailwindVitePlugin(plugin) {
2052
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
2053
+ const { name } = plugin;
2054
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
2055
+ }
2056
+ function removeTailwindVitePlugins(plugins) {
2057
+ let removed = 0;
2058
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
2059
+ plugins.splice(i, 1);
2060
+ removed++;
2061
+ }
2062
+ return removed;
2063
+ }
2064
+ function disableTailwindVitePlugin(plugin) {
2065
+ if (!isTailwindVitePlugin(plugin)) return false;
2066
+ const mutablePlugin = plugin;
2067
+ for (const hook of [
2068
+ "configResolved",
2069
+ "configureServer",
2070
+ "transform",
2071
+ "hotUpdate",
2072
+ "handleHotUpdate"
2073
+ ]) delete mutablePlugin[hook];
2074
+ return true;
2075
+ }
2076
+ function disableAndRemoveTailwindVitePlugins(plugins) {
2077
+ let removed = 0;
2078
+ for (let i = plugins.length - 1; i >= 0; i--) {
2079
+ const plugin = plugins[i];
2080
+ if (Array.isArray(plugin)) {
2081
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
2082
+ if (plugin.length === 0) plugins.splice(i, 1);
2083
+ continue;
2084
+ }
2085
+ if (disableTailwindVitePlugin(plugin)) {
2086
+ plugins.splice(i, 1);
2087
+ removed++;
2088
+ }
2089
+ }
2090
+ return removed;
2091
+ }
2092
+ //#endregion
2093
+ //#region src/bundlers/vite/postcss-config.ts
2094
+ async function resolveFilteredPostcssConfig(root) {
2095
+ try {
2096
+ const loaded = await (0, postcss_load_config.default)({}, root);
2097
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
2098
+ const removed = removeTailwindPostcssPlugins(plugins);
2099
+ if (removed === 0) return;
2100
+ return {
2101
+ options: loaded.options,
2102
+ plugins,
2103
+ removed
2104
+ };
2105
+ } catch (error) {
2106
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
2107
+ throw error;
2108
+ }
2109
+ }
2110
+ //#endregion
2111
+ //#region src/bundlers/vite/resolve-app-type.ts
2112
+ const PACKAGE_JSON_FILE$1 = "package.json";
2113
+ const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
2114
+ const TARO_SCRIPT_RE = /\btaro\b/u;
2115
+ const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
2116
+ function resolveDependencyNames(pkg) {
2117
+ return new Set([
2118
+ ...Object.keys(pkg.dependencies ?? {}),
2119
+ ...Object.keys(pkg.devDependencies ?? {}),
2120
+ ...Object.keys(pkg.peerDependencies ?? {}),
2121
+ ...Object.keys(pkg.optionalDependencies ?? {})
2122
+ ]);
2123
+ }
2124
+ function hasScriptMatch(pkg, pattern) {
2125
+ return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
2126
+ }
2127
+ function resolveAppTypeFromPackageJson(pkg) {
2128
+ const dependencyNames = resolveDependencyNames(pkg);
2129
+ if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
2130
+ if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
2131
+ if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
2132
+ if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
2133
+ if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
2134
+ }
2135
+ function tryReadUniAppManifest(root) {
2136
+ const manifestPath = node_path.default.join(root, "manifest.json");
2137
+ if (!(0, node_fs.existsSync)(manifestPath)) return;
2138
+ try {
2139
+ return JSON.parse((0, node_fs.readFileSync)(manifestPath, "utf8"));
2140
+ } catch {}
2141
+ }
2142
+ function tryReadPackageJson(root) {
2143
+ const packageJsonPath = node_path.default.join(root, PACKAGE_JSON_FILE$1);
2144
+ if (!(0, node_fs.existsSync)(packageJsonPath)) return;
2145
+ try {
2146
+ return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8"));
2147
+ } catch {}
2148
+ }
2149
+ function resolveAppTypeFromMarkers(root) {
2150
+ for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if ((0, node_fs.existsSync)(node_path.default.join(root, relativePath))) return appType;
2151
+ }
2152
+ function resolveImplicitAppTypeFromViteRoot(root) {
2153
+ const resolvedRoot = node_path.default.resolve(root);
2154
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return;
2155
+ const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
2156
+ if (markerDetected) return markerDetected;
2157
+ let current = resolvedRoot;
2158
+ while (true) {
2159
+ const manifest = tryReadUniAppManifest(current);
2160
+ if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
2161
+ const pkg = tryReadPackageJson(current);
2162
+ if (pkg) {
2163
+ const detected = resolveAppTypeFromPackageJson(pkg);
2164
+ if (detected) return detected;
2165
+ }
2166
+ const parent = node_path.default.dirname(current);
2167
+ if (parent === current) break;
2168
+ current = parent;
2169
+ }
2170
+ }
2171
+ //#endregion
2172
+ //#region src/bundlers/shared/css-imports.ts
2173
+ const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
2174
+ const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
2175
+ function normalizeTailwindcssSpecifier(specifier) {
2176
+ if (specifier === "tailwindcss$" || specifier === "weapp-tailwindcss$") return specifier.slice(0, -1);
2177
+ return specifier;
2178
+ }
2179
+ function getTailwindcssSubpath(specifier) {
2180
+ if (specifier === "tailwindcss" || specifier === "weapp-tailwindcss") return "index.css";
2181
+ return specifier.replace(/^(?:tailwindcss|weapp-tailwindcss)\//, "");
2182
+ }
2183
+ function resolveTailwindcssImport(specifier, pkgDir, options) {
2184
+ const normalized = normalizeTailwindcssSpecifier(specifier);
2185
+ if (!tailwindcssImportRE.test(normalized)) return null;
2186
+ if (normalized === "tailwindcss" || normalized === "weapp-tailwindcss") return options?.rootImport ?? (options?.join ?? node_path.default.join)(pkgDir, "index.css");
2187
+ return (options?.join ?? node_path.default.join)(pkgDir, getTailwindcssSubpath(normalized));
2188
+ }
2189
+ function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
2190
+ let hasReplacements = false;
2191
+ const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
2192
+ const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
2193
+ if (!replacement) return full;
2194
+ hasReplacements = true;
2195
+ return `${prefix}${quote}${replacement}${suffix}`;
2196
+ });
2197
+ return hasReplacements ? rewritten : void 0;
2198
+ }
2199
+ //#endregion
2200
+ //#region src/bundlers/vite/rewrite-css-imports.ts
2201
+ function joinPosixPath(base, subpath) {
2202
+ if (base.endsWith("/")) return `${base}${subpath}`;
2203
+ return `${base}/${subpath}`;
2204
+ }
2205
+ function isCssLikeImporter(importer) {
2206
+ if (!importer) return false;
2207
+ const normalized = (0, _weapp_tailwindcss_shared.cleanUrl)(importer);
2208
+ return require_bundle_state.isSourceStyleRequest(importer) || require_bundle_state.isCSSRequest(normalized) || normalized.endsWith("/*");
2209
+ }
2210
+ function stripTailwindConfigDirectives(code) {
2211
+ return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
2212
+ }
2213
+ function createRewriteCssImportsPlugins(options) {
2214
+ if (!options.shouldRewrite && !options.shouldOwnTailwindGeneration) return [];
2215
+ const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
2216
+ const resolveAppType = () => getAppType?.() ?? appType;
2217
+ return [{
2218
+ name: `${require_precheck.vitePluginName}:rewrite-css-imports`,
2219
+ enforce: "pre",
2220
+ resolveId(id, importer) {
2221
+ if (!options.shouldRewrite) return null;
2222
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
2223
+ join: joinPosixPath,
2224
+ appType: resolveAppType(),
2225
+ rootImport
2226
+ });
2227
+ if (!replacement) return null;
2228
+ if (importer && !isCssLikeImporter(importer)) return null;
2229
+ return replacement;
2230
+ },
2231
+ async transform(code, id) {
2232
+ if (!require_bundle_state.isCSSRequest(id)) return null;
2233
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2234
+ const normalizedCode = require_v3_engine.hasTailwindRootDirectives(code) ? require_v3_engine.normalizeTailwindConfigDirectives(code, node_path.default.dirname(file)) : code;
2235
+ await options.onCssSourceTransform?.(id, normalizedCode);
2236
+ const hasTailwindRoot = require_v3_engine.hasTailwindRootDirectives(normalizedCode);
2237
+ if (hasTailwindRoot) await options.onTailwindRootCss?.(id, normalizedCode);
2238
+ if (options.shouldOwnTailwindGeneration && (hasTailwindRoot || options.shouldGenerateCss?.(id, normalizedCode))) {
2239
+ const generatedCss = await options.generateTailwindCss?.(id, normalizedCode, this);
2240
+ if (generatedCss !== void 0) return {
2241
+ code: generatedCss,
2242
+ map: null
2243
+ };
2244
+ }
2245
+ if (!options.shouldRewrite) return null;
2246
+ const rewritten = rewriteTailwindcssImportsInCode(normalizedCode, weappTailwindcssDirPosix, {
2247
+ join: joinPosixPath,
2248
+ appType: resolveAppType(),
2249
+ rootImport
2250
+ });
2251
+ const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? normalizedCode) : rewritten;
2252
+ if (!nextCode || nextCode === code) return null;
2253
+ return {
2254
+ code: nextCode,
2255
+ map: null
2256
+ };
2257
+ }
2258
+ }];
2259
+ }
2260
+ function hasVitePipelineTailwindGenerationDirective(code) {
2261
+ return require_v3_engine.hasTailwindRootDirectives(code) || require_v3_engine.hasTailwindApplyDirective(code);
2262
+ }
2263
+ //#endregion
2264
+ //#region src/bundlers/vite/runtime-class-set.ts
2265
+ function createViteRuntimeClassSet(options) {
2266
+ const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
2267
+ const runtimeState = {
2268
+ twPatcher: initialTwPatcher,
2269
+ readyPromise: require_precheck.createTailwindRuntimeReadyPromise(initialTwPatcher),
2270
+ refreshTailwindcssPatcher
2271
+ };
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 });
2274
+ let runtimeSet;
2275
+ let runtimeSetPromise;
2276
+ let runtimeRefreshSignature;
2277
+ let runtimeRefreshOptionsKey;
2278
+ function resolveRuntimeRefreshOptions() {
2279
+ const configPath = require_v3_engine.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
2280
+ const signature = require_v3_engine.getRuntimeClassSetSignature(runtimeState.twPatcher);
2281
+ const optionsKey = JSON.stringify({
2282
+ appType: opts.appType,
2283
+ uniAppX: uniAppXEnabled,
2284
+ customAttributesEntities,
2285
+ disabledDefaultTemplateHandler,
2286
+ configPath
2287
+ });
2288
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
2289
+ runtimeRefreshSignature = signature;
2290
+ runtimeRefreshOptionsKey = optionsKey;
2291
+ return {
2292
+ changed,
2293
+ signature,
2294
+ optionsKey
2295
+ };
2296
+ }
2297
+ async function refreshRuntimeState(force) {
2298
+ const invalidation = resolveRuntimeRefreshOptions();
2299
+ const refreshed = await require_precheck.refreshTailwindRuntimeState(runtimeState, {
2300
+ force: force || invalidation.changed,
2301
+ clearCache: force || invalidation.changed
2302
+ });
2303
+ if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
2304
+ if (refreshed) {
2305
+ runtimeSet = void 0;
2306
+ runtimeSetPromise = void 0;
2307
+ }
2308
+ }
2309
+ async function ensureRuntimeClassSet(force = false) {
2310
+ const forceRuntimeRefresh = force || node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
2311
+ await refreshRuntimeState(force);
2312
+ await runtimeState.readyPromise;
2313
+ if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
2314
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
2315
+ const invalidation = resolveRuntimeRefreshOptions();
2316
+ runtimeSetPromise = require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
2317
+ force: forceRuntimeRefresh || invalidation.changed,
2318
+ skipRefresh: forceRuntimeRefresh,
2319
+ clearCache: forceRuntimeRefresh || invalidation.changed
2320
+ });
2321
+ }
2322
+ const task = runtimeSetPromise;
2323
+ try {
2324
+ runtimeSet = await task;
2325
+ return runtimeSet;
2326
+ } finally {
2327
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
2328
+ }
2329
+ }
2330
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, options = {}) {
2331
+ const forceRuntimeRefresh = forceRefresh || node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
2332
+ const invalidation = resolveRuntimeRefreshOptions();
2333
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
2334
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
2335
+ await refreshRuntimeState(shouldRefreshPatcher);
2336
+ await runtimeState.readyPromise;
2337
+ if (shouldRefreshPatcher) {
2338
+ runtimeSet = void 0;
2339
+ runtimeSetPromise = void 0;
2340
+ await bundleRuntimeClassSetManager.reset();
2341
+ await transformRuntimeClassSetManager.reset();
2342
+ }
2343
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
2344
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
2345
+ runtimeSet = nextRuntimeSet;
2346
+ return nextRuntimeSet;
2347
+ } catch (error) {
2348
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
2349
+ await bundleRuntimeClassSetManager.reset();
2350
+ }
2351
+ if (runtimeState.twPatcher.majorVersion === 3 && !forceRuntimeRefresh) {
2352
+ if (options.transformOnly) try {
2353
+ return await transformRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
2354
+ } catch (error) {
2355
+ debug("incremental transform runtime set sync failed, fallback to full collect: %O", error);
2356
+ await transformRuntimeClassSetManager.reset();
2357
+ }
2358
+ try {
2359
+ let baseClassSet = options.baseClassSet;
2360
+ if (!baseClassSet && (!runtimeSet || shouldRefreshPatcher)) baseClassSet = await require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
2361
+ force: true,
2362
+ skipRefresh: shouldRefreshPatcher,
2363
+ clearCache: shouldRefreshPatcher
2364
+ });
2365
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot, {
2366
+ baseClassSet: baseClassSet ?? (options.allowBaselineOnlyInitialSync === true ? runtimeSet : void 0),
2367
+ skipInitialFullScanWithBase: options.allowBaselineOnlyInitialSync === true && Boolean(runtimeSet)
2368
+ });
2369
+ runtimeSet = nextRuntimeSet;
2370
+ return nextRuntimeSet;
2371
+ } catch (error) {
2372
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
2373
+ await bundleRuntimeClassSetManager.reset();
2374
+ }
2375
+ }
2376
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
2377
+ const task = require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
2378
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
2379
+ skipRefresh: forceRuntimeRefresh,
2380
+ clearCache: forceRuntimeRefresh || invalidation.changed
2381
+ });
2382
+ runtimeSetPromise = task;
2383
+ try {
2384
+ runtimeSet = await task;
2385
+ return runtimeSet;
2386
+ } finally {
2387
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
2388
+ }
2389
+ }
2390
+ return {
2391
+ runtimeState,
2392
+ refreshRuntimeState,
2393
+ ensureRuntimeClassSet,
2394
+ ensureBundleRuntimeClassSet
2395
+ };
2396
+ }
2397
+ //#endregion
2398
+ //#region src/bundlers/vite/serve-css-generation.ts
2399
+ const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
2400
+ const COMMON_JS_PROXY_RE = /\?commonjs-proxy/;
2401
+ const VITE_CSS_HMR_MODULE_RE = /\b__vite__updateStyle\s*\(/;
2402
+ const VITE_CSS_CONST_RE = /\bconst\s+__vite__css\s*=\s*("(?:\\[\s\S]|[^"])*")/;
2403
+ function decodeJsStringLiteral(literal) {
2404
+ try {
2405
+ return JSON.parse(literal);
2406
+ } catch {
2407
+ return;
2408
+ }
2409
+ }
2410
+ function encodeJsStringLiteral(value) {
2411
+ return JSON.stringify(value);
2412
+ }
2413
+ function extractViteCssHmrModuleCss(code) {
2414
+ const match = VITE_CSS_CONST_RE.exec(code);
2415
+ if (!match?.[1]) return;
2416
+ const css = decodeJsStringLiteral(match[1]);
2417
+ if (typeof css !== "string") return;
2418
+ return {
2419
+ css,
2420
+ start: match.index + match[0].lastIndexOf(match[1]),
2421
+ end: match.index + match[0].length
2422
+ };
2423
+ }
2424
+ function replaceViteCssHmrModuleCss(code, css) {
2425
+ const extracted = extractViteCssHmrModuleCss(code);
2426
+ if (!extracted) return;
2427
+ return `${code.slice(0, extracted.start)}${encodeJsStringLiteral(css)}${code.slice(extracted.end)}`;
2428
+ }
2429
+ function isViteServeStyleRequest(id, command) {
2430
+ return command === "serve" && require_bundle_state.isSourceStyleRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
2431
+ }
2432
+ function isViteServeCssRootRequest(id, command) {
2433
+ return command === "serve" && require_bundle_state.isCSSRequest(id) && !SPECIAL_QUERY_RE.test(id) && !COMMON_JS_PROXY_RE.test(id);
2434
+ }
2435
+ function isViteCssHmrModule(code, id, command) {
2436
+ return isViteServeStyleRequest(id, command) && VITE_CSS_HMR_MODULE_RE.test(code) && /[?&](?:direct|vue)(?:&|$)/.test(id);
2437
+ }
2438
+ function createViteServeCssGenerationPlugins(options) {
2439
+ return [{
2440
+ name: `${require_precheck.vitePluginName}:generate:serve`,
2441
+ apply: "serve",
2442
+ enforce: "pre",
2443
+ async transform(code, id) {
2444
+ if (!options.shouldGenerate() || !isViteServeCssRootRequest(id, options.getCommand())) return;
2445
+ if (!require_v3_engine.hasTailwindRootDirectives(code)) return;
2446
+ await options.onTailwindRootCss?.(id, code);
2447
+ const generatedCss = await options.generateCss(id, code, this);
2448
+ if (generatedCss === void 0 || generatedCss === code) return;
2449
+ return {
2450
+ code: generatedCss,
2451
+ map: null
2452
+ };
2453
+ }
2454
+ }, {
2455
+ name: `${require_precheck.vitePluginName}:generate:serve-hmr`,
2456
+ apply: "serve",
2457
+ enforce: "post",
2458
+ async transform(code, id) {
2459
+ if (!options.shouldGenerate() || !isViteCssHmrModule(code, id, options.getCommand())) return;
2460
+ const extracted = extractViteCssHmrModuleCss(code);
2461
+ if (!extracted) return;
2462
+ await options.onTailwindRootCss?.(id, extracted.css);
2463
+ const generatedCss = await options.generateCss(id, extracted.css, this);
2464
+ if (generatedCss === void 0 || generatedCss === extracted.css) return;
2465
+ const nextCode = replaceViteCssHmrModuleCss(code, generatedCss);
2466
+ if (nextCode === void 0 || nextCode === code) return;
2467
+ return {
2468
+ code: nextCode,
2469
+ map: null
2470
+ };
2471
+ }
2472
+ }];
2473
+ }
2474
+ //#endregion
2475
+ //#region src/bundlers/vite/tailwind-basedir.ts
2476
+ const PACKAGE_JSON_FILE = "package.json";
2477
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
2478
+ const resolvedRoot = node_path.default.resolve(root);
2479
+ if (!(0, node_fs.existsSync)(resolvedRoot)) return resolvedRoot;
2480
+ const searchRoots = [];
2481
+ let current = resolvedRoot;
2482
+ while (true) {
2483
+ searchRoots.push(current);
2484
+ const parent = node_path.default.dirname(current);
2485
+ if (parent === current) break;
2486
+ current = parent;
2487
+ }
2488
+ const tailwindConfigPath = require_v3_engine.findTailwindConfig(searchRoots);
2489
+ if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
2490
+ const packageRoot = require_v3_engine.findNearestPackageRoot(resolvedRoot);
2491
+ if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
2492
+ return resolvedRoot;
2493
+ }
2494
+ //#endregion
2495
+ //#region src/bundlers/vite/index.ts
2496
+ const debug = require_v3_engine.createDebug();
2497
+ const weappTailwindcssPackageDir = require_bundle_state.resolvePackageDir("weapp-tailwindcss");
2498
+ const weappTailwindcssDirPosix = require_bundle_state.slash(weappTailwindcssPackageDir);
2499
+ const sourceCandidateScanSnapshotCache = /* @__PURE__ */ new Map();
2500
+ const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
2501
+ function normalizeSignaturePath(value) {
2502
+ return require_bundle_state.slash(node_path.default.resolve(value));
2503
+ }
2504
+ function serializeInlineCandidates(inlineCandidates) {
2505
+ return {
2506
+ excluded: [...inlineCandidates?.excluded ?? []].sort(),
2507
+ included: [...inlineCandidates?.included ?? []].sort()
2508
+ };
2509
+ }
2510
+ function serializeSourceEntries(entries) {
2511
+ return (entries ?? []).map((entry) => ({
2512
+ base: normalizeSignaturePath(entry.base),
2513
+ negated: entry.negated,
2514
+ pattern: entry.pattern
2515
+ })).sort((a, b) => `${a.base}\0${a.pattern}\0${a.negated}`.localeCompare(`${b.base}\0${b.pattern}\0${b.negated}`));
2516
+ }
2517
+ function createSourceCandidateScanSignature(input) {
2518
+ return JSON.stringify({
2519
+ inlineCandidates: serializeInlineCandidates(input.inlineCandidates),
2520
+ outDir: input.outDir ? normalizeSignaturePath(input.outDir) : void 0,
2521
+ roots: input.roots.map((root) => ({
2522
+ entries: serializeSourceEntries(root.entries),
2523
+ root: normalizeSignaturePath(root.root)
2524
+ })),
2525
+ scanAllSources: input.scanAllSources ?? false
2526
+ });
2527
+ }
2528
+ function stripSourceHash(sourceFile) {
2529
+ const hashIndex = sourceFile.indexOf("#");
2530
+ return hashIndex === -1 ? sourceFile : sourceFile.slice(0, hashIndex);
2531
+ }
2532
+ function normalizeCssSourceIdentity(sourceFile) {
2533
+ const cleanSourceFile = stripSourceHash(sourceFile);
2534
+ const { filename, query } = parseVueRequest(cleanSourceFile);
2535
+ const normalizedFile = require_bundle_state.normalizeOutputPathKey(filename);
2536
+ if (query.type === "style") return `${normalizedFile}?type=style&index=${query.index ?? 0}`;
2537
+ return require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery(cleanSourceFile));
2538
+ }
2539
+ /**
2540
+ * @name WeappTailwindcss
2541
+ * @description uni-app vite / uni-app-x 版本插件
2542
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
2543
+ */
2544
+ function WeappTailwindcss(options = {}) {
2545
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
2546
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
2547
+ const opts = require_precheck.getCompilerContext({
2548
+ ...options,
2549
+ __internalDeferMissingCssEntriesWarning: true
2550
+ });
2551
+ const normalizedCssEntries = require_tailwindcss.normalizeCssEntries(options.cssEntries, opts.tailwindcssBasedir ?? node_process.default.cwd());
2552
+ if (normalizedCssEntries) opts.cssEntries ?? (opts.cssEntries = normalizedCssEntries);
2553
+ if (opts.cssEntries?.length) {
2554
+ var _opts$tailwindcss, _opts$tailwindcss$v;
2555
+ opts.tailwindcss ?? (opts.tailwindcss = {});
2556
+ (_opts$tailwindcss = opts.tailwindcss).v4 ?? (_opts$tailwindcss.v4 = {});
2557
+ (_opts$tailwindcss$v = opts.tailwindcss.v4).cssEntries ?? (_opts$tailwindcss$v.cssEntries = opts.cssEntries);
2558
+ }
2559
+ const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
2560
+ const uniAppXEnabled = require_tailwindcss.isUniAppXEnabled(uniAppX);
2561
+ const disabledOptions = require_bundle_state.resolvePluginDisabledState(disabled);
2562
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
2563
+ const shouldOwnTailwindGeneration = !disabledOptions.plugin;
2564
+ const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
2565
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
2566
+ const shouldInferAppType = !hasExplicitAppType && generatorOptions.target !== "web";
2567
+ const hasInitialTailwindCssRoots = require_tailwindcss.hasConfiguredTailwindV4CssRoots({
2568
+ ...options,
2569
+ cssEntries: opts.cssEntries ?? options.cssEntries
2570
+ });
2571
+ const autoCssSourceContent = /* @__PURE__ */ new Map();
2572
+ let refreshRuntimeStateForAutoCssSources;
2573
+ let autoCssSourcesRefresh;
2574
+ let autoCssSourcesDiscovered = false;
2575
+ const syncTailwindCssSourceCandidates = async (id, css) => {
2576
+ await sourceCandidateCollector.syncCss(id, css);
2577
+ cacheCurrentSourceCandidateScan();
2578
+ };
2579
+ const registerAutoCssSource = async (id, css, options = {}) => {
2580
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
2581
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2582
+ if (!node_path.default.isAbsolute(file)) return;
2583
+ const sourceFile = node_path.default.normalize(file);
2584
+ const sourceBase = node_path.default.dirname(sourceFile);
2585
+ const sourceCss = require_v3_engine.normalizeTailwindSourceForGenerator(require_v3_engine.normalizeTailwindConfigDirectives(css, sourceBase), { importFallback: true });
2586
+ if (autoCssSourceContent.get(sourceFile) === sourceCss) return;
2587
+ autoCssSourceContent.set(sourceFile, sourceCss);
2588
+ await syncTailwindCssSourceCandidates(sourceFile, sourceCss);
2589
+ if (!require_tailwindcss.upsertTailwindV4CssSource(opts, {
2590
+ file: sourceFile,
2591
+ base: sourceBase,
2592
+ css: sourceCss,
2593
+ dependencies: await require_v3_engine.resolveViteTailwindV4CssDependencies(sourceCss, sourceBase)
2594
+ })) return;
2595
+ invalidateSourceCandidateScan();
2596
+ debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
2597
+ if (options.refresh === false) return;
2598
+ autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
2599
+ await refreshRuntimeStateForAutoCssSources?.(true);
2600
+ await syncSourceCandidateScan({ force: true });
2601
+ });
2602
+ await autoCssSourcesRefresh;
2603
+ };
2604
+ const discoverAndRegisterAutoCssSources = async () => {
2605
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots || !resolvedConfig?.root) return;
2606
+ const cssEntries = await require_v3_engine.discoverTailwindV4CssEntries(resolvedConfig.root, resolvedConfig.build?.outDir);
2607
+ autoCssSourcesDiscovered = true;
2608
+ let changed = false;
2609
+ for (const cssEntry of cssEntries) {
2610
+ const sourceFile = node_path.default.resolve(cssEntry);
2611
+ const sourceBase = node_path.default.dirname(sourceFile);
2612
+ const sourceCss = require_v3_engine.normalizeTailwindSourceForGenerator(require_v3_engine.normalizeTailwindConfigDirectives(await (0, node_fs_promises.readFile)(sourceFile, "utf8"), sourceBase), { importFallback: true });
2613
+ if (autoCssSourceContent.get(sourceFile) === sourceCss) continue;
2614
+ autoCssSourceContent.set(sourceFile, sourceCss);
2615
+ await syncTailwindCssSourceCandidates(sourceFile, sourceCss);
2616
+ changed = require_tailwindcss.upsertTailwindV4CssSource(opts, {
2617
+ file: sourceFile,
2618
+ base: sourceBase,
2619
+ css: sourceCss,
2620
+ dependencies: (await require_v3_engine.resolveTailwindV4EntriesFromCssCached(sourceCss, sourceBase))?.dependencies ?? []
2621
+ }) || changed;
2622
+ }
2623
+ if (!changed) return;
2624
+ invalidateSourceCandidateScan();
2625
+ await refreshRuntimeStateForAutoCssSources?.(true);
2626
+ };
2627
+ const customAttributesEntities = require_precheck.toCustomAttributesEntities(customAttributes);
2628
+ let resolvedConfig;
2629
+ let recordedGeneratorCandidates;
2630
+ const sourceCandidateExtractor = tailwindcssMajorVersion === 3 ? require_source_candidates.createTailwindV3DefaultExtractor() : void 0;
2631
+ const sourceCandidateCollector = require_source_candidates.createSourceCandidateCollector({
2632
+ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
2633
+ extractor: sourceCandidateExtractor
2634
+ });
2635
+ const sourceCandidateScanCache = /* @__PURE__ */ new Map();
2636
+ let sourceScanEntries;
2637
+ let sourceScanMatcher;
2638
+ let sourceScanDependencies = /* @__PURE__ */ new Set();
2639
+ let sourceScanExplicit = false;
2640
+ let sourceCandidateScanSignature;
2641
+ let sourceCandidateScanInvalidated = true;
2642
+ const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
2643
+ const pendingSourceCandidateSyncByFile = /* @__PURE__ */ new Map();
2644
+ const processedCssAssets = /* @__PURE__ */ new WeakSet();
2645
+ const viteProcessedCssSourceFiles = /* @__PURE__ */ new Set();
2646
+ const viteGeneratedCssByFile = /* @__PURE__ */ new Map();
2647
+ const viteProcessedCssAssetResults = /* @__PURE__ */ new Map();
2648
+ const rememberedCssSources = /* @__PURE__ */ new Map();
2649
+ const rememberedCssSignatureByFile = /* @__PURE__ */ new Map();
2650
+ const tailwindRootCssModuleIds = /* @__PURE__ */ new Set();
2651
+ const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
2652
+ opts,
2653
+ initialTwPatcher,
2654
+ refreshTailwindcssPatcher,
2655
+ uniAppXEnabled,
2656
+ customAttributesEntities,
2657
+ disabledDefaultTemplateHandler,
2658
+ debug
2659
+ });
2660
+ const hmrTimingRecorder = require_incremental_runtime_class_set.createHmrTimingRecorder("vite");
2661
+ refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2662
+ onLoad();
2663
+ const getResolvedConfig = () => resolvedConfig;
2664
+ const markCssAssetProcessed = (asset, _file) => {
2665
+ processedCssAssets.add(asset);
2666
+ };
2667
+ const isCssAssetProcessed = (asset, file) => {
2668
+ if (processedCssAssets.has(asset)) return true;
2669
+ if (!file) return false;
2670
+ const record = viteProcessedCssAssetResults.get(require_bundle_state.normalizeOutputPathKey(file));
2671
+ if (!record) return false;
2672
+ return (typeof asset.source === "string" ? asset.source : asset.source instanceof Uint8Array ? node_buffer.Buffer.from(asset.source).toString() : String(asset.source ?? "")) === record.css;
2673
+ };
2674
+ const recordGeneratorCandidates = (candidates) => {
2675
+ recordedGeneratorCandidates = new Set(candidates);
2676
+ };
2677
+ const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2678
+ const invalidateRecordedGeneratorCandidates = () => {
2679
+ recordedGeneratorCandidates = void 0;
2680
+ };
2681
+ const getSourceCandidates = () => sourceCandidateCollector.values();
2682
+ const getSourceCandidatesForEntries = (entries) => sourceCandidateCollector.valuesForEntries(entries);
2683
+ const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
2684
+ 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
+ const hasSourceCandidateScanState = () => sourceCandidateScanSignature !== void 0;
2686
+ const normalizeSourceScanDependency = (file) => node_path.default.normalize(node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file)));
2687
+ const isSourceScanDependency = (file) => sourceScanDependencies.has(normalizeSourceScanDependency(file));
2688
+ const invalidateSourceCandidateScan = () => {
2689
+ sourceCandidateScanInvalidated = true;
2690
+ };
2691
+ const collectSourceCandidateScanRoots = (root, entries) => {
2692
+ if (entries?.length) return [{
2693
+ entries,
2694
+ explicit: sourceScanExplicit,
2695
+ root
2696
+ }];
2697
+ if (sourceScanExplicit) return [];
2698
+ const roots = [{
2699
+ entries,
2700
+ root
2701
+ }];
2702
+ const normalizedRoot = node_path.default.resolve(root);
2703
+ const seenRoots = new Set([normalizedRoot]);
2704
+ const basedir = opts.tailwindcssBasedir ? node_path.default.resolve(opts.tailwindcssBasedir) : void 0;
2705
+ if (basedir && !seenRoots.has(basedir)) {
2706
+ roots.push({ root: basedir });
2707
+ seenRoots.add(basedir);
2708
+ }
2709
+ for (const cssEntry of opts.tailwindcss?.v4?.cssEntries ?? []) {
2710
+ const cssEntryRoot = node_path.default.dirname(node_path.default.resolve(cssEntry));
2711
+ if (seenRoots.has(cssEntryRoot)) continue;
2712
+ roots.push({ root: cssEntryRoot });
2713
+ seenRoots.add(cssEntryRoot);
2714
+ }
2715
+ return roots;
2716
+ };
2717
+ const scanSourceCandidateRoots = async (roots, outDir) => {
2718
+ await Promise.all(roots.map((root) => sourceCandidateCollector.scanRoot({
2719
+ entries: root.entries,
2720
+ explicit: root.explicit,
2721
+ root: root.root,
2722
+ outDir
2723
+ })));
2724
+ };
2725
+ const cacheCurrentSourceCandidateScan = () => {
2726
+ if (sourceCandidateScanSignature) {
2727
+ sourceCandidateScanCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
2728
+ sourceCandidateScanSnapshotCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
2729
+ }
2730
+ };
2731
+ const shouldDiscoverAutoCssSources = () => {
2732
+ if (!autoCssSourcesDiscovered) return true;
2733
+ if (!isWatchLikeBuild()) return true;
2734
+ return sourceCandidateScanInvalidated;
2735
+ };
2736
+ async function syncSourceCandidateScan(options = {}) {
2737
+ if (!shouldOwnTailwindGeneration) return;
2738
+ if (!options.force && isWatchLikeBuild() && hasSourceCandidateScanState() && !sourceCandidateScanInvalidated) {
2739
+ debug("reuse vite source candidate scan definition for watch rebuild");
2740
+ return;
2741
+ }
2742
+ const root = resolvedConfig?.root ?? node_process.default.cwd();
2743
+ const outDir = resolvedConfig?.build?.outDir;
2744
+ const sourceScan = await require_v3_engine.resolveViteSourceScanEntries(opts, runtimeState.twPatcher, {
2745
+ outDir,
2746
+ root
2747
+ });
2748
+ sourceScanEntries = sourceScan?.entries;
2749
+ sourceScanExplicit = sourceScan?.explicit ?? false;
2750
+ sourceScanMatcher = require_v3_engine.createViteSourceScanMatcher(sourceScanEntries);
2751
+ sourceScanDependencies = new Set((sourceScan?.dependencies ?? []).map(normalizeSourceScanDependency));
2752
+ const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
2753
+ const nextScanSignature = createSourceCandidateScanSignature({
2754
+ inlineCandidates: sourceScan?.inlineCandidates,
2755
+ outDir,
2756
+ roots,
2757
+ scanAllSources: !sourceScanExplicit
2758
+ });
2759
+ if (hasSourceCandidateScanState() && sourceCandidateScanSignature === nextScanSignature) {
2760
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2761
+ sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2762
+ debug("reuse vite source candidate scan for watch rebuild");
2763
+ sourceCandidateScanInvalidated = false;
2764
+ return;
2765
+ }
2766
+ const cachedScan = isWatchLikeBuild() ? sourceCandidateScanCache.get(nextScanSignature) ?? sourceCandidateScanSnapshotCache.get(nextScanSignature) : void 0;
2767
+ if (cachedScan) {
2768
+ sourceCandidateCollector.restore(cachedScan);
2769
+ sourceCandidateScanSignature = nextScanSignature;
2770
+ debug("reuse cached vite source candidate scan for watch rebuild");
2771
+ sourceCandidateScanInvalidated = false;
2772
+ return;
2773
+ }
2774
+ sourceCandidateCollector.clear();
2775
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2776
+ await scanSourceCandidateRoots(roots, outDir);
2777
+ sourceCandidateScanSignature = nextScanSignature;
2778
+ sourceCandidateScanInvalidated = false;
2779
+ if (isWatchLikeBuild()) {
2780
+ sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2781
+ sourceCandidateScanSnapshotCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2782
+ }
2783
+ }
2784
+ const waitForSourceCandidateSyncs = async () => {
2785
+ while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2786
+ };
2787
+ const syncChangedSourceCandidateFile = (id) => {
2788
+ if (!shouldOwnTailwindGeneration || !require_source_candidates.isSourceCandidateRequest(id)) return Promise.resolve();
2789
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2790
+ const refreshRememberedCssSourceTask = refreshRememberedCssSourceByCurrentFile(file);
2791
+ if (isSourceScanDependency(file)) invalidateSourceCandidateScan();
2792
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2793
+ sourceCandidateCollector.remove(file);
2794
+ cacheCurrentSourceCandidateScan();
2795
+ return refreshRememberedCssSourceTask;
2796
+ }
2797
+ if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2798
+ cacheCurrentSourceCandidateScan();
2799
+ return refreshRememberedCssSourceTask;
2800
+ }
2801
+ const existingTask = pendingSourceCandidateSyncByFile.get(file);
2802
+ if (existingTask) return Promise.all([refreshRememberedCssSourceTask, existingTask]).then(() => void 0);
2803
+ const task = sourceCandidateCollector.syncCurrentFile(id).catch((error) => {
2804
+ debug("source candidate watch sync failed: %s %O", id, error);
2805
+ }).then(() => {
2806
+ cacheCurrentSourceCandidateScan();
2807
+ }).finally(() => {
2808
+ pendingSourceCandidateSyncs.delete(task);
2809
+ pendingSourceCandidateSyncByFile.delete(file);
2810
+ });
2811
+ pendingSourceCandidateSyncs.add(task);
2812
+ pendingSourceCandidateSyncByFile.set(file, task);
2813
+ return Promise.all([refreshRememberedCssSourceTask, task]).then(() => void 0);
2814
+ };
2815
+ const shouldCollectTransformedSourceCandidates = (id) => {
2816
+ if (id.search(/[?#]/) < 0) return true;
2817
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2818
+ return !/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file);
2819
+ };
2820
+ const rememberCssSource = (entry, cssRuntimeSignature) => {
2821
+ const key = require_bundle_state.normalizeOutputPathKey(entry.outputFile);
2822
+ const previous = rememberedCssSources.get(key);
2823
+ rememberedCssSources.set(key, entry);
2824
+ const normalizedSourceFile = normalizeCssSourceIdentity(entry.sourceFile);
2825
+ for (const [rememberedKey, remembered] of rememberedCssSources) {
2826
+ if (rememberedKey === key || normalizeCssSourceIdentity(remembered.sourceFile) !== normalizedSourceFile) continue;
2827
+ rememberedCssSources.set(rememberedKey, {
2828
+ ...remembered,
2829
+ rawSource: entry.rawSource,
2830
+ sourceFile: entry.sourceFile
2831
+ });
2832
+ rememberedCssSignatureByFile.delete(rememberedKey);
2833
+ }
2834
+ if (cssRuntimeSignature) rememberedCssSignatureByFile.set(key, cssRuntimeSignature);
2835
+ else if (previous?.rawSource !== entry.rawSource || previous?.sourceFile !== entry.sourceFile) rememberedCssSignatureByFile.delete(key);
2836
+ };
2837
+ const refreshRememberedCssSourceEntry = (rememberedKey, remembered, sourceFile, rawSource) => {
2838
+ if (remembered.rawSource === rawSource && remembered.sourceFile === sourceFile) return remembered;
2839
+ const nextRemembered = {
2840
+ ...remembered,
2841
+ rawSource,
2842
+ sourceFile
2843
+ };
2844
+ rememberedCssSources.set(rememberedKey, nextRemembered);
2845
+ rememberedCssSignatureByFile.delete(rememberedKey);
2846
+ return nextRemembered;
2847
+ };
2848
+ const refreshRememberedCssSourceBySourceFile = (sourceFile, rawSource) => {
2849
+ const normalizedSourceFile = normalizeCssSourceIdentity(sourceFile);
2850
+ for (const [rememberedKey, remembered] of rememberedCssSources) {
2851
+ if (normalizeCssSourceIdentity(remembered.sourceFile) !== normalizedSourceFile) continue;
2852
+ refreshRememberedCssSourceEntry(rememberedKey, remembered, sourceFile, rawSource);
2853
+ }
2854
+ };
2855
+ const extractSfcStyleBlock = (source, index) => {
2856
+ const targetIndex = index ?? 0;
2857
+ SFC_STYLE_BLOCK_RE.lastIndex = 0;
2858
+ let currentIndex = 0;
2859
+ let match = SFC_STYLE_BLOCK_RE.exec(source);
2860
+ while (match !== null) {
2861
+ if (currentIndex === targetIndex) return match[1] ?? "";
2862
+ currentIndex++;
2863
+ match = SFC_STYLE_BLOCK_RE.exec(source);
2864
+ }
2865
+ };
2866
+ const refreshRememberedCssSourceByCurrentFile = async (sourceFile) => {
2867
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(sourceFile);
2868
+ const normalizedSourceFile = require_bundle_state.normalizeOutputPathKey(file);
2869
+ const matchedRememberedSources = [...rememberedCssSources.values()].filter((remembered) => require_bundle_state.normalizeOutputPathKey(require_bundle_state.stripRequestQuery((0, _weapp_tailwindcss_shared.cleanUrl)(remembered.sourceFile))) === normalizedSourceFile);
2870
+ 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;
2880
+ }
2881
+ if (require_bundle_state.isSourceStyleRequest(file)) refreshRememberedCssSourceBySourceFile(file, source);
2882
+ } catch (error) {
2883
+ debug("refresh remembered css source failed: %s %O", file, error);
2884
+ }
2885
+ };
2886
+ const refreshRememberedCssSource = async (remembered) => {
2887
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(require_bundle_state.stripRequestQuery(remembered.sourceFile));
2888
+ const rememberedKey = [...rememberedCssSources.entries()].find(([, entry]) => entry === remembered)?.[0];
2889
+ 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);
2900
+ }
2901
+ };
2902
+ const getRememberedCssSources = () => rememberedCssSources;
2903
+ const getRememberedCssSourceEntry = (file) => rememberedCssSources.get(require_bundle_state.normalizeOutputPathKey(file));
2904
+ const getRememberedCssSignature = (file) => rememberedCssSignatureByFile.get(require_bundle_state.normalizeOutputPathKey(file));
2905
+ const setRememberedCssSignature = (file, cssRuntimeSignature) => {
2906
+ rememberedCssSignatureByFile.set(require_bundle_state.normalizeOutputPathKey(file), cssRuntimeSignature);
2907
+ };
2908
+ const recordCssAssetResult = (file, css) => {
2909
+ viteGeneratedCssByFile.set(file, css);
2910
+ };
2911
+ const recordViteProcessedCssAssetResult = (file, css, options = {}) => {
2912
+ viteProcessedCssAssetResults.set(require_bundle_state.normalizeOutputPathKey(file), {
2913
+ css,
2914
+ injectIntoMain: options.injectIntoMain
2915
+ });
2916
+ };
2917
+ const getViteProcessedCssAssetResults = () => viteProcessedCssAssetResults.entries();
2918
+ const getViteProcessedCssAssetResult = (file) => viteProcessedCssAssetResults.get(require_bundle_state.normalizeOutputPathKey(file));
2919
+ const normalizeViteProcessedCssFile = (file) => node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file));
2920
+ const markViteProcessedCssSource = (file) => {
2921
+ viteProcessedCssSourceFiles.add(normalizeViteProcessedCssFile(file));
2922
+ };
2923
+ const rememberTailwindRootCssModule = (id) => {
2924
+ if (!shouldOwnTailwindGeneration) return;
2925
+ tailwindRootCssModuleIds.add(id);
2926
+ tailwindRootCssModuleIds.add((0, _weapp_tailwindcss_shared.cleanUrl)(id));
2927
+ };
2928
+ const resolveHotTailwindCssModules = (ctx) => {
2929
+ const modules = [];
2930
+ const seenModules = /* @__PURE__ */ new Set();
2931
+ const collectModule = (mod) => {
2932
+ if (mod == null || seenModules.has(mod)) return;
2933
+ if (!require_bundle_state.isSourceStyleRequest(mod.id ?? mod.url)) return;
2934
+ seenModules.add(mod);
2935
+ ctx.server.moduleGraph.invalidateModule(mod);
2936
+ modules.push(mod);
2937
+ };
2938
+ for (const id of tailwindRootCssModuleIds) {
2939
+ const candidates = [
2940
+ ctx.server.moduleGraph.getModuleById(id),
2941
+ ctx.server.moduleGraph.getModuleById((0, _weapp_tailwindcss_shared.cleanUrl)(id)),
2942
+ ...ctx.server.moduleGraph.getModulesByFile(id) ?? [],
2943
+ ...ctx.server.moduleGraph.getModulesByFile((0, _weapp_tailwindcss_shared.cleanUrl)(id)) ?? []
2944
+ ];
2945
+ for (const mod of candidates) collectModule(mod);
2946
+ }
2947
+ return modules;
2948
+ };
2949
+ const resolveModuleHotUrl = (mod) => {
2950
+ if (typeof mod.url === "string" && mod.url.length > 0) return mod.url;
2951
+ if (typeof mod.id === "string" && mod.id.startsWith("/")) return mod.id;
2952
+ };
2953
+ const includesHotModule = (modules, target) => {
2954
+ const targetUrl = resolveModuleHotUrl(target);
2955
+ const targetId = target.id;
2956
+ return modules.some((mod) => {
2957
+ if (mod === target) return true;
2958
+ return targetUrl !== void 0 && resolveModuleHotUrl(mod) === targetUrl || typeof targetId === "string" && targetId.length > 0 && mod.id === targetId;
2959
+ });
2960
+ };
2961
+ const hasSelfAcceptingNonStyleHotModule = (modules) => {
2962
+ return modules.some((mod) => {
2963
+ return !require_bundle_state.isSourceStyleRequest(mod.id ?? mod.url) && mod.isSelfAccepting === true;
2964
+ });
2965
+ };
2966
+ const isUniViteProject = () => {
2967
+ return resolvedConfig?.plugins?.some((plugin) => plugin.name.includes("uni")) ?? false;
2968
+ };
2969
+ const sendSupplementalCssHotUpdates = (ctx, cssModules) => {
2970
+ const updates = cssModules.filter((mod) => !includesHotModule(ctx.modules, mod)).map((mod) => {
2971
+ const hotUrl = resolveModuleHotUrl(mod);
2972
+ if (!hotUrl) return;
2973
+ return {
2974
+ type: "js-update",
2975
+ timestamp: ctx.timestamp,
2976
+ path: hotUrl,
2977
+ acceptedPath: hotUrl,
2978
+ explicitImportRequired: false,
2979
+ isWithinCircularImport: false
2980
+ };
2981
+ }).filter((update) => update !== void 0);
2982
+ if (updates.length === 0) return;
2983
+ queueMicrotask(() => {
2984
+ ctx.server.ws?.send?.({
2985
+ type: "update",
2986
+ updates
2987
+ });
2988
+ });
2989
+ };
2990
+ const sendFullReloadForUnresolvedHotUpdate = (ctx) => {
2991
+ ctx.server.ws?.send?.({
2992
+ type: "full-reload",
2993
+ path: "*",
2994
+ triggeredBy: ctx.file
2995
+ });
2996
+ };
2997
+ const matchesViteProcessedCssSource = (candidate) => {
2998
+ const normalized = normalizeViteProcessedCssFile(candidate);
2999
+ return viteProcessedCssSourceFiles.has(normalized);
3000
+ };
3001
+ const isViteProcessedCssAsset = (asset, file) => {
3002
+ if (require_bundle_state.hasBundlerGeneratedCssMarker(asset.source)) return true;
3003
+ return [
3004
+ file,
3005
+ asset.originalFileName,
3006
+ ...asset.originalFileNames ?? []
3007
+ ].filter((item) => typeof item === "string" && item.length > 0).some((candidate) => matchesViteProcessedCssSource((0, _weapp_tailwindcss_shared.cleanUrl)(candidate)));
3008
+ };
3009
+ const transformCssHandlerOptions = createCssHandlerOptionsCache({
3010
+ getAppType: () => opts.appType,
3011
+ mainCssChunkMatcher,
3012
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
3013
+ getOutputRoot: () => resolvedConfig?.build?.outDir ? node_path.default.resolve(resolvedConfig.root, resolvedConfig.build.outDir) : resolvedConfig?.root,
3014
+ getExtraOptions: () => resolveUniAppXNativeCssHandlerOptions(opts)
3015
+ });
3016
+ const generateTailwindCssForVitePipeline = async (id, code, hookContext) => {
3017
+ if (!shouldOwnTailwindGeneration) return;
3018
+ await runtimeState.readyPromise;
3019
+ await waitForSourceCandidateSyncs();
3020
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3021
+ const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
3022
+ const isNativeAppStyleTarget = require_utils.resolveUniUtsPlatform().isApp;
3023
+ const outputFile = resolveViteCssPipelineOutputFile(file, opts, rootDir, generatorOptions.target === "web", isNativeAppStyleTarget);
3024
+ const runtime = getRecordedGeneratorCandidates() ?? getSourceCandidates() ?? await ensureRuntimeClassSet();
3025
+ const cssHandlerOptions = transformCssHandlerOptions.getCssHandlerOptions(outputFile);
3026
+ const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
3027
+ opts,
3028
+ runtimeState,
3029
+ runtime,
3030
+ rawSource: code,
3031
+ file,
3032
+ cssHandlerOptions,
3033
+ cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(outputFile),
3034
+ getSourceCandidatesForEntries,
3035
+ styleHandler,
3036
+ debug,
3037
+ previousCss: viteGeneratedCssByFile.get(file),
3038
+ deferEmptyScopedCssSource: true
3039
+ });
3040
+ if (!generated) return;
3041
+ 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 });
3044
+ if (isNativeAppStyleTarget && outputFile.endsWith(".css")) hookContext?.emitFile?.({
3045
+ type: "asset",
3046
+ fileName: outputFile,
3047
+ source: generated.css
3048
+ });
3049
+ markViteProcessedCssSource(file);
3050
+ rememberTailwindRootCssModule(id);
3051
+ recordGeneratorCandidates(runtime);
3052
+ rememberCssSource({
3053
+ outputFile,
3054
+ rawSource: code,
3055
+ sourceFile: id
3056
+ });
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}`;
3059
+ };
3060
+ const rewritePlugins = createRewriteCssImportsPlugins({
3061
+ getAppType: () => opts.appType,
3062
+ generateTailwindCss: generateTailwindCssForVitePipeline,
3063
+ rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
3064
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
3065
+ onCssSourceTransform: (id, code) => refreshRememberedCssSourceBySourceFile(id, code),
3066
+ shouldGenerateCss: (_id, code) => hasVitePipelineTailwindGenerationDirective(code),
3067
+ shouldOwnTailwindGeneration,
3068
+ shouldRewrite: shouldRewriteCssImports,
3069
+ weappTailwindcssDirPosix
3070
+ });
3071
+ if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
3072
+ const generateBundleHook = createGenerateBundleHook({
3073
+ opts,
3074
+ runtimeState,
3075
+ ensureRuntimeClassSet,
3076
+ ensureBundleRuntimeClassSet,
3077
+ debug,
3078
+ getResolvedConfig,
3079
+ markCssAssetProcessed,
3080
+ isCssAssetProcessed,
3081
+ isViteProcessedCssAsset,
3082
+ recordCssAssetResult,
3083
+ recordViteProcessedCssAssetResult,
3084
+ getViteProcessedCssAssetResults,
3085
+ getViteProcessedCssAssetResult,
3086
+ getSourceCandidates,
3087
+ getSourceCandidatesForEntries,
3088
+ waitForSourceCandidateSyncs,
3089
+ rememberCssSource,
3090
+ refreshRememberedCssSource,
3091
+ getRememberedCssSources,
3092
+ getRememberedCssSignature,
3093
+ setRememberedCssSignature,
3094
+ recordGeneratorCandidates,
3095
+ hmrTimingRecorder
3096
+ });
3097
+ const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
3098
+ opts,
3099
+ runtimeState,
3100
+ ensureRuntimeClassSet,
3101
+ debug,
3102
+ getResolvedConfig,
3103
+ markCssAssetProcessed,
3104
+ isCssAssetProcessed,
3105
+ isViteProcessedCssAsset,
3106
+ recordCssAssetResult,
3107
+ recordViteProcessedCssAssetResult,
3108
+ getViteProcessedCssAssetResults,
3109
+ getRecordedGeneratorCandidates,
3110
+ getSourceCandidates,
3111
+ getSourceCandidatesForEntries,
3112
+ waitForSourceCandidateSyncs,
3113
+ rememberMainCssSource: (file, rawSource) => rememberCssSource({
3114
+ outputFile: file,
3115
+ rawSource,
3116
+ sourceFile: file
3117
+ }),
3118
+ getRememberedMainCssSource: getRememberedCssSourceEntry
3119
+ });
3120
+ const isIosPlatform = require_utils.resolveUniUtsPlatform().isAppIos;
3121
+ const prepareTailwindGeneration = async () => {
3122
+ if (shouldDiscoverAutoCssSources()) await discoverAndRegisterAutoCssSources();
3123
+ await syncSourceCandidateScan();
3124
+ };
3125
+ const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
3126
+ appType: opts.appType ?? "uni-app-x",
3127
+ customAttributesEntities,
3128
+ disabledDefaultTemplateHandler,
3129
+ isIosPlatform,
3130
+ mainCssChunkMatcher,
3131
+ runtimeState,
3132
+ styleHandler,
3133
+ generateCss: generateTailwindCssForVitePipeline,
3134
+ jsHandler,
3135
+ ensureRuntimeClassSet,
3136
+ getResolvedConfig,
3137
+ uniAppX
3138
+ }) : void 0;
3139
+ const plugins = [
3140
+ ...rewritePlugins,
3141
+ {
3142
+ name: `${require_precheck.vitePluginName}:source-candidates`,
3143
+ enforce: "pre",
3144
+ async transform(code, id) {
3145
+ if (!shouldOwnTailwindGeneration || !require_source_candidates.isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
3146
+ return hmrTimingRecorder.measure("sourceCandidates.transform", async () => {
3147
+ invalidateRecordedGeneratorCandidates();
3148
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
3149
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
3150
+ sourceCandidateCollector.remove(file);
3151
+ cacheCurrentSourceCandidateScan();
3152
+ return;
3153
+ }
3154
+ if (sourceScanExplicit && sourceScanEntries?.length === 0) {
3155
+ cacheCurrentSourceCandidateScan();
3156
+ return;
3157
+ }
3158
+ await sourceCandidateCollector.merge(id, code);
3159
+ cacheCurrentSourceCandidateScan();
3160
+ }, { emit: false });
3161
+ },
3162
+ async watchChange(id, change) {
3163
+ await hmrTimingRecorder.measure("sourceCandidates.watchChange", async () => {
3164
+ if (shouldOwnTailwindGeneration && require_source_candidates.isSourceCandidateRequest(id)) invalidateRecordedGeneratorCandidates();
3165
+ if (isSourceScanDependency(id)) invalidateSourceCandidateScan();
3166
+ if (change.event === "delete") {
3167
+ sourceCandidateCollector.remove(id);
3168
+ cacheCurrentSourceCandidateScan();
3169
+ return;
3170
+ }
3171
+ await syncChangedSourceCandidateFile(id);
3172
+ }, { emit: false });
3173
+ },
3174
+ async handleHotUpdate(ctx) {
3175
+ return hmrTimingRecorder.measure("sourceCandidates.handleHotUpdate", async () => {
3176
+ const isSourceCandidateHotUpdate = shouldOwnTailwindGeneration && require_source_candidates.isSourceCandidateRequest(ctx.file);
3177
+ await syncChangedSourceCandidateFile(ctx.file);
3178
+ if (isSourceCandidateHotUpdate) invalidateRecordedGeneratorCandidates();
3179
+ const cssModules = resolveHotTailwindCssModules(ctx);
3180
+ if (isSourceCandidateHotUpdate && !require_bundle_state.isSourceStyleRequest(ctx.file) && (!hasSelfAcceptingNonStyleHotModule(ctx.modules) && cssModules.length === 0 || cssModules.length > 0 && isUniViteProject())) {
3181
+ sendFullReloadForUnresolvedHotUpdate(ctx);
3182
+ return [];
3183
+ }
3184
+ sendSupplementalCssHotUpdates(ctx, cssModules);
3185
+ return cssModules.length > 0 ? [...ctx.modules, ...cssModules] : void 0;
3186
+ }, { emit: false });
3187
+ },
3188
+ async buildStart() {
3189
+ await hmrTimingRecorder.measure("sourceCandidates.buildStart", async () => {
3190
+ await prepareTailwindGeneration();
3191
+ }, { emit: false });
3192
+ }
3193
+ },
3194
+ ...createViteServeCssGenerationPlugins({
3195
+ generateCss: generateTailwindCssForVitePipeline,
3196
+ getCommand: () => resolvedConfig?.command,
3197
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
3198
+ shouldGenerate: () => shouldOwnTailwindGeneration
3199
+ }),
3200
+ {
3201
+ name: `${require_precheck.vitePluginName}:post`,
3202
+ enforce: "post",
3203
+ config(config) {
3204
+ if (!shouldOwnTailwindGeneration) return;
3205
+ if (Array.isArray(config.plugins)) {
3206
+ const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
3207
+ if (removed > 0) debug("disable official tailwind vite plugins in generator mode: %d", removed);
3208
+ }
3209
+ const root = config.root ? node_path.default.resolve(config.root) : node_process.default.cwd();
3210
+ const baseConfig = { resolve: { alias: [{
3211
+ find: /^tailwindcss$/,
3212
+ replacement: node_path.default.join(weappTailwindcssPackageDir, "generator-placeholder.css")
3213
+ }] } };
3214
+ if (config.css?.postcss !== void 0) return baseConfig;
3215
+ return resolveFilteredPostcssConfig(root).then((postcssConfig) => {
3216
+ if (!postcssConfig) return baseConfig;
3217
+ debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", postcssConfig.removed);
3218
+ return {
3219
+ ...baseConfig,
3220
+ css: { postcss: {
3221
+ ...postcssConfig.options,
3222
+ plugins: postcssConfig.plugins
3223
+ } }
3224
+ };
3225
+ });
3226
+ },
3227
+ async configResolved(config) {
3228
+ await hmrTimingRecorder.measure("configResolved", async () => {
3229
+ resolvedConfig = config;
3230
+ if (shouldOwnTailwindGeneration) {
3231
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
3232
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
3233
+ }
3234
+ const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
3235
+ let shouldRefreshRuntime = false;
3236
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
3237
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
3238
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
3239
+ const previousBasedir = opts.tailwindcssBasedir;
3240
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
3241
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
3242
+ shouldRefreshRuntime = true;
3243
+ }
3244
+ }
3245
+ if (shouldInferAppType && resolvedRoot) {
3246
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
3247
+ if (nextAppType && opts.appType !== nextAppType) {
3248
+ const previousAppType = opts.appType;
3249
+ opts.appType = nextAppType;
3250
+ _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
3251
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
3252
+ shouldRefreshRuntime = true;
3253
+ }
3254
+ }
3255
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
3256
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
3257
+ const postcssPlugins = config.css.postcss.plugins;
3258
+ if (shouldOwnTailwindGeneration) {
3259
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
3260
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
3261
+ }
3262
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
3263
+ if (idx > -1) {
3264
+ postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
3265
+ debug("remove postcss-html-transform plugin from vite config");
3266
+ }
3267
+ }
3268
+ }, { emit: false });
3269
+ },
3270
+ generateBundle: generateBundleHook
3271
+ },
3272
+ cssFinalizerOutputPlugin
3273
+ ];
3274
+ if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
3275
+ return plugins;
3276
+ }
3277
+ //#endregion
3278
+ Object.defineProperty(exports, "WeappTailwindcss", {
3279
+ enumerable: true,
3280
+ get: function() {
3281
+ return WeappTailwindcss;
3282
+ }
3283
+ });