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