weapp-tailwindcss 5.0.0-next.5 → 5.0.0-next.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +2 -0
  2. package/dist/bundlers/shared/css-cleanup/color-gamut.d.ts +3 -0
  3. package/dist/bundlers/shared/css-cleanup/root-cleanups.d.ts +4 -0
  4. package/dist/bundlers/shared/css-cleanup/selectors.d.ts +8 -0
  5. package/dist/bundlers/shared/css-cleanup.d.ts +1 -2
  6. package/dist/bundlers/shared/generator-css/config-directive.d.ts +2 -0
  7. package/dist/bundlers/shared/generator-css/directives.d.ts +12 -0
  8. package/dist/bundlers/shared/generator-css/legacy-compat.d.ts +7 -0
  9. package/dist/bundlers/shared/generator-css/legacy-selectors.d.ts +5 -0
  10. package/dist/bundlers/shared/generator-css/legacy-units.d.ts +1 -0
  11. package/dist/bundlers/shared/generator-css/markers.d.ts +16 -0
  12. package/dist/bundlers/shared/generator-css/source-files.d.ts +11 -0
  13. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +10 -0
  14. package/dist/bundlers/shared/generator-css.d.ts +10 -23
  15. package/dist/bundlers/vite/css-finalizer.d.ts +1 -1
  16. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +2 -0
  17. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +20 -0
  18. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +3 -0
  19. package/dist/bundlers/vite/generate-bundle/dirty-state.d.ts +1 -0
  20. package/dist/bundlers/vite/generate-bundle/js-entries.d.ts +2 -0
  21. package/dist/bundlers/vite/generate-bundle/js-handler-options.d.ts +8 -0
  22. package/dist/bundlers/vite/generate-bundle/js-linking.d.ts +13 -0
  23. package/dist/bundlers/vite/generate-bundle/metrics.d.ts +17 -0
  24. package/dist/bundlers/vite/generate-bundle/process-plan.d.ts +9 -0
  25. package/dist/bundlers/vite/generate-bundle/rollup-assets.d.ts +7 -0
  26. package/dist/bundlers/vite/generate-bundle/signatures.d.ts +8 -0
  27. package/dist/bundlers/vite/generate-bundle.d.ts +1 -1
  28. package/dist/bundlers/vite/official-tailwind-plugins.d.ts +5 -0
  29. package/dist/bundlers/vite/postcss-config.d.ts +6 -0
  30. package/dist/bundlers/vite/rewrite-css-imports.d.ts +1 -0
  31. package/dist/bundlers/vite/runtime-class-set.d.ts +22 -0
  32. package/dist/bundlers/vite/tailwind-basedir.d.ts +1 -0
  33. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +1 -0
  34. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -1
  35. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +2 -0
  36. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +1 -0
  37. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +2 -0
  38. package/dist/cache-BVAiJV3J.js +502 -0
  39. package/dist/cache-CHs4DXui.mjs +434 -0
  40. package/dist/cli/helpers.d.ts +1 -2
  41. package/dist/cli/mount-options.d.ts +2 -2
  42. package/dist/cli/types.d.ts +0 -2
  43. package/dist/cli.js +107 -603
  44. package/dist/cli.mjs +118 -613
  45. package/dist/constants.d.ts +0 -1
  46. package/dist/context/tailwindcss.d.ts +1 -1
  47. package/dist/core.js +13 -20
  48. package/dist/core.mjs +8 -14
  49. package/dist/css-macro/postcss.js +1 -1
  50. package/dist/css-macro/postcss.mjs +1 -1
  51. package/dist/css-macro.js +2 -2
  52. package/dist/css-macro.mjs +2 -2
  53. package/dist/defaults.d.ts +15 -1
  54. package/dist/defaults.js +28 -7
  55. package/dist/defaults.mjs +25 -8
  56. package/dist/{generator-9UEp8OoQ.js → generator-DKkhJbOg.js} +24 -7
  57. package/dist/{generator-Dpp-5s8z.mjs → generator-UBmfduYg.mjs} +20 -3
  58. package/dist/{generator-css-MyjZhF0z.mjs → generator-css-BIapP56i.mjs} +691 -606
  59. package/dist/{generator-css-CGueCYbX.js → generator-css-Mksw8PgB.js} +703 -606
  60. package/dist/generator.js +1 -1
  61. package/dist/generator.mjs +1 -1
  62. package/dist/gulp.js +33 -21
  63. package/dist/gulp.mjs +29 -17
  64. package/dist/index.js +5 -5
  65. package/dist/index.mjs +4 -4
  66. package/dist/logger-BRy6XPQ2.js +1 -0
  67. package/dist/logger-Bub1jggA.mjs +2 -0
  68. package/dist/postcss/config-directive.d.ts +1 -0
  69. package/dist/postcss/context.d.ts +9 -0
  70. package/dist/postcss/source-files.d.ts +8 -0
  71. package/dist/postcss/tailwind-version.d.ts +3 -0
  72. package/dist/postcss-QIXwT40c.js +298 -0
  73. package/dist/postcss-w48mGIhe.mjs +288 -0
  74. package/dist/postcss.js +3 -285
  75. package/dist/postcss.mjs +1 -278
  76. package/dist/{recorder-D4BKt75Q.js → precheck-B32p-gLI.js} +139 -274
  77. package/dist/{recorder-BIW3Kuke.mjs → precheck-B4RH6ZNN.mjs} +105 -239
  78. package/dist/presets.js +6 -4
  79. package/dist/presets.mjs +4 -2
  80. package/dist/runtime-patch-CwN5ya72.mjs +71 -0
  81. package/dist/runtime-patch-D6mBo_KB.js +85 -0
  82. package/dist/tailwindcss/runtime-patch.d.ts +5 -0
  83. package/dist/tailwindcss/runtime.d.ts +2 -3
  84. package/dist/tailwindcss/targets.d.ts +1 -5
  85. package/dist/tailwindcss/v4/css-sources.d.ts +5 -0
  86. package/dist/tailwindcss/v4/patcher.d.ts +1 -1
  87. package/dist/{logger-D9clu_3f.js → tailwindcss-Bu-RWIHx.js} +70 -413
  88. package/dist/{logger-1gx9UllH.mjs → tailwindcss-C5IgPlQ0.mjs} +56 -382
  89. package/dist/types/index.d.ts +1 -6
  90. package/dist/uni-app-x/vite.d.ts +1 -1
  91. package/dist/{vite-fDM-UQpR.mjs → vite-BwgRVgxH.mjs} +677 -525
  92. package/dist/{vite-BkMGwDeH.js → vite-DyZuiyap.js} +704 -552
  93. package/dist/vite.js +1 -1
  94. package/dist/vite.mjs +1 -1
  95. package/dist/weapp-tw-css-import-rewrite-loader.js +10 -1
  96. package/dist/{webpack-CICGEKT9.js → webpack-CNV2dx3Q.js} +72 -37
  97. package/dist/{webpack-D2Wdk28V.mjs → webpack-CT6EEENx.mjs} +58 -23
  98. package/dist/webpack.js +1 -1
  99. package/dist/webpack.mjs +1 -1
  100. package/package.json +6 -9
  101. package/dist/bundlers/shared/generator-candidates.d.ts +0 -5
  102. package/dist/bundlers/webpack/shared/css-imports.d.ts +0 -6
  103. package/dist/cli/config.d.ts +0 -5
  104. package/dist/cli/helpers/patch-cwd.d.ts +0 -1
  105. package/dist/cli/mount-options/patch-status.d.ts +0 -2
  106. package/dist/cli/patch-options.d.ts +0 -6
  107. package/dist/cli/tokens.d.ts +0 -4
  108. package/dist/cli/workspace/package-dirs.d.ts +0 -3
  109. package/dist/cli/workspace/patch-package.d.ts +0 -3
  110. package/dist/cli/workspace/patch-utils.d.ts +0 -3
  111. package/dist/cli/workspace/types.d.ts +0 -11
  112. package/dist/cli/workspace/workspace-globs.d.ts +0 -2
  113. package/dist/cli/workspace/workspace-io.d.ts +0 -1
  114. package/dist/cli/workspace/workspace-lock.d.ts +0 -1
  115. package/dist/cli/workspace.d.ts +0 -2
  116. package/dist/js/syntax.d.ts +0 -10
  117. package/dist/patcher-options-DnqazL9E.js +0 -34
  118. package/dist/patcher-options-GuOwX0-k.mjs +0 -17
  119. package/dist/tailwindcss/recorder.d.ts +0 -13
  120. package/dist/tailwindcss/targets/paths.d.ts +0 -13
  121. package/dist/tailwindcss/targets/record-io.d.ts +0 -5
  122. package/dist/tailwindcss/targets/recorder.d.ts +0 -3
  123. package/dist/tailwindcss/targets/types.d.ts +0 -35
  124. package/dist/version-CWBxRFPB.js +0 -56
  125. package/dist/version-WNz3MwRv.mjs +0 -49
  126. /package/dist/{constants-p1dyh1x1.js → constants-BoB_6lFw.js} +0 -0
  127. /package/dist/{constants-B-_T5UnW.mjs → constants-E_loJC49.mjs} +0 -0
  128. /package/dist/{run-tasks-Cq5A5nVD.js → run-tasks-B50A3pxt.js} +0 -0
  129. /package/dist/{run-tasks-DUVrDJGl.mjs → run-tasks-DdNi-hkk.mjs} +0 -0
  130. /package/dist/{utils-DmC9_In3.js → utils-BiShvil9.js} +0 -0
  131. /package/dist/{utils-7DUGTFED.mjs → utils-Btw1iOVV.mjs} +0 -0
@@ -1,27 +1,29 @@
1
- import { d as filterUnsupportedMiniProgramTailwindV4Candidates, f as loadTailwindV4DesignSystem, i as normalizeWeappTailwindcssGeneratorOptions, s as resolveTailwindV4SourceFromPatcher } from "./generator-Dpp-5s8z.mjs";
2
- import { r as resolveTailwindcssOptions } from "./patcher-options-GuOwX0-k.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-BIW3Kuke.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-1gx9UllH.mjs";
6
- import { i as processCachedTask, n as hasTailwindGeneratedCssMarkers, r as hasTailwindSourceDirectives, t as generateCssByGenerator } from "./generator-css-MyjZhF0z.mjs";
7
- import { a as resolveOutputSpecifier, i as normalizeOutputPathKey, n as resolvePackageDir, o as toAbsoluteOutputPath, r as resolvePluginDisabledState, t as pushConcurrentTaskFactories } from "./run-tasks-DUVrDJGl.mjs";
1
+ import { c as resolveTailwindcssOptions, l as findNearestPackageRoot, n as getRuntimeClassSetSignature, s as findTailwindConfig } from "./cache-CHs4DXui.mjs";
2
+ import { n as createDebug } from "./runtime-patch-CwN5ya72.mjs";
3
+ import { d as filterUnsupportedMiniProgramTailwindV4Candidates, f as loadTailwindV4DesignSystem, i as normalizeWeappTailwindcssGeneratorOptions, s as resolveTailwindV4SourceFromPatcher } from "./generator-UBmfduYg.mjs";
4
+ import { a as hasTailwindSourceDirectives, i as hasTailwindRootDirectives, n as validateCandidatesByGenerator, o as hasTailwindGeneratedCssMarkers, r as processCachedTask, t as generateCssByGenerator } from "./generator-css-BIapP56i.mjs";
5
+ import { a as analyzeSource, c as isClassContextLiteralPath, d as traverse$1, 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-B4RH6ZNN.mjs";
6
+ import { o as resolveUniUtsPlatform } from "./utils-Btw1iOVV.mjs";
7
+ import { c as upsertTailwindV4CssSource, i as resolveUniAppXOptions, r as isUniAppXEnabled, s as hasConfiguredTailwindV4CssRoots } from "./tailwindcss-C5IgPlQ0.mjs";
8
+ import { a as resolveOutputSpecifier, i as normalizeOutputPathKey, n as resolvePackageDir, o as toAbsoluteOutputPath, r as resolvePluginDisabledState, t as pushConcurrentTaskFactories } from "./run-tasks-DdNi-hkk.mjs";
9
+ import { t as logger$1 } from "./logger-Bub1jggA.mjs";
8
10
  import path from "node:path";
9
11
  import process from "node:process";
12
+ import { logger } from "@weapp-tailwindcss/logger";
13
+ import { cleanUrl as cleanUrl$1, ensurePosix } from "@weapp-tailwindcss/shared";
10
14
  import { extractRawCandidatesWithPositions, extractValidCandidates } from "tailwindcss-patch";
11
- import { Buffer } from "node:buffer";
12
15
  import fs, { existsSync, readFileSync } from "node:fs";
16
+ import { Buffer } from "node:buffer";
13
17
  import { readFile } from "node:fs/promises";
14
- import { logger } from "@weapp-tailwindcss/logger";
15
- import { cleanUrl as cleanUrl$1, ensurePosix } from "@weapp-tailwindcss/shared";
16
18
  import MagicString from "magic-string";
17
19
  import { splitCode } from "@weapp-tailwindcss/shared/extractors";
18
20
  import { Parser } from "htmlparser2";
19
21
  import fg from "fast-glob";
20
22
  import postcssHtmlTransform from "@weapp-tailwindcss/postcss/html-transform";
21
- import postcssrc from "postcss-load-config";
22
23
  import { NodeTypes } from "@vue/compiler-dom";
23
24
  import { parse } from "@vue/compiler-sfc";
24
25
  import { parse as parse$1 } from "comment-json";
26
+ import postcssrc from "postcss-load-config";
25
27
  //#region src/uni-app-x/component-local-style.ts
26
28
  const EXPRESSION_WRAPPER_PREFIX = "(\n";
27
29
  const EXPRESSION_WRAPPER_SUFFIX = "\n)";
@@ -61,8 +63,8 @@ var UniAppXComponentLocalStyleCollector = class {
61
63
  constructor(fileId, runtimeSet) {
62
64
  this.fileId = fileId;
63
65
  this.runtimeSet = runtimeSet;
64
- this.aliasByUtility = /* @__PURE__ */ new Map();
65
- this.aliasByLookup = /* @__PURE__ */ new Map();
66
+ _defineProperty(this, "aliasByUtility", /* @__PURE__ */ new Map());
67
+ _defineProperty(this, "aliasByLookup", /* @__PURE__ */ new Map());
66
68
  }
67
69
  ensureAlias(utility) {
68
70
  const cached = this.aliasByUtility.get(utility);
@@ -419,14 +421,14 @@ function createUniAppXPlugins(options) {
419
421
  const cssPlugins = [{
420
422
  name: "weapp-tailwindcss:uni-app-x:css",
421
423
  async transform(code, id) {
422
- await runtimeState.patchPromise;
424
+ await runtimeState.readyPromise;
423
425
  return transformStyle(code, id);
424
426
  }
425
427
  }, {
426
428
  name: "weapp-tailwindcss:uni-app-x:css:pre",
427
429
  enforce: "pre",
428
430
  async transform(code, id) {
429
- await runtimeState.patchPromise;
431
+ await runtimeState.readyPromise;
430
432
  const { query } = parseVueRequest(id);
431
433
  const lang = query.lang;
432
434
  if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
@@ -544,7 +546,7 @@ function createViteCssFinalizerOutputPlugin(context) {
544
546
  if (getResolvedConfig()?.command !== "build") return;
545
547
  const entries = Object.entries(bundle).filter(([, output]) => output.type === "asset" && opts.cssMatcher(output.fileName) && (!isCssAssetProcessed(output, output.fileName) || shouldFinalizeProcessedCssAsset(opts, output.fileName)));
546
548
  if (entries.length === 0) return;
547
- await runtimeState.patchPromise;
549
+ await runtimeState.readyPromise;
548
550
  await waitForSourceCandidateSyncs?.();
549
551
  const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
550
552
  const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
@@ -835,7 +837,160 @@ function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
835
837
  state.dependentsByLinkedFile = invertLinkedByEntry(state.linkedByEntry);
836
838
  }
837
839
  //#endregion
838
- //#region src/bundlers/vite/generate-bundle.ts
840
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
841
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
842
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
843
+ function isArbitraryValueCandidate(candidate) {
844
+ return candidate.includes("[") && candidate.includes("]");
845
+ }
846
+ function collectUnescapedDynamicCandidates(source) {
847
+ const matches = /* @__PURE__ */ new Set();
848
+ for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
849
+ QUOTED_LITERAL_RE.lastIndex = 0;
850
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
851
+ while (quoted !== null) {
852
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
853
+ for (const candidate of splitCode(literal, true)) {
854
+ const normalized = candidate.trim();
855
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
856
+ matches.add(normalized);
857
+ }
858
+ quoted = QUOTED_LITERAL_RE.exec(expression);
859
+ }
860
+ }
861
+ return [...matches];
862
+ }
863
+ function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
864
+ if (candidates.has("container")) return candidates;
865
+ if (!sourceCandidates.has("container")) return candidates;
866
+ return new Set([...candidates, "container"]);
867
+ }
868
+ //#endregion
869
+ //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
870
+ function createCssHandlerOptionsCache(options) {
871
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
872
+ const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
873
+ const getCssHandlerOptions = (file) => {
874
+ const majorVersion = options.getMajorVersion();
875
+ const isMainChunk = options.mainCssChunkMatcher(file, options.appType);
876
+ const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
877
+ const cached = cssHandlerOptionsCache.get(cacheKey);
878
+ if (cached) return cached;
879
+ const created = {
880
+ isMainChunk,
881
+ postcssOptions: { options: { from: file } },
882
+ majorVersion
883
+ };
884
+ cssHandlerOptionsCache.set(cacheKey, created);
885
+ return created;
886
+ };
887
+ const getCssUserHandlerOptions = (file) => {
888
+ const cacheKey = `${options.getMajorVersion() ?? "unknown"}:${file}`;
889
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
890
+ if (cached) return cached;
891
+ const created = {
892
+ ...getCssHandlerOptions(file),
893
+ isMainChunk: false
894
+ };
895
+ cssUserHandlerOptionsCache.set(cacheKey, created);
896
+ return created;
897
+ };
898
+ return {
899
+ getCssHandlerOptions,
900
+ getCssUserHandlerOptions
901
+ };
902
+ }
903
+ //#endregion
904
+ //#region src/bundlers/vite/generate-bundle/css-share-scope.ts
905
+ const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
906
+ const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
907
+ const CSS_IMPORT_RE = /@import\b/i;
908
+ function isPathIndependentCssUrl(value) {
909
+ const normalized = value.trim();
910
+ return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
911
+ }
912
+ function hasPathDependentCssUrl(rawSource) {
913
+ CSS_URL_FUNCTION_RE.lastIndex = 0;
914
+ let match = CSS_URL_FUNCTION_RE.exec(rawSource);
915
+ while (match !== null) {
916
+ if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
917
+ match = CSS_URL_FUNCTION_RE.exec(rawSource);
918
+ }
919
+ return false;
920
+ }
921
+ function createCssTransformShareScope(file, rawSource) {
922
+ if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${normalizeOutputPathKey(path.dirname(file))}`;
923
+ return "global";
924
+ }
925
+ function createCssTransformShareScopeKey(opts, file, rawSource) {
926
+ if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${normalizeOutputPathKey(file)}`;
927
+ return createCssTransformShareScope(file, rawSource);
928
+ }
929
+ function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
930
+ return `${runtimeSignature}:${generatorCandidateSignature}`;
931
+ }
932
+ //#endregion
933
+ //#region src/bundlers/vite/generate-bundle/dirty-state.ts
934
+ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
935
+ const currentFileSet = new Set(currentBundleFiles);
936
+ for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
937
+ return false;
938
+ }
939
+ //#endregion
940
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
941
+ function createJsEntryResolver(jsEntries) {
942
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
943
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
944
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
945
+ }
946
+ //#endregion
947
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
948
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
949
+ return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
950
+ }
951
+ function createJsHandlerOptionsFactory(options) {
952
+ return (absoluteFilename, extra) => ({
953
+ ...extra,
954
+ filename: absoluteFilename,
955
+ tailwindcssMajorVersion: options.getMajorVersion(),
956
+ moduleGraph: options.moduleGraph,
957
+ babelParserOptions: {
958
+ ...extra?.babelParserOptions ?? {},
959
+ sourceFilename: absoluteFilename
960
+ }
961
+ });
962
+ }
963
+ //#endregion
964
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
965
+ function createLinkedUpdateHelpers(options) {
966
+ const pendingLinkedUpdates = [];
967
+ const handleLinkedUpdate = (fileName, previous, next) => {
968
+ options.onUpdate(fileName, previous, next);
969
+ options.debug("js linked handle: %s", fileName);
970
+ };
971
+ const scheduleLinkedApply = (entry, code) => {
972
+ pendingLinkedUpdates.push(() => {
973
+ if (entry.output.type === "chunk") entry.output.code = code;
974
+ else entry.output.source = code;
975
+ });
976
+ };
977
+ const applyLinkedUpdates = (linked) => {
978
+ applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
979
+ };
980
+ return {
981
+ applyLinkedUpdates,
982
+ pendingLinkedUpdates
983
+ };
984
+ }
985
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
986
+ if (!linked || !linkedSet) return;
987
+ for (const id of Object.keys(linked)) {
988
+ const linkedEntry = getJsEntry(id);
989
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
990
+ }
991
+ }
992
+ //#endregion
993
+ //#region src/bundlers/vite/generate-bundle/metrics.ts
839
994
  function formatDebugFileList(files, limit = 8) {
840
995
  if (files.size === 0) return "-";
841
996
  const sorted = [...files].sort();
@@ -861,9 +1016,6 @@ function createEmptyMetrics() {
861
1016
  function measureElapsed(start) {
862
1017
  return performance.now() - start;
863
1018
  }
864
- function resolveUniAppXJsTransformEnabled(uniAppX) {
865
- return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
866
- }
867
1019
  function formatCacheHitRate(metric) {
868
1020
  if (metric.total === 0) return "0.00%";
869
1021
  return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
@@ -871,6 +1023,50 @@ function formatCacheHitRate(metric) {
871
1023
  function formatMs(value) {
872
1024
  return value.toFixed(2);
873
1025
  }
1026
+ //#endregion
1027
+ //#region src/bundlers/vite/generate-bundle/process-plan.ts
1028
+ function logBundleProcessPlan(options) {
1029
+ const { debug, snapshot, useIncrementalMode, iteration } = options;
1030
+ const { processFiles } = snapshot;
1031
+ if (useIncrementalMode) {
1032
+ 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));
1033
+ 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));
1034
+ return;
1035
+ }
1036
+ 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));
1037
+ }
1038
+ //#endregion
1039
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
1040
+ function createReplayCssAsset(fileName, source) {
1041
+ return {
1042
+ type: "asset",
1043
+ fileName,
1044
+ name: void 0,
1045
+ source,
1046
+ needsCodeReference: false,
1047
+ names: [],
1048
+ originalFileName: null,
1049
+ originalFileNames: []
1050
+ };
1051
+ }
1052
+ function isAddWatchFileInvalidRollupPhaseError(error) {
1053
+ const candidate = error;
1054
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
1055
+ }
1056
+ function registerGeneratorDependencies(ctx, dependencies) {
1057
+ if (typeof ctx.addWatchFile !== "function") return;
1058
+ for (const dependency of dependencies ?? []) try {
1059
+ ctx.addWatchFile(dependency);
1060
+ } catch (error) {
1061
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
1062
+ logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
1063
+ continue;
1064
+ }
1065
+ throw error;
1066
+ }
1067
+ }
1068
+ //#endregion
1069
+ //#region src/bundlers/vite/generate-bundle/signatures.ts
874
1070
  function summarizeStringDiff(previous, next) {
875
1071
  if (previous === next) return "same";
876
1072
  const previousLength = previous.length;
@@ -917,128 +1113,22 @@ function getSnapshotHash(snapshotMap, file, fallback) {
917
1113
  function hasRuntimeAffectingSourceChanges(changedByType) {
918
1114
  return changedByType.html.size > 0 || changedByType.js.size > 0;
919
1115
  }
920
- const CSS_URL_FUNCTION_RE = /url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/gi;
921
- const CSS_PATH_INDEPENDENT_URL_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i;
922
- const CSS_IMPORT_RE = /@import\b/i;
923
- function isPathIndependentCssUrl(value) {
924
- const normalized = value.trim();
925
- return normalized.length > 0 && CSS_PATH_INDEPENDENT_URL_RE.test(normalized);
926
- }
927
- function hasPathDependentCssUrl(rawSource) {
928
- CSS_URL_FUNCTION_RE.lastIndex = 0;
929
- let match = CSS_URL_FUNCTION_RE.exec(rawSource);
930
- while (match !== null) {
931
- if (!isPathIndependentCssUrl(match[1] ?? match[2] ?? match[3] ?? "")) return true;
932
- match = CSS_URL_FUNCTION_RE.exec(rawSource);
933
- }
934
- return false;
935
- }
936
- function createCssTransformShareScope(file, rawSource) {
937
- if (CSS_IMPORT_RE.test(rawSource) || hasPathDependentCssUrl(rawSource)) return `dir:${normalizeOutputPathKey(path.dirname(file))}`;
938
- return "global";
939
- }
940
- function createCssTransformShareScopeKey(opts, file, rawSource) {
941
- if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${normalizeOutputPathKey(file)}`;
942
- return createCssTransformShareScope(file, rawSource);
943
- }
944
- function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
945
- return `${runtimeSignature}:${generatorCandidateSignature}`;
946
- }
947
- function createReplayCssAsset(fileName, source) {
948
- return {
949
- type: "asset",
950
- fileName,
951
- name: void 0,
952
- source,
953
- needsCodeReference: false,
954
- names: [],
955
- originalFileName: null,
956
- originalFileNames: []
957
- };
958
- }
959
- function isAddWatchFileInvalidRollupPhaseError(error) {
960
- const candidate = error;
961
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
962
- }
963
- function registerGeneratorDependencies(ctx, dependencies) {
964
- if (typeof ctx.addWatchFile !== "function") return;
965
- for (const dependency of dependencies ?? []) try {
966
- ctx.addWatchFile(dependency);
967
- } catch (error) {
968
- if (isAddWatchFileInvalidRollupPhaseError(error)) {
969
- logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
970
- continue;
971
- }
972
- throw error;
973
- }
974
- }
975
- function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
976
- const currentFileSet = new Set(currentBundleFiles);
977
- for (const file of previousBundleFiles) if (!currentFileSet.has(file)) return true;
978
- return false;
979
- }
980
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
981
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
982
- function isArbitraryValueCandidate(candidate) {
983
- return candidate.includes("[") && candidate.includes("]");
984
- }
985
- function collectUnescapedDynamicCandidates(source) {
986
- const matches = /* @__PURE__ */ new Set();
987
- for (const expression of source.match(MUSTACHE_EXPRESSION_RE) ?? []) {
988
- QUOTED_LITERAL_RE.lastIndex = 0;
989
- let quoted = QUOTED_LITERAL_RE.exec(expression);
990
- while (quoted !== null) {
991
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
992
- for (const candidate of splitCode(literal, true)) {
993
- const normalized = candidate.trim();
994
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
995
- matches.add(normalized);
996
- }
997
- quoted = QUOTED_LITERAL_RE.exec(expression);
998
- }
999
- }
1000
- return [...matches];
1001
- }
1002
- function collectLegacyContainerCompatCandidates(sourceCandidates, candidates) {
1003
- if (candidates.has("container")) return candidates;
1004
- if (!sourceCandidates.has("container")) return candidates;
1005
- return new Set([...candidates, "container"]);
1006
- }
1116
+ //#endregion
1117
+ //#region src/bundlers/vite/generate-bundle.ts
1007
1118
  function createGenerateBundleHook(context) {
1008
1119
  const state = createBundleBuildState();
1009
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
1010
- const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
1120
+ const cssHandlerOptions = createCssHandlerOptionsCache({
1121
+ appType: context.opts.appType,
1122
+ mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
1123
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion
1124
+ });
1011
1125
  return async function generateBundle(_opt, bundle) {
1012
1126
  const addWatchFile = (id) => this.addWatchFile?.(id);
1013
1127
  const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
1014
- const { appType, cache, mainCssChunkMatcher, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
1128
+ const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
1015
1129
  const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator);
1016
- const getCssHandlerOptions = (file) => {
1017
- const majorVersion = runtimeState.twPatcher.majorVersion;
1018
- const isMainChunk = mainCssChunkMatcher(file, appType);
1019
- const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
1020
- const cached = cssHandlerOptionsCache.get(cacheKey);
1021
- if (cached) return cached;
1022
- const created = {
1023
- isMainChunk,
1024
- postcssOptions: { options: { from: file } },
1025
- majorVersion
1026
- };
1027
- cssHandlerOptionsCache.set(cacheKey, created);
1028
- return created;
1029
- };
1030
- const getCssUserHandlerOptions = (file) => {
1031
- const cacheKey = `${runtimeState.twPatcher.majorVersion ?? "unknown"}:${file}`;
1032
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
1033
- if (cached) return cached;
1034
- const created = {
1035
- ...getCssHandlerOptions(file),
1036
- isMainChunk: false
1037
- };
1038
- cssUserHandlerOptionsCache.set(cacheKey, created);
1039
- return created;
1040
- };
1041
- await runtimeState.patchPromise;
1130
+ const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
1131
+ await runtimeState.readyPromise;
1042
1132
  debug("start");
1043
1133
  onStart();
1044
1134
  const metrics = createEmptyMetrics();
@@ -1055,52 +1145,56 @@ function createGenerateBundleHook(context) {
1055
1145
  const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
1056
1146
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
1057
1147
  const processFiles = snapshot.processFiles;
1058
- if (useIncrementalMode) {
1059
- 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));
1060
- 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));
1061
- } 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));
1148
+ logBundleProcessPlan({
1149
+ debug,
1150
+ snapshot,
1151
+ useIncrementalMode,
1152
+ iteration: state.iteration + 1
1153
+ });
1062
1154
  const jsEntries = snapshot.jsEntries;
1063
- const normalizedJsEntries = /* @__PURE__ */ new Map();
1064
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
1065
- const getJsEntry = (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
1155
+ const getJsEntry = createJsEntryResolver(jsEntries);
1066
1156
  const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
1067
1157
  const runtimeStart = performance.now();
1068
1158
  const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
1069
1159
  const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
1070
1160
  await waitForSourceCandidateSyncs?.();
1071
1161
  const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
1072
- const collectedGeneratorCandidates = new Set(sourceCandidates);
1162
+ const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
1073
1163
  const generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
1074
1164
  const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
1075
1165
  recordGeneratorCandidates?.(generatorRuntime);
1076
- const defaultTemplateHandlerOptions = { runtimeSet: runtime };
1166
+ let transformRuntime = runtime;
1167
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0) {
1168
+ const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
1169
+ const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
1170
+ if (mainCssEntry) {
1171
+ const validatedRuntime = await validateCandidatesByGenerator({
1172
+ opts,
1173
+ runtimeState,
1174
+ candidates: generatorRuntime,
1175
+ rawSource: mainCssEntry.source,
1176
+ file: mainCssEntry.file,
1177
+ cssHandlerOptions: getCssHandlerOptions(mainCssEntry.file),
1178
+ cssUserHandlerOptions: getCssUserHandlerOptions(mainCssEntry.file),
1179
+ styleHandler,
1180
+ debug
1181
+ });
1182
+ if (validatedRuntime.size > 0) transformRuntime = new Set([...runtime, ...validatedRuntime]);
1183
+ }
1184
+ }
1185
+ const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
1077
1186
  metrics.runtimeSet = measureElapsed(runtimeStart);
1078
1187
  if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
1079
- debug("get runtimeSet, class count: %d", runtime.size);
1188
+ debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
1080
1189
  const runtimeSignature = getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1081
- const handleLinkedUpdate = (fileName, previous, next) => {
1082
- onUpdate(fileName, previous, next);
1083
- debug("js linked handle: %s", fileName);
1084
- };
1085
- const pendingLinkedUpdates = [];
1086
- const scheduleLinkedApply = (entry, code) => {
1087
- pendingLinkedUpdates.push(() => {
1088
- if (entry.output.type === "chunk") entry.output.code = code;
1089
- else entry.output.source = code;
1090
- });
1091
- };
1092
- const applyLinkedUpdates = (linked) => {
1093
- applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
1094
- };
1095
- const createHandlerOptions = (absoluteFilename, extra) => ({
1096
- ...extra,
1097
- filename: absoluteFilename,
1098
- tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
1099
- moduleGraph: moduleGraphOptions,
1100
- babelParserOptions: {
1101
- ...extra?.babelParserOptions ?? {},
1102
- sourceFilename: absoluteFilename
1103
- }
1190
+ const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
1191
+ jsEntries,
1192
+ onUpdate,
1193
+ debug
1194
+ });
1195
+ const createHandlerOptions = createJsHandlerOptionsFactory({
1196
+ getMajorVersion: () => runtimeState.twPatcher.majorVersion,
1197
+ moduleGraph: moduleGraphOptions
1104
1198
  });
1105
1199
  const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
1106
1200
  const sharedCssResultCache = /* @__PURE__ */ new Map();
@@ -1178,7 +1272,7 @@ function createGenerateBundleHook(context) {
1178
1272
  }
1179
1273
  const runTransform = async () => {
1180
1274
  const start = performance.now();
1181
- await runtimeState.patchPromise;
1275
+ await runtimeState.readyPromise;
1182
1276
  const generated = await generateCssByGenerator({
1183
1277
  opts,
1184
1278
  runtimeState,
@@ -1249,15 +1343,12 @@ function createGenerateBundleHook(context) {
1249
1343
  metrics.js.transformed++;
1250
1344
  return { result: rawSource };
1251
1345
  }
1252
- const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
1346
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1253
1347
  metrics.js.elapsed += measureElapsed(start);
1254
1348
  metrics.js.transformed++;
1255
1349
  onUpdate(file, rawSource, code);
1256
1350
  debug("js handle: %s", file);
1257
- if (linked) for (const id of Object.keys(linked)) {
1258
- const linkedEntry = getJsEntry(id);
1259
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1260
- }
1351
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1261
1352
  applyLinkedUpdates(linked);
1262
1353
  return { result: code };
1263
1354
  }
@@ -1268,10 +1359,7 @@ function createGenerateBundleHook(context) {
1268
1359
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1269
1360
  const baseApplyLinkedUpdates = applyLinkedUpdates;
1270
1361
  const wrappedApplyLinkedUpdates = (linked) => {
1271
- if (linked) for (const id of Object.keys(linked)) {
1272
- const linkedEntry = getJsEntry(id);
1273
- if (linkedEntry && linkedSet) linkedSet.add(linkedEntry.fileName);
1274
- }
1362
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1275
1363
  baseApplyLinkedUpdates(linked);
1276
1364
  };
1277
1365
  const factory = createUniAppXAssetTask(file, originalSource, outDir, {
@@ -1282,7 +1370,7 @@ function createGenerateBundleHook(context) {
1282
1370
  debug,
1283
1371
  jsHandler,
1284
1372
  onUpdate,
1285
- runtimeSet: runtime,
1373
+ runtimeSet: transformRuntime,
1286
1374
  applyLinkedResults: wrappedApplyLinkedUpdates,
1287
1375
  uniAppX
1288
1376
  });
@@ -1362,11 +1450,239 @@ function createGenerateBundleHook(context) {
1362
1450
  };
1363
1451
  }
1364
1452
  //#endregion
1365
- //#region src/bundlers/vite/incremental-runtime-class-set.ts
1366
- const debug$1 = createDebug("[vite:runtime-set] ");
1367
- const EXTENSION_DOT_PREFIX_RE = /^\./;
1368
- function createExtractOptions(context, source) {
1369
- return {
1453
+ //#region src/bundlers/vite/official-tailwind-plugins.ts
1454
+ const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1455
+ function getPostcssPluginName(plugin) {
1456
+ if (!plugin) return;
1457
+ if (typeof plugin === "function" && "postcss" in plugin) try {
1458
+ return getPostcssPluginName(plugin());
1459
+ } catch {
1460
+ return;
1461
+ }
1462
+ if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1463
+ const { postcssPlugin } = plugin;
1464
+ return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1465
+ }
1466
+ function isTailwindPostcssPlugin(plugin) {
1467
+ const name = getPostcssPluginName(plugin);
1468
+ return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1469
+ }
1470
+ function removeTailwindPostcssPlugins(plugins) {
1471
+ let removed = 0;
1472
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1473
+ plugins.splice(i, 1);
1474
+ removed++;
1475
+ }
1476
+ return removed;
1477
+ }
1478
+ function isTailwindVitePlugin(plugin) {
1479
+ if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1480
+ const { name } = plugin;
1481
+ return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1482
+ }
1483
+ function removeTailwindVitePlugins(plugins) {
1484
+ let removed = 0;
1485
+ for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1486
+ plugins.splice(i, 1);
1487
+ removed++;
1488
+ }
1489
+ return removed;
1490
+ }
1491
+ function disableTailwindVitePlugin(plugin) {
1492
+ if (!isTailwindVitePlugin(plugin)) return false;
1493
+ const mutablePlugin = plugin;
1494
+ for (const hook of [
1495
+ "configResolved",
1496
+ "configureServer",
1497
+ "transform",
1498
+ "hotUpdate",
1499
+ "handleHotUpdate"
1500
+ ]) delete mutablePlugin[hook];
1501
+ return true;
1502
+ }
1503
+ function disableAndRemoveTailwindVitePlugins(plugins) {
1504
+ let removed = 0;
1505
+ for (let i = plugins.length - 1; i >= 0; i--) {
1506
+ const plugin = plugins[i];
1507
+ if (Array.isArray(plugin)) {
1508
+ removed += disableAndRemoveTailwindVitePlugins(plugin);
1509
+ if (plugin.length === 0) plugins.splice(i, 1);
1510
+ continue;
1511
+ }
1512
+ if (disableTailwindVitePlugin(plugin)) {
1513
+ plugins.splice(i, 1);
1514
+ removed++;
1515
+ }
1516
+ }
1517
+ return removed;
1518
+ }
1519
+ //#endregion
1520
+ //#region src/bundlers/vite/postcss-config.ts
1521
+ async function resolveFilteredPostcssConfig(root) {
1522
+ try {
1523
+ const loaded = await postcssrc({}, root);
1524
+ const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1525
+ const removed = removeTailwindPostcssPlugins(plugins);
1526
+ if (removed === 0) return;
1527
+ return {
1528
+ options: loaded.options,
1529
+ plugins,
1530
+ removed
1531
+ };
1532
+ } catch (error) {
1533
+ if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1534
+ throw error;
1535
+ }
1536
+ }
1537
+ //#endregion
1538
+ //#region src/bundlers/vite/resolve-app-type.ts
1539
+ const PACKAGE_JSON_FILE$1 = "package.json";
1540
+ const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1541
+ const TARO_SCRIPT_RE = /\btaro\b/u;
1542
+ const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1543
+ function resolveDependencyNames(pkg) {
1544
+ return new Set([
1545
+ ...Object.keys(pkg.dependencies ?? {}),
1546
+ ...Object.keys(pkg.devDependencies ?? {}),
1547
+ ...Object.keys(pkg.peerDependencies ?? {}),
1548
+ ...Object.keys(pkg.optionalDependencies ?? {})
1549
+ ]);
1550
+ }
1551
+ function hasScriptMatch(pkg, pattern) {
1552
+ return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1553
+ }
1554
+ function resolveAppTypeFromPackageJson(pkg) {
1555
+ const dependencyNames = resolveDependencyNames(pkg);
1556
+ if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1557
+ if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1558
+ if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1559
+ if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1560
+ if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1561
+ }
1562
+ function tryReadUniAppManifest(root) {
1563
+ const manifestPath = path.join(root, "manifest.json");
1564
+ if (!existsSync(manifestPath)) return;
1565
+ try {
1566
+ return JSON.parse(readFileSync(manifestPath, "utf8"));
1567
+ } catch {}
1568
+ }
1569
+ function tryReadPackageJson(root) {
1570
+ const packageJsonPath = path.join(root, PACKAGE_JSON_FILE$1);
1571
+ if (!existsSync(packageJsonPath)) return;
1572
+ try {
1573
+ return JSON.parse(readFileSync(packageJsonPath, "utf8"));
1574
+ } catch {}
1575
+ }
1576
+ function resolveAppTypeFromMarkers(root) {
1577
+ for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if (existsSync(path.join(root, relativePath))) return appType;
1578
+ }
1579
+ function resolveImplicitAppTypeFromViteRoot(root) {
1580
+ const resolvedRoot = path.resolve(root);
1581
+ if (!existsSync(resolvedRoot)) return;
1582
+ const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1583
+ if (markerDetected) return markerDetected;
1584
+ let current = resolvedRoot;
1585
+ while (true) {
1586
+ const manifest = tryReadUniAppManifest(current);
1587
+ if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1588
+ const pkg = tryReadPackageJson(current);
1589
+ if (pkg) {
1590
+ const detected = resolveAppTypeFromPackageJson(pkg);
1591
+ if (detected) return detected;
1592
+ }
1593
+ const parent = path.dirname(current);
1594
+ if (parent === current) break;
1595
+ current = parent;
1596
+ }
1597
+ }
1598
+ //#endregion
1599
+ //#region src/bundlers/shared/css-imports.ts
1600
+ const tailwindcssImportRE = /^tailwindcss(?:\/.*)?$/;
1601
+ const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])(tailwindcss(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1602
+ function normalizeTailwindcssSpecifier(specifier) {
1603
+ if (specifier === "tailwindcss$") return "tailwindcss";
1604
+ return specifier;
1605
+ }
1606
+ function getTailwindcssSubpath(specifier) {
1607
+ if (specifier === "tailwindcss") return "index.css";
1608
+ return specifier.slice(12);
1609
+ }
1610
+ function resolveTailwindcssImport(specifier, pkgDir, options) {
1611
+ const normalized = normalizeTailwindcssSpecifier(specifier);
1612
+ if (!tailwindcssImportRE.test(normalized)) return null;
1613
+ if (normalized === "tailwindcss") return options?.rootImport ?? "weapp-tailwindcss/index.css";
1614
+ return (options?.join ?? path.join)(pkgDir, getTailwindcssSubpath(normalized));
1615
+ }
1616
+ function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1617
+ let hasReplacements = false;
1618
+ const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1619
+ const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1620
+ if (!replacement) return full;
1621
+ hasReplacements = true;
1622
+ return `${prefix}${quote}${replacement}${suffix}`;
1623
+ });
1624
+ return hasReplacements ? rewritten : void 0;
1625
+ }
1626
+ //#endregion
1627
+ //#region src/bundlers/vite/rewrite-css-imports.ts
1628
+ function joinPosixPath(base, subpath) {
1629
+ if (base.endsWith("/")) return `${base}${subpath}`;
1630
+ return `${base}/${subpath}`;
1631
+ }
1632
+ function isCssLikeImporter(importer) {
1633
+ if (!importer) return false;
1634
+ const normalized = cleanUrl$1(importer);
1635
+ return isCSSRequest(normalized) || normalized.endsWith("/*");
1636
+ }
1637
+ function stripTailwindConfigDirectives(code) {
1638
+ return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1639
+ }
1640
+ function createRewriteCssImportsPlugins(options) {
1641
+ if (!options.shouldRewrite) return [];
1642
+ const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1643
+ const resolveAppType = () => getAppType?.() ?? appType;
1644
+ return [{
1645
+ name: `${vitePluginName}:rewrite-css-imports`,
1646
+ enforce: "pre",
1647
+ resolveId: {
1648
+ order: "pre",
1649
+ handler(id, importer) {
1650
+ const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1651
+ join: joinPosixPath,
1652
+ appType: resolveAppType(),
1653
+ rootImport
1654
+ });
1655
+ if (!replacement) return null;
1656
+ if (importer && !isCssLikeImporter(importer)) return null;
1657
+ return replacement;
1658
+ }
1659
+ },
1660
+ transform: {
1661
+ order: "pre",
1662
+ async handler(code, id) {
1663
+ if (!isCSSRequest(id)) return null;
1664
+ if (hasTailwindRootDirectives(code)) await options.onTailwindRootCss?.(id, code);
1665
+ const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1666
+ join: joinPosixPath,
1667
+ appType: resolveAppType(),
1668
+ rootImport
1669
+ });
1670
+ const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1671
+ if (!nextCode || nextCode === code) return null;
1672
+ return {
1673
+ code: nextCode,
1674
+ map: null
1675
+ };
1676
+ }
1677
+ }
1678
+ }];
1679
+ }
1680
+ //#endregion
1681
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
1682
+ const debug$1 = createDebug("[vite:runtime-set] ");
1683
+ const EXTENSION_DOT_PREFIX_RE = /^\./;
1684
+ function createExtractOptions(context, source) {
1685
+ return {
1370
1686
  cwd: context.projectRoot,
1371
1687
  base: context.base,
1372
1688
  baseFallbacks: context.baseFallbacks,
@@ -1526,146 +1842,111 @@ function createBundleRuntimeClassSetManager(options = {}) {
1526
1842
  };
1527
1843
  }
1528
1844
  //#endregion
1529
- //#region src/bundlers/vite/resolve-app-type.ts
1530
- const PACKAGE_JSON_FILE$1 = "package.json";
1531
- const MPX_SCRIPT_RE = /\bmpx(?:-cli-service)?\b/u;
1532
- const TARO_SCRIPT_RE = /\btaro\b/u;
1533
- const TAILWINDCSS_VITE_MARKERS = [["src/app.mpx", "mpx"], ["app.mpx", "mpx"]];
1534
- function resolveDependencyNames(pkg) {
1535
- return new Set([
1536
- ...Object.keys(pkg.dependencies ?? {}),
1537
- ...Object.keys(pkg.devDependencies ?? {}),
1538
- ...Object.keys(pkg.peerDependencies ?? {}),
1539
- ...Object.keys(pkg.optionalDependencies ?? {})
1540
- ]);
1541
- }
1542
- function hasScriptMatch(pkg, pattern) {
1543
- return Object.values(pkg.scripts ?? {}).some((script) => pattern.test(script));
1544
- }
1545
- function resolveAppTypeFromPackageJson(pkg) {
1546
- const dependencyNames = resolveDependencyNames(pkg);
1547
- if (dependencyNames.has("weapp-vite") || [...dependencyNames].some((name) => name.startsWith("@weapp-vite/"))) return "weapp-vite";
1548
- if ([...dependencyNames].some((name) => name.startsWith("@mpxjs/")) || hasScriptMatch(pkg, MPX_SCRIPT_RE)) return "mpx";
1549
- if ([...dependencyNames].some((name) => name.startsWith("@tarojs/")) || hasScriptMatch(pkg, TARO_SCRIPT_RE)) return "taro";
1550
- if (dependencyNames.has("@dcloudio/vite-plugin-uni")) return "uni-app-vite";
1551
- if (dependencyNames.has("@dcloudio/vue-cli-plugin-uni") || dependencyNames.has("@dcloudio/uni-app") || Object.hasOwn(pkg, "uni-app")) return "uni-app";
1552
- }
1553
- function tryReadUniAppManifest(root) {
1554
- const manifestPath = path.join(root, "manifest.json");
1555
- if (!existsSync(manifestPath)) return;
1556
- try {
1557
- return JSON.parse(readFileSync(manifestPath, "utf8"));
1558
- } catch {}
1559
- }
1560
- function tryReadPackageJson(root) {
1561
- const packageJsonPath = path.join(root, PACKAGE_JSON_FILE$1);
1562
- if (!existsSync(packageJsonPath)) return;
1563
- try {
1564
- return JSON.parse(readFileSync(packageJsonPath, "utf8"));
1565
- } catch {}
1566
- }
1567
- function resolveAppTypeFromMarkers(root) {
1568
- for (const [relativePath, appType] of TAILWINDCSS_VITE_MARKERS) if (existsSync(path.join(root, relativePath))) return appType;
1569
- }
1570
- function resolveImplicitAppTypeFromViteRoot(root) {
1571
- const resolvedRoot = path.resolve(root);
1572
- if (!existsSync(resolvedRoot)) return;
1573
- const markerDetected = resolveAppTypeFromMarkers(resolvedRoot);
1574
- if (markerDetected) return markerDetected;
1575
- let current = resolvedRoot;
1576
- while (true) {
1577
- const manifest = tryReadUniAppManifest(current);
1578
- if (manifest && Object.hasOwn(manifest, "uni-app-x")) return "uni-app-x";
1579
- const pkg = tryReadPackageJson(current);
1580
- if (pkg) {
1581
- const detected = resolveAppTypeFromPackageJson(pkg);
1582
- if (detected) return detected;
1845
+ //#region src/bundlers/vite/runtime-class-set.ts
1846
+ function createViteRuntimeClassSet(options) {
1847
+ const { opts, initialTwPatcher, refreshTailwindcssPatcher, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
1848
+ const runtimeState = {
1849
+ twPatcher: initialTwPatcher,
1850
+ readyPromise: createTailwindRuntimeReadyPromise(initialTwPatcher),
1851
+ refreshTailwindcssPatcher
1852
+ };
1853
+ const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1854
+ let runtimeSet;
1855
+ let runtimeSetPromise;
1856
+ let runtimeRefreshSignature;
1857
+ let runtimeRefreshOptionsKey;
1858
+ function resolveRuntimeRefreshOptions() {
1859
+ const configPath = resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1860
+ const signature = getRuntimeClassSetSignature(runtimeState.twPatcher);
1861
+ const optionsKey = JSON.stringify({
1862
+ appType: opts.appType,
1863
+ uniAppX: uniAppXEnabled,
1864
+ customAttributesEntities,
1865
+ disabledDefaultTemplateHandler,
1866
+ configPath
1867
+ });
1868
+ const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1869
+ runtimeRefreshSignature = signature;
1870
+ runtimeRefreshOptionsKey = optionsKey;
1871
+ return {
1872
+ changed,
1873
+ signature,
1874
+ optionsKey
1875
+ };
1876
+ }
1877
+ async function refreshRuntimeState(force) {
1878
+ const invalidation = resolveRuntimeRefreshOptions();
1879
+ const refreshed = await refreshTailwindRuntimeState(runtimeState, {
1880
+ force: force || invalidation.changed,
1881
+ clearCache: force || invalidation.changed
1882
+ });
1883
+ if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1884
+ if (refreshed) {
1885
+ runtimeSet = void 0;
1886
+ runtimeSetPromise = void 0;
1583
1887
  }
1584
- const parent = path.dirname(current);
1585
- if (parent === current) break;
1586
- current = parent;
1587
1888
  }
1588
- }
1589
- //#endregion
1590
- //#region src/bundlers/shared/css-imports.ts
1591
- const tailwindcssImportRE = /^tailwindcss(?:\/.*)?$/;
1592
- const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])(tailwindcss(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
1593
- function normalizeTailwindcssSpecifier(specifier) {
1594
- if (specifier === "tailwindcss$") return "tailwindcss";
1595
- return specifier;
1596
- }
1597
- function getTailwindcssSubpath(specifier) {
1598
- if (specifier === "tailwindcss") return "index.css";
1599
- return specifier.slice(12);
1600
- }
1601
- function resolveTailwindcssImport(specifier, pkgDir, options) {
1602
- const normalized = normalizeTailwindcssSpecifier(specifier);
1603
- if (!tailwindcssImportRE.test(normalized)) return null;
1604
- if (normalized === "tailwindcss") return options?.rootImport ?? "weapp-tailwindcss/index.css";
1605
- return (options?.join ?? path.join)(pkgDir, getTailwindcssSubpath(normalized));
1606
- }
1607
- function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
1608
- let hasReplacements = false;
1609
- const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
1610
- const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
1611
- if (!replacement) return full;
1612
- hasReplacements = true;
1613
- return `${prefix}${quote}${replacement}${suffix}`;
1614
- });
1615
- return hasReplacements ? rewritten : void 0;
1616
- }
1617
- //#endregion
1618
- //#region src/bundlers/vite/rewrite-css-imports.ts
1619
- function joinPosixPath(base, subpath) {
1620
- if (base.endsWith("/")) return `${base}${subpath}`;
1621
- return `${base}/${subpath}`;
1622
- }
1623
- function isCssLikeImporter(importer) {
1624
- if (!importer) return false;
1625
- const normalized = cleanUrl$1(importer);
1626
- return isCSSRequest(normalized) || normalized.endsWith("/*");
1627
- }
1628
- function stripTailwindConfigDirectives(code) {
1629
- return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
1630
- }
1631
- function createRewriteCssImportsPlugins(options) {
1632
- if (!options.shouldRewrite) return [];
1633
- const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
1634
- const resolveAppType = () => getAppType?.() ?? appType;
1635
- return [{
1636
- name: `${vitePluginName}:rewrite-css-imports`,
1637
- enforce: "pre",
1638
- resolveId: {
1639
- order: "pre",
1640
- handler(id, importer) {
1641
- const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
1642
- join: joinPosixPath,
1643
- appType: resolveAppType(),
1644
- rootImport
1645
- });
1646
- if (!replacement) return null;
1647
- if (importer && !isCssLikeImporter(importer)) return null;
1648
- return replacement;
1649
- }
1650
- },
1651
- transform: {
1652
- order: "pre",
1653
- handler(code, id) {
1654
- if (!isCSSRequest(id)) return null;
1655
- const rewritten = rewriteTailwindcssImportsInCode(code, weappTailwindcssDirPosix, {
1656
- join: joinPosixPath,
1657
- appType: resolveAppType(),
1658
- rootImport
1659
- });
1660
- const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? code) : rewritten;
1661
- if (!nextCode || nextCode === code) return null;
1662
- return {
1663
- code: nextCode,
1664
- map: null
1665
- };
1666
- }
1889
+ async function ensureRuntimeClassSet(force = false) {
1890
+ const forceRuntimeRefresh = force || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1891
+ await refreshRuntimeState(force);
1892
+ await runtimeState.readyPromise;
1893
+ if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
1894
+ if (forceRuntimeRefresh || !runtimeSetPromise) {
1895
+ const invalidation = resolveRuntimeRefreshOptions();
1896
+ runtimeSetPromise = collectRuntimeClassSet(runtimeState.twPatcher, {
1897
+ force: forceRuntimeRefresh || invalidation.changed,
1898
+ skipRefresh: forceRuntimeRefresh,
1899
+ clearCache: forceRuntimeRefresh || invalidation.changed
1900
+ });
1667
1901
  }
1668
- }];
1902
+ const task = runtimeSetPromise;
1903
+ try {
1904
+ runtimeSet = await task;
1905
+ return runtimeSet;
1906
+ } finally {
1907
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1908
+ }
1909
+ }
1910
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1911
+ const forceRuntimeRefresh = forceRefresh || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1912
+ const invalidation = resolveRuntimeRefreshOptions();
1913
+ const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
1914
+ const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
1915
+ await refreshRuntimeState(shouldRefreshPatcher);
1916
+ await runtimeState.readyPromise;
1917
+ if (shouldRefreshPatcher) {
1918
+ runtimeSet = void 0;
1919
+ runtimeSetPromise = void 0;
1920
+ await bundleRuntimeClassSetManager.reset();
1921
+ }
1922
+ if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
1923
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
1924
+ runtimeSet = nextRuntimeSet;
1925
+ return nextRuntimeSet;
1926
+ } catch (error) {
1927
+ debug("incremental runtime set sync failed, fallback to full collect: %O", error);
1928
+ await bundleRuntimeClassSetManager.reset();
1929
+ }
1930
+ if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
1931
+ const task = collectRuntimeClassSet(runtimeState.twPatcher, {
1932
+ force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
1933
+ skipRefresh: forceRuntimeRefresh,
1934
+ clearCache: forceRuntimeRefresh || invalidation.changed
1935
+ });
1936
+ runtimeSetPromise = task;
1937
+ try {
1938
+ runtimeSet = await task;
1939
+ return runtimeSet;
1940
+ } finally {
1941
+ if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1942
+ }
1943
+ }
1944
+ return {
1945
+ runtimeState,
1946
+ refreshRuntimeState,
1947
+ ensureRuntimeClassSet,
1948
+ ensureBundleRuntimeClassSet
1949
+ };
1669
1950
  }
1670
1951
  //#endregion
1671
1952
  //#region src/bundlers/vite/source-candidates.ts
@@ -1820,92 +2101,8 @@ function createSourceCandidateCollector() {
1820
2101
  };
1821
2102
  }
1822
2103
  //#endregion
1823
- //#region src/bundlers/vite/index.ts
1824
- const debug = createDebug();
1825
- const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
1826
- const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
2104
+ //#region src/bundlers/vite/tailwind-basedir.ts
1827
2105
  const PACKAGE_JSON_FILE = "package.json";
1828
- const tailwindPostcssPluginNames = new Set(["tailwindcss", "@tailwindcss/postcss"]);
1829
- function getPostcssPluginName(plugin) {
1830
- if (!plugin) return;
1831
- if (typeof plugin === "function" && "postcss" in plugin) try {
1832
- return getPostcssPluginName(plugin());
1833
- } catch {
1834
- return;
1835
- }
1836
- if (typeof plugin !== "object" || !("postcssPlugin" in plugin)) return;
1837
- const { postcssPlugin } = plugin;
1838
- return typeof postcssPlugin === "string" ? postcssPlugin : void 0;
1839
- }
1840
- function isTailwindPostcssPlugin(plugin) {
1841
- const name = getPostcssPluginName(plugin);
1842
- return typeof name === "string" && tailwindPostcssPluginNames.has(name);
1843
- }
1844
- function removeTailwindPostcssPlugins(plugins) {
1845
- let removed = 0;
1846
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindPostcssPlugin(plugins[i])) {
1847
- plugins.splice(i, 1);
1848
- removed++;
1849
- }
1850
- return removed;
1851
- }
1852
- async function resolveFilteredPostcssConfig(root) {
1853
- try {
1854
- const loaded = await postcssrc({}, root);
1855
- const plugins = Array.isArray(loaded.plugins) ? [...loaded.plugins] : [];
1856
- const removed = removeTailwindPostcssPlugins(plugins);
1857
- if (removed === 0) return;
1858
- return {
1859
- options: loaded.options,
1860
- plugins,
1861
- removed
1862
- };
1863
- } catch (error) {
1864
- if ((error instanceof Error ? error.message : String(error)).includes("No PostCSS Config found")) return;
1865
- throw error;
1866
- }
1867
- }
1868
- function isTailwindVitePlugin(plugin) {
1869
- if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
1870
- const { name } = plugin;
1871
- return typeof name === "string" && name.startsWith("@tailwindcss/vite");
1872
- }
1873
- function removeTailwindVitePlugins(plugins) {
1874
- let removed = 0;
1875
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
1876
- plugins.splice(i, 1);
1877
- removed++;
1878
- }
1879
- return removed;
1880
- }
1881
- function disableTailwindVitePlugin(plugin) {
1882
- if (!isTailwindVitePlugin(plugin)) return false;
1883
- const mutablePlugin = plugin;
1884
- for (const hook of [
1885
- "configResolved",
1886
- "configureServer",
1887
- "transform",
1888
- "hotUpdate",
1889
- "handleHotUpdate"
1890
- ]) delete mutablePlugin[hook];
1891
- return true;
1892
- }
1893
- function disableAndRemoveTailwindVitePlugins(plugins) {
1894
- let removed = 0;
1895
- for (let i = plugins.length - 1; i >= 0; i--) {
1896
- const plugin = plugins[i];
1897
- if (Array.isArray(plugin)) {
1898
- removed += disableAndRemoveTailwindVitePlugins(plugin);
1899
- if (plugin.length === 0) plugins.splice(i, 1);
1900
- continue;
1901
- }
1902
- if (disableTailwindVitePlugin(plugin)) {
1903
- plugins.splice(i, 1);
1904
- removed++;
1905
- }
1906
- }
1907
- return removed;
1908
- }
1909
2106
  function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1910
2107
  const resolvedRoot = path.resolve(root);
1911
2108
  if (!existsSync(resolvedRoot)) return resolvedRoot;
@@ -1923,6 +2120,11 @@ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1923
2120
  if (packageRoot && existsSync(path.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1924
2121
  return resolvedRoot;
1925
2122
  }
2123
+ //#endregion
2124
+ //#region src/bundlers/vite/index.ts
2125
+ const debug = createDebug();
2126
+ const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
2127
+ const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1926
2128
  /**
1927
2129
  * @name WeappTailwindcss
1928
2130
  * @description uni-app vite / uni-app-x 版本插件
@@ -1931,131 +2133,68 @@ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1931
2133
  function WeappTailwindcss(options = {}) {
1932
2134
  const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
1933
2135
  const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1934
- const opts = getCompilerContext(options);
2136
+ const opts = getCompilerContext({
2137
+ ...options,
2138
+ __internalDeferMissingCssEntriesWarning: true
2139
+ });
1935
2140
  const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, twPatcher: initialTwPatcher, refreshTailwindcssPatcher, uniAppX, disabledDefaultTemplateHandler } = opts;
1936
2141
  const uniAppXEnabled = isUniAppXEnabled(uniAppX);
1937
2142
  const disabledOptions = resolvePluginDisabledState(disabled);
1938
2143
  const tailwindcssMajorVersion = initialTwPatcher.majorVersion ?? 0;
1939
2144
  const shouldOwnTailwindGeneration = !disabledOptions.plugin;
1940
2145
  const shouldRewriteCssImports = tailwindcssMajorVersion >= 4;
2146
+ const hasInitialTailwindCssRoots = hasConfiguredTailwindV4CssRoots({
2147
+ ...options,
2148
+ cssEntries: opts.cssEntries ?? options.cssEntries
2149
+ });
2150
+ const autoCssSourceContent = /* @__PURE__ */ new Map();
2151
+ let refreshRuntimeStateForAutoCssSources;
2152
+ let autoCssSourcesRefresh;
2153
+ const registerAutoCssSource = async (id, css) => {
2154
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
2155
+ const file = cleanUrl$1(id);
2156
+ if (!path.isAbsolute(file)) return;
2157
+ const sourceFile = path.normalize(file);
2158
+ if (autoCssSourceContent.get(sourceFile) === css) return;
2159
+ autoCssSourceContent.set(sourceFile, css);
2160
+ upsertTailwindV4CssSource(opts, {
2161
+ file: sourceFile,
2162
+ css
2163
+ });
2164
+ debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
2165
+ autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
2166
+ await refreshRuntimeStateForAutoCssSources?.(true);
2167
+ });
2168
+ await autoCssSourcesRefresh;
2169
+ };
1941
2170
  const rewritePlugins = createRewriteCssImportsPlugins({
1942
2171
  getAppType: () => opts.appType,
1943
2172
  rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
2173
+ onTailwindRootCss: (id, code) => registerAutoCssSource(id, code),
1944
2174
  shouldOwnTailwindGeneration,
1945
2175
  shouldRewrite: shouldRewriteCssImports,
1946
2176
  weappTailwindcssDirPosix
1947
2177
  });
1948
2178
  if (disabledOptions.plugin) return rewritePlugins.length ? rewritePlugins : void 0;
1949
2179
  const customAttributesEntities = toCustomAttributesEntities(customAttributes);
1950
- const patchRecorderState = setupPatchRecorder(initialTwPatcher, opts.tailwindcssBasedir, {
1951
- source: "runtime",
1952
- cwd: opts.tailwindcssBasedir ?? process.cwd()
1953
- });
1954
- const runtimeState = {
1955
- twPatcher: initialTwPatcher,
1956
- patchPromise: patchRecorderState.patchPromise,
1957
- refreshTailwindcssPatcher,
1958
- onPatchCompleted: patchRecorderState.onPatchCompleted
1959
- };
1960
- let runtimeSet;
1961
- let runtimeSetPromise;
1962
2180
  let resolvedConfig;
1963
- let runtimeRefreshSignature;
1964
- let runtimeRefreshOptionsKey;
1965
2181
  let recordedGeneratorCandidates;
1966
- const bundleRuntimeClassSetManager = createBundleRuntimeClassSetManager();
1967
2182
  const sourceCandidateCollector = createSourceCandidateCollector();
1968
2183
  const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1969
2184
  const processedCssAssets = /* @__PURE__ */ new WeakSet();
1970
2185
  const processedCssAssetFiles = /* @__PURE__ */ new Set();
1971
2186
  const rememberedMainCssSources = /* @__PURE__ */ new Map();
1972
2187
  const rememberedMainCssSignatureByFile = /* @__PURE__ */ new Map();
1973
- function resolveRuntimeRefreshOptions() {
1974
- const configPath = resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1975
- const signature = getRuntimeClassSetSignature(runtimeState.twPatcher);
1976
- const optionsKey = JSON.stringify({
1977
- appType: opts.appType,
1978
- uniAppX: uniAppXEnabled,
1979
- customAttributesEntities,
1980
- disabledDefaultTemplateHandler,
1981
- configPath
1982
- });
1983
- const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1984
- runtimeRefreshSignature = signature;
1985
- runtimeRefreshOptionsKey = optionsKey;
1986
- return {
1987
- changed,
1988
- signature,
1989
- optionsKey
1990
- };
1991
- }
1992
- async function refreshRuntimeState(force) {
1993
- const invalidation = resolveRuntimeRefreshOptions();
1994
- const refreshed = await refreshTailwindRuntimeState(runtimeState, {
1995
- force: force || invalidation.changed,
1996
- clearCache: force || invalidation.changed
1997
- });
1998
- if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1999
- if (refreshed) {
2000
- runtimeSet = void 0;
2001
- runtimeSetPromise = void 0;
2002
- }
2003
- }
2004
- async function ensureRuntimeClassSet(force = false) {
2005
- const forceRuntimeRefresh = force || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
2006
- await refreshRuntimeState(force);
2007
- await runtimeState.patchPromise;
2008
- if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
2009
- if (forceRuntimeRefresh || !runtimeSetPromise) {
2010
- const invalidation = resolveRuntimeRefreshOptions();
2011
- runtimeSetPromise = collectRuntimeClassSet(runtimeState.twPatcher, {
2012
- force: forceRuntimeRefresh || invalidation.changed,
2013
- skipRefresh: forceRuntimeRefresh,
2014
- clearCache: forceRuntimeRefresh || invalidation.changed
2015
- });
2016
- }
2017
- const task = runtimeSetPromise;
2018
- try {
2019
- runtimeSet = await task;
2020
- return runtimeSet;
2021
- } finally {
2022
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
2023
- }
2024
- }
2025
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
2026
- const forceRuntimeRefresh = forceRefresh || process.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
2027
- const invalidation = resolveRuntimeRefreshOptions();
2028
- const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
2029
- const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
2030
- await refreshRuntimeState(shouldRefreshPatcher);
2031
- await runtimeState.patchPromise;
2032
- if (shouldRefreshPatcher) {
2033
- runtimeSet = void 0;
2034
- runtimeSetPromise = void 0;
2035
- await bundleRuntimeClassSetManager.reset();
2036
- }
2037
- if (runtimeState.twPatcher.majorVersion === 4 && !forceRuntimeRefresh) try {
2038
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot);
2039
- runtimeSet = nextRuntimeSet;
2040
- return nextRuntimeSet;
2041
- } catch (error) {
2042
- debug("incremental runtime set sync failed, fallback to full collect: %O", error);
2043
- await bundleRuntimeClassSetManager.reset();
2044
- }
2045
- if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
2046
- const task = collectRuntimeClassSet(runtimeState.twPatcher, {
2047
- force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
2048
- skipRefresh: forceRuntimeRefresh,
2049
- clearCache: forceRuntimeRefresh || invalidation.changed
2050
- });
2051
- runtimeSetPromise = task;
2052
- try {
2053
- runtimeSet = await task;
2054
- return runtimeSet;
2055
- } finally {
2056
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
2057
- }
2058
- }
2188
+ const { runtimeState, refreshRuntimeState, ensureRuntimeClassSet, ensureBundleRuntimeClassSet } = createViteRuntimeClassSet({
2189
+ opts,
2190
+ initialTwPatcher,
2191
+ refreshTailwindcssPatcher,
2192
+ uniAppXEnabled,
2193
+ customAttributesEntities,
2194
+ disabledDefaultTemplateHandler,
2195
+ debug
2196
+ });
2197
+ refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2059
2198
  onLoad();
2060
2199
  const getResolvedConfig = () => resolvedConfig;
2061
2200
  const markCssAssetProcessed = (asset, file) => {
@@ -2093,6 +2232,22 @@ function WeappTailwindcss(options = {}) {
2093
2232
  const setRememberedMainCssSignature = (file, cssRuntimeSignature) => {
2094
2233
  rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
2095
2234
  };
2235
+ const generateBundleHook = createGenerateBundleHook({
2236
+ opts,
2237
+ runtimeState,
2238
+ ensureRuntimeClassSet,
2239
+ ensureBundleRuntimeClassSet,
2240
+ debug,
2241
+ getResolvedConfig,
2242
+ markCssAssetProcessed,
2243
+ getSourceCandidates,
2244
+ waitForSourceCandidateSyncs,
2245
+ rememberMainCssSource,
2246
+ getRememberedMainCssSources,
2247
+ getRememberedMainCssSignature,
2248
+ setRememberedMainCssSignature,
2249
+ recordGeneratorCandidates
2250
+ });
2096
2251
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2097
2252
  opts,
2098
2253
  runtimeState,
@@ -2148,6 +2303,18 @@ function WeappTailwindcss(options = {}) {
2148
2303
  root,
2149
2304
  outDir
2150
2305
  });
2306
+ const basedir = opts.tailwindcssBasedir ? path.resolve(opts.tailwindcssBasedir) : void 0;
2307
+ if (basedir && basedir !== path.resolve(root)) await sourceCandidateCollector.scanRoot({
2308
+ root: basedir,
2309
+ outDir
2310
+ });
2311
+ for (const cssEntry of opts.tailwindcss?.cssEntries ?? []) {
2312
+ const cssEntryRoot = path.dirname(path.resolve(cssEntry));
2313
+ if (cssEntryRoot !== path.resolve(root) && cssEntryRoot !== basedir) await sourceCandidateCollector.scanRoot({
2314
+ root: cssEntryRoot,
2315
+ outDir
2316
+ });
2317
+ }
2151
2318
  }
2152
2319
  },
2153
2320
  {
@@ -2220,22 +2387,7 @@ function WeappTailwindcss(options = {}) {
2220
2387
  },
2221
2388
  generateBundle: {
2222
2389
  order: "post",
2223
- handler: createGenerateBundleHook({
2224
- opts,
2225
- runtimeState,
2226
- ensureRuntimeClassSet,
2227
- ensureBundleRuntimeClassSet,
2228
- debug,
2229
- getResolvedConfig,
2230
- markCssAssetProcessed,
2231
- getSourceCandidates,
2232
- waitForSourceCandidateSyncs,
2233
- rememberMainCssSource,
2234
- getRememberedMainCssSources,
2235
- getRememberedMainCssSignature,
2236
- setRememberedMainCssSignature,
2237
- recordGeneratorCandidates
2238
- })
2390
+ handler: generateBundleHook
2239
2391
  },
2240
2392
  outputOptions(options) {
2241
2393
  const plugins = options.plugins;