weapp-tailwindcss 5.0.0-next.2 → 5.0.0-next.20

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 (220) hide show
  1. package/README.md +6 -7
  2. package/bin/weapp-tailwindcss.js +1 -21
  3. package/dist/bundle-state-BlXvU4jl.js +530 -0
  4. package/dist/bundle-state-PO6MysTJ.mjs +414 -0
  5. package/dist/bundlers/shared/cache.d.ts +6 -6
  6. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +2 -0
  7. package/dist/bundlers/shared/css-cleanup/color-gamut.d.ts +3 -0
  8. package/dist/bundlers/shared/css-cleanup/root-cleanups.d.ts +5 -0
  9. package/dist/bundlers/shared/css-cleanup/selectors.d.ts +8 -0
  10. package/dist/bundlers/shared/css-cleanup.d.ts +7 -3
  11. package/dist/bundlers/shared/css-imports.d.ts +3 -3
  12. package/dist/bundlers/shared/generated-css-marker.d.ts +3 -0
  13. package/dist/bundlers/shared/generator-css/config-directive.d.ts +2 -0
  14. package/dist/bundlers/shared/generator-css/directives.d.ts +20 -0
  15. package/dist/bundlers/shared/generator-css/legacy-compat.d.ts +7 -0
  16. package/dist/bundlers/shared/generator-css/legacy-selectors.d.ts +5 -0
  17. package/dist/bundlers/shared/generator-css/legacy-units.d.ts +1 -0
  18. package/dist/bundlers/shared/generator-css/markers.d.ts +28 -0
  19. package/dist/bundlers/shared/generator-css/source-files.d.ts +14 -0
  20. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +24 -0
  21. package/dist/bundlers/shared/generator-css.d.ts +16 -22
  22. package/dist/bundlers/shared/hmr-timing.d.ts +22 -0
  23. package/dist/bundlers/shared/style-requests.d.ts +2 -0
  24. package/dist/bundlers/vite/bundle-state.d.ts +1 -0
  25. package/dist/bundlers/vite/css-finalizer.d.ts +7 -1
  26. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +2 -0
  27. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +24 -0
  28. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +4 -0
  29. package/dist/bundlers/vite/generate-bundle/dirty-state.d.ts +1 -0
  30. package/dist/bundlers/vite/generate-bundle/js-entries.d.ts +2 -0
  31. package/dist/bundlers/vite/generate-bundle/js-handler-options.d.ts +8 -0
  32. package/dist/bundlers/vite/generate-bundle/js-linking.d.ts +13 -0
  33. package/dist/bundlers/vite/generate-bundle/metrics.d.ts +17 -0
  34. package/dist/bundlers/vite/generate-bundle/process-plan.d.ts +9 -0
  35. package/dist/bundlers/vite/generate-bundle/rollup-assets.d.ts +7 -0
  36. package/dist/bundlers/vite/generate-bundle/signatures.d.ts +8 -0
  37. package/dist/bundlers/vite/generate-bundle.d.ts +14 -2
  38. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +5 -1
  39. package/dist/bundlers/vite/index.d.ts +1 -1
  40. package/dist/bundlers/vite/official-tailwind-plugins.d.ts +5 -0
  41. package/dist/bundlers/vite/postcss-config.d.ts +6 -0
  42. package/dist/bundlers/vite/processed-css-assets.d.ts +32 -0
  43. package/dist/bundlers/vite/rewrite-css-imports.d.ts +8 -3
  44. package/dist/bundlers/vite/runtime-class-set.d.ts +25 -0
  45. package/dist/bundlers/vite/source-candidates.d.ts +16 -1
  46. package/dist/bundlers/vite/source-scan.d.ts +26 -0
  47. package/dist/bundlers/vite/static-config-content.d.ts +5 -0
  48. package/dist/bundlers/vite/tailwind-basedir.d.ts +1 -0
  49. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +6 -0
  50. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +6 -2
  51. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +9 -3
  52. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +1 -0
  53. package/dist/bundlers/webpack/loaders/runtime-registry.d.ts +31 -0
  54. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +2 -6
  55. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +3 -7
  56. package/dist/cache/index.d.ts +6 -6
  57. package/dist/cli/context.d.ts +1 -14
  58. package/dist/cli/doctor/types.d.ts +11 -11
  59. package/dist/cli/helpers.d.ts +1 -2
  60. package/dist/cli/mount-options.d.ts +2 -0
  61. package/dist/cli/types.d.ts +0 -2
  62. package/dist/cli/vscode-entry.d.ts +3 -3
  63. package/dist/cli.js +605 -611
  64. package/dist/cli.mjs +614 -620
  65. package/dist/constants.d.ts +1 -2
  66. package/dist/core.js +13 -20
  67. package/dist/core.mjs +8 -14
  68. package/dist/css-macro/postcss.js +3 -2
  69. package/dist/css-macro/postcss.mjs +3 -2
  70. package/dist/css-macro.d.ts +1 -0
  71. package/dist/css-macro.js +2 -2
  72. package/dist/css-macro.mjs +2 -2
  73. package/dist/defaults-B1igPF_e.mjs +150 -0
  74. package/dist/defaults-IHhYxNeU.js +193 -0
  75. package/dist/defaults.d.ts +15 -1
  76. package/dist/defaults.js +6 -131
  77. package/dist/defaults.mjs +2 -129
  78. package/dist/escape.js +10 -2
  79. package/dist/escape.mjs +10 -2
  80. package/dist/generator/index.d.ts +1 -1
  81. package/dist/generator/options.d.ts +9 -8
  82. package/dist/generator/types.d.ts +3 -3
  83. package/dist/generator-DIuglJub.mjs +32 -0
  84. package/dist/generator-N4jy1HCk.js +55 -0
  85. package/dist/generator.js +12 -11
  86. package/dist/generator.mjs +2 -1
  87. package/dist/gulp.js +185 -47
  88. package/dist/gulp.mjs +179 -41
  89. package/dist/incremental-runtime-class-set-CJ0Pnsw2.js +2348 -0
  90. package/dist/incremental-runtime-class-set-hF-uiw6W.mjs +2285 -0
  91. package/dist/index.d.ts +1 -1
  92. package/dist/index.js +6 -6
  93. package/dist/index.mjs +5 -5
  94. package/dist/js/babel/cache-options.d.ts +3 -0
  95. package/dist/js/babel/parse.d.ts +7 -4
  96. package/dist/js/index.d.ts +1 -0
  97. package/dist/js/literal-transform.d.ts +2 -0
  98. package/dist/js/precheck.d.ts +2 -2
  99. package/dist/lightningcss/style-handler/selector-transform.d.ts +1 -1
  100. package/dist/lightningcss/style-handler.d.ts +3 -3
  101. package/dist/logger-CZUxvJJD.mjs +2 -0
  102. package/dist/logger-EVNB9z7i.js +1 -0
  103. package/dist/postcss/config-directive.d.ts +1 -0
  104. package/dist/postcss/context.d.ts +9 -0
  105. package/dist/postcss/source-files.d.ts +8 -0
  106. package/dist/postcss/tailwind-version.d.ts +3 -0
  107. package/dist/postcss-D4UdbBQ6.mjs +228 -0
  108. package/dist/postcss-DlY-YRvA.js +237 -0
  109. package/dist/postcss.d.ts +2 -2
  110. package/dist/postcss.js +3 -276
  111. package/dist/postcss.mjs +1 -269
  112. package/dist/{recorder-gYSNLfOP.js → precheck-BjEbVEpX.js} +218 -314
  113. package/dist/{recorder-zsgatmkB.mjs → precheck-tbk626YL.mjs} +186 -281
  114. package/dist/presets.js +13 -11
  115. package/dist/presets.mjs +11 -9
  116. package/dist/reset.d.ts +1 -0
  117. package/dist/runtime-registry-D5qnaSpo.js +5516 -0
  118. package/dist/shared/mpx.d.ts +1 -0
  119. package/dist/source-candidates-BrvneDDd.mjs +209 -0
  120. package/dist/source-candidates-gxijpPI3.js +222 -0
  121. package/dist/tailwindcss/miniprogram.d.ts +5 -1
  122. package/dist/tailwindcss/patcher-options.d.ts +3 -51
  123. package/dist/tailwindcss/patcher.d.ts +1 -2
  124. package/dist/tailwindcss/runtime/cache.d.ts +4 -3
  125. package/dist/tailwindcss/runtime-patch.d.ts +5 -0
  126. package/dist/tailwindcss/runtime.d.ts +11 -12
  127. package/dist/tailwindcss/source-scan.d.ts +35 -0
  128. package/dist/tailwindcss/targets.d.ts +1 -5
  129. package/dist/tailwindcss/v3-engine/types.d.ts +17 -14
  130. package/dist/tailwindcss/v4/css-entries.d.ts +2 -2
  131. package/dist/tailwindcss/v4/css-sources.d.ts +5 -0
  132. package/dist/tailwindcss/v4/patcher-options.d.ts +1 -23
  133. package/dist/tailwindcss/v4/patcher.d.ts +1 -0
  134. package/dist/tailwindcss/v4-engine/source.d.ts +2 -2
  135. package/dist/tailwindcss/v4-engine/types.d.ts +17 -5
  136. package/dist/tailwindcss/version.d.ts +4 -0
  137. package/dist/tailwindcss-BhG7BtB-.js +651 -0
  138. package/dist/tailwindcss-c6ROlNNW.mjs +600 -0
  139. package/dist/typedoc.export.d.ts +0 -2
  140. package/dist/types/index.d.ts +51 -48
  141. package/dist/types/shared.d.ts +3 -0
  142. package/dist/types/user-defined-options/general.d.ts +23 -23
  143. package/dist/types/user-defined-options/important.d.ts +31 -28
  144. package/dist/types/user-defined-options/lifecycle.d.ts +4 -4
  145. package/dist/types/user-defined-options/matcher.d.ts +6 -6
  146. package/dist/uni-app-x/vite.d.ts +1 -1
  147. package/dist/utils/disabled.d.ts +2 -3
  148. package/dist/utils/object.d.ts +9 -0
  149. package/dist/{utils-DmC9_In3.js → utils-4ODFyoqD.js} +1 -1
  150. package/dist/{utils-7DUGTFED.mjs → utils-CGBVVNm6.mjs} +1 -1
  151. package/dist/v3-engine-5LoZUH-4.js +3695 -0
  152. package/dist/v3-engine-DIXDEDmL.mjs +3406 -0
  153. package/dist/{vite-CrlzCNqz.mjs → vite-B5faZcbE.mjs} +1256 -1088
  154. package/dist/vite-MyXBNux0.js +2368 -0
  155. package/dist/vite.d.ts +1 -2
  156. package/dist/vite.js +3 -4
  157. package/dist/vite.mjs +2 -2
  158. package/dist/weapp-tw-css-import-rewrite-loader.js +5157 -16
  159. package/dist/weapp-tw-runtime-classset-loader.js +32 -7
  160. package/dist/webpack-BnVyDmsD.mjs +836 -0
  161. package/dist/webpack-Mz1V0A9p.js +846 -0
  162. package/dist/webpack.js +1 -1
  163. package/dist/webpack.mjs +1 -1
  164. package/package.json +27 -37
  165. package/dist/bundlers/shared/generator-candidates.d.ts +0 -5
  166. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-assets.d.ts +0 -14
  167. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4-loaders.d.ts +0 -15
  168. package/dist/bundlers/webpack/BaseUnifiedPlugin/v4.d.ts +0 -9
  169. package/dist/bundlers/webpack/shared/css-imports.d.ts +0 -6
  170. package/dist/cli/config.d.ts +0 -5
  171. package/dist/cli/helpers/patch-cwd.d.ts +0 -1
  172. package/dist/cli/mount-options/patch-status.d.ts +0 -2
  173. package/dist/cli/patch-options.d.ts +0 -6
  174. package/dist/cli/tokens.d.ts +0 -4
  175. package/dist/cli/workspace/package-dirs.d.ts +0 -3
  176. package/dist/cli/workspace/patch-package.d.ts +0 -3
  177. package/dist/cli/workspace/patch-utils.d.ts +0 -3
  178. package/dist/cli/workspace/types.d.ts +0 -11
  179. package/dist/cli/workspace/workspace-globs.d.ts +0 -2
  180. package/dist/cli/workspace/workspace-io.d.ts +0 -1
  181. package/dist/cli/workspace/workspace-lock.d.ts +0 -1
  182. package/dist/cli/workspace.d.ts +0 -2
  183. package/dist/css-imports-BbrbluP9.js +0 -177
  184. package/dist/css-imports-CSdPq_Sc.mjs +0 -128
  185. package/dist/experimental/index.d.ts +0 -2
  186. package/dist/experimental/oxc/ast-utils.d.ts +0 -30
  187. package/dist/experimental/oxc/index.d.ts +0 -2
  188. package/dist/experimental/oxc/module-specifiers.d.ts +0 -2
  189. package/dist/experimental/shared/cache.d.ts +0 -3
  190. package/dist/experimental/shared/transform.d.ts +0 -3
  191. package/dist/experimental/shared.d.ts +0 -8
  192. package/dist/experimental/swc/ast-utils.d.ts +0 -30
  193. package/dist/experimental/swc/index.d.ts +0 -2
  194. package/dist/experimental/swc/module-specifiers.d.ts +0 -2
  195. package/dist/generator-Y-Ikv4Fu.mjs +0 -1177
  196. package/dist/generator-css-B5ejWUMv.mjs +0 -1098
  197. package/dist/generator-css-D3OdPRiS.js +0 -1125
  198. package/dist/generator-mmhXzZnv.js +0 -1276
  199. package/dist/js/syntax.d.ts +0 -10
  200. package/dist/loader-anchors-CNkWT8hx.js +0 -273
  201. package/dist/loader-anchors-TrU7EUr7.mjs +0 -205
  202. package/dist/logger-BZ45DZJT.js +0 -1003
  203. package/dist/logger-BoVx1Dbt.mjs +0 -935
  204. package/dist/patcher-options-6gJN2EXy.js +0 -115
  205. package/dist/patcher-options-DQfR5xxT.mjs +0 -92
  206. package/dist/tailwindcss/recorder.d.ts +0 -13
  207. package/dist/tailwindcss/targets/paths.d.ts +0 -13
  208. package/dist/tailwindcss/targets/record-io.d.ts +0 -5
  209. package/dist/tailwindcss/targets/recorder.d.ts +0 -3
  210. package/dist/tailwindcss/targets/types.d.ts +0 -35
  211. package/dist/types/disabled-options.d.ts +0 -4
  212. package/dist/vite-BC9U7ahn.js +0 -2199
  213. package/dist/webpack-Bu6M-Hbw.mjs +0 -441
  214. package/dist/webpack-DD7A6V0u.js +0 -456
  215. package/dist/webpack4.d.ts +0 -4
  216. package/dist/webpack4.js +0 -387
  217. package/dist/webpack4.mjs +0 -379
  218. package/scripts/postinstall.mjs +0 -59
  219. /package/dist/{constants-B-_T5UnW.mjs → constants-BG12WAKw.mjs} +0 -0
  220. /package/dist/{constants-p1dyh1x1.js → constants-BeeyfJ9k.js} +0 -0
@@ -1,27 +1,25 @@
1
- import { d as filterUnsupportedMiniProgramTailwindV4Candidates, f as loadTailwindV4DesignSystem, i as normalizeWeappTailwindcssGeneratorOptions, s as resolveTailwindV4SourceFromPatcher } from "./generator-Y-Ikv4Fu.mjs";
2
- import { r as resolveTailwindcssOptions } from "./patcher-options-DQfR5xxT.mjs";
3
- import { _ as refreshTailwindRuntimeState, a as createAttributeMatcher, c as isClassContextLiteralPath, d as traverse$1, f as toCustomAttributesEntities, h as collectRuntimeClassSet, i as generateCode, l as replaceWxml, m as vitePluginName, n as shouldSkipJsTransform, o as analyzeSource, r as getCompilerContext, s as JsTokenUpdater, t as setupPatchRecorder, u as babelParse, v as createDebug } from "./recorder-zsgatmkB.mjs";
4
- import { o as resolveUniUtsPlatform } from "./utils-7DUGTFED.mjs";
5
- import { a as resolveUniAppXOptions, d as getRuntimeClassSetSignature, i as isUniAppXEnabled, l as findNearestPackageRoot, o as findTailwindConfig, t as logger$1 } from "./logger-BoVx1Dbt.mjs";
6
- import { i as processCachedTask, n as hasTailwindGeneratedCssMarkers, r as hasTailwindSourceDirectives, t as generateCssByGenerator } from "./generator-css-B5ejWUMv.mjs";
7
- import { a as resolveDisabledOptions, c as toAbsoluteOutputPath, i as resolvePackageDir, n as rewriteTailwindcssImportsInCode, o as normalizeOutputPathKey, r as pushConcurrentTaskFactories, s as resolveOutputSpecifier, t as resolveTailwindcssImport } from "./css-imports-CSdPq_Sc.mjs";
1
+ import { D as filterUnsupportedMiniProgramTailwindV4Candidates, G as resolveTailwindcssOptions, K as omitUndefined, V as createDebug, W as findTailwindConfig, _ as resolveViteSourceScanEntries, g as resolveTailwindV4EntriesFromCssCached, l as getRuntimeClassSetSignature, m as discoverTailwindV4CssEntries, p as createViteSourceScanMatcher, q as findNearestPackageRoot, v as resolveViteTailwindV4CssDependencies } from "./v3-engine-DIXDEDmL.mjs";
2
+ import { i as normalizeWeappTailwindcssGeneratorOptions } from "./generator-DIuglJub.mjs";
3
+ import { a as validateCandidatesByGenerator, c as hasTailwindSourceDirectives, i as generateCssByGenerator, l as normalizeTailwindSourceForGenerator, n as createHmrTimingRecorder, o as processCachedTask, s as hasTailwindRootDirectives, t as createBundleRuntimeClassSetManager, u as hasTailwindGeneratedCssMarkers } from "./incremental-runtime-class-set-hF-uiw6W.mjs";
4
+ import { a as analyzeSource, c as isClassContextLiteralPath, g as createTailwindRuntimeReadyPromise, h as collectRuntimeClassSet, i as createAttributeMatcher, l as replaceWxml, m as toCustomAttributesEntities, n as getCompilerContext, o as JsTokenUpdater, p as vitePluginName, r as generateCode, s as _defineProperty, t as shouldSkipJsTransform, u as babelParse, v as refreshTailwindRuntimeState } from "./precheck-tbk626YL.mjs";
5
+ import { o as resolveUniUtsPlatform } from "./utils-CGBVVNm6.mjs";
6
+ import { c as upsertTailwindV4CssSource, i as resolveUniAppXOptions, r as isUniAppXEnabled, s as hasConfiguredTailwindV4CssRoots } from "./tailwindcss-c6ROlNNW.mjs";
7
+ import { n as isSourceCandidateRequest, t as createSourceCandidateCollector } from "./source-candidates-BrvneDDd.mjs";
8
+ import { a as createBundleModuleGraphOptions, b as toAbsoluteOutputPath, c as hasBundlerGeneratedCssMarker, d as resolvePluginDisabledState, f as cleanUrl, g as isSourceStyleRequest, h as slash, i as applyLinkedResults, l as stripBundlerGeneratedCssMarkers, m as isCSSRequest, n as createBundleBuildState, o as pushConcurrentTaskFactories, p as formatPostcssSourceMap, r as updateBundleBuildState, s as createBundlerGeneratedCssMarker, t as buildBundleSnapshot, u as resolvePackageDir, v as normalizeOutputPathKey } from "./bundle-state-PO6MysTJ.mjs";
9
+ import { t as logger$1 } from "./logger-CZUxvJJD.mjs";
10
+ import fs, { existsSync, readFileSync } from "node:fs";
11
+ import postcss from "postcss";
8
12
  import path from "node:path";
9
13
  import process from "node:process";
10
- import { extractRawCandidatesWithPositions, extractValidCandidates } from "tailwindcss-patch";
11
- import { Buffer } from "node:buffer";
12
- import fs, { existsSync, readFileSync } from "node:fs";
13
- import { readFile } from "node:fs/promises";
14
14
  import { logger } from "@weapp-tailwindcss/logger";
15
- import { cleanUrl as cleanUrl$1, ensurePosix } from "@weapp-tailwindcss/shared";
15
+ import { readFile } from "node:fs/promises";
16
16
  import MagicString from "magic-string";
17
17
  import { splitCode } from "@weapp-tailwindcss/shared/extractors";
18
- import { Parser } from "htmlparser2";
19
- import fg from "fast-glob";
20
18
  import postcssHtmlTransform from "@weapp-tailwindcss/postcss/html-transform";
21
- import postcssrc from "postcss-load-config";
22
19
  import { NodeTypes } from "@vue/compiler-dom";
23
20
  import { parse } from "@vue/compiler-sfc";
24
21
  import { parse as parse$1 } from "comment-json";
22
+ import postcssrc from "postcss-load-config";
25
23
  //#region src/uni-app-x/component-local-style.ts
26
24
  const EXPRESSION_WRAPPER_PREFIX = "(\n";
27
25
  const EXPRESSION_WRAPPER_SUFFIX = "\n)";
@@ -61,8 +59,8 @@ var UniAppXComponentLocalStyleCollector = class {
61
59
  constructor(fileId, runtimeSet) {
62
60
  this.fileId = fileId;
63
61
  this.runtimeSet = runtimeSet;
64
- this.aliasByUtility = /* @__PURE__ */ new Map();
65
- this.aliasByLookup = /* @__PURE__ */ new Map();
62
+ _defineProperty(this, "aliasByUtility", /* @__PURE__ */ new Map());
63
+ _defineProperty(this, "aliasByLookup", /* @__PURE__ */ new Map());
66
64
  }
67
65
  ensureAlias(utility) {
68
66
  const cached = this.aliasByUtility.get(utility);
@@ -276,7 +274,7 @@ function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
276
274
  //#endregion
277
275
  //#region src/bundlers/vite/query.ts
278
276
  function parseVueRequest(id) {
279
- const [filename, rawQuery] = id.split(`?`, 2);
277
+ const [filename = id, rawQuery] = id.split(`?`, 2);
280
278
  const searchParams = new URLSearchParams(rawQuery);
281
279
  const query = Object.fromEntries(searchParams);
282
280
  if (query.vue != null) query.vue = true;
@@ -293,35 +291,6 @@ function parseVueRequest(id) {
293
291
  };
294
292
  }
295
293
  //#endregion
296
- //#region src/bundlers/vite/utils.ts
297
- function slash(p) {
298
- return ensurePosix(p);
299
- }
300
- const isWindows = process.platform === "win32";
301
- const cssLangRE = new RegExp(`\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`);
302
- function isCSSRequest(request) {
303
- return cssLangRE.test(request);
304
- }
305
- function normalizePath(id) {
306
- return path.posix.normalize(isWindows ? ensurePosix(id) : id);
307
- }
308
- async function formatPostcssSourceMap(rawMap, file) {
309
- const inputFileDir = path.dirname(file);
310
- const sources = rawMap.sources.map((source) => {
311
- const cleanSource = cleanUrl$1(decodeURIComponent(source));
312
- if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
313
- return normalizePath(path.resolve(inputFileDir, cleanSource));
314
- });
315
- return {
316
- file,
317
- mappings: rawMap.mappings,
318
- names: rawMap.names,
319
- sources,
320
- sourcesContent: rawMap.sourcesContent,
321
- version: rawMap.version
322
- };
323
- }
324
- //#endregion
325
294
  //#region src/uni-app-x/style-isolation.ts
326
295
  const manifestCache = /* @__PURE__ */ new Map();
327
296
  function resolveUniAppXStyleIsolationEnabled(root) {
@@ -355,12 +324,12 @@ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
355
324
  function isPreprocessorRequest(id, lang) {
356
325
  const normalizedLang = lang?.toLowerCase();
357
326
  if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
358
- const inlineLangMatch = id.match(INLINE_LANG_RE);
359
- if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) return true;
327
+ const inlineLang = id.match(INLINE_LANG_RE)?.[1];
328
+ if (inlineLang && preprocessorLangs.has(inlineLang.toLowerCase())) return true;
360
329
  return PREPROCESSOR_EXT_RE.test(id);
361
330
  }
362
331
  function resolveUniAppXCssTarget(id) {
363
- return UVUE_NVUE_RE.test(cleanUrl$1(id)) ? "uvue" : void 0;
332
+ return UVUE_NVUE_RE.test(cleanUrl(id)) ? "uvue" : void 0;
364
333
  }
365
334
  function resolveUniAppXJsTransformEnabled$1(uniAppX) {
366
335
  return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
@@ -391,7 +360,7 @@ function createUniAppXPlugins(options) {
391
360
  const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
392
361
  let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
393
362
  if (!styleHandlerOptions) {
394
- styleHandlerOptions = {
363
+ styleHandlerOptions = omitUndefined({
395
364
  isMainChunk: mainCssChunkMatcher(id, appType),
396
365
  uniAppXCssTarget: resolveUniAppXCssTarget(id),
397
366
  uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
@@ -403,13 +372,13 @@ function createUniAppXPlugins(options) {
403
372
  sourcesContent: true
404
373
  }
405
374
  } }
406
- };
375
+ });
407
376
  cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
408
377
  }
409
378
  const postcssResult = await styleHandler(code, styleHandlerOptions);
410
379
  const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
411
380
  for (const warning of warnings) logger$1.warn(warning.toString());
412
- const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl$1(id));
381
+ const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl(id));
413
382
  return {
414
383
  code: postcssResult.css,
415
384
  map: postcssMap
@@ -419,14 +388,14 @@ function createUniAppXPlugins(options) {
419
388
  const cssPlugins = [{
420
389
  name: "weapp-tailwindcss:uni-app-x:css",
421
390
  async transform(code, id) {
422
- await runtimeState.patchPromise;
391
+ await runtimeState.readyPromise;
423
392
  return transformStyle(code, id);
424
393
  }
425
394
  }, {
426
395
  name: "weapp-tailwindcss:uni-app-x:css:pre",
427
396
  enforce: "pre",
428
397
  async transform(code, id) {
429
- await runtimeState.patchPromise;
398
+ await runtimeState.readyPromise;
430
399
  const { query } = parseVueRequest(id);
431
400
  const lang = query.lang;
432
401
  if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
@@ -503,32 +472,134 @@ function createUniAppXAssetTask(file, originalSource, outDir, options) {
503
472
  };
504
473
  }
505
474
  //#endregion
475
+ //#region src/bundlers/vite/processed-css-assets.ts
476
+ const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
477
+ function isCssOutputFile(file) {
478
+ return CSS_OUTPUT_FILE_RE.test(file);
479
+ }
480
+ function getAssetFile(bundleFile, asset) {
481
+ return asset.fileName || bundleFile;
482
+ }
483
+ function readAssetSource(asset) {
484
+ return typeof asset.source === "string" ? asset.source : asset.source.toString();
485
+ }
486
+ function appendCss(baseCss, css) {
487
+ if (baseCss.length === 0) return css;
488
+ if (css.length === 0) return baseCss;
489
+ return `${baseCss}\n${css}`;
490
+ }
491
+ function collectViteProcessedCssAssetResults(bundle, options) {
492
+ let collected = 0;
493
+ for (const [bundleFile, output] of Object.entries(bundle)) {
494
+ if (output.type !== "asset") continue;
495
+ const file = getAssetFile(bundleFile, output);
496
+ if (!isCssOutputFile(file) || !options.isViteProcessedCssAsset?.(output, file)) continue;
497
+ const rawSource = readAssetSource(output);
498
+ const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
499
+ if (nextCss !== rawSource) output.source = nextCss;
500
+ options.markCssAssetProcessed?.(output, file);
501
+ options.recordCssAssetResult?.(file, nextCss);
502
+ options.recordViteProcessedCssAssetResult?.(file, nextCss);
503
+ options.debug?.("collect vite-processed css asset: %s bytes=%d", file, nextCss.length);
504
+ collected++;
505
+ }
506
+ return collected;
507
+ }
508
+ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
509
+ const viteCssResults = [...options.getViteProcessedCssAssetResults?.() ?? []].filter(([file, css]) => isCssOutputFile(file) && css.length > 0);
510
+ if (viteCssResults.length === 0) return 0;
511
+ let injected = 0;
512
+ for (const [bundleFile, output] of Object.entries(bundle)) {
513
+ if (output.type !== "asset") continue;
514
+ const file = getAssetFile(bundleFile, output);
515
+ if (!options.opts.cssMatcher(file) || !options.opts.mainCssChunkMatcher(file, options.opts.appType)) continue;
516
+ const mainFileKey = normalizeOutputPathKey(file);
517
+ const originalSource = readAssetSource(output);
518
+ let nextCss = originalSource;
519
+ for (const [sourceFile, sourceCss] of viteCssResults) {
520
+ if (normalizeOutputPathKey(sourceFile) === mainFileKey || options.opts.mainCssChunkMatcher(sourceFile, options.opts.appType)) continue;
521
+ const css = stripBundlerGeneratedCssMarkers(sourceCss).trim();
522
+ if (css.length === 0 || nextCss.includes(css)) continue;
523
+ nextCss = appendCss(nextCss, css);
524
+ }
525
+ if (nextCss === originalSource) continue;
526
+ output.source = nextCss;
527
+ options.markCssAssetProcessed?.(output, file);
528
+ options.recordCssAssetResult?.(file, nextCss);
529
+ options.onUpdate?.(file, originalSource, nextCss);
530
+ options.debug?.("inject vite-processed css into main css asset: %s bytes=%d", file, nextCss.length);
531
+ injected++;
532
+ }
533
+ return injected;
534
+ }
535
+ //#endregion
506
536
  //#region src/bundlers/vite/css-finalizer.ts
537
+ function isAddWatchFileInvalidRollupPhaseError$1(error) {
538
+ const candidate = error;
539
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
540
+ }
541
+ function registerGeneratorDependencies$1(ctx, dependencies) {
542
+ if (typeof ctx.addWatchFile !== "function") return;
543
+ for (const dependency of dependencies ?? []) try {
544
+ ctx.addWatchFile(dependency);
545
+ } catch (error) {
546
+ if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
547
+ logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
548
+ continue;
549
+ }
550
+ throw error;
551
+ }
552
+ }
507
553
  function createCssHandlerOptions(opts, majorVersion, file) {
508
554
  return {
509
555
  isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
510
556
  postcssOptions: { options: { from: file } },
511
- majorVersion
557
+ ...majorVersion === void 0 ? {} : { majorVersion }
512
558
  };
513
559
  }
514
560
  function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
515
- if (hasTailwindGeneratedCssMarkers(rawSource) || hasTailwindSourceDirectives(rawSource)) return true;
561
+ const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
562
+ if (generatorOptions.target === "web") return false;
563
+ if (hasTailwindGeneratedCssMarkers(rawSource) || hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return true;
564
+ if (opts.twPatcher.majorVersion === 3) return false;
516
565
  return processed && shouldFinalizeProcessedCssAsset(opts, file);
517
566
  }
518
567
  function shouldFinalizeProcessedCssAsset(opts, file) {
519
- return normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType);
568
+ return opts.mainCssChunkMatcher(file, opts.appType);
520
569
  }
521
570
  function createViteCssFinalizerOutputPlugin(context) {
522
571
  return {
523
572
  name: "weapp-tailwindcss:adaptor:css-finalizer",
573
+ enforce: "post",
524
574
  generateBundle: {
525
575
  order: "post",
526
576
  async handler(_options, bundle) {
527
- const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource } = context;
577
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
528
578
  if (getResolvedConfig()?.command !== "build") return;
529
- const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
530
- if (entries.length === 0) return;
531
- await runtimeState.patchPromise;
579
+ collectViteProcessedCssAssetResults(bundle, {
580
+ isViteProcessedCssAsset,
581
+ markCssAssetProcessed,
582
+ recordCssAssetResult,
583
+ recordViteProcessedCssAssetResult,
584
+ debug
585
+ });
586
+ const isCssOutputAssetEntry = (entry) => {
587
+ const [, output] = entry;
588
+ return output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName));
589
+ };
590
+ const entries = Object.entries(bundle).filter(isCssOutputAssetEntry);
591
+ if (entries.length === 0) {
592
+ injectViteProcessedCssIntoMainCssAssets(bundle, {
593
+ opts,
594
+ getViteProcessedCssAssetResults,
595
+ markCssAssetProcessed,
596
+ recordCssAssetResult,
597
+ debug,
598
+ onUpdate: opts.onUpdate
599
+ });
600
+ return;
601
+ }
602
+ await runtimeState.readyPromise;
532
603
  await waitForSourceCandidateSyncs?.();
533
604
  const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
534
605
  const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
@@ -537,288 +608,219 @@ function createViteCssFinalizerOutputPlugin(context) {
537
608
  await Promise.all(entries.map(async ([bundleFile, output]) => {
538
609
  const file = output.fileName || bundleFile;
539
610
  const rawSource = output.source.toString();
611
+ if (isViteProcessedCssAsset?.(output, file)) {
612
+ const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
613
+ output.source = nextCss;
614
+ markCssAssetProcessed(output, file);
615
+ recordCssAssetResult?.(file, nextCss);
616
+ debug("css finalizer skip vite-processed css: %s", file);
617
+ return;
618
+ }
540
619
  const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.twPatcher.majorVersion, file);
541
620
  const cssUserHandlerOptions = {
542
621
  ...cssHandlerOptions,
543
622
  isMainChunk: false
544
623
  };
545
- const generated = shouldGenerateCssByGenerator(opts, file, rawSource, isCssAssetProcessed(output, file)) ? await generateCssByGenerator({
624
+ const processed = isCssAssetProcessed(output, file);
625
+ const generatorRawSource = processed && cssHandlerOptions.isMainChunk ? getRememberedMainCssSource?.(file) ?? rawSource : rawSource;
626
+ const generated = shouldGenerateCssByGenerator(opts, file, generatorRawSource, processed) ? await generateCssByGenerator({
546
627
  opts,
547
628
  runtimeState,
548
629
  runtime: generatorRuntime,
549
- rawSource,
630
+ rawSource: generatorRawSource,
550
631
  file,
551
632
  cssHandlerOptions,
552
633
  cssUserHandlerOptions,
634
+ getSourceCandidatesForEntries,
553
635
  styleHandler: opts.styleHandler,
554
636
  debug
555
637
  }) : void 0;
556
638
  const nextCss = generated?.css ?? (await opts.styleHandler(rawSource, cssHandlerOptions)).css;
557
639
  if (generated) {
640
+ registerGeneratorDependencies$1(this, generated.dependencies);
558
641
  debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
559
642
  recordCssAssetResult?.(file, nextCss);
560
- if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource);
643
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, generatorRawSource);
561
644
  }
562
645
  output.source = nextCss;
563
646
  markCssAssetProcessed(output, file);
564
647
  opts.onUpdate(file, rawSource, nextCss);
565
648
  debug("css finalizer handle: %s", file);
566
649
  }));
650
+ injectViteProcessedCssIntoMainCssAssets(bundle, {
651
+ opts,
652
+ getViteProcessedCssAssetResults,
653
+ markCssAssetProcessed,
654
+ recordCssAssetResult,
655
+ debug,
656
+ onUpdate: opts.onUpdate
657
+ });
567
658
  }
568
659
  }
569
660
  };
570
661
  }
571
662
  //#endregion
572
- //#region src/bundlers/vite/bundle-entries.ts
573
- function readOutputEntry(entry) {
574
- if (entry.output.type === "chunk") return entry.output.code;
575
- const source = entry.output.source;
576
- if (typeof source === "string") return source;
577
- if (source instanceof Uint8Array) return Buffer.from(source).toString();
578
- const fallbackSource = source;
579
- if (fallbackSource == null) return;
580
- if (typeof fallbackSource.toString === "function") return fallbackSource.toString();
581
- }
582
- function isJavaScriptEntry(entry) {
583
- if (entry.output.type === "chunk") return true;
584
- return entry.fileName.endsWith(".js");
585
- }
586
- function createBundleModuleGraphOptions(outputDir, entries) {
587
- const normalizedEntries = /* @__PURE__ */ new Map();
588
- for (const [id, entry] of entries) normalizedEntries.set(normalizeOutputPathKey(id), entry);
589
- const getEntry = (id) => entries.get(id) ?? normalizedEntries.get(normalizeOutputPathKey(id));
590
- return {
591
- resolve(specifier, importer) {
592
- return resolveOutputSpecifier(specifier, importer, outputDir, (candidate) => Boolean(getEntry(candidate)));
593
- },
594
- load(id) {
595
- const entry = getEntry(id);
596
- if (!entry) return;
597
- return readOutputEntry(entry);
598
- },
599
- filter(id) {
600
- return Boolean(getEntry(id));
601
- }
602
- };
603
- }
604
- function applyLinkedResults(linked, entries, onLinkedUpdate, onApplied) {
605
- if (!linked) return;
606
- const normalizedEntries = /* @__PURE__ */ new Map();
607
- for (const [entryId, entry] of entries) normalizedEntries.set(normalizeOutputPathKey(entryId), entry);
608
- for (const [id, { code }] of Object.entries(linked)) {
609
- const entry = entries.get(id) ?? normalizedEntries.get(normalizeOutputPathKey(id));
610
- if (!entry) continue;
611
- const previous = readOutputEntry(entry);
612
- if (previous == null || previous === code) continue;
613
- if (entry.output.type === "chunk") entry.output.code = code;
614
- else entry.output.source = code;
615
- onApplied?.(entry, code);
616
- onLinkedUpdate(entry.fileName, previous, code);
617
- }
618
- }
619
- //#endregion
620
- //#region src/bundlers/vite/runtime-affecting-signature.ts
621
- const CSS_BLOCK_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
622
- const CSS_AROUND_PUNCTUATION_RE = /\s*([{}:;,>+~()])\s*/g;
623
- const CSS_TRAILING_DECLARATION_SEMICOLON_RE = /;\}/g;
624
- const CSS_WHITESPACE_RE = /\s+/g;
625
- function createHtmlRuntimeAffectingSignature(source) {
626
- try {
627
- const parts = [];
628
- const parser = new Parser({
629
- onattribute(name, value) {
630
- parts.push(`a:${name}=${value}`);
631
- },
632
- oncomment(data) {
633
- parts.push(`c:${data}`);
634
- },
635
- ontext(data) {
636
- const value = data.trim();
637
- if (value.length > 0) parts.push(`t:${value}`);
638
- }
639
- }, { xmlMode: true });
640
- parser.write(source);
641
- parser.end();
642
- return parts.join("\n");
643
- } catch {
644
- return source;
645
- }
663
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
664
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
665
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
666
+ function isArbitraryValueCandidate(candidate) {
667
+ return candidate.includes("[") && candidate.includes("]");
646
668
  }
647
- function createJsRuntimeAffectingSignature(source) {
648
- try {
649
- const ast = babelParse(source, {
650
- cache: true,
651
- cacheKey: "vite-runtime-affecting:unambiguous",
652
- plugins: ["jsx", "typescript"],
653
- sourceType: "unambiguous"
654
- });
655
- const parts = [];
656
- traverse$1(ast, {
657
- noScope: true,
658
- StringLiteral(path) {
659
- parts.push(`s:${path.node.value}`);
660
- },
661
- TemplateElement(path) {
662
- parts.push(`t:${path.node.value.raw}`);
663
- },
664
- JSXText(path) {
665
- const value = path.node.value.trim();
666
- if (value.length > 0) parts.push(`x:${value}`);
669
+ function collectUnescapedDynamicCandidates(source) {
670
+ const matches = /* @__PURE__ */ new Set();
671
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
672
+ QUOTED_LITERAL_RE.lastIndex = 0;
673
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
674
+ while (quoted !== null) {
675
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
676
+ for (const candidate of splitCode(literal, true)) {
677
+ const normalized = candidate.trim();
678
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
679
+ matches.add(normalized);
667
680
  }
668
- });
669
- const comments = ast.comments;
670
- if (Array.isArray(comments)) {
671
- for (const comment of comments) if (typeof comment?.value === "string" && comment.value.length > 0) parts.push(`c:${comment.value}`);
681
+ quoted = QUOTED_LITERAL_RE.exec(expression);
672
682
  }
673
- return parts.join("\n");
674
- } catch {
675
- return source;
676
683
  }
684
+ return [...matches];
677
685
  }
678
- function createCssRuntimeAffectingSignature(source) {
679
- return source.replace(CSS_BLOCK_COMMENT_RE, "").replace(CSS_AROUND_PUNCTUATION_RE, "$1").replace(CSS_TRAILING_DECLARATION_SEMICOLON_RE, "}").replace(CSS_WHITESPACE_RE, " ").trim();
680
- }
681
- function createRuntimeAffectingSourceSignature(source, type) {
682
- if (type === "html") return createHtmlRuntimeAffectingSignature(source);
683
- if (type === "js") return createJsRuntimeAffectingSignature(source);
684
- if (type === "css") return createCssRuntimeAffectingSignature(source);
685
- return source;
686
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
687
+ if (candidates.has("container")) return candidates;
688
+ if (!sourceCandidates.has("container")) return candidates;
689
+ return new Set([...candidates, "container"]);
686
690
  }
687
691
  //#endregion
688
- //#region src/bundlers/vite/bundle-state.ts
689
- function createBundleBuildState() {
690
- return {
691
- iteration: 0,
692
- sourceHashByFile: /* @__PURE__ */ new Map(),
693
- runtimeAffectingSignatureByFile: /* @__PURE__ */ new Map(),
694
- runtimeAffectingHashByFile: /* @__PURE__ */ new Map(),
695
- linkedByEntry: /* @__PURE__ */ new Map(),
696
- dependentsByLinkedFile: /* @__PURE__ */ new Map()
692
+ //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
693
+ function createCssHandlerOptionsCache(options) {
694
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
695
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
696
+ const getCssHandlerOptions = (file) => {
697
+ const majorVersion = options.getMajorVersion();
698
+ const appType = options.getAppType();
699
+ const isMainChunk = options.mainCssChunkMatcher(file, appType);
700
+ const outputRoot = options.getOutputRoot?.();
701
+ const cacheKey = `${majorVersion ?? "unknown"}:${appType ?? "unknown"}:${isMainChunk ? "1" : "0"}:${outputRoot ?? ""}:${file}`;
702
+ const cached = cssHandlerOptionsCache.get(cacheKey);
703
+ if (cached) return cached;
704
+ const created = {
705
+ isMainChunk,
706
+ postcssOptions: { options: { from: file } },
707
+ majorVersion,
708
+ sourceOptions: { outputRoot }
709
+ };
710
+ cssHandlerOptionsCache.set(cacheKey, created);
711
+ return created;
697
712
  };
698
- }
699
- function createChangedByType() {
700
- return {
701
- html: /* @__PURE__ */ new Set(),
702
- js: /* @__PURE__ */ new Set(),
703
- css: /* @__PURE__ */ new Set(),
704
- other: /* @__PURE__ */ new Set()
713
+ const getCssUserHandlerOptions = (file) => {
714
+ const majorVersion = options.getMajorVersion();
715
+ const outputRoot = options.getOutputRoot?.();
716
+ const cacheKey = `${majorVersion ?? "unknown"}:${outputRoot ?? ""}:${file}`;
717
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
718
+ if (cached) return cached;
719
+ const created = {
720
+ ...getCssHandlerOptions(file),
721
+ isMainChunk: false
722
+ };
723
+ cssUserHandlerOptionsCache.set(cacheKey, created);
724
+ return created;
705
725
  };
706
- }
707
- function createProcessFiles() {
708
726
  return {
709
- html: /* @__PURE__ */ new Set(),
710
- js: /* @__PURE__ */ new Set(),
711
- css: /* @__PURE__ */ new Set()
727
+ getCssHandlerOptions,
728
+ getCssUserHandlerOptions
712
729
  };
713
730
  }
714
- function readEntrySource(output) {
715
- if (output.type === "chunk") return output.code;
716
- return output.source.toString();
731
+ //#endregion
732
+ //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
733
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
734
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
735
+ const CSS_IMPORT_RE = /@import\b/i;
736
+ function isPathIndependentCssUrl(value) {
737
+ const normalized = value.trim();
738
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
739
+ }
740
+ function hasPathDependentCssUrl(rawSource) {
741
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
742
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
743
+ while (match !== null) {
744
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
745
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
746
+ }
747
+ return false;
717
748
  }
718
- function classifyBundleEntry(file, opts) {
719
- if (opts.cssMatcher(file)) return "css";
720
- if (opts.htmlMatcher(file)) return "html";
721
- if (opts.jsMatcher(file) || opts.wxsMatcher(file)) return "js";
722
- return "other";
749
+ function createCssTransformShareScope(file, rawSource) {
750
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${normalizeOutputPathKey(path.dirname(file))}`;
751
+ return "global";
723
752
  }
724
- function collectJsEntries(fileName, output, outDir, store) {
725
- const entry = {
726
- fileName,
727
- output
753
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
754
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${normalizeOutputPathKey(file)}`;
755
+ const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
756
+ if (hasTailwindGeneratedCssMarkers(rawSource) || hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return `source:${normalizeOutputPathKey(file)}`;
757
+ return createCssTransformShareScope(file, rawSource);
758
+ }
759
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
760
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
761
+ }
762
+ //#endregion
763
+ //#region src/bundlers/vite/generate-bundle/dirty-state.ts
764
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
765
+ const currentFileSet = new Set(currentBundleFiles);
766
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
767
+ return false;
768
+ }
769
+ //#endregion
770
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
771
+ function createJsEntryResolver(jsEntries) {
772
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
773
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
774
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
775
+ }
776
+ //#endregion
777
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
778
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
779
+ return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
780
+ }
781
+ function createJsHandlerOptionsFactory(options) {
782
+ return (absoluteFilename, extra) => ({
783
+ ...extra,
784
+ filename: absoluteFilename,
785
+ tailwindcssMajorVersion: options.getMajorVersion(),
786
+ moduleGraph: options.moduleGraph,
787
+ babelParserOptions: {
788
+ ...extra?.babelParserOptions ?? {},
789
+ sourceFilename: absoluteFilename
790
+ }
791
+ });
792
+ }
793
+ //#endregion
794
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
795
+ function createLinkedUpdateHelpers(options) {
796
+ const pendingLinkedUpdates = [];
797
+ const handleLinkedUpdate = (fileName, previous, next) => {
798
+ options.onUpdate(fileName, previous, next);
799
+ options.debug("js linked handle: %s", fileName);
728
800
  };
729
- if (!isJavaScriptEntry(entry)) return;
730
- const absolute = toAbsoluteOutputPath(fileName, outDir);
731
- store.set(absolute, entry);
732
- }
733
- function markProcessFile(type, file, processFiles) {
734
- if (type === "html" || type === "js" || type === "css") processFiles[type].add(file);
735
- }
736
- function buildBundleSnapshot(bundle, opts, outDir, state, forceAll = false) {
737
- const sourceHashByFile = /* @__PURE__ */ new Map();
738
- const runtimeAffectingSignatureByFile = /* @__PURE__ */ new Map();
739
- const runtimeAffectingHashByFile = /* @__PURE__ */ new Map();
740
- const changedByType = createChangedByType();
741
- const runtimeAffectingChangedByType = createChangedByType();
742
- const processFiles = createProcessFiles();
743
- const linkedImpactsByEntry = /* @__PURE__ */ new Map();
744
- const jsEntries = /* @__PURE__ */ new Map();
745
- const entries = [];
746
- const firstRun = state.linkedByEntry.size === 0;
747
- for (const [file, output] of Object.entries(bundle)) {
748
- const type = classifyBundleEntry(file, opts);
749
- const source = readEntrySource(output);
750
- const hash = opts.cache.computeHash(source);
751
- sourceHashByFile.set(file, hash);
752
- const previousHash = state.sourceHashByFile.get(file);
753
- const changed = previousHash == null || previousHash !== hash;
754
- const previousRuntimeAffectingSignature = state.runtimeAffectingSignatureByFile.get(file);
755
- const previousRuntimeAffectingHash = state.runtimeAffectingHashByFile.get(file);
756
- const canReuseRuntimeAffectingSignature = !changed && previousRuntimeAffectingSignature != null && previousRuntimeAffectingHash != null;
757
- const runtimeAffectingSignature = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingSignature : createRuntimeAffectingSourceSignature(source, type);
758
- const runtimeAffectingHash = canReuseRuntimeAffectingSignature ? previousRuntimeAffectingHash : opts.cache.computeHash(runtimeAffectingSignature);
759
- runtimeAffectingSignatureByFile.set(file, runtimeAffectingSignature);
760
- runtimeAffectingHashByFile.set(file, runtimeAffectingHash);
761
- if (changed) changedByType[type].add(file);
762
- if (previousRuntimeAffectingHash == null || previousRuntimeAffectingHash !== runtimeAffectingHash) runtimeAffectingChangedByType[type].add(file);
763
- if (forceAll || firstRun) markProcessFile(type, file, processFiles);
764
- else if (type === "html") processFiles.html.add(file);
765
- else if (changed && (type === "js" || type === "css")) processFiles[type].add(file);
766
- collectJsEntries(file, output, outDir, jsEntries);
767
- entries.push({
768
- file,
769
- output,
770
- source,
771
- type
801
+ const scheduleLinkedApply = (entry, code) => {
802
+ pendingLinkedUpdates.push(() => {
803
+ if (entry.output.type === "chunk") entry.output.code = code;
804
+ else entry.output.source = code;
772
805
  });
773
- }
774
- if (!forceAll && !firstRun) for (const changedFile of changedByType.js) {
775
- const dependents = state.dependentsByLinkedFile.get(changedFile);
776
- if (!dependents) continue;
777
- for (const entryFile of dependents) {
778
- processFiles.js.add(entryFile);
779
- let impacts = linkedImpactsByEntry.get(entryFile);
780
- if (!impacts) {
781
- impacts = /* @__PURE__ */ new Set();
782
- linkedImpactsByEntry.set(entryFile, impacts);
783
- }
784
- impacts.add(changedFile);
785
- }
786
- }
806
+ };
807
+ const applyLinkedUpdates = (linked) => {
808
+ applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
809
+ };
787
810
  return {
788
- entries,
789
- jsEntries,
790
- sourceHashByFile,
791
- runtimeAffectingSignatureByFile,
792
- runtimeAffectingHashByFile,
793
- changedByType,
794
- runtimeAffectingChangedByType,
795
- processFiles,
796
- linkedImpactsByEntry
811
+ applyLinkedUpdates,
812
+ pendingLinkedUpdates
797
813
  };
798
814
  }
799
- function invertLinkedByEntry(linkedByEntry) {
800
- const dependentsByLinkedFile = /* @__PURE__ */ new Map();
801
- for (const [entryFile, linkedFiles] of linkedByEntry.entries()) for (const linkedFile of linkedFiles) {
802
- let dependents = dependentsByLinkedFile.get(linkedFile);
803
- if (!dependents) {
804
- dependents = /* @__PURE__ */ new Set();
805
- dependentsByLinkedFile.set(linkedFile, dependents);
806
- }
807
- dependents.add(entryFile);
815
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
816
+ if (!linked || !linkedSet) return;
817
+ for (const id of Object.keys(linked)) {
818
+ const linkedEntry = getJsEntry(id);
819
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
808
820
  }
809
- return dependentsByLinkedFile;
810
- }
811
- function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
812
- const incremental = options.incremental === true;
813
- state.iteration += 1;
814
- state.sourceHashByFile = incremental ? new Map([...state.sourceHashByFile, ...snapshot.sourceHashByFile]) : snapshot.sourceHashByFile;
815
- state.runtimeAffectingSignatureByFile = incremental ? new Map([...state.runtimeAffectingSignatureByFile, ...snapshot.runtimeAffectingSignatureByFile]) : snapshot.runtimeAffectingSignatureByFile;
816
- state.runtimeAffectingHashByFile = incremental ? new Map([...state.runtimeAffectingHashByFile, ...snapshot.runtimeAffectingHashByFile]) : snapshot.runtimeAffectingHashByFile;
817
- state.linkedByEntry = incremental ? new Map([...state.linkedByEntry, ...linkedByEntry]) : linkedByEntry;
818
- state.dependentsByLinkedFile = invertLinkedByEntry(state.linkedByEntry);
819
821
  }
820
822
  //#endregion
821
- //#region src/bundlers/vite/generate-bundle.ts
823
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
822
824
  function formatDebugFileList(files, limit = 8) {
823
825
  if (files.size === 0) return "-";
824
826
  const sorted = [...files].sort();
@@ -844,9 +846,6 @@ function createEmptyMetrics() {
844
846
  function measureElapsed(start) {
845
847
  return performance.now() - start;
846
848
  }
847
- function resolveUniAppXJsTransformEnabled(uniAppX) {
848
- return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
849
- }
850
849
  function formatCacheHitRate(metric) {
851
850
  if (metric.total === 0) return "0.00%";
852
851
  return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
@@ -854,6 +853,50 @@ function formatCacheHitRate(metric) {
854
853
  function formatMs(value) {
855
854
  return value.toFixed(2);
856
855
  }
856
+ //#endregion
857
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
858
+ function logBundleProcessPlan(options) {
859
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
860
+ const { processFiles } = snapshot;
861
+ if (useIncrementalMode) {
862
+ 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));
863
+ 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));
864
+ return;
865
+ }
866
+ 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));
867
+ }
868
+ //#endregion
869
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
870
+ function createReplayCssAsset(fileName, source) {
871
+ return {
872
+ type: "asset",
873
+ fileName,
874
+ name: void 0,
875
+ source,
876
+ needsCodeReference: false,
877
+ names: [],
878
+ originalFileName: null,
879
+ originalFileNames: []
880
+ };
881
+ }
882
+ function isAddWatchFileInvalidRollupPhaseError(error) {
883
+ const candidate = error;
884
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
885
+ }
886
+ function registerGeneratorDependencies(ctx, dependencies) {
887
+ if (typeof ctx.addWatchFile !== "function") return;
888
+ for (const dependency of dependencies ?? []) try {
889
+ ctx.addWatchFile(dependency);
890
+ } catch (error) {
891
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
892
+ logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
893
+ continue;
894
+ }
895
+ throw error;
896
+ }
897
+ }
898
+ //#endregion
899
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
857
900
  function summarizeStringDiff(previous, next) {
858
901
  if (previous === next) return "same";
859
902
  const previousLength = previous.length;
@@ -900,173 +943,167 @@ function getSnapshotHash(snapshotMap, file, fallback) {
900
943
  function hasRuntimeAffectingSourceChanges(changedByType) {
901
944
  return changedByType.html.size > 0 || changedByType.js.size > 0;
902
945
  }
903
- const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
904
- const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
905
- const CSS_IMPORT_RE = /@import\b/i;
906
- function isPathIndependentCssUrl(value) {
907
- const normalized = value.trim();
908
- return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
909
- }
910
- function hasPathDependentCssUrl(rawSource) {
911
- CSS_URL_FUNCTION_RE.lastIndex = 0;
912
- let match = CSS_URL_FUNCTION_RE.exec(rawSource);
913
- while (match !== null) {
914
- if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
915
- match = CSS_URL_FUNCTION_RE.exec(rawSource);
916
- }
917
- return false;
918
- }
919
- function createCssTransformShareScope(file, rawSource) {
920
- if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${normalizeOutputPathKey(path.dirname(file))}`;
921
- return "global";
922
- }
923
- function createCssTransformShareScopeKey(opts, file, rawSource) {
924
- if (normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force" && opts.mainCssChunkMatcher(file, opts.appType)) return `main:${normalizeOutputPathKey(file)}`;
925
- return createCssTransformShareScope(file, rawSource);
926
- }
927
- function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
928
- return `${runtimeSignature}:${generatorCandidateSignature}`;
929
- }
930
- function createReplayCssAsset(fileName, source) {
931
- return {
932
- type: "asset",
933
- fileName,
934
- name: void 0,
935
- source,
936
- needsCodeReference: false,
937
- names: [],
938
- originalFileName: null,
939
- originalFileNames: []
940
- };
941
- }
942
- function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
943
- const currentFileSet = new Set(currentBundleFiles);
944
- for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
945
- return false;
946
- }
947
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
948
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
949
- function isArbitraryValueCandidate(candidate) {
950
- return candidate.includes("[") && candidate.includes("]");
951
- }
952
- function collectUnescapedDynamicCandidates(source) {
953
- const matches = /* @__PURE__ */ new Set();
954
- for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
955
- QUOTED_LITERAL_RE.lastIndex = 0;
956
- let quoted = QUOTED_LITERAL_RE.exec(expression);
957
- while (quoted !== null) {
958
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
959
- for (const candidate of splitCode(literal, true)) {
960
- const normalized = candidate.trim();
961
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
962
- matches.add(normalized);
963
- }
964
- quoted = QUOTED_LITERAL_RE.exec(expression);
965
- }
946
+ //#endregion
947
+ //#region src/bundlers/vite/generate-bundle.ts
948
+ function addSiblingCssFile(files, file) {
949
+ if (file.endsWith(".wxml")) files.add(file.replace(/\.wxml$/, ".wxss"));
950
+ else if (file.endsWith(".js")) files.add(file.replace(/\.js$/, ".wxss"));
951
+ }
952
+ function collectRuntimeLinkedCssFiles(snapshot) {
953
+ const files = /* @__PURE__ */ new Set();
954
+ for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file);
955
+ for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file);
956
+ return files;
957
+ }
958
+ function resolveReplayCssOutputFile(rootDir, file) {
959
+ const normalizedFile = normalizeOutputPathKey(path.isAbsolute(file) ? path.relative(rootDir, file) : file);
960
+ if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return normalizeOutputPathKey(path.basename(file));
961
+ return normalizedFile;
962
+ }
963
+ const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
964
+ const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
965
+ function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget) {
966
+ if (isWebGeneratorTarget || opts.cssMatcher(file) || !SOURCE_STYLE_OUTPUT_EXT_RE.test(file) || !isCSSRequest(file)) return file;
967
+ return file.replace(SOURCE_STYLE_OUTPUT_EXT_RE, ".wxss");
968
+ }
969
+ function canProcessViteSourceStyleAsCss(source, file) {
970
+ if (SOURCE_STYLE_NON_CSS_SYNTAX_RE.test(source)) return false;
971
+ try {
972
+ postcss.parse(source, { from: file });
973
+ return true;
974
+ } catch {
975
+ return false;
966
976
  }
967
- return [...matches];
968
- }
969
- function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
970
- if (candidates.has("container")) return candidates;
971
- if (!sourceCandidates.has("container")) return candidates;
972
- return new Set([...candidates, "container"]);
973
977
  }
974
978
  function createGenerateBundleHook(context) {
975
979
  const state = createBundleBuildState();
976
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
977
- const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
980
+ const lastCssResultByFile = /* @__PURE__ */ new Map();
981
+ let currentOutDir;
982
+ const cssHandlerOptions = createCssHandlerOptionsCache({
983
+ getAppType: () => context.opts.appType,
984
+ mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
985
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion,
986
+ getOutputRoot: () => currentOutDir
987
+ });
978
988
  return async function generateBundle(_opt, bundle) {
979
- const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
980
- const { appType, cache, mainCssChunkMatcher, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
989
+ const addWatchFile = (id) => this.addWatchFile?.(id);
990
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, isViteProcessedCssAsset, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates, hmrTimingRecorder } = context;
991
+ const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
981
992
  const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
982
- const getCssHandlerOptions = (file) => {
983
- const majorVersion = runtimeState.twPatcher.majorVersion;
984
- const isMainChunk = mainCssChunkMatcher(file, appType);
985
- const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
986
- const cached = cssHandlerOptionsCache.get(cacheKey);
987
- if (cached) return cached;
988
- const created = {
989
- isMainChunk,
990
- postcssOptions: { options: { from: file } },
991
- majorVersion
992
- };
993
- cssHandlerOptionsCache.set(cacheKey, created);
994
- return created;
995
- };
996
- const getCssUserHandlerOptions = (file) => {
997
- const cacheKey = `${runtimeState.twPatcher.majorVersion ?? "unknown"}:${file}`;
998
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
999
- if (cached) return cached;
1000
- const created = {
1001
- ...getCssHandlerOptions(file),
1002
- isMainChunk: false
1003
- };
1004
- cssUserHandlerOptionsCache.set(cacheKey, created);
1005
- return created;
1006
- };
1007
- await runtimeState.patchPromise;
993
+ const isWebGeneratorTarget = generatorOptions.target === "web";
994
+ const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
995
+ await runtimeState.readyPromise;
1008
996
  debug("start");
1009
997
  onStart();
998
+ collectViteProcessedCssAssetResults(bundle, {
999
+ isViteProcessedCssAsset,
1000
+ markCssAssetProcessed,
1001
+ recordCssAssetResult,
1002
+ recordViteProcessedCssAssetResult,
1003
+ debug
1004
+ });
1005
+ const hmrTimingStartedAt = performance.now();
1006
+ const timingDetails = {};
1007
+ const recordTimingDetail = (name, startedAt) => {
1008
+ timingDetails[name] = (timingDetails[name] ?? 0) + Math.max(0, performance.now() - startedAt);
1009
+ };
1010
+ const timeTask = async (name, task) => {
1011
+ const start = performance.now();
1012
+ try {
1013
+ await task();
1014
+ } finally {
1015
+ recordTimingDetail(`tasks.${name}`, start);
1016
+ }
1017
+ };
1010
1018
  const metrics = createEmptyMetrics();
1011
- const forceRuntimeRefreshByEnv = process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1012
- const disableDirtyOptimization = process.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
1013
- const disableJsPrecheck = process.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
1014
- const debugCssDiff = process.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
1019
+ const forceRuntimeRefreshByEnv = process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1020
+ const disableDirtyOptimization = process.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1";
1021
+ const disableJsPrecheck = process.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1";
1022
+ const debugCssDiff = process.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
1023
+ const disableV3OxideSourceRuntime = process.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1";
1015
1024
  const resolvedConfig = getResolvedConfig();
1016
1025
  const bundleFiles = Object.keys(bundle);
1017
- const useIncrementalMode = !(resolvedConfig?.command === "build") || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1026
+ const buildCommand = resolvedConfig?.command === "build";
1027
+ const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
1028
+ const useIncrementalMode = !buildCommand || hasPreviousBundleState || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
1018
1029
  const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process.cwd();
1019
1030
  const outDir = resolvedConfig?.build?.outDir ? path.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
1031
+ currentOutDir = outDir;
1032
+ const snapshotStart = performance.now();
1020
1033
  const snapshot = buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
1034
+ recordTimingDetail("snapshot", snapshotStart);
1021
1035
  const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
1022
1036
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1023
1037
  const processFiles = snapshot.processFiles;
1024
- if (useIncrementalMode) {
1025
- debug("dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]", state.iteration + 1, 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));
1026
- debug("process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]", state.iteration + 1, processFiles.html.size, formatDebugFileList(processFiles.html), processFiles.js.size, formatDebugFileList(processFiles.js), processFiles.css.size, formatDebugFileList(processFiles.css));
1027
- } else 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));
1028
- const jsEntries = snapshot.jsEntries;
1029
- const normalizedJsEntries = /* @__PURE__ */ new Map();
1030
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
1031
- const getJsEntry = (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
1038
+ logBundleProcessPlan({
1039
+ debug,
1040
+ snapshot,
1041
+ useIncrementalMode,
1042
+ iteration: state.iteration + 1
1043
+ });
1044
+ const sourceCandidateWaitStart = performance.now();
1045
+ await waitForSourceCandidateSyncs?.();
1046
+ recordTimingDetail("sourceCandidates.wait", sourceCandidateWaitStart);
1047
+ const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1048
+ const jsEntries = snapshot.jsEntries;
1049
+ const getJsEntry = createJsEntryResolver(jsEntries);
1032
1050
  const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
1051
+ const hasCssAssetEntry = snapshot.entries.some((entry) => entry.type === "css" && entry.output.type === "asset");
1052
+ const hasRuntimeAffectingChanges = hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1053
+ const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !forceRuntimeRefreshByEnv && !disableV3OxideSourceRuntime;
1033
1054
  const runtimeStart = performance.now();
1034
- const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1055
+ const runtime = useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, {
1056
+ allowBaselineOnlyInitialSync: true,
1057
+ baseClassSet: sourceCandidates
1058
+ }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1059
+ if (useV3OxideSourceRuntime) debug("[tailwindcss:v3] use oxide source candidates as runtime input, candidates=%d", sourceCandidates.size);
1035
1060
  const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1036
- await waitForSourceCandidateSyncs?.();
1037
- const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1038
- const collectedGeneratorCandidates = generatorOptions.mode === "force" ? new Set(sourceCandidates) : new Set([...runtime, ...sourceCandidates]);
1039
- const generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
1061
+ const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
1062
+ let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
1063
+ let transformRuntime = runtime;
1064
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0 && !useV3OxideSourceRuntime) {
1065
+ const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
1066
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
1067
+ if (mainCssEntry) {
1068
+ const validatedRuntime = await validateCandidatesByGenerator({
1069
+ opts,
1070
+ runtimeState,
1071
+ candidates: generatorRuntime,
1072
+ rawSource: mainCssEntry.source,
1073
+ file: mainCssEntry.file,
1074
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
1075
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
1076
+ styleHandler,
1077
+ debug
1078
+ });
1079
+ if (validatedRuntime.size > 0) {
1080
+ generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, validatedRuntime);
1081
+ transformRuntime = generatorRuntime;
1082
+ } else {
1083
+ generatorRuntime = validatedRuntime;
1084
+ transformRuntime = validatedRuntime;
1085
+ }
1086
+ }
1087
+ }
1040
1088
  const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1089
+ const generatorCandidatesChanged = state.generatorCandidateSignature !== generatorCandidateSignature;
1090
+ const runtimeLinkedCssFiles = collectRuntimeLinkedCssFiles(snapshot);
1041
1091
  recordGeneratorCandidates?.(generatorRuntime);
1042
- const defaultTemplateHandlerOptions = { runtimeSet: runtime };
1092
+ const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
1043
1093
  metrics.runtimeSet = measureElapsed(runtimeStart);
1094
+ timingDetails["runtime"] = metrics.runtimeSet;
1044
1095
  if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1045
- debug("get runtimeSet, class count: %d", runtime.size);
1096
+ debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
1046
1097
  const runtimeSignature = getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1047
- const handleLinkedUpdate = (fileName, previous, next) => {
1048
- onUpdate(fileName, previous, next);
1049
- debug("js linked handle: %s", fileName);
1050
- };
1051
- const pendingLinkedUpdates = [];
1052
- const scheduleLinkedApply = (entry, code) => {
1053
- pendingLinkedUpdates.push(() => {
1054
- if (entry.output.type === "chunk") entry.output.code = code;
1055
- else entry.output.source = code;
1056
- });
1057
- };
1058
- const applyLinkedUpdates = (linked) => {
1059
- applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1060
- };
1061
- const createHandlerOptions = (absoluteFilename, extra) => ({
1062
- ...extra,
1063
- filename: absoluteFilename,
1064
- tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
1065
- moduleGraph: moduleGraphOptions,
1066
- babelParserOptions: {
1067
- ...extra?.babelParserOptions ?? {},
1068
- sourceFilename: absoluteFilename
1069
- }
1098
+ const shouldProcessTailwindGeneration = !useIncrementalMode || hasRuntimeAffectingChanges || generatorCandidatesChanged || snapshot.processFiles.css.size > 0;
1099
+ const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
1100
+ jsEntries,
1101
+ onUpdate,
1102
+ debug
1103
+ });
1104
+ const createHandlerOptions = createJsHandlerOptionsFactory({
1105
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
1106
+ moduleGraph: moduleGraphOptions
1070
1107
  });
1071
1108
  const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1072
1109
  const sharedCssResultCache = /* @__PURE__ */ new Map();
@@ -1078,7 +1115,7 @@ function createGenerateBundleHook(context) {
1078
1115
  metrics.html.total++;
1079
1116
  if (!processFiles.html.has(file)) continue;
1080
1117
  const rawSource = originalEntrySource;
1081
- tasks.push(processCachedTask({
1118
+ tasks.push(timeTask("html", () => processCachedTask({
1082
1119
  cache,
1083
1120
  cacheKey: file,
1084
1121
  hashKey: `${file}:html:${runtimeSignature}`,
@@ -1096,7 +1133,7 @@ function createGenerateBundleHook(context) {
1096
1133
  let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1097
1134
  if (unresolvedDynamicCandidates.length > 0) {
1098
1135
  logger.warn("检测到 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
1099
- transformed = await templateHandler(rawSource, { runtimeSet: await context.ensureRuntimeClassSet(true) });
1136
+ transformed = await templateHandler(rawSource, { runtimeSet: new Set([...await context.ensureRuntimeClassSet(true), ...unresolvedDynamicCandidates]) });
1100
1137
  unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
1101
1138
  if (unresolvedDynamicCandidates.length > 0) logger.warn("WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
1102
1139
  }
@@ -1106,26 +1143,74 @@ function createGenerateBundleHook(context) {
1106
1143
  debug("html handle: %s", file);
1107
1144
  return { result: transformed };
1108
1145
  }
1109
- }));
1146
+ })));
1110
1147
  continue;
1111
1148
  }
1112
1149
  if (type === "css" && originalSource.type === "asset") {
1113
1150
  metrics.css.total++;
1114
1151
  const rawSource = originalEntrySource;
1152
+ const outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget);
1153
+ if (outputFile !== file && !canProcessViteSourceStyleAsCss(rawSource, file)) {
1154
+ delete bundle[file];
1155
+ debug("css skip raw source style asset: %s -> %s", file, outputFile);
1156
+ continue;
1157
+ }
1158
+ const applyCssResult = (source) => {
1159
+ if (outputFile !== file) {
1160
+ delete bundle[file];
1161
+ if (typeof this.emitFile === "function") this.emitFile({
1162
+ type: "asset",
1163
+ fileName: outputFile,
1164
+ source
1165
+ });
1166
+ else bundle[outputFile] = originalSource;
1167
+ originalSource.fileName = outputFile;
1168
+ }
1169
+ originalSource.source = source;
1170
+ };
1171
+ if (isViteProcessedCssAsset?.(originalSource, file)) {
1172
+ const nextCss = stripBundlerGeneratedCssMarkers(rawSource);
1173
+ applyCssResult(nextCss);
1174
+ markCssAssetProcessed?.(originalSource, outputFile);
1175
+ recordCssAssetResult?.(outputFile, nextCss);
1176
+ onUpdate(outputFile, rawSource, nextCss);
1177
+ debug("css skip vite-processed asset: %s", outputFile);
1178
+ continue;
1179
+ }
1180
+ if (isWebGeneratorTarget) {
1181
+ applyCssResult(rawSource);
1182
+ markCssAssetProcessed?.(originalSource, outputFile);
1183
+ onUpdate(outputFile, rawSource, rawSource);
1184
+ debug("css skip web target: %s", outputFile);
1185
+ continue;
1186
+ }
1115
1187
  const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1116
1188
  const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
1117
1189
  const cssHandlerOptions = getCssHandlerOptions(file);
1118
- const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1190
+ const shouldTrackGeneratorRuntime = shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file));
1191
+ const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? generatorCandidateSignature : "generator:stable";
1192
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
1119
1193
  const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1120
- tasks.push(processCachedTask({
1194
+ if (!shouldTrackGeneratorRuntime) {
1195
+ const lastCss = lastCssResultByFile.get(outputFile) ?? lastCssResultByFile.get(file);
1196
+ if (lastCss != null) {
1197
+ applyCssResult(lastCss);
1198
+ markCssAssetProcessed?.(originalSource, outputFile);
1199
+ metrics.css.cacheHits++;
1200
+ debug("css replay last result: %s", outputFile);
1201
+ continue;
1202
+ }
1203
+ }
1204
+ tasks.push(timeTask("css", () => processCachedTask({
1121
1205
  cache,
1122
1206
  cacheKey: file,
1123
1207
  hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1124
- hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${generatorCandidateSignature}`,
1208
+ hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${scopedGeneratorCandidateSignature}`,
1125
1209
  applyResult(source) {
1126
- originalSource.source = source;
1127
- markCssAssetProcessed?.(originalSource, file);
1128
- if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource, cssRuntimeSignature);
1210
+ applyCssResult(source);
1211
+ lastCssResultByFile.set(outputFile, source);
1212
+ markCssAssetProcessed?.(originalSource, outputFile);
1213
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(outputFile, rawSource, cssRuntimeSignature);
1129
1214
  },
1130
1215
  onCacheHit() {
1131
1216
  metrics.css.cacheHits++;
@@ -1144,7 +1229,8 @@ function createGenerateBundleHook(context) {
1144
1229
  }
1145
1230
  const runTransform = async () => {
1146
1231
  const start = performance.now();
1147
- await runtimeState.patchPromise;
1232
+ await runtimeState.readyPromise;
1233
+ const previousCss = useIncrementalMode && !snapshot.changedByType.css.has(file) ? lastCssResultByFile.get(file) : void 0;
1148
1234
  const generated = await generateCssByGenerator({
1149
1235
  opts,
1150
1236
  runtimeState,
@@ -1153,16 +1239,19 @@ function createGenerateBundleHook(context) {
1153
1239
  file,
1154
1240
  cssHandlerOptions,
1155
1241
  cssUserHandlerOptions: getCssUserHandlerOptions(file),
1242
+ getSourceCandidatesForEntries,
1156
1243
  styleHandler,
1157
- debug
1244
+ debug,
1245
+ previousCss
1158
1246
  });
1159
1247
  if (generated) {
1248
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1160
1249
  if (debugCssDiff) debug("css diff %s: %s", file, summarizeStringDiff(rawSource, generated.css));
1161
1250
  debug("css generated result: %s bytes=%d", file, generated.css.length);
1162
- recordCssAssetResult?.(file, generated.css);
1251
+ recordCssAssetResult?.(outputFile, generated.css);
1163
1252
  metrics.css.elapsed += measureElapsed(start);
1164
1253
  metrics.css.transformed++;
1165
- debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, file);
1254
+ debug("css handle via tailwind v%s engine(%s): %s", runtimeState.twPatcher.majorVersion, generated.target, outputFile);
1166
1255
  return generated.css;
1167
1256
  }
1168
1257
  const { css } = await styleHandler(rawSource, getCssHandlerOptions(file));
@@ -1174,11 +1263,11 @@ function createGenerateBundleHook(context) {
1174
1263
  const cssTask = cssSharedCacheKey ? sharedCssResultCache.get(cssSharedCacheKey) ?? runTransform() : runTransform();
1175
1264
  if (cssSharedCacheKey && !sharedCssResultCache.has(cssSharedCacheKey)) sharedCssResultCache.set(cssSharedCacheKey, cssTask);
1176
1265
  const css = await cssTask;
1177
- onUpdate(file, rawSource, css);
1178
- debug("css handle: %s", file);
1266
+ onUpdate(outputFile, rawSource, css);
1267
+ debug("css handle: %s", outputFile);
1179
1268
  return { result: css };
1180
1269
  }
1181
- }));
1270
+ })));
1182
1271
  continue;
1183
1272
  }
1184
1273
  if (type !== "js") continue;
@@ -1191,41 +1280,40 @@ function createGenerateBundleHook(context) {
1191
1280
  const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1192
1281
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1193
1282
  jsTaskFactories.push(async () => {
1194
- const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1195
- await processCachedTask({
1196
- cache,
1197
- cacheKey: file,
1198
- hashKey: `${file}:js`,
1199
- hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1200
- applyResult(source) {
1201
- originalSource.code = source;
1202
- },
1203
- onCacheHit() {
1204
- metrics.js.cacheHits++;
1205
- debug("js cache hit: %s", file);
1206
- },
1207
- async transform() {
1208
- const start = performance.now();
1209
- const rawSource = originalSource.code;
1210
- if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1211
- const handlerOptions = createHandlerOptions(absoluteFile);
1212
- if (!disableJsPrecheck && shouldSkipJsTransform(rawSource, handlerOptions)) {
1283
+ await timeTask("js", async () => {
1284
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1285
+ await processCachedTask({
1286
+ cache,
1287
+ cacheKey: file,
1288
+ hashKey: `${file}:js`,
1289
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1290
+ applyResult(source) {
1291
+ originalSource.code = source;
1292
+ },
1293
+ onCacheHit() {
1294
+ metrics.js.cacheHits++;
1295
+ debug("js cache hit: %s", file);
1296
+ },
1297
+ async transform() {
1298
+ const start = performance.now();
1299
+ const rawSource = originalSource.code;
1300
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1301
+ const handlerOptions = createHandlerOptions(absoluteFile);
1302
+ if (!disableJsPrecheck && shouldSkipJsTransform(rawSource, handlerOptions)) {
1303
+ metrics.js.elapsed += measureElapsed(start);
1304
+ metrics.js.transformed++;
1305
+ return { result: rawSource };
1306
+ }
1307
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1213
1308
  metrics.js.elapsed += measureElapsed(start);
1214
1309
  metrics.js.transformed++;
1215
- return { result: rawSource };
1216
- }
1217
- const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1218
- metrics.js.elapsed += measureElapsed(start);
1219
- metrics.js.transformed++;
1220
- onUpdate(file, rawSource, code);
1221
- debug("js handle: %s", file);
1222
- if (linked) for (const id of Object.keys(linked)) {
1223
- const linkedEntry = getJsEntry(id);
1224
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1310
+ onUpdate(file, rawSource, code);
1311
+ debug("js handle: %s", file);
1312
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1313
+ applyLinkedUpdates(linked);
1314
+ return { result: code };
1225
1315
  }
1226
- applyLinkedUpdates(linked);
1227
- return { result: code };
1228
- }
1316
+ });
1229
1317
  });
1230
1318
  });
1231
1319
  } else if (uniAppX && originalSource.type === "asset") {
@@ -1233,10 +1321,7 @@ function createGenerateBundleHook(context) {
1233
1321
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1234
1322
  const baseApplyLinkedUpdates = applyLinkedUpdates;
1235
1323
  const wrappedApplyLinkedUpdates = (linked) => {
1236
- if (linked) for (const id of Object.keys(linked)) {
1237
- const linkedEntry = getJsEntry(id);
1238
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1239
- }
1324
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1240
1325
  baseApplyLinkedUpdates(linked);
1241
1326
  };
1242
1327
  const factory = createUniAppXAssetTask(file, originalSource, outDir, {
@@ -1247,247 +1332,190 @@ function createGenerateBundleHook(context) {
1247
1332
  debug,
1248
1333
  jsHandler,
1249
1334
  onUpdate,
1250
- runtimeSet: runtime,
1335
+ runtimeSet: transformRuntime,
1251
1336
  applyLinkedResults: wrappedApplyLinkedUpdates,
1252
1337
  uniAppX
1253
1338
  });
1254
1339
  jsTaskFactories.push(async () => {
1255
- const start = performance.now();
1256
- if (!shouldTransformJs) {
1257
- debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1340
+ await timeTask("js", async () => {
1341
+ const start = performance.now();
1342
+ if (!shouldTransformJs) {
1343
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1344
+ await factory();
1345
+ metrics.js.elapsed += measureElapsed(start);
1346
+ metrics.js.transformed++;
1347
+ return;
1348
+ }
1349
+ const currentSource = originalEntrySource;
1350
+ const precheckOptions = createHandlerOptions(path.resolve(outDir, file), {
1351
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1352
+ babelParserOptions: {
1353
+ plugins: ["typescript"],
1354
+ sourceType: "unambiguous"
1355
+ }
1356
+ });
1357
+ if (!disableJsPrecheck && shouldSkipJsTransform(currentSource, precheckOptions)) {
1358
+ metrics.js.elapsed += measureElapsed(start);
1359
+ metrics.js.transformed++;
1360
+ return;
1361
+ }
1258
1362
  await factory();
1259
1363
  metrics.js.elapsed += measureElapsed(start);
1260
1364
  metrics.js.transformed++;
1261
- return;
1262
- }
1263
- const currentSource = originalEntrySource;
1264
- const precheckOptions = createHandlerOptions(path.resolve(outDir, file), {
1265
- uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1266
- babelParserOptions: {
1267
- plugins: ["typescript"],
1268
- sourceType: "unambiguous"
1269
- }
1270
1365
  });
1271
- if (!disableJsPrecheck && shouldSkipJsTransform(currentSource, precheckOptions)) {
1272
- metrics.js.elapsed += measureElapsed(start);
1273
- metrics.js.transformed++;
1274
- return;
1275
- }
1276
- await factory();
1277
- metrics.js.elapsed += measureElapsed(start);
1278
- metrics.js.transformed++;
1279
1366
  });
1280
1367
  }
1281
1368
  }
1282
1369
  const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1283
- if (useIncrementalMode && generatorOptions.mode === "force") for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1370
+ if (useIncrementalMode) for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1284
1371
  if (bundleFiles.includes(file) || getRememberedMainCssSignature?.(file) === cssRuntimeSignature) continue;
1285
- tasks.push((async () => {
1372
+ const outputFile = resolveReplayCssOutputFile(rootDir, file);
1373
+ tasks.push(timeTask("css.replay", async () => {
1286
1374
  const start = performance.now();
1287
- const cssHandlerOptions = getCssHandlerOptions(file);
1375
+ const cssHandlerOptions = getCssHandlerOptions(outputFile);
1288
1376
  const generated = await generateCssByGenerator({
1289
1377
  opts,
1290
1378
  runtimeState,
1291
1379
  runtime: generatorRuntime,
1292
1380
  rawSource,
1293
- file,
1381
+ file: outputFile,
1294
1382
  cssHandlerOptions,
1295
- cssUserHandlerOptions: getCssUserHandlerOptions(file),
1383
+ cssUserHandlerOptions: getCssUserHandlerOptions(outputFile),
1384
+ getSourceCandidatesForEntries,
1296
1385
  styleHandler,
1297
1386
  debug
1298
1387
  });
1299
1388
  const css = generated?.css ?? (await styleHandler(rawSource, cssHandlerOptions)).css;
1300
1389
  setRememberedMainCssSignature?.(file, cssRuntimeSignature);
1301
1390
  if (generated) {
1302
- recordCssAssetResult?.(file, generated.css);
1303
- debug("css replay generated result: %s bytes=%d", file, css.length);
1391
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
1392
+ recordCssAssetResult?.(outputFile, generated.css);
1393
+ debug("css replay generated result: %s bytes=%d", outputFile, css.length);
1304
1394
  }
1305
- const replayAsset = createReplayCssAsset(file, css);
1395
+ const replayAsset = createReplayCssAsset(outputFile, css);
1306
1396
  if (typeof this.emitFile === "function") this.emitFile({
1307
1397
  type: "asset",
1308
- fileName: file,
1398
+ fileName: outputFile,
1309
1399
  source: css
1310
1400
  });
1311
- else bundle[file] = replayAsset;
1312
- markCssAssetProcessed?.(replayAsset, file);
1401
+ else bundle[outputFile] = replayAsset;
1402
+ markCssAssetProcessed?.(replayAsset, outputFile);
1313
1403
  metrics.css.elapsed += measureElapsed(start);
1314
1404
  metrics.css.transformed++;
1315
- onUpdate(file, rawSource, css);
1316
- debug("css replay handle: %s", file);
1317
- })());
1405
+ onUpdate(outputFile, rawSource, css);
1406
+ debug("css replay handle: %s", outputFile);
1407
+ }));
1318
1408
  }
1319
1409
  pushConcurrentTaskFactories(tasks, jsTaskFactories);
1410
+ const tasksStart = performance.now();
1320
1411
  await Promise.all(tasks);
1412
+ recordTimingDetail("tasks", tasksStart);
1321
1413
  for (const apply of pendingLinkedUpdates) apply();
1414
+ injectViteProcessedCssIntoMainCssAssets(bundle, {
1415
+ opts,
1416
+ getViteProcessedCssAssetResults,
1417
+ markCssAssetProcessed,
1418
+ recordCssAssetResult,
1419
+ debug,
1420
+ onUpdate
1421
+ });
1422
+ const stateUpdateStart = performance.now();
1322
1423
  updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1424
+ state.generatorCandidateSignature = generatorCandidateSignature;
1425
+ recordTimingDetail("state.update", stateUpdateStart);
1323
1426
  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));
1427
+ if (hmrTimingRecorder) {
1428
+ hmrTimingRecorder.record("generateBundle", performance.now() - hmrTimingStartedAt, timingDetails);
1429
+ hmrTimingRecorder.emitTotal();
1430
+ }
1324
1431
  onEnd();
1325
1432
  debug("end");
1326
1433
  };
1327
1434
  }
1328
1435
  //#endregion
1329
- //#region src/bundlers/vite/incremental-runtime-class-set.ts
1330
- const debug$1 = createDebug("[vite:runtime-set] ");
1331
- const EXTENSION_DOT_PREFIX_RE = /^\./;
1332
- function createExtractOptions(context, source) {
1333
- return {
1334
- cwd: context.projectRoot,
1335
- base: context.base,
1336
- baseFallbacks: context.baseFallbacks,
1337
- css: context.css,
1338
- content: source,
1339
- extension: "html"
1340
- };
1341
- }
1342
- function createRuntimeEntries(snapshot) {
1343
- return snapshot.entries.filter((entry) => entry.type === "html" || entry.type === "js");
1436
+ //#region src/bundlers/vite/official-tailwind-plugins.ts
1437
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1438
+ function getPostcssPluginName(plugin) {
1439
+ if (!plugin) return;
1440
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1441
+ return getPostcssPluginName(plugin());
1442
+ } catch {
1443
+ return;
1444
+ }
1445
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1446
+ const { postcssPlugin } = plugin;
1447
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1344
1448
  }
1345
- function collectChangedRuntimeFiles(snapshot) {
1346
- return new Set([...snapshot.runtimeAffectingChangedByType.html, ...snapshot.runtimeAffectingChangedByType.js]);
1449
+ function isTailwindPostcssPlugin(plugin) {
1450
+ const name = getPostcssPluginName(plugin);
1451
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1347
1452
  }
1348
- function resolveEntryExtension(entry) {
1349
- const ext = entry.file.split(/[?#]/, 1)[0]?.split(".").pop()?.replace(EXTENSION_DOT_PREFIX_RE, "") ?? "";
1350
- if (ext.length > 0) return ext;
1351
- return entry.type === "html" ? "html" : "js";
1453
+ function removeTailwindPostcssPlugins(plugins) {
1454
+ let removed = 0;
1455
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1456
+ plugins.splice(i, 1);
1457
+ removed++;
1458
+ }
1459
+ return removed;
1352
1460
  }
1353
- function createCandidateValidationSource(candidates) {
1354
- return [...new Set(candidates)].sort().join("\n");
1461
+ function isTailwindVitePlugin(plugin) {
1462
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1463
+ const { name } = plugin;
1464
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1355
1465
  }
1356
- function removeCandidateSet$1(candidateCountByClass, runtimeSet, candidates) {
1357
- for (const className of candidates) {
1358
- const count = candidateCountByClass.get(className);
1359
- if (count == null) continue;
1360
- if (count <= 1) {
1361
- candidateCountByClass.delete(className);
1362
- runtimeSet.delete(className);
1363
- continue;
1364
- }
1365
- candidateCountByClass.set(className, count - 1);
1466
+ function removeTailwindVitePlugins(plugins) {
1467
+ let removed = 0;
1468
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1469
+ plugins.splice(i, 1);
1470
+ removed++;
1366
1471
  }
1472
+ return removed;
1367
1473
  }
1368
- function addCandidateSet$1(candidateCountByClass, runtimeSet, candidates) {
1369
- for (const className of candidates) {
1370
- const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
1371
- candidateCountByClass.set(className, nextCount);
1372
- runtimeSet.add(className);
1373
- }
1474
+ function disableTailwindVitePlugin(plugin) {
1475
+ if (!isTailwindVitePlugin(plugin)) return false;
1476
+ const mutablePlugin = plugin;
1477
+ for (const hook of [
1478
+ "configResolved",
1479
+ "configureServer",
1480
+ "transform",
1481
+ "hotUpdate",
1482
+ "handleHotUpdate"
1483
+ ]) delete mutablePlugin[hook];
1484
+ return true;
1374
1485
  }
1375
- function createBundleRuntimeClassSetManager(options = {}) {
1376
- const customExtractCandidates = options.extractCandidates;
1377
- const extractCandidates = customExtractCandidates ?? extractValidCandidates;
1378
- const extractRawCandidates = options.extractRawCandidates ?? extractRawCandidatesWithPositions;
1379
- const runtimeSet = /* @__PURE__ */ new Set();
1380
- const candidateCountByClass = /* @__PURE__ */ new Map();
1381
- const candidatesByFile = /* @__PURE__ */ new Map();
1382
- const candidateValidityCache = /* @__PURE__ */ new Map();
1383
- let runtimeSignature;
1384
- let validationContext;
1385
- let designSystemPromise;
1386
- async function reset() {
1387
- runtimeSet.clear();
1388
- candidateCountByClass.clear();
1389
- candidatesByFile.clear();
1390
- candidateValidityCache.clear();
1391
- runtimeSignature = void 0;
1392
- validationContext = void 0;
1393
- designSystemPromise = void 0;
1394
- }
1395
- async function resolveValidationContextCached(patcher) {
1396
- if (!validationContext) validationContext = await resolveTailwindV4SourceFromPatcher(patcher);
1397
- return validationContext;
1398
- }
1399
- async function loadDesignSystem(context) {
1400
- if (!designSystemPromise) designSystemPromise = loadTailwindV4DesignSystem(context);
1401
- return designSystemPromise;
1402
- }
1403
- function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
1404
- const parsedCandidates = [...unknownCandidates].filter((candidate) => designSystem.parseCandidate(candidate).length > 0);
1405
- const cssByCandidate = parsedCandidates.length > 0 ? designSystem.candidatesToCss(parsedCandidates) : [];
1406
- const validCandidates = /* @__PURE__ */ new Set();
1407
- for (let index = 0; index < parsedCandidates.length; index += 1) {
1408
- const candidate = parsedCandidates[index];
1409
- const css = cssByCandidate[index];
1410
- if (candidate && typeof css === "string" && css.trim().length > 0) validCandidates.add(candidate);
1411
- }
1412
- for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1413
- }
1414
- async function validateUnknownCandidates(patcher, unknownCandidates) {
1415
- if (unknownCandidates.size === 0) return;
1416
- const context = await resolveValidationContextCached(patcher);
1417
- if (!customExtractCandidates) try {
1418
- populateCandidateValidityCacheFromDesignSystem(await loadDesignSystem(context), unknownCandidates);
1419
- return;
1420
- } catch (error) {
1421
- debug$1("incremental design-system validation failed: %O", error);
1422
- designSystemPromise = void 0;
1423
- throw error;
1486
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1487
+ let removed = 0;
1488
+ for (let i = plugins.length - 1; i >= 0; i--) {
1489
+ const plugin = plugins[i];
1490
+ if (Array.isArray(plugin)) {
1491
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1492
+ if (plugin.length === 0) plugins.splice(i, 1);
1493
+ continue;
1424
1494
  }
1425
- const source = createCandidateValidationSource(unknownCandidates);
1426
- const validCandidates = new Set(await extractCandidates(createExtractOptions(context, source)));
1427
- for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
1428
- }
1429
- async function extractEntryRawCandidates(entry) {
1430
- const matches = await extractRawCandidates(entry.source, resolveEntryExtension(entry));
1431
- const candidates = /* @__PURE__ */ new Set();
1432
- for (const match of matches) {
1433
- const candidate = match?.rawCandidate;
1434
- if (typeof candidate === "string" && candidate.length > 0) candidates.add(candidate);
1495
+ if (disableTailwindVitePlugin(plugin)) {
1496
+ plugins.splice(i, 1);
1497
+ removed++;
1435
1498
  }
1436
- return candidates;
1437
1499
  }
1438
- async function sync(patcher, snapshot) {
1439
- const nextSignature = getRuntimeClassSetSignature(patcher) ?? "runtime:missing";
1440
- const runtimeEntries = createRuntimeEntries(snapshot);
1441
- const runtimeEntriesByFile = new Map(runtimeEntries.map((entry) => [entry.file, entry]));
1442
- const currentRuntimeFiles = new Set(runtimeEntriesByFile.keys());
1443
- const fullRebuild = runtimeSignature !== nextSignature || candidatesByFile.size === 0;
1444
- if (runtimeSignature !== nextSignature) {
1445
- debug$1("runtime signature changed, reset incremental runtime set: %s", nextSignature);
1446
- await reset();
1447
- }
1448
- runtimeSignature = nextSignature;
1449
- for (const [file, previousCandidates] of candidatesByFile) {
1450
- if (currentRuntimeFiles.has(file)) continue;
1451
- removeCandidateSet$1(candidateCountByClass, runtimeSet, previousCandidates);
1452
- candidatesByFile.delete(file);
1453
- }
1454
- const changedRuntimeFiles = fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
1455
- if (changedRuntimeFiles.length === 0) return new Set(runtimeSet);
1456
- const rawCandidatesByFile = /* @__PURE__ */ new Map();
1457
- const unknownCandidates = /* @__PURE__ */ new Set();
1458
- await Promise.all(changedRuntimeFiles.map(async (file) => {
1459
- const entry = runtimeEntriesByFile.get(file);
1460
- if (!entry) return;
1461
- const candidates = await extractEntryRawCandidates(entry);
1462
- rawCandidatesByFile.set(file, candidates);
1463
- for (const candidate of candidates) if (!candidateValidityCache.has(candidate)) unknownCandidates.add(candidate);
1464
- }));
1465
- await validateUnknownCandidates(patcher, unknownCandidates);
1466
- let rawCandidateCount = 0;
1467
- for (const file of changedRuntimeFiles) {
1468
- const nextRawCandidates = rawCandidatesByFile.get(file);
1469
- const previousCandidates = candidatesByFile.get(file);
1470
- if (previousCandidates) removeCandidateSet$1(candidateCountByClass, runtimeSet, previousCandidates);
1471
- if (!nextRawCandidates || nextRawCandidates.size === 0) {
1472
- candidatesByFile.delete(file);
1473
- continue;
1474
- }
1475
- rawCandidateCount += nextRawCandidates.size;
1476
- const nextCandidates = new Set([...nextRawCandidates].filter((candidate) => candidateValidityCache.get(candidate) === true));
1477
- if (nextCandidates.size === 0) {
1478
- candidatesByFile.delete(file);
1479
- continue;
1480
- }
1481
- addCandidateSet$1(candidateCountByClass, runtimeSet, nextCandidates);
1482
- candidatesByFile.set(file, nextCandidates);
1483
- }
1484
- debug$1("incremental runtime set synced, changedFiles=%d rawCandidates=%d validateMisses=%d runtimeSize=%d trackedFiles=%d", changedRuntimeFiles.length, rawCandidateCount, unknownCandidates.size, runtimeSet.size, candidatesByFile.size);
1485
- return new Set(runtimeSet);
1500
+ return removed;
1501
+ }
1502
+ //#endregion
1503
+ //#region src/bundlers/vite/postcss-config.ts
1504
+ async function resolveFilteredPostcssConfig(root) {
1505
+ try {
1506
+ const loaded = await postcssrc({}, root);
1507
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1508
+ const removed = removeTailwindPostcssPlugins(plugins);
1509
+ if (removed === 0) return;
1510
+ return {
1511
+ options: loaded.options,
1512
+ plugins,
1513
+ removed
1514
+ };
1515
+ } catch (error) {
1516
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1517
+ throw error;
1486
1518
  }
1487
- return {
1488
- sync,
1489
- reset
1490
- };
1491
1519
  }
1492
1520
  //#endregion
1493
1521
  //#region src/bundlers/vite/resolve-app-type.ts
@@ -1551,6 +1579,34 @@ function resolveImplicitAppTypeFromViteRoot(root) {
1551
1579
  }
1552
1580
  }
1553
1581
  //#endregion
1582
+ //#region src/bundlers/shared/css-imports.ts
1583
+ const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
1584
+ const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1585
+ function normalizeTailwindcssSpecifier(specifier) {
1586
+ if (specifier === "tailwindcss$" || specifier === "weapp-tailwindcss$") return specifier.slice(0, -1);
1587
+ return specifier;
1588
+ }
1589
+ function getTailwindcssSubpath(specifier) {
1590
+ if (specifier === "tailwindcss" || specifier === "weapp-tailwindcss") return "index.css";
1591
+ return specifier.replace(/^(?:tailwindcss|weapp-tailwindcss)\//, "");
1592
+ }
1593
+ function resolveTailwindcssImport(specifier, pkgDir, options) {
1594
+ const normalized = normalizeTailwindcssSpecifier(specifier);
1595
+ if (!tailwindcssImportRE.test(normalized)) return null;
1596
+ if (normalized === "tailwindcss" || normalized === "weapp-tailwindcss") return options?.rootImport ?? (options?.join ?? path.join)(pkgDir, "index.css");
1597
+ return (options?.join ?? path.join)(pkgDir, getTailwindcssSubpath(normalized));
1598
+ }
1599
+ function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1600
+ let hasReplacements = false;
1601
+ const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1602
+ const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1603
+ if (!replacement) return full;
1604
+ hasReplacements = true;
1605
+ return `${prefix}${quote}${replacement}${suffix}`;
1606
+ });
1607
+ return hasReplacements ? rewritten : void 0;
1608
+ }
1609
+ //#endregion
1554
1610
  //#region src/bundlers/vite/rewrite-css-imports.ts
1555
1611
  function joinPosixPath(base, subpath) {
1556
1612
  if (base.endsWith("/")) return `${base}${subpath}`;
@@ -1558,350 +1614,69 @@ function joinPosixPath(base, subpath) {
1558
1614
  }
1559
1615
  function isCssLikeImporter(importer) {
1560
1616
  if (!importer) return false;
1561
- const normalized = cleanUrl$1(importer);
1562
- return isCSSRequest(normalized) || normalized.endsWith("/*");
1617
+ const normalized = cleanUrl(importer);
1618
+ return isSourceStyleRequest(importer) || isCSSRequest(normalized) || normalized.endsWith("/*");
1619
+ }
1620
+ function stripTailwindConfigDirectives(code) {
1621
+ return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1563
1622
  }
1564
1623
  function createRewriteCssImportsPlugins(options) {
1565
1624
  if (!options.shouldRewrite) return [];
1566
- const { appType, getAppType, rootImport, weappTailwindcssDirPosix } = options;
1625
+ const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1567
1626
  const resolveAppType = () => getAppType?.() ?? appType;
1568
1627
  return [{
1569
1628
  name: `${vitePluginName}:rewrite-css-imports`,
1570
1629
  enforce: "pre",
1571
- resolveId: {
1572
- order: "pre",
1573
- handler(id, importer) {
1574
- const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1575
- join: joinPosixPath,
1576
- appType: resolveAppType(),
1577
- rootImport
1578
- });
1579
- if (!replacement) return null;
1580
- if (importer && !isCssLikeImporter(importer)) return null;
1581
- return replacement;
1582
- }
1630
+ resolveId(id, importer) {
1631
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1632
+ join: joinPosixPath,
1633
+ appType: resolveAppType(),
1634
+ rootImport
1635
+ });
1636
+ if (!replacement) return null;
1637
+ if (importer && !isCssLikeImporter(importer)) return null;
1638
+ return replacement;
1583
1639
  },
1584
- transform: {
1585
- order: "pre",
1586
- handler(code, id) {
1587
- if (!isCSSRequest(id)) return null;
1588
- const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1589
- join: joinPosixPath,
1590
- appType: resolveAppType(),
1591
- rootImport
1592
- });
1593
- if (!rewritten) return null;
1594
- return {
1595
- code: rewritten,
1596
- map: null
1597
- };
1640
+ async transform(code, id) {
1641
+ if (!isCSSRequest(id)) return null;
1642
+ if (hasTailwindRootDirectives(code)) {
1643
+ await options.onTailwindRootCss?.(id, code);
1644
+ if (options.shouldOwnTailwindGeneration) {
1645
+ const generatedCss = await options.generateTailwindCss?.(id, code, this);
1646
+ if (generatedCss !== void 0) return {
1647
+ code: generatedCss,
1648
+ map: null
1649
+ };
1650
+ }
1598
1651
  }
1652
+ const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1653
+ join: joinPosixPath,
1654
+ appType: resolveAppType(),
1655
+ rootImport
1656
+ });
1657
+ const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1658
+ if (!nextCode || nextCode === code) return null;
1659
+ return {
1660
+ code: nextCode,
1661
+ map: null
1662
+ };
1599
1663
  }
1600
1664
  }];
1601
1665
  }
1602
1666
  //#endregion
1603
- //#region src/bundlers/vite/source-candidates.ts
1604
- const CLEAN_URL_RE = /[?#].*$/;
1605
- const SOURCE_CANDIDATE_EXTENSIONS = [
1606
- "js",
1607
- "jsx",
1608
- "mjs",
1609
- "cjs",
1610
- "ts",
1611
- "tsx",
1612
- "mts",
1613
- "cts",
1614
- "vue",
1615
- "uvue",
1616
- "nvue",
1617
- "svelte",
1618
- "mpx",
1619
- "html",
1620
- "wxml",
1621
- "axml",
1622
- "jxml",
1623
- "ksml",
1624
- "ttml",
1625
- "qml",
1626
- "tyml",
1627
- "xhsml",
1628
- "swan",
1629
- "css",
1630
- "wxss",
1631
- "acss",
1632
- "jxss",
1633
- "ttss",
1634
- "qss",
1635
- "tyss",
1636
- "scss",
1637
- "sass",
1638
- "less",
1639
- "styl",
1640
- "stylus"
1641
- ];
1642
- const SOURCE_CANDIDATE_EXTENSION_RE = /\.(?:[cm]?[jt]sx?|vue|uvue|nvue|svelte|mpx|html|wxml|axml|jxml|ksml|ttml|qml|tyml|xhsml|swan|css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|stylus?)$/;
1643
- const CSS_SOURCE_CANDIDATE_EXTENSION_RE = /^(?:css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|styl|stylus)$/;
1644
- const SOURCE_CANDIDATE_GLOB = `**/*.{${SOURCE_CANDIDATE_EXTENSIONS.join(",")}}`;
1645
- const DEFAULT_SCAN_IGNORE = ["**/node_modules/**", "**/.git/**"];
1646
- function cleanUrl(id) {
1647
- return id.replace(CLEAN_URL_RE, "");
1648
- }
1649
- function toPosixPath(value) {
1650
- return value.split(path.sep).join("/");
1651
- }
1652
- function resolveOutDirIgnorePattern(root, outDir) {
1653
- if (!outDir) return;
1654
- const relative = path.relative(root, path.resolve(root, outDir));
1655
- if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return;
1656
- return `${toPosixPath(relative)}/**`;
1657
- }
1658
- function resolveSourceCandidateExtension(id) {
1659
- const normalized = cleanUrl(id);
1660
- return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
1661
- }
1662
- function isSourceCandidateRequest(id) {
1663
- return SOURCE_CANDIDATE_EXTENSION_RE.test(cleanUrl(id));
1664
- }
1665
- function removeCandidateSet(candidateCount, candidates) {
1666
- for (const candidate of candidates) {
1667
- const count = candidateCount.get(candidate);
1668
- if (count == null) continue;
1669
- if (count <= 1) {
1670
- candidateCount.delete(candidate);
1671
- continue;
1672
- }
1673
- candidateCount.set(candidate, count - 1);
1674
- }
1675
- }
1676
- function addCandidateSet(candidateCount, candidates) {
1677
- for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
1678
- }
1679
- const CSS_APPLY_RE = /@apply\s+([^;{}]+)/g;
1680
- const CSS_APPLY_IMPORTANT = "!important";
1681
- function extractCssApplyCandidates(source) {
1682
- const candidates = /* @__PURE__ */ new Set();
1683
- CSS_APPLY_RE.lastIndex = 0;
1684
- let match = CSS_APPLY_RE.exec(source);
1685
- while (match !== null) {
1686
- const params = match[1] ?? "";
1687
- for (const candidate of splitCode(params, true)) {
1688
- const normalized = candidate.trim();
1689
- if (normalized && normalized !== CSS_APPLY_IMPORTANT) candidates.add(normalized);
1690
- }
1691
- match = CSS_APPLY_RE.exec(source);
1692
- }
1693
- return candidates;
1694
- }
1695
- function createSourceCandidateCollector() {
1696
- const candidatesById = /* @__PURE__ */ new Map();
1697
- const candidateCount = /* @__PURE__ */ new Map();
1698
- async function sync(id, source) {
1699
- const normalizedId = cleanUrl(id);
1700
- const extension = resolveSourceCandidateExtension(normalizedId);
1701
- const nextCandidates = /* @__PURE__ */ new Set();
1702
- if (CSS_SOURCE_CANDIDATE_EXTENSION_RE.test(extension)) for (const candidate of extractCssApplyCandidates(source)) nextCandidates.add(candidate);
1703
- else {
1704
- const matches = await extractRawCandidatesWithPositions(source, extension);
1705
- for (const match of matches) {
1706
- const candidate = match.rawCandidate;
1707
- if (typeof candidate === "string" && candidate.length > 0) nextCandidates.add(candidate);
1708
- }
1709
- }
1710
- remove(normalizedId);
1711
- if (nextCandidates.size === 0) return;
1712
- candidatesById.set(normalizedId, nextCandidates);
1713
- addCandidateSet(candidateCount, nextCandidates);
1714
- }
1715
- async function syncFile(id) {
1716
- const normalizedId = cleanUrl(id);
1717
- await sync(normalizedId, await readFile(normalizedId, "utf8"));
1718
- }
1719
- async function scanRoot({ root, outDir }) {
1720
- const resolvedRoot = path.resolve(root);
1721
- const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, outDir);
1722
- const files = await fg(SOURCE_CANDIDATE_GLOB, {
1723
- absolute: true,
1724
- cwd: resolvedRoot,
1725
- ignore: outDirIgnore ? [...DEFAULT_SCAN_IGNORE, outDirIgnore] : DEFAULT_SCAN_IGNORE,
1726
- onlyFiles: true,
1727
- unique: true
1728
- });
1729
- await Promise.all(files.map((file) => syncFile(file)));
1730
- }
1731
- function remove(id) {
1732
- const normalizedId = cleanUrl(id);
1733
- const previousCandidates = candidatesById.get(normalizedId);
1734
- if (!previousCandidates) return;
1735
- removeCandidateSet(candidateCount, previousCandidates);
1736
- candidatesById.delete(normalizedId);
1737
- }
1738
- function values() {
1739
- return new Set(candidateCount.keys());
1740
- }
1741
- function clear() {
1742
- candidatesById.clear();
1743
- candidateCount.clear();
1744
- }
1745
- return {
1746
- sync,
1747
- syncFile,
1748
- scanRoot,
1749
- remove,
1750
- values,
1751
- clear
1752
- };
1753
- }
1754
- //#endregion
1755
- //#region src/bundlers/vite/index.ts
1756
- const debug = createDebug();
1757
- const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
1758
- const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1759
- const PACKAGE_JSON_FILE = "package.json";
1760
- const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1761
- function getPostcssPluginName(plugin) {
1762
- if (!plugin) return;
1763
- if (typeof plugin === "function" && "postcss" in plugin) try {
1764
- return getPostcssPluginName(plugin());
1765
- } catch {
1766
- return;
1767
- }
1768
- if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1769
- const { postcssPlugin } = plugin;
1770
- return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1771
- }
1772
- function isTailwindPostcssPlugin(plugin) {
1773
- const name = getPostcssPluginName(plugin);
1774
- return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1775
- }
1776
- function removeTailwindPostcssPlugins(plugins) {
1777
- let removed = 0;
1778
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1779
- plugins.splice(i, 1);
1780
- removed++;
1781
- }
1782
- return removed;
1783
- }
1784
- async function resolveFilteredPostcssConfig(root) {
1785
- try {
1786
- const loaded = await postcssrc({}, root);
1787
- const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1788
- const removed = removeTailwindPostcssPlugins(plugins);
1789
- if (removed === 0) return;
1790
- return {
1791
- options: loaded.options,
1792
- plugins,
1793
- removed
1794
- };
1795
- } catch (error) {
1796
- if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1797
- throw error;
1798
- }
1799
- }
1800
- function isTailwindVitePlugin(plugin) {
1801
- if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1802
- const { name } = plugin;
1803
- return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1804
- }
1805
- function removeTailwindVitePlugins(plugins) {
1806
- let removed = 0;
1807
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1808
- plugins.splice(i, 1);
1809
- removed++;
1810
- }
1811
- return removed;
1812
- }
1813
- function disableTailwindVitePlugin(plugin) {
1814
- if (!isTailwindVitePlugin(plugin)) return false;
1815
- const mutablePlugin = plugin;
1816
- for (const hook of [
1817
- "configResolved",
1818
- "configureServer",
1819
- "transform",
1820
- "hotUpdate",
1821
- "handleHotUpdate"
1822
- ]) delete mutablePlugin[hook];
1823
- return true;
1824
- }
1825
- function disableAndRemoveTailwindVitePlugins(plugins) {
1826
- let removed = 0;
1827
- for (let i = plugins.length - 1; i >= 0; i--) {
1828
- const plugin = plugins[i];
1829
- if (Array.isArray(plugin)) {
1830
- removed += disableAndRemoveTailwindVitePlugins(plugin);
1831
- if (plugin.length === 0) plugins.splice(i, 1);
1832
- continue;
1833
- }
1834
- if (disableTailwindVitePlugin(plugin)) {
1835
- plugins.splice(i, 1);
1836
- removed++;
1837
- }
1838
- }
1839
- return removed;
1840
- }
1841
- function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1842
- const resolvedRoot = path.resolve(root);
1843
- if (!existsSync(resolvedRoot)) return resolvedRoot;
1844
- const searchRoots = [];
1845
- let current = resolvedRoot;
1846
- while (true) {
1847
- searchRoots.push(current);
1848
- const parent = path.dirname(current);
1849
- if (parent === current) break;
1850
- current = parent;
1851
- }
1852
- const tailwindConfigPath = findTailwindConfig(searchRoots);
1853
- if (tailwindConfigPath) return path.dirname(tailwindConfigPath);
1854
- const packageRoot = findNearestPackageRoot(resolvedRoot);
1855
- if (packageRoot && existsSync(path.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1856
- return resolvedRoot;
1857
- }
1858
- /**
1859
- * @name UnifiedViteWeappTailwindcssPlugin
1860
- * @description uni-app vite / uni-app-x 版本插件
1861
- * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1862
- */
1863
- function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1864
- const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1865
- const rewriteCssImportsSpecified = Object.hasOwn(options, "rewriteCssImports");
1866
- const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1867
- const opts = getCompilerContext(options);
1868
- const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1869
- const uniAppXEnabled = isUniAppXEnabled(uniAppX);
1870
- const disabledOptions = resolveDisabledOptions(disabled);
1871
- const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1872
- const shouldOwnTailwindGeneration = normalizeWeappTailwindcssGeneratorOptions(opts.generator).mode === "force";
1873
- const shouldRewriteCssImports = opts.rewriteCssImports !== false && !disabledOptions.rewriteCssImports && (rewriteCssImportsSpecified || tailwindcssMajorVersion >= 4);
1874
- const rewritePlugins = createRewriteCssImportsPlugins({
1875
- getAppType: () => opts.appType,
1876
- rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
1877
- shouldRewrite: shouldRewriteCssImports,
1878
- weappTailwindcssDirPosix
1879
- });
1880
- if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1881
- const customAttributesEntities = toCustomAttributesEntities(customAttributes);
1882
- const patchRecorderState = setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1883
- source: "runtime",
1884
- cwd: opts.tailwindcssBasedir ?? process.cwd()
1885
- });
1667
+ //#region src/bundlers/vite/runtime-class-set.ts
1668
+ function createViteRuntimeClassSet(options) {
1669
+ const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
1886
1670
  const runtimeState = {
1887
1671
  twPatcher: initialTwPatcher,
1888
- patchPromise: patchRecorderState.patchPromise,
1889
- refreshTailwindcssPatcher,
1890
- onPatchCompleted: patchRecorderState.onPatchCompleted
1672
+ readyPromise: createTailwindRuntimeReadyPromise(initialTwPatcher),
1673
+ refreshTailwindcssPatcher
1891
1674
  };
1675
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1892
1676
  let runtimeSet;
1893
1677
  let runtimeSetPromise;
1894
- let resolvedConfig;
1895
1678
  let runtimeRefreshSignature;
1896
1679
  let runtimeRefreshOptionsKey;
1897
- let recordedGeneratorCandidates;
1898
- const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1899
- const sourceCandidateCollector = createSourceCandidateCollector();
1900
- const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1901
- const processedCssAssets = /* @__PURE__ */ new WeakSet();
1902
- const processedCssAssetFiles = /* @__PURE__ */ new Set();
1903
- const rememberedMainCssSources = /* @__PURE__ */ new Map();
1904
- const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
1905
1680
  function resolveRuntimeRefreshOptions() {
1906
1681
  const configPath = resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1907
1682
  const signature = getRuntimeClassSetSignature(runtimeState.twPatcher);
@@ -1910,8 +1685,7 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1910
1685
  uniAppX: uniAppXEnabled,
1911
1686
  customAttributesEntities,
1912
1687
  disabledDefaultTemplateHandler,
1913
- configPath,
1914
- rewriteCssImports: shouldRewriteCssImports
1688
+ configPath
1915
1689
  });
1916
1690
  const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1917
1691
  runtimeRefreshSignature = signature;
@@ -1935,9 +1709,9 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1935
1709
  }
1936
1710
  }
1937
1711
  async function ensureRuntimeClassSet(force = false) {
1938
- const forceRuntimeRefresh = force || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1712
+ const forceRuntimeRefresh = force || process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1939
1713
  await refreshRuntimeState(force);
1940
- await runtimeState.patchPromise;
1714
+ await runtimeState.readyPromise;
1941
1715
  if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1942
1716
  if (forceRuntimeRefresh || !runtimeSetPromise) {
1943
1717
  const invalidation = resolveRuntimeRefreshOptions();
@@ -1955,13 +1729,13 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1955
1729
  if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1956
1730
  }
1957
1731
  }
1958
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1959
- const forceRuntimeRefresh = forceRefresh || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1732
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, options = {}) {
1733
+ const forceRuntimeRefresh = forceRefresh || process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1960
1734
  const invalidation = resolveRuntimeRefreshOptions();
1961
1735
  const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1962
1736
  const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1963
1737
  await refreshRuntimeState(shouldRefreshPatcher);
1964
- await runtimeState.patchPromise;
1738
+ await runtimeState.readyPromise;
1965
1739
  if (shouldRefreshPatcher) {
1966
1740
  runtimeSet = void 0;
1967
1741
  runtimeSetPromise = void 0;
@@ -1975,6 +1749,23 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1975
1749
  debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1976
1750
  await bundleRuntimeClassSetManager.reset();
1977
1751
  }
1752
+ if (runtimeState.twPatcher.majorVersion === 3 && !forceRuntimeRefresh) try {
1753
+ let baseClassSet = options.baseClassSet;
1754
+ if (!baseClassSet && (!runtimeSet || shouldRefreshPatcher)) baseClassSet = await collectRuntimeClassSet(runtimeState.twPatcher, {
1755
+ force: true,
1756
+ skipRefresh: shouldRefreshPatcher,
1757
+ clearCache: shouldRefreshPatcher
1758
+ });
1759
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot, {
1760
+ baseClassSet: baseClassSet ?? (options.allowBaselineOnlyInitialSync === true ? runtimeSet : void 0),
1761
+ skipInitialFullScanWithBase: options.allowBaselineOnlyInitialSync === true && Boolean(runtimeSet)
1762
+ });
1763
+ runtimeSet = nextRuntimeSet;
1764
+ return nextRuntimeSet;
1765
+ } catch (error) {
1766
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1767
+ await bundleRuntimeClassSetManager.reset();
1768
+ }
1978
1769
  if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1979
1770
  const task = collectRuntimeClassSet(runtimeState.twPatcher, {
1980
1771
  force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
@@ -1989,6 +1780,170 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1989
1780
  if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1990
1781
  }
1991
1782
  }
1783
+ return {
1784
+ runtimeState,
1785
+ refreshRuntimeState,
1786
+ ensureRuntimeClassSet,
1787
+ ensureBundleRuntimeClassSet
1788
+ };
1789
+ }
1790
+ //#endregion
1791
+ //#region src/bundlers/vite/tailwind-basedir.ts
1792
+ const PACKAGE_JSON_FILE = "package.json";
1793
+ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1794
+ const resolvedRoot = path.resolve(root);
1795
+ if (!existsSync(resolvedRoot)) return resolvedRoot;
1796
+ const searchRoots = [];
1797
+ let current = resolvedRoot;
1798
+ while (true) {
1799
+ searchRoots.push(current);
1800
+ const parent = path.dirname(current);
1801
+ if (parent === current) break;
1802
+ current = parent;
1803
+ }
1804
+ const tailwindConfigPath = findTailwindConfig(searchRoots);
1805
+ if (tailwindConfigPath) return path.dirname(tailwindConfigPath);
1806
+ const packageRoot = findNearestPackageRoot(resolvedRoot);
1807
+ if (packageRoot && existsSync(path.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1808
+ return resolvedRoot;
1809
+ }
1810
+ //#endregion
1811
+ //#region src/bundlers/vite/index.ts
1812
+ const debug = createDebug();
1813
+ const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
1814
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1815
+ const sourceCandidateScanSnapshotCache = /* @__PURE__ */ new Map();
1816
+ function normalizeSignaturePath(value) {
1817
+ return slash(path.resolve(value));
1818
+ }
1819
+ function serializeInlineCandidates(inlineCandidates) {
1820
+ return {
1821
+ excluded: [...inlineCandidates?.excluded ?? []].sort(),
1822
+ included: [...inlineCandidates?.included ?? []].sort()
1823
+ };
1824
+ }
1825
+ function serializeSourceEntries(entries) {
1826
+ return (entries ?? []).map((entry) => ({
1827
+ base: normalizeSignaturePath(entry.base),
1828
+ negated: entry.negated,
1829
+ pattern: entry.pattern
1830
+ })).sort((a, b) => `${a.base}\0${a.pattern}\0${a.negated}`.localeCompare(`${b.base}\0${b.pattern}\0${b.negated}`));
1831
+ }
1832
+ function createSourceCandidateScanSignature(input) {
1833
+ return JSON.stringify({
1834
+ inlineCandidates: serializeInlineCandidates(input.inlineCandidates),
1835
+ outDir: input.outDir ? normalizeSignaturePath(input.outDir) : void 0,
1836
+ roots: input.roots.map((root) => ({
1837
+ entries: serializeSourceEntries(root.entries),
1838
+ root: normalizeSignaturePath(root.root)
1839
+ })),
1840
+ scanAllSources: input.scanAllSources ?? false
1841
+ });
1842
+ }
1843
+ /**
1844
+ * @name WeappTailwindcss
1845
+ * @description uni-app vite / uni-app-x 版本插件
1846
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
1847
+ */
1848
+ function WeappTailwindcss(options = {}) {
1849
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1850
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1851
+ const opts = getCompilerContext({
1852
+ ...options,
1853
+ __internalDeferMissingCssEntriesWarning: true
1854
+ });
1855
+ const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1856
+ const uniAppXEnabled = isUniAppXEnabled(uniAppX);
1857
+ const disabledOptions = resolvePluginDisabledState(disabled);
1858
+ const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1859
+ const shouldOwnTailwindGeneration = !disabledOptions.plugin;
1860
+ const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
1861
+ const shouldInferAppType = !hasExplicitAppType && opts.generator?.target !== "web";
1862
+ const hasInitialTailwindCssRoots = hasConfiguredTailwindV4CssRoots({
1863
+ ...options,
1864
+ cssEntries: opts.cssEntries ?? options.cssEntries
1865
+ });
1866
+ const autoCssSourceContent = /* @__PURE__ */ new Map();
1867
+ let refreshRuntimeStateForAutoCssSources;
1868
+ let autoCssSourcesRefresh;
1869
+ let autoCssSourcesDiscovered = false;
1870
+ const registerAutoCssSource = async (id, css, options = {}) => {
1871
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
1872
+ const file = cleanUrl(id);
1873
+ if (!path.isAbsolute(file)) return;
1874
+ const sourceFile = path.normalize(file);
1875
+ const sourceCss = normalizeTailwindSourceForGenerator(css, { importFallback: true });
1876
+ if (autoCssSourceContent.get(sourceFile) === sourceCss) return;
1877
+ autoCssSourceContent.set(sourceFile, sourceCss);
1878
+ const dependencies = await resolveViteTailwindV4CssDependencies(sourceCss, path.dirname(sourceFile));
1879
+ if (!upsertTailwindV4CssSource(opts, {
1880
+ file: sourceFile,
1881
+ base: path.dirname(sourceFile),
1882
+ css: sourceCss,
1883
+ dependencies
1884
+ })) return;
1885
+ invalidateSourceCandidateScan();
1886
+ debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
1887
+ if (options.refresh === false) return;
1888
+ autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
1889
+ await refreshRuntimeStateForAutoCssSources?.(true);
1890
+ await syncSourceCandidateScan({ force: true });
1891
+ });
1892
+ await autoCssSourcesRefresh;
1893
+ };
1894
+ const discoverAndRegisterAutoCssSources = async () => {
1895
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots || !resolvedConfig?.root) return;
1896
+ const cssEntries = await discoverTailwindV4CssEntries(resolvedConfig.root, resolvedConfig.build?.outDir);
1897
+ autoCssSourcesDiscovered = true;
1898
+ let changed = false;
1899
+ for (const cssEntry of cssEntries) {
1900
+ const sourceFile = path.resolve(cssEntry);
1901
+ const sourceCss = normalizeTailwindSourceForGenerator(await readFile(sourceFile, "utf8"), { importFallback: true });
1902
+ if (autoCssSourceContent.get(sourceFile) === sourceCss) continue;
1903
+ autoCssSourceContent.set(sourceFile, sourceCss);
1904
+ const resolved = await resolveTailwindV4EntriesFromCssCached(sourceCss, path.dirname(sourceFile));
1905
+ changed = upsertTailwindV4CssSource(opts, {
1906
+ file: sourceFile,
1907
+ base: path.dirname(sourceFile),
1908
+ css: sourceCss,
1909
+ dependencies: resolved?.dependencies ?? []
1910
+ }) || changed;
1911
+ }
1912
+ if (!changed) return;
1913
+ invalidateSourceCandidateScan();
1914
+ await refreshRuntimeStateForAutoCssSources?.(true);
1915
+ };
1916
+ const customAttributesEntities = toCustomAttributesEntities(customAttributes);
1917
+ let resolvedConfig;
1918
+ let recordedGeneratorCandidates;
1919
+ const sourceCandidateCollector = createSourceCandidateCollector();
1920
+ const sourceCandidateScanCache = /* @__PURE__ */ new Map();
1921
+ let sourceScanEntries;
1922
+ let sourceScanMatcher;
1923
+ let sourceScanDependencies = /* @__PURE__ */ new Set();
1924
+ let sourceScanExplicit = false;
1925
+ let sourceCandidateScanSignature;
1926
+ let sourceCandidateScanInvalidated = true;
1927
+ const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1928
+ const pendingSourceCandidateSyncByFile = /* @__PURE__ */ new Map();
1929
+ const processedCssAssets = /* @__PURE__ */ new WeakSet();
1930
+ const processedCssAssetFiles = /* @__PURE__ */ new Set();
1931
+ const viteProcessedCssSourceFiles = /* @__PURE__ */ new Set();
1932
+ const viteGeneratedCssByFile = /* @__PURE__ */ new Map();
1933
+ const viteProcessedCssAssetResults = /* @__PURE__ */ new Map();
1934
+ const rememberedMainCssSources = /* @__PURE__ */ new Map();
1935
+ const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
1936
+ const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
1937
+ opts,
1938
+ initialTwPatcher,
1939
+ refreshTailwindcssPatcher,
1940
+ uniAppXEnabled,
1941
+ customAttributesEntities,
1942
+ disabledDefaultTemplateHandler,
1943
+ debug
1944
+ });
1945
+ const hmrTimingRecorder = createHmrTimingRecorder("vite");
1946
+ refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
1992
1947
  onLoad();
1993
1948
  const getResolvedConfig = () => resolvedConfig;
1994
1949
  const markCssAssetProcessed = (asset, file) => {
@@ -2003,29 +1958,240 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
2003
1958
  };
2004
1959
  const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2005
1960
  const getSourceCandidates = () => sourceCandidateCollector.values();
1961
+ const getSourceCandidatesForEntries = (entries) => sourceCandidateCollector.valuesForEntries(entries);
2006
1962
  const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
1963
+ const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
1964
+ const hasSourceCandidateScanState = () => sourceCandidateScanSignature !== void 0;
1965
+ const normalizeSourceScanDependency = (file) => path.normalize(path.resolve(cleanUrl(file)));
1966
+ const isSourceScanDependency = (file) => sourceScanDependencies.has(normalizeSourceScanDependency(file));
1967
+ const invalidateSourceCandidateScan = () => {
1968
+ sourceCandidateScanInvalidated = true;
1969
+ };
1970
+ const collectSourceCandidateScanRoots = (root, entries) => {
1971
+ if (entries?.length) return [{
1972
+ entries,
1973
+ root
1974
+ }];
1975
+ if (sourceScanExplicit) return [];
1976
+ const roots = [{
1977
+ entries,
1978
+ root
1979
+ }];
1980
+ const normalizedRoot = path.resolve(root);
1981
+ const seenRoots = new Set([normalizedRoot]);
1982
+ const basedir = opts.tailwindcssBasedir ? path.resolve(opts.tailwindcssBasedir) : void 0;
1983
+ if (basedir && !seenRoots.has(basedir)) {
1984
+ roots.push({ root: basedir });
1985
+ seenRoots.add(basedir);
1986
+ }
1987
+ for (const cssEntry of opts.tailwindcss?.v4?.cssEntries ?? []) {
1988
+ const cssEntryRoot = path.dirname(path.resolve(cssEntry));
1989
+ if (seenRoots.has(cssEntryRoot)) continue;
1990
+ roots.push({ root: cssEntryRoot });
1991
+ seenRoots.add(cssEntryRoot);
1992
+ }
1993
+ return roots;
1994
+ };
1995
+ const scanSourceCandidateRoots = async (roots, outDir) => {
1996
+ await Promise.all(roots.map((root) => sourceCandidateCollector.scanRoot({
1997
+ entries: root.entries,
1998
+ root: root.root,
1999
+ outDir
2000
+ })));
2001
+ };
2002
+ const cacheCurrentSourceCandidateScan = () => {
2003
+ if (sourceCandidateScanSignature) {
2004
+ sourceCandidateScanCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
2005
+ sourceCandidateScanSnapshotCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
2006
+ }
2007
+ };
2008
+ const shouldDiscoverAutoCssSources = () => {
2009
+ if (!autoCssSourcesDiscovered) return true;
2010
+ if (!isWatchLikeBuild()) return true;
2011
+ return sourceCandidateScanInvalidated;
2012
+ };
2013
+ async function syncSourceCandidateScan(options = {}) {
2014
+ if (!shouldOwnTailwindGeneration) return;
2015
+ if (!options.force && isWatchLikeBuild() && hasSourceCandidateScanState() && !sourceCandidateScanInvalidated) {
2016
+ debug("reuse vite source candidate scan definition for watch rebuild");
2017
+ return;
2018
+ }
2019
+ const root = resolvedConfig?.root ?? process.cwd();
2020
+ const outDir = resolvedConfig?.build?.outDir;
2021
+ const sourceScan = await resolveViteSourceScanEntries(opts, runtimeState.twPatcher, {
2022
+ outDir,
2023
+ root
2024
+ });
2025
+ sourceScanEntries = sourceScan?.entries;
2026
+ sourceScanExplicit = sourceScan?.explicit ?? false;
2027
+ sourceScanMatcher = createViteSourceScanMatcher(sourceScanEntries);
2028
+ sourceScanDependencies = new Set((sourceScan?.dependencies ?? []).map(normalizeSourceScanDependency));
2029
+ const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
2030
+ const nextScanSignature = createSourceCandidateScanSignature({
2031
+ inlineCandidates: sourceScan?.inlineCandidates,
2032
+ outDir,
2033
+ roots,
2034
+ scanAllSources: !sourceScanExplicit
2035
+ });
2036
+ if (hasSourceCandidateScanState() && sourceCandidateScanSignature === nextScanSignature) {
2037
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2038
+ sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2039
+ debug("reuse vite source candidate scan for watch rebuild");
2040
+ sourceCandidateScanInvalidated = false;
2041
+ return;
2042
+ }
2043
+ const cachedScan = isWatchLikeBuild() ? sourceCandidateScanCache.get(nextScanSignature) ?? sourceCandidateScanSnapshotCache.get(nextScanSignature) : void 0;
2044
+ if (cachedScan) {
2045
+ sourceCandidateCollector.restore(cachedScan);
2046
+ sourceCandidateScanSignature = nextScanSignature;
2047
+ debug("reuse cached vite source candidate scan for watch rebuild");
2048
+ sourceCandidateScanInvalidated = false;
2049
+ return;
2050
+ }
2051
+ sourceCandidateCollector.clear();
2052
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2053
+ await scanSourceCandidateRoots(roots, outDir);
2054
+ sourceCandidateScanSignature = nextScanSignature;
2055
+ sourceCandidateScanInvalidated = false;
2056
+ if (isWatchLikeBuild()) {
2057
+ sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2058
+ sourceCandidateScanSnapshotCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
2059
+ }
2060
+ }
2007
2061
  const waitForSourceCandidateSyncs = async () => {
2008
2062
  while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2009
2063
  };
2010
2064
  const syncChangedSourceCandidateFile = (id) => {
2011
2065
  if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return Promise.resolve();
2012
- const task = sourceCandidateCollector.syncFile(id).catch((error) => {
2066
+ const file = cleanUrl(id);
2067
+ if (isSourceScanDependency(file)) invalidateSourceCandidateScan();
2068
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2069
+ sourceCandidateCollector.remove(file);
2070
+ cacheCurrentSourceCandidateScan();
2071
+ return Promise.resolve();
2072
+ }
2073
+ if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2074
+ cacheCurrentSourceCandidateScan();
2075
+ return Promise.resolve();
2076
+ }
2077
+ const existingTask = pendingSourceCandidateSyncByFile.get(file);
2078
+ if (existingTask) return existingTask;
2079
+ const task = sourceCandidateCollector.syncCurrentFile(id).catch((error) => {
2013
2080
  debug("source candidate watch sync failed: %s %O", id, error);
2081
+ }).then(() => {
2082
+ cacheCurrentSourceCandidateScan();
2014
2083
  }).finally(() => {
2015
2084
  pendingSourceCandidateSyncs.delete(task);
2085
+ pendingSourceCandidateSyncByFile.delete(file);
2016
2086
  });
2017
2087
  pendingSourceCandidateSyncs.add(task);
2088
+ pendingSourceCandidateSyncByFile.set(file, task);
2018
2089
  return task;
2019
2090
  };
2091
+ const shouldCollectTransformedSourceCandidates = (id) => {
2092
+ if (id.search(/[?#]/) < 0) return true;
2093
+ const file = cleanUrl(id);
2094
+ return !/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file);
2095
+ };
2020
2096
  const rememberMainCssSource = (file, rawSource, cssRuntimeSignature) => {
2021
2097
  rememberedMainCssSources.set(file, rawSource);
2022
2098
  if (cssRuntimeSignature) rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2023
2099
  };
2024
2100
  const getRememberedMainCssSources = () => rememberedMainCssSources;
2101
+ const getRememberedMainCssSource = (file) => rememberedMainCssSources.get(file);
2025
2102
  const getRememberedMainCssSignature = (file) => rememberedMainCssSignatureByFile.get(file);
2026
2103
  const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2027
2104
  rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2028
2105
  };
2106
+ const recordCssAssetResult = (file, css) => {
2107
+ viteGeneratedCssByFile.set(file, css);
2108
+ };
2109
+ const recordViteProcessedCssAssetResult = (file, css) => {
2110
+ viteProcessedCssAssetResults.set(normalizeOutputPathKey(file), css);
2111
+ };
2112
+ const getViteProcessedCssAssetResults = () => viteProcessedCssAssetResults.entries();
2113
+ const normalizeViteProcessedCssFile = (file) => path.resolve(cleanUrl(file));
2114
+ const markViteProcessedCssSource = (file) => {
2115
+ viteProcessedCssSourceFiles.add(normalizeViteProcessedCssFile(file));
2116
+ };
2117
+ const matchesViteProcessedCssSource = (candidate) => {
2118
+ const normalized = normalizeViteProcessedCssFile(candidate);
2119
+ return viteProcessedCssSourceFiles.has(normalized);
2120
+ };
2121
+ const isViteProcessedCssAsset = (asset, file) => {
2122
+ if (hasBundlerGeneratedCssMarker(asset.source)) return true;
2123
+ return [
2124
+ file,
2125
+ asset.originalFileName,
2126
+ ...asset.originalFileNames ?? []
2127
+ ].filter((item) => typeof item === "string" && item.length > 0).some((candidate) => matchesViteProcessedCssSource(cleanUrl(candidate)));
2128
+ };
2129
+ const transformCssHandlerOptions = createCssHandlerOptionsCache({
2130
+ getAppType: () => opts.appType,
2131
+ mainCssChunkMatcher,
2132
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
2133
+ getOutputRoot: () => resolvedConfig?.build?.outDir ? path.resolve(resolvedConfig.root, resolvedConfig.build.outDir) : resolvedConfig?.root
2134
+ });
2135
+ const generateTailwindCssForVitePipeline = async (id, code, hookContext) => {
2136
+ if (!shouldOwnTailwindGeneration) return;
2137
+ await runtimeState.readyPromise;
2138
+ await waitForSourceCandidateSyncs();
2139
+ const file = cleanUrl(id);
2140
+ const runtime = getRecordedGeneratorCandidates() ?? getSourceCandidates() ?? await ensureRuntimeClassSet();
2141
+ const generated = await generateCssByGenerator({
2142
+ opts,
2143
+ runtimeState,
2144
+ runtime,
2145
+ rawSource: code,
2146
+ file,
2147
+ cssHandlerOptions: transformCssHandlerOptions.getCssHandlerOptions(file),
2148
+ cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(file),
2149
+ getSourceCandidatesForEntries,
2150
+ styleHandler,
2151
+ debug,
2152
+ previousCss: viteGeneratedCssByFile.get(file)
2153
+ });
2154
+ if (!generated) return;
2155
+ for (const dependency of generated.dependencies) hookContext?.addWatchFile?.(dependency);
2156
+ viteGeneratedCssByFile.set(file, generated.css);
2157
+ markViteProcessedCssSource(file);
2158
+ recordGeneratorCandidates(runtime);
2159
+ rememberMainCssSource(file, code);
2160
+ debug("css generated for vite postcss pipeline: %s bytes=%d", file, generated.css.length);
2161
+ return `${createBundlerGeneratedCssMarker("vite", normalizeViteProcessedCssFile(file))}\n${generated.css}`;
2162
+ };
2163
+ const rewritePlugins = createRewriteCssImportsPlugins({
2164
+ getAppType: () => opts.appType,
2165
+ generateTailwindCss: generateTailwindCssForVitePipeline,
2166
+ rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
2167
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
2168
+ shouldOwnTailwindGeneration,
2169
+ shouldRewrite: shouldRewriteCssImports,
2170
+ weappTailwindcssDirPosix
2171
+ });
2172
+ if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
2173
+ const generateBundleHook = createGenerateBundleHook({
2174
+ opts,
2175
+ runtimeState,
2176
+ ensureRuntimeClassSet,
2177
+ ensureBundleRuntimeClassSet,
2178
+ debug,
2179
+ getResolvedConfig,
2180
+ markCssAssetProcessed,
2181
+ isViteProcessedCssAsset,
2182
+ recordCssAssetResult,
2183
+ recordViteProcessedCssAssetResult,
2184
+ getViteProcessedCssAssetResults,
2185
+ getSourceCandidates,
2186
+ getSourceCandidatesForEntries,
2187
+ waitForSourceCandidateSyncs,
2188
+ rememberMainCssSource,
2189
+ getRememberedMainCssSources,
2190
+ getRememberedMainCssSignature,
2191
+ setRememberedMainCssSignature,
2192
+ recordGeneratorCandidates,
2193
+ hmrTimingRecorder
2194
+ });
2029
2195
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2030
2196
  opts,
2031
2197
  runtimeState,
@@ -2034,12 +2200,22 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
2034
2200
  getResolvedConfig,
2035
2201
  markCssAssetProcessed,
2036
2202
  isCssAssetProcessed,
2203
+ isViteProcessedCssAsset,
2204
+ recordCssAssetResult,
2205
+ recordViteProcessedCssAssetResult,
2206
+ getViteProcessedCssAssetResults,
2037
2207
  getRecordedGeneratorCandidates,
2038
2208
  getSourceCandidates,
2209
+ getSourceCandidatesForEntries,
2039
2210
  waitForSourceCandidateSyncs,
2040
- rememberMainCssSource
2211
+ rememberMainCssSource,
2212
+ getRememberedMainCssSource
2041
2213
  });
2042
2214
  const isIosPlatform = resolveUniUtsPlatform().isAppIos;
2215
+ const prepareTailwindGeneration = async () => {
2216
+ if (shouldDiscoverAutoCssSources()) await discoverAndRegisterAutoCssSources();
2217
+ await syncSourceCandidateScan();
2218
+ };
2043
2219
  const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
2044
2220
  appType: opts.appType ?? "uni-app-x",
2045
2221
  customAttributesEntities,
@@ -2059,28 +2235,42 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
2059
2235
  name: `${vitePluginName}:source-candidates`,
2060
2236
  enforce: "pre",
2061
2237
  async transform(code, id) {
2062
- if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return;
2063
- await sourceCandidateCollector.sync(id, code);
2238
+ if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
2239
+ return hmrTimingRecorder.measure("sourceCandidates.transform", async () => {
2240
+ const file = cleanUrl(id);
2241
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2242
+ sourceCandidateCollector.remove(file);
2243
+ cacheCurrentSourceCandidateScan();
2244
+ return;
2245
+ }
2246
+ if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2247
+ cacheCurrentSourceCandidateScan();
2248
+ return;
2249
+ }
2250
+ await sourceCandidateCollector.merge(id, code);
2251
+ cacheCurrentSourceCandidateScan();
2252
+ }, { emit: false });
2064
2253
  },
2065
2254
  async watchChange(id, change) {
2066
- if (change.event === "delete") {
2067
- sourceCandidateCollector.remove(id);
2068
- return;
2069
- }
2070
- await syncChangedSourceCandidateFile(id);
2255
+ await hmrTimingRecorder.measure("sourceCandidates.watchChange", async () => {
2256
+ if (isSourceScanDependency(id)) invalidateSourceCandidateScan();
2257
+ if (change.event === "delete") {
2258
+ sourceCandidateCollector.remove(id);
2259
+ cacheCurrentSourceCandidateScan();
2260
+ return;
2261
+ }
2262
+ await syncChangedSourceCandidateFile(id);
2263
+ }, { emit: false });
2071
2264
  },
2072
2265
  async handleHotUpdate(ctx) {
2073
- await syncChangedSourceCandidateFile(ctx.file);
2266
+ await hmrTimingRecorder.measure("sourceCandidates.handleHotUpdate", async () => {
2267
+ await syncChangedSourceCandidateFile(ctx.file);
2268
+ }, { emit: false });
2074
2269
  },
2075
2270
  async buildStart() {
2076
- if (!shouldOwnTailwindGeneration) return;
2077
- if (resolvedConfig?.command === "build" && !isWatchBuild()) sourceCandidateCollector.clear();
2078
- const root = resolvedConfig?.root ?? process.cwd();
2079
- const outDir = resolvedConfig?.build?.outDir;
2080
- await sourceCandidateCollector.scanRoot({
2081
- root,
2082
- outDir
2083
- });
2271
+ await hmrTimingRecorder.measure("sourceCandidates.buildStart", async () => {
2272
+ await prepareTailwindGeneration();
2273
+ }, { emit: false });
2084
2274
  }
2085
2275
  },
2086
2276
  {
@@ -2111,76 +2301,54 @@ function UnifiedViteWeappTailwindcssPlugin(options = {}) {
2111
2301
  });
2112
2302
  },
2113
2303
  async configResolved(config) {
2114
- resolvedConfig = config;
2115
- if (shouldOwnTailwindGeneration) {
2116
- const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2117
- if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2118
- }
2119
- const resolvedRoot = config.root ? path.resolve(config.root) : void 0;
2120
- let shouldRefreshRuntime = false;
2121
- if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2122
- const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2123
- if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2124
- const previousBasedir = opts.tailwindcssBasedir;
2125
- opts.tailwindcssBasedir = nextTailwindcssBasedir;
2126
- debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2127
- shouldRefreshRuntime = true;
2304
+ await hmrTimingRecorder.measure("configResolved", async () => {
2305
+ resolvedConfig = config;
2306
+ if (shouldOwnTailwindGeneration) {
2307
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2308
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2128
2309
  }
2129
- }
2130
- if (!hasExplicitAppType && resolvedRoot) {
2131
- const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2132
- if (nextAppType && opts.appType !== nextAppType) {
2133
- const previousAppType = opts.appType;
2134
- opts.appType = nextAppType;
2135
- logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2136
- debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2137
- shouldRefreshRuntime = true;
2310
+ const resolvedRoot = config.root ? path.resolve(config.root) : void 0;
2311
+ let shouldRefreshRuntime = false;
2312
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2313
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2314
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2315
+ const previousBasedir = opts.tailwindcssBasedir;
2316
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
2317
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2318
+ shouldRefreshRuntime = true;
2319
+ }
2138
2320
  }
2139
- }
2140
- if (shouldRefreshRuntime) await refreshRuntimeState(true);
2141
- if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2142
- const postcssPlugins = config.css.postcss.plugins;
2143
- if (shouldOwnTailwindGeneration) {
2144
- const removed = removeTailwindPostcssPlugins(postcssPlugins);
2145
- if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2321
+ if (shouldInferAppType && resolvedRoot) {
2322
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2323
+ if (nextAppType && opts.appType !== nextAppType) {
2324
+ const previousAppType = opts.appType;
2325
+ opts.appType = nextAppType;
2326
+ logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2327
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2328
+ shouldRefreshRuntime = true;
2329
+ }
2146
2330
  }
2147
- const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2148
- if (idx > -1) {
2149
- postcssPlugins.splice(idx, 1, postcssHtmlTransform());
2150
- debug("remove postcss-html-transform plugin from vite config");
2331
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
2332
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2333
+ const postcssPlugins = config.css.postcss.plugins;
2334
+ if (shouldOwnTailwindGeneration) {
2335
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
2336
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2337
+ }
2338
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2339
+ if (idx > -1) {
2340
+ postcssPlugins.splice(idx, 1, postcssHtmlTransform());
2341
+ debug("remove postcss-html-transform plugin from vite config");
2342
+ }
2151
2343
  }
2152
- }
2153
- },
2154
- generateBundle: {
2155
- order: "post",
2156
- handler: createGenerateBundleHook({
2157
- opts,
2158
- runtimeState,
2159
- ensureRuntimeClassSet,
2160
- ensureBundleRuntimeClassSet,
2161
- debug,
2162
- getResolvedConfig,
2163
- markCssAssetProcessed,
2164
- getSourceCandidates,
2165
- waitForSourceCandidateSyncs,
2166
- rememberMainCssSource,
2167
- getRememberedMainCssSources,
2168
- getRememberedMainCssSignature,
2169
- setRememberedMainCssSignature,
2170
- recordGeneratorCandidates
2171
- })
2344
+ }, { emit: false });
2172
2345
  },
2173
- outputOptions(options) {
2174
- const plugins = options.plugins;
2175
- return {
2176
- ...options,
2177
- plugins: Array.isArray(plugins) ? [...plugins, cssFinalizerOutputPlugin] : [cssFinalizerOutputPlugin]
2178
- };
2179
- }
2180
- }
2346
+ generateBundle: generateBundleHook
2347
+ },
2348
+ cssFinalizerOutputPlugin
2181
2349
  ];
2182
2350
  if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
2183
2351
  return plugins;
2184
2352
  }
2185
2353
  //#endregion
2186
- export { UnifiedViteWeappTailwindcssPlugin as t };
2354
+ export { WeappTailwindcss as t };