weapp-tailwindcss 5.0.3 → 5.0.4

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