weapp-tailwindcss 5.0.0-next.11 → 5.0.0-next.13

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 (81) hide show
  1. package/dist/{bundle-state-BRkhpjio.js → bundle-state-Bz8vLnCf.js} +3 -2
  2. package/dist/{bundle-state-BrtFgX-A.mjs → bundle-state-CP2XS3Uj.mjs} +3 -2
  3. package/dist/bundlers/shared/css-cleanup.d.ts +6 -1
  4. package/dist/bundlers/shared/generator-css/source-files.d.ts +9 -6
  5. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +16 -2
  6. package/dist/bundlers/shared/generator-css.d.ts +4 -0
  7. package/dist/bundlers/shared/hmr-timing.d.ts +18 -1
  8. package/dist/bundlers/vite/bundle-state.d.ts +1 -0
  9. package/dist/bundlers/vite/css-finalizer.d.ts +2 -0
  10. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +5 -1
  11. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +1 -0
  12. package/dist/bundlers/vite/generate-bundle.d.ts +8 -1
  13. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +1 -0
  14. package/dist/bundlers/vite/runtime-class-set.d.ts +4 -1
  15. package/dist/bundlers/vite/source-candidates.d.ts +11 -0
  16. package/dist/bundlers/vite/source-scan.d.ts +18 -1
  17. package/dist/bundlers/vite/static-config-content.d.ts +5 -0
  18. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +5 -0
  19. package/dist/cli.js +453 -9
  20. package/dist/cli.mjs +451 -8
  21. package/dist/core.js +1 -1
  22. package/dist/core.mjs +1 -1
  23. package/dist/css-macro/postcss.js +1 -1
  24. package/dist/css-macro/postcss.mjs +1 -1
  25. package/dist/css-macro.js +2 -2
  26. package/dist/css-macro.mjs +2 -2
  27. package/dist/defaults.js +1 -1
  28. package/dist/defaults.mjs +1 -1
  29. package/dist/generator-C9H44wEF.mjs +32 -0
  30. package/dist/generator-CRORPkpW.js +55 -0
  31. package/dist/generator.js +12 -11
  32. package/dist/generator.mjs +2 -1
  33. package/dist/gulp.js +49 -13
  34. package/dist/gulp.mjs +46 -10
  35. package/dist/{incremental-runtime-class-set-CBMefNHQ.js → incremental-runtime-class-set-DN9KKjSi.js} +512 -103
  36. package/dist/{incremental-runtime-class-set-DaS2yw5c.mjs → incremental-runtime-class-set-Dbn4yPfZ.mjs} +491 -88
  37. package/dist/index.js +4 -4
  38. package/dist/index.mjs +4 -4
  39. package/dist/{postcss-BdcRlSpp.js → postcss-Ab7YzAbs.js} +30 -19
  40. package/dist/{postcss-Bs-RbNzK.js → postcss-CZE8k8oP.js} +59 -53
  41. package/dist/{postcss-xZDiTRII.mjs → postcss-CtlrNknb.mjs} +19 -8
  42. package/dist/postcss.js +1 -1
  43. package/dist/postcss.mjs +1 -1
  44. package/dist/{precheck-D5eEdqeH.js → precheck-CRX-pMKJ.js} +37 -17
  45. package/dist/{precheck-DtBGFS-n.mjs → precheck-SG48aLG2.mjs} +29 -9
  46. package/dist/presets.js +6 -6
  47. package/dist/presets.mjs +4 -4
  48. package/dist/source-candidates-C4YgmZ8A.js +274 -0
  49. package/dist/source-candidates-CyupdLKi.mjs +259 -0
  50. package/dist/tailwindcss/runtime/cache.d.ts +1 -0
  51. package/dist/tailwindcss/v3-engine/types.d.ts +3 -0
  52. package/dist/tailwindcss/v4-engine/types.d.ts +8 -0
  53. package/dist/{tailwindcss-DGM8lHUj.mjs → tailwindcss-BbTVeQkG.mjs} +9 -4
  54. package/dist/{tailwindcss-B78nj6n7.js → tailwindcss-DZ6jVYb4.js} +21 -16
  55. package/dist/v3-engine-D61eilBl.mjs +3208 -0
  56. package/dist/v3-engine-DwV1E6rX.js +3461 -0
  57. package/dist/{vite-C8S1wfyQ.mjs → vite-Ti_qSctn.mjs} +380 -542
  58. package/dist/{vite-BEj9JOOA.js → vite-xKS6RvLR.js} +385 -550
  59. package/dist/vite.js +1 -1
  60. package/dist/vite.mjs +1 -1
  61. package/dist/weapp-tw-css-import-rewrite-loader.js +29 -9
  62. package/dist/weapp-tw-runtime-classset-loader.js +1 -1
  63. package/dist/{webpack-ZGIKKpFf.mjs → webpack-DvptFz7B.mjs} +36 -19
  64. package/dist/{webpack-Dm1IXTIh.js → webpack-wfNutjMm.js} +40 -23
  65. package/dist/webpack.js +1 -1
  66. package/dist/webpack.mjs +1 -1
  67. package/package.json +3 -3
  68. package/dist/cache-B_9E7FxF.js +0 -517
  69. package/dist/cache-DEDxBMIw.mjs +0 -443
  70. package/dist/generator-CahkD2vq.mjs +0 -1469
  71. package/dist/generator-Ck1Dd1V0.js +0 -1568
  72. package/dist/runtime-patch-CqB-A4zA.js +0 -85
  73. package/dist/runtime-patch-DGKsVkiG.mjs +0 -71
  74. package/dist/source-scan-CIVTa3Cj.js +0 -297
  75. package/dist/source-scan-CJ0y0XBj.mjs +0 -258
  76. /package/dist/{constants-BeeyfJ9k.js → constants-BoB_6lFw.js} +0 -0
  77. /package/dist/{constants-BG12WAKw.mjs → constants-E_loJC49.mjs} +0 -0
  78. /package/dist/{logger-EVNB9z7i.js → logger-BRy6XPQ2.js} +0 -0
  79. /package/dist/{logger-CZUxvJJD.mjs → logger-Bub1jggA.mjs} +0 -0
  80. /package/dist/{utils-CGBVVNm6.mjs → utils-CycMvPn_.mjs} +0 -0
  81. /package/dist/{utils-4ODFyoqD.js → utils-D0MZP_tr.js} +0 -0
@@ -1,34 +1,25 @@
1
1
  const require_chunk = require("./chunk-8l464Juk.js");
2
- const require_cache = require("./cache-B_9E7FxF.js");
3
- const require_runtime_patch = require("./runtime-patch-CqB-A4zA.js");
4
- const require_generator = require("./generator-Ck1Dd1V0.js");
5
- const require_incremental_runtime_class_set = require("./incremental-runtime-class-set-CBMefNHQ.js");
6
- const require_precheck = require("./precheck-D5eEdqeH.js");
7
- const require_utils = require("./utils-4ODFyoqD.js");
8
- const require_tailwindcss = require("./tailwindcss-B78nj6n7.js");
9
- const require_source_scan = require("./source-scan-CIVTa3Cj.js");
10
- const require_bundle_state = require("./bundle-state-BRkhpjio.js");
11
- require("./logger-EVNB9z7i.js");
12
- let postcss = require("postcss");
13
- postcss = require_chunk.__toESM(postcss);
2
+ const require_v3_engine = require("./v3-engine-DwV1E6rX.js");
3
+ const require_generator = require("./generator-CRORPkpW.js");
4
+ const require_incremental_runtime_class_set = require("./incremental-runtime-class-set-DN9KKjSi.js");
5
+ const require_precheck = require("./precheck-CRX-pMKJ.js");
6
+ const require_utils = require("./utils-D0MZP_tr.js");
7
+ const require_tailwindcss = require("./tailwindcss-DZ6jVYb4.js");
8
+ const require_source_candidates = require("./source-candidates-C4YgmZ8A.js");
9
+ const require_bundle_state = require("./bundle-state-Bz8vLnCf.js");
10
+ require("./logger-BRy6XPQ2.js");
11
+ let node_fs = require("node:fs");
12
+ node_fs = require_chunk.__toESM(node_fs);
14
13
  let node_path = require("node:path");
15
14
  node_path = require_chunk.__toESM(node_path);
16
15
  let node_process = require("node:process");
17
16
  node_process = require_chunk.__toESM(node_process);
18
17
  let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
19
18
  let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
20
- let tailwindcss_patch = require("tailwindcss-patch");
21
- let node_fs = require("node:fs");
22
- node_fs = require_chunk.__toESM(node_fs);
23
- let tailwindcss_config = require("tailwindcss-config");
24
19
  let node_fs_promises = require("node:fs/promises");
25
20
  let magic_string = require("magic-string");
26
21
  magic_string = require_chunk.__toESM(magic_string);
27
22
  let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
28
- let fast_glob = require("fast-glob");
29
- fast_glob = require_chunk.__toESM(fast_glob);
30
- let micromatch = require("micromatch");
31
- micromatch = require_chunk.__toESM(micromatch);
32
23
  let _weapp_tailwindcss_postcss_html_transform = require("@weapp-tailwindcss/postcss/html-transform");
33
24
  _weapp_tailwindcss_postcss_html_transform = require_chunk.__toESM(_weapp_tailwindcss_postcss_html_transform);
34
25
  let _vue_compiler_dom = require("@vue/compiler-dom");
@@ -405,7 +396,7 @@ function createUniAppXPlugins(options) {
405
396
  const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
406
397
  let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
407
398
  if (!styleHandlerOptions) {
408
- styleHandlerOptions = require_cache.omitUndefined({
399
+ styleHandlerOptions = require_v3_engine.omitUndefined({
409
400
  isMainChunk: mainCssChunkMatcher(id, appType),
410
401
  uniAppXCssTarget: resolveUniAppXCssTarget(id),
411
402
  uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
@@ -544,6 +535,7 @@ function createCssHandlerOptions(opts, majorVersion, file) {
544
535
  function shouldGenerateCssByGenerator(opts, file, rawSource, processed) {
545
536
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
546
537
  if (require_incremental_runtime_class_set.hasTailwindGeneratedCssMarkers(rawSource) || require_incremental_runtime_class_set.hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return true;
538
+ if (opts.twPatcher.majorVersion === 3) return false;
547
539
  return processed && shouldFinalizeProcessedCssAsset(opts, file);
548
540
  }
549
541
  function shouldFinalizeProcessedCssAsset(opts, file) {
@@ -555,7 +547,7 @@ function createViteCssFinalizerOutputPlugin(context) {
555
547
  generateBundle: {
556
548
  order: "post",
557
549
  async handler(_options, bundle) {
558
- const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource } = context;
550
+ const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource } = context;
559
551
  if (getResolvedConfig()?.command !== "build") return;
560
552
  const isCssOutputAssetEntry = (entry) => {
561
553
  const [, output] = entry;
@@ -568,7 +560,7 @@ function createViteCssFinalizerOutputPlugin(context) {
568
560
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
569
561
  const runtime = getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet();
570
562
  const collectedGeneratorCandidates = new Set([...runtime, ...getSourceCandidates?.() ?? []]);
571
- const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
563
+ const generatorRuntime = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp" ? require_v3_engine.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates;
572
564
  await Promise.all(entries.map(async ([bundleFile, output]) => {
573
565
  const file = output.fileName || bundleFile;
574
566
  const rawSource = output.source.toString();
@@ -585,6 +577,7 @@ function createViteCssFinalizerOutputPlugin(context) {
585
577
  file,
586
578
  cssHandlerOptions,
587
579
  cssUserHandlerOptions,
580
+ getSourceCandidatesForEntries,
588
581
  styleHandler: opts.styleHandler,
589
582
  debug
590
583
  }) : void 0;
@@ -640,20 +633,25 @@ function createCssHandlerOptionsCache(options) {
640
633
  const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
641
634
  const getCssHandlerOptions = (file) => {
642
635
  const majorVersion = options.getMajorVersion();
643
- const isMainChunk = options.mainCssChunkMatcher(file, options.appType);
644
- const cacheKey = `${majorVersion ?? "unknown"}:${isMainChunk ? "1" : "0"}:${file}`;
636
+ const appType = options.getAppType();
637
+ const isMainChunk = options.mainCssChunkMatcher(file, appType);
638
+ const outputRoot = options.getOutputRoot?.();
639
+ const cacheKey = `${majorVersion ?? "unknown"}:${appType ?? "unknown"}:${isMainChunk ? "1" : "0"}:${outputRoot ?? ""}:${file}`;
645
640
  const cached = cssHandlerOptionsCache.get(cacheKey);
646
641
  if (cached) return cached;
647
642
  const created = {
648
643
  isMainChunk,
649
644
  postcssOptions: { options: { from: file } },
650
- majorVersion
645
+ majorVersion,
646
+ sourceOptions: { outputRoot }
651
647
  };
652
648
  cssHandlerOptionsCache.set(cacheKey, created);
653
649
  return created;
654
650
  };
655
651
  const getCssUserHandlerOptions = (file) => {
656
- const cacheKey = `${options.getMajorVersion() ?? "unknown"}:${file}`;
652
+ const majorVersion = options.getMajorVersion();
653
+ const outputRoot = options.getOutputRoot?.();
654
+ const cacheKey = `${majorVersion ?? "unknown"}:${outputRoot ?? ""}:${file}`;
657
655
  const cached = cssUserHandlerOptionsCache.get(cacheKey);
658
656
  if (cached) return cached;
659
657
  const created = {
@@ -692,6 +690,8 @@ function createCssTransformShareScope(file, rawSource) {
692
690
  }
693
691
  function createCssTransformShareScopeKey(opts, file, rawSource) {
694
692
  if (opts.mainCssChunkMatcher(file, opts.appType)) return `main:${require_bundle_state.normalizeOutputPathKey(file)}`;
693
+ const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
694
+ if (require_incremental_runtime_class_set.hasTailwindGeneratedCssMarkers(rawSource) || require_incremental_runtime_class_set.hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return `source:${require_bundle_state.normalizeOutputPathKey(file)}`;
695
695
  return createCssTransformShareScope(file, rawSource);
696
696
  }
697
697
  function createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature) {
@@ -883,16 +883,29 @@ function hasRuntimeAffectingSourceChanges(changedByType) {
883
883
  }
884
884
  //#endregion
885
885
  //#region src/bundlers/vite/generate-bundle.ts
886
+ function addSiblingCssFile(files, file) {
887
+ if (file.endsWith(".wxml")) files.add(file.replace(/\.wxml$/, ".wxss"));
888
+ else if (file.endsWith(".js")) files.add(file.replace(/\.js$/, ".wxss"));
889
+ }
890
+ function collectRuntimeLinkedCssFiles(snapshot) {
891
+ const files = /* @__PURE__ */ new Set();
892
+ for (const file of snapshot.runtimeAffectingChangedByType.html) addSiblingCssFile(files, file);
893
+ for (const file of snapshot.runtimeAffectingChangedByType.js) addSiblingCssFile(files, file);
894
+ return files;
895
+ }
886
896
  function createGenerateBundleHook(context) {
887
897
  const state = require_bundle_state.createBundleBuildState();
898
+ const lastCssResultByFile = /* @__PURE__ */ new Map();
899
+ let currentOutDir;
888
900
  const cssHandlerOptions = createCssHandlerOptionsCache({
889
- appType: context.opts.appType,
901
+ getAppType: () => context.opts.appType,
890
902
  mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
891
- getMajorVersion: () => context.runtimeState.twPatcher.majorVersion
903
+ getMajorVersion: () => context.runtimeState.twPatcher.majorVersion,
904
+ getOutputRoot: () => currentOutDir
892
905
  });
893
906
  return async function generateBundle(_opt, bundle) {
894
907
  const addWatchFile = (id) => this.addWatchFile?.(id);
895
- const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates } = context;
908
+ const { opts, runtimeState, ensureBundleRuntimeClassSet, debug, getResolvedConfig, markCssAssetProcessed, recordCssAssetResult, getSourceCandidates, getSourceCandidatesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSources, getRememberedMainCssSignature, setRememberedMainCssSignature, recordGeneratorCandidates, hmrTimingRecorder } = context;
896
909
  const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
897
910
  const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(opts.generator);
898
911
  const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
@@ -900,17 +913,35 @@ function createGenerateBundleHook(context) {
900
913
  debug("start");
901
914
  onStart();
902
915
  const hmrTimingStartedAt = performance.now();
916
+ const timingDetails = {};
917
+ const recordTimingDetail = (name, startedAt) => {
918
+ timingDetails[name] = (timingDetails[name] ?? 0) + Math.max(0, performance.now() - startedAt);
919
+ };
920
+ const timeTask = async (name, task) => {
921
+ const start = performance.now();
922
+ try {
923
+ await task();
924
+ } finally {
925
+ recordTimingDetail(`tasks.${name}`, start);
926
+ }
927
+ };
903
928
  const metrics = createEmptyMetrics();
904
929
  const forceRuntimeRefreshByEnv = node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
905
930
  const disableDirtyOptimization = node_process.default.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1";
906
931
  const disableJsPrecheck = node_process.default.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1";
907
932
  const debugCssDiff = node_process.default.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1";
933
+ const disableV3OxideSourceRuntime = node_process.default.env["WEAPP_TW_VITE_DISABLE_V3_OXIDE_RUNTIME"] === "1";
908
934
  const resolvedConfig = getResolvedConfig();
909
935
  const bundleFiles = Object.keys(bundle);
910
- const useIncrementalMode = !(resolvedConfig?.command === "build") || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
936
+ const buildCommand = resolvedConfig?.command === "build";
937
+ const hasPreviousBundleState = state.iteration > 0 || state.sourceHashByFile.size > 0;
938
+ const useIncrementalMode = !buildCommand || hasPreviousBundleState || hasOmittedKnownBundleFiles(bundleFiles, state.sourceHashByFile.keys());
911
939
  const rootDir = resolvedConfig?.root ? node_path.default.resolve(resolvedConfig.root) : node_process.default.cwd();
912
940
  const outDir = resolvedConfig?.build?.outDir ? node_path.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
941
+ currentOutDir = outDir;
942
+ const snapshotStart = performance.now();
913
943
  const snapshot = require_bundle_state.buildBundleSnapshot(bundle, opts, outDir, state, disableDirtyOptimization || !useIncrementalMode);
944
+ recordTimingDetail("snapshot", snapshotStart);
914
945
  const useBundleRuntimeClassSet = useIncrementalMode || runtimeState.twPatcher.majorVersion === 4;
915
946
  const forceRuntimeRefreshBySource = useIncrementalMode && hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
916
947
  const processFiles = snapshot.processFiles;
@@ -920,18 +951,27 @@ function createGenerateBundleHook(context) {
920
951
  useIncrementalMode,
921
952
  iteration: state.iteration + 1
922
953
  });
954
+ const sourceCandidateWaitStart = performance.now();
955
+ await waitForSourceCandidateSyncs?.();
956
+ recordTimingDetail("sourceCandidates.wait", sourceCandidateWaitStart);
957
+ const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
923
958
  const jsEntries = snapshot.jsEntries;
924
959
  const getJsEntry = createJsEntryResolver(jsEntries);
925
960
  const moduleGraphOptions = require_bundle_state.createBundleModuleGraphOptions(outDir, jsEntries);
961
+ const hasCssAssetEntry = snapshot.entries.some((entry) => entry.type === "css" && entry.output.type === "asset");
962
+ const hasRuntimeAffectingChanges = hasRuntimeAffectingSourceChanges(snapshot.runtimeAffectingChangedByType);
963
+ const useV3OxideSourceRuntime = runtimeState.twPatcher.majorVersion === 3 && sourceCandidates.size > 0 && hasCssAssetEntry && !forceRuntimeRefreshByEnv && !disableV3OxideSourceRuntime;
926
964
  const runtimeStart = performance.now();
927
- const runtime = useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
965
+ const runtime = useV3OxideSourceRuntime ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, {
966
+ allowBaselineOnlyInitialSync: true,
967
+ baseClassSet: sourceCandidates
968
+ }) : useBundleRuntimeClassSet ? await ensureBundleRuntimeClassSet(snapshot, forceRuntimeRefreshByEnv, { allowBaselineOnlyInitialSync: buildCommand }) : await context.ensureRuntimeClassSet(forceRuntimeRefreshByEnv);
969
+ if (useV3OxideSourceRuntime) debug("[tailwindcss:v3] use oxide source candidates as runtime input, candidates=%d", sourceCandidates.size);
928
970
  const shouldFilterTailwindV4MiniProgramCandidates = runtimeState.twPatcher.majorVersion === 4 && generatorOptions.target === "weapp";
929
- await waitForSourceCandidateSyncs?.();
930
- const sourceCandidates = getSourceCandidates?.() ?? /* @__PURE__ */ new Set();
931
971
  const collectedGeneratorCandidates = new Set([...runtime, ...sourceCandidates]);
932
- let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? require_generator.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
972
+ let generatorRuntime = collectLegacyContainerCompatCandidates(sourceCandidates, shouldFilterTailwindV4MiniProgramCandidates ? require_v3_engine.filterUnsupportedMiniProgramTailwindV4Candidates(collectedGeneratorCandidates) : collectedGeneratorCandidates);
933
973
  let transformRuntime = runtime;
934
- if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0) {
974
+ if (runtimeState.twPatcher.majorVersion === 3 && generatorRuntime.size > 0 && !useV3OxideSourceRuntime) {
935
975
  const cssEntries = snapshot.entries.filter((entry) => entry.type === "css" && entry.output.type === "asset");
936
976
  const mainCssEntry = cssEntries.find((entry) => getCssHandlerOptions(entry.file).isMainChunk) ?? cssEntries[0];
937
977
  if (mainCssEntry) {
@@ -956,12 +996,16 @@ function createGenerateBundleHook(context) {
956
996
  }
957
997
  }
958
998
  const generatorCandidateSignature = createCandidateSignature(generatorRuntime);
999
+ const generatorCandidatesChanged = state.generatorCandidateSignature !== generatorCandidateSignature;
1000
+ const runtimeLinkedCssFiles = collectRuntimeLinkedCssFiles(snapshot);
959
1001
  recordGeneratorCandidates?.(generatorRuntime);
960
1002
  const defaultTemplateHandlerOptions = { runtimeSet: transformRuntime };
961
1003
  metrics.runtimeSet = measureElapsed(runtimeStart);
1004
+ timingDetails.runtime = metrics.runtimeSet;
962
1005
  if (forceRuntimeRefreshBySource) debug("runtimeSet forced refresh due to source changes: html=%d js=%d", snapshot.runtimeAffectingChangedByType.html.size, snapshot.runtimeAffectingChangedByType.js.size);
963
1006
  debug("get runtimeSet, class count: %d, transform class count: %d", runtime.size, transformRuntime.size);
964
- const runtimeSignature = require_cache.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1007
+ const runtimeSignature = require_v3_engine.getRuntimeClassSetSignature(runtimeState.twPatcher) ?? "runtime:missing";
1008
+ const shouldProcessTailwindGeneration = !useIncrementalMode || hasRuntimeAffectingChanges || generatorCandidatesChanged || snapshot.processFiles.css.size > 0;
965
1009
  const { applyLinkedUpdates, pendingLinkedUpdates } = createLinkedUpdateHelpers({
966
1010
  jsEntries,
967
1011
  onUpdate,
@@ -981,7 +1025,7 @@ function createGenerateBundleHook(context) {
981
1025
  metrics.html.total++;
982
1026
  if (!processFiles.html.has(file)) continue;
983
1027
  const rawSource = originalEntrySource;
984
- tasks.push(require_incremental_runtime_class_set.processCachedTask({
1028
+ tasks.push(timeTask("html", () => require_incremental_runtime_class_set.processCachedTask({
985
1029
  cache,
986
1030
  cacheKey: file,
987
1031
  hashKey: `${file}:html:${runtimeSignature}`,
@@ -1009,7 +1053,7 @@ function createGenerateBundleHook(context) {
1009
1053
  debug("html handle: %s", file);
1010
1054
  return { result: transformed };
1011
1055
  }
1012
- }));
1056
+ })));
1013
1057
  continue;
1014
1058
  }
1015
1059
  if (type === "css" && originalSource.type === "asset") {
@@ -1018,15 +1062,28 @@ function createGenerateBundleHook(context) {
1018
1062
  const cssRuntimeAffectingSignature = snapshot.runtimeAffectingSignatureByFile.get(file) ?? rawSource;
1019
1063
  const cssShareScope = createCssTransformShareScopeKey(opts, file, rawSource);
1020
1064
  const cssHandlerOptions = getCssHandlerOptions(file);
1021
- const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1065
+ const shouldTrackGeneratorRuntime = shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file));
1066
+ const scopedGeneratorCandidateSignature = shouldTrackGeneratorRuntime ? generatorCandidateSignature : "generator:stable";
1067
+ const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, scopedGeneratorCandidateSignature);
1022
1068
  const cssSharedCacheKey = `${cssShareScope}:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}:${cssHandlerOptions.isMainChunk ? "1" : "0"}:${cssRuntimeAffectingSignature}`;
1023
- tasks.push(require_incremental_runtime_class_set.processCachedTask({
1069
+ if (!shouldTrackGeneratorRuntime) {
1070
+ const lastCss = lastCssResultByFile.get(file);
1071
+ if (lastCss != null) {
1072
+ originalSource.source = lastCss;
1073
+ markCssAssetProcessed?.(originalSource, file);
1074
+ metrics.css.cacheHits++;
1075
+ debug("css replay last result: %s", file);
1076
+ continue;
1077
+ }
1078
+ }
1079
+ tasks.push(timeTask("css", () => require_incremental_runtime_class_set.processCachedTask({
1024
1080
  cache,
1025
1081
  cacheKey: file,
1026
1082
  hashKey: `${file}:css:${cssRuntimeSignature}:${runtimeState.twPatcher.majorVersion ?? "unknown"}`,
1027
- hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${generatorCandidateSignature}`,
1083
+ hash: `${getSnapshotHash(snapshot.runtimeAffectingHashByFile, file, cssRuntimeAffectingSignature)}:${scopedGeneratorCandidateSignature}`,
1028
1084
  applyResult(source) {
1029
1085
  originalSource.source = source;
1086
+ lastCssResultByFile.set(file, source);
1030
1087
  markCssAssetProcessed?.(originalSource, file);
1031
1088
  if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, rawSource, cssRuntimeSignature);
1032
1089
  },
@@ -1048,6 +1105,7 @@ function createGenerateBundleHook(context) {
1048
1105
  const runTransform = async () => {
1049
1106
  const start = performance.now();
1050
1107
  await runtimeState.readyPromise;
1108
+ const previousCss = useIncrementalMode && !snapshot.changedByType.css.has(file) ? lastCssResultByFile.get(file) : void 0;
1051
1109
  const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
1052
1110
  opts,
1053
1111
  runtimeState,
@@ -1056,8 +1114,10 @@ function createGenerateBundleHook(context) {
1056
1114
  file,
1057
1115
  cssHandlerOptions,
1058
1116
  cssUserHandlerOptions: getCssUserHandlerOptions(file),
1117
+ getSourceCandidatesForEntries,
1059
1118
  styleHandler,
1060
- debug
1119
+ debug,
1120
+ previousCss
1061
1121
  });
1062
1122
  if (generated) {
1063
1123
  registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
@@ -1082,7 +1142,7 @@ function createGenerateBundleHook(context) {
1082
1142
  debug("css handle: %s", file);
1083
1143
  return { result: css };
1084
1144
  }
1085
- }));
1145
+ })));
1086
1146
  continue;
1087
1147
  }
1088
1148
  if (type !== "js") continue;
@@ -1095,38 +1155,40 @@ function createGenerateBundleHook(context) {
1095
1155
  const linkedSet = useIncrementalMode ? /* @__PURE__ */ new Set() : void 0;
1096
1156
  if (linkedByEntry && linkedSet) linkedByEntry.set(file, linkedSet);
1097
1157
  jsTaskFactories.push(async () => {
1098
- const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1099
- await require_incremental_runtime_class_set.processCachedTask({
1100
- cache,
1101
- cacheKey: file,
1102
- hashKey: `${file}:js`,
1103
- hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1104
- applyResult(source) {
1105
- originalSource.code = source;
1106
- },
1107
- onCacheHit() {
1108
- metrics.js.cacheHits++;
1109
- debug("js cache hit: %s", file);
1110
- },
1111
- async transform() {
1112
- const start = performance.now();
1113
- const rawSource = originalSource.code;
1114
- if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1115
- const handlerOptions = createHandlerOptions(absoluteFile);
1116
- if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
1158
+ await timeTask("js", async () => {
1159
+ const hashSalt = createJsHashSalt(runtimeSignature, useIncrementalMode ? createLinkedImpactSignature(file, snapshot.linkedImpactsByEntry, snapshot.sourceHashByFile) : void 0);
1160
+ await require_incremental_runtime_class_set.processCachedTask({
1161
+ cache,
1162
+ cacheKey: file,
1163
+ hashKey: `${file}:js`,
1164
+ hash: `${getSnapshotHash(snapshot.sourceHashByFile, file, initialRawSource)}:${hashSalt}`,
1165
+ applyResult(source) {
1166
+ originalSource.code = source;
1167
+ },
1168
+ onCacheHit() {
1169
+ metrics.js.cacheHits++;
1170
+ debug("js cache hit: %s", file);
1171
+ },
1172
+ async transform() {
1173
+ const start = performance.now();
1174
+ const rawSource = originalSource.code;
1175
+ if (!shouldTransformJs) debug("js cache replay miss, fallback transform: %s", file);
1176
+ const handlerOptions = createHandlerOptions(absoluteFile);
1177
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(rawSource, handlerOptions)) {
1178
+ metrics.js.elapsed += measureElapsed(start);
1179
+ metrics.js.transformed++;
1180
+ return { result: rawSource };
1181
+ }
1182
+ const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1117
1183
  metrics.js.elapsed += measureElapsed(start);
1118
1184
  metrics.js.transformed++;
1119
- return { result: rawSource };
1185
+ onUpdate(file, rawSource, code);
1186
+ debug("js handle: %s", file);
1187
+ collectLinkedFileNames(linked, getJsEntry, linkedSet);
1188
+ applyLinkedUpdates(linked);
1189
+ return { result: code };
1120
1190
  }
1121
- const { code, linked } = await jsHandler(rawSource, transformRuntime, handlerOptions);
1122
- metrics.js.elapsed += measureElapsed(start);
1123
- metrics.js.transformed++;
1124
- onUpdate(file, rawSource, code);
1125
- debug("js handle: %s", file);
1126
- collectLinkedFileNames(linked, getJsEntry, linkedSet);
1127
- applyLinkedUpdates(linked);
1128
- return { result: code };
1129
- }
1191
+ });
1130
1192
  });
1131
1193
  });
1132
1194
  } else if (uniAppX && originalSource.type === "asset") {
@@ -1150,37 +1212,39 @@ function createGenerateBundleHook(context) {
1150
1212
  uniAppX
1151
1213
  });
1152
1214
  jsTaskFactories.push(async () => {
1153
- const start = performance.now();
1154
- if (!shouldTransformJs) {
1155
- debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1215
+ await timeTask("js", async () => {
1216
+ const start = performance.now();
1217
+ if (!shouldTransformJs) {
1218
+ debug("js skip transform (clean, uni-app-x), replay cache: %s", file);
1219
+ await factory();
1220
+ metrics.js.elapsed += measureElapsed(start);
1221
+ metrics.js.transformed++;
1222
+ return;
1223
+ }
1224
+ const currentSource = originalEntrySource;
1225
+ const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
1226
+ uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1227
+ babelParserOptions: {
1228
+ plugins: ["typescript"],
1229
+ sourceType: "unambiguous"
1230
+ }
1231
+ });
1232
+ if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
1233
+ metrics.js.elapsed += measureElapsed(start);
1234
+ metrics.js.transformed++;
1235
+ return;
1236
+ }
1156
1237
  await factory();
1157
1238
  metrics.js.elapsed += measureElapsed(start);
1158
1239
  metrics.js.transformed++;
1159
- return;
1160
- }
1161
- const currentSource = originalEntrySource;
1162
- const precheckOptions = createHandlerOptions(node_path.default.resolve(outDir, file), {
1163
- uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
1164
- babelParserOptions: {
1165
- plugins: ["typescript"],
1166
- sourceType: "unambiguous"
1167
- }
1168
1240
  });
1169
- if (!disableJsPrecheck && require_precheck.shouldSkipJsTransform(currentSource, precheckOptions)) {
1170
- metrics.js.elapsed += measureElapsed(start);
1171
- metrics.js.transformed++;
1172
- return;
1173
- }
1174
- await factory();
1175
- metrics.js.elapsed += measureElapsed(start);
1176
- metrics.js.transformed++;
1177
1241
  });
1178
1242
  }
1179
1243
  }
1180
1244
  const cssRuntimeSignature = createCssRuntimeSignature(runtimeSignature, generatorCandidateSignature);
1181
1245
  if (useIncrementalMode) for (const [file, rawSource] of getRememberedMainCssSources?.() ?? []) {
1182
1246
  if (bundleFiles.includes(file) || getRememberedMainCssSignature?.(file) === cssRuntimeSignature) continue;
1183
- tasks.push((async () => {
1247
+ tasks.push(timeTask("css.replay", async () => {
1184
1248
  const start = performance.now();
1185
1249
  const cssHandlerOptions = getCssHandlerOptions(file);
1186
1250
  const generated = await require_incremental_runtime_class_set.generateCssByGenerator({
@@ -1191,6 +1255,7 @@ function createGenerateBundleHook(context) {
1191
1255
  file,
1192
1256
  cssHandlerOptions,
1193
1257
  cssUserHandlerOptions: getCssUserHandlerOptions(file),
1258
+ getSourceCandidatesForEntries,
1194
1259
  styleHandler,
1195
1260
  debug
1196
1261
  });
@@ -1213,14 +1278,22 @@ function createGenerateBundleHook(context) {
1213
1278
  metrics.css.transformed++;
1214
1279
  onUpdate(file, rawSource, css);
1215
1280
  debug("css replay handle: %s", file);
1216
- })());
1281
+ }));
1217
1282
  }
1218
1283
  require_bundle_state.pushConcurrentTaskFactories(tasks, jsTaskFactories);
1284
+ const tasksStart = performance.now();
1219
1285
  await Promise.all(tasks);
1286
+ recordTimingDetail("tasks", tasksStart);
1220
1287
  for (const apply of pendingLinkedUpdates) apply();
1288
+ const stateUpdateStart = performance.now();
1221
1289
  require_bundle_state.updateBundleBuildState(state, snapshot, useIncrementalMode ? linkedByEntry ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(), { incremental: useIncrementalMode });
1290
+ state.generatorCandidateSignature = generatorCandidateSignature;
1291
+ recordTimingDetail("state.update", stateUpdateStart);
1222
1292
  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));
1223
- require_incremental_runtime_class_set.emitHmrTiming("vite", "generateBundle", performance.now() - hmrTimingStartedAt);
1293
+ if (hmrTimingRecorder) {
1294
+ hmrTimingRecorder.record("generateBundle", performance.now() - hmrTimingStartedAt, timingDetails);
1295
+ hmrTimingRecorder.emitTotal();
1296
+ }
1224
1297
  onEnd();
1225
1298
  debug("end");
1226
1299
  };
@@ -1468,8 +1541,8 @@ function createViteRuntimeClassSet(options) {
1468
1541
  let runtimeRefreshSignature;
1469
1542
  let runtimeRefreshOptionsKey;
1470
1543
  function resolveRuntimeRefreshOptions() {
1471
- const configPath = require_cache.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1472
- const signature = require_cache.getRuntimeClassSetSignature(runtimeState.twPatcher);
1544
+ const configPath = require_v3_engine.resolveTailwindcssOptions(runtimeState.twPatcher.options)?.config;
1545
+ const signature = require_v3_engine.getRuntimeClassSetSignature(runtimeState.twPatcher);
1473
1546
  const optionsKey = JSON.stringify({
1474
1547
  appType: opts.appType,
1475
1548
  uniAppX: uniAppXEnabled,
@@ -1519,7 +1592,7 @@ function createViteRuntimeClassSet(options) {
1519
1592
  if (runtimeSetPromise === task) runtimeSetPromise = void 0;
1520
1593
  }
1521
1594
  }
1522
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false) {
1595
+ async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, options = {}) {
1523
1596
  const forceRuntimeRefresh = forceRefresh || node_process.default.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
1524
1597
  const invalidation = resolveRuntimeRefreshOptions();
1525
1598
  const shouldRefreshPatcher = forceRuntimeRefresh || invalidation.changed;
@@ -1540,13 +1613,16 @@ function createViteRuntimeClassSet(options) {
1540
1613
  await bundleRuntimeClassSetManager.reset();
1541
1614
  }
1542
1615
  if (runtimeState.twPatcher.majorVersion === 3 && !forceRuntimeRefresh) try {
1543
- let baseClassSet;
1544
- if (!runtimeSet || shouldRefreshPatcher) baseClassSet = await require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1616
+ let baseClassSet = options.baseClassSet;
1617
+ if (!baseClassSet && (!runtimeSet || shouldRefreshPatcher)) baseClassSet = await require_precheck.collectRuntimeClassSet(runtimeState.twPatcher, {
1545
1618
  force: true,
1546
1619
  skipRefresh: shouldRefreshPatcher,
1547
1620
  clearCache: shouldRefreshPatcher
1548
1621
  });
1549
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot, { baseClassSet });
1622
+ const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.twPatcher, snapshot, {
1623
+ baseClassSet: baseClassSet ?? (options.allowBaselineOnlyInitialSync === true ? runtimeSet : void 0),
1624
+ skipInitialFullScanWithBase: options.allowBaselineOnlyInitialSync === true && Boolean(runtimeSet)
1625
+ });
1550
1626
  runtimeSet = nextRuntimeSet;
1551
1627
  return nextRuntimeSet;
1552
1628
  } catch (error) {
@@ -1575,374 +1651,6 @@ function createViteRuntimeClassSet(options) {
1575
1651
  };
1576
1652
  }
1577
1653
  //#endregion
1578
- //#region src/bundlers/vite/source-candidates.ts
1579
- const CLEAN_URL_RE = /[?#].*$/;
1580
- const SOURCE_CANDIDATE_EXTENSIONS = [
1581
- "js",
1582
- "jsx",
1583
- "mjs",
1584
- "cjs",
1585
- "ts",
1586
- "tsx",
1587
- "mts",
1588
- "cts",
1589
- "vue",
1590
- "uvue",
1591
- "nvue",
1592
- "svelte",
1593
- "mpx",
1594
- "html",
1595
- "wxml",
1596
- "axml",
1597
- "jxml",
1598
- "ksml",
1599
- "ttml",
1600
- "qml",
1601
- "tyml",
1602
- "xhsml",
1603
- "swan",
1604
- "css",
1605
- "wxss",
1606
- "acss",
1607
- "jxss",
1608
- "ttss",
1609
- "qss",
1610
- "tyss",
1611
- "scss",
1612
- "sass",
1613
- "less",
1614
- "styl",
1615
- "stylus"
1616
- ];
1617
- 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?)$/;
1618
- const CSS_SOURCE_CANDIDATE_EXTENSION_RE = /^(?:css|wxss|acss|jxss|ttss|qss|tyss|scss|sass|less|styl|stylus)$/;
1619
- const SOURCE_CANDIDATE_GLOB = `**/*.{${SOURCE_CANDIDATE_EXTENSIONS.join(",")}}`;
1620
- const DEFAULT_SCAN_IGNORE = ["**/node_modules/**", "**/.git/**"];
1621
- function cleanUrl(id) {
1622
- return id.replace(CLEAN_URL_RE, "");
1623
- }
1624
- function toPosixPath$1(value) {
1625
- return value.split(node_path.default.sep).join("/");
1626
- }
1627
- function resolveOutDirIgnorePattern(root, outDir) {
1628
- if (!outDir) return;
1629
- const relative = node_path.default.relative(root, node_path.default.resolve(root, outDir));
1630
- if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) return;
1631
- return `${toPosixPath$1(relative)}/**`;
1632
- }
1633
- function resolveSourceCandidateExtension(id) {
1634
- const normalized = cleanUrl(id);
1635
- return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
1636
- }
1637
- function isSourceCandidateRequest(id) {
1638
- return SOURCE_CANDIDATE_EXTENSION_RE.test(cleanUrl(id));
1639
- }
1640
- function removeCandidateSet(candidateCount, candidates) {
1641
- for (const candidate of candidates) {
1642
- const count = candidateCount.get(candidate);
1643
- if (count == null) continue;
1644
- if (count <= 1) {
1645
- candidateCount.delete(candidate);
1646
- continue;
1647
- }
1648
- candidateCount.set(candidate, count - 1);
1649
- }
1650
- }
1651
- function addCandidateSet(candidateCount, candidates) {
1652
- for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
1653
- }
1654
- const CSS_APPLY_RE = /@apply\s+([^;{}]+)/g;
1655
- const CSS_APPLY_IMPORTANT = "!important";
1656
- function extractCssApplyCandidates(source) {
1657
- const candidates = /* @__PURE__ */ new Set();
1658
- CSS_APPLY_RE.lastIndex = 0;
1659
- let match = CSS_APPLY_RE.exec(source);
1660
- while (match !== null) {
1661
- const params = match[1] ?? "";
1662
- for (const candidate of (0, _weapp_tailwindcss_shared_extractors.splitCode)(params, true)) {
1663
- const normalized = candidate.trim();
1664
- if (normalized && normalized !== CSS_APPLY_IMPORTANT) candidates.add(normalized);
1665
- }
1666
- match = CSS_APPLY_RE.exec(source);
1667
- }
1668
- return candidates;
1669
- }
1670
- function createSourceCandidateCollector() {
1671
- const candidatesById = /* @__PURE__ */ new Map();
1672
- const candidateCount = /* @__PURE__ */ new Map();
1673
- let inlineIncludedCandidates = /* @__PURE__ */ new Set();
1674
- let inlineExcludedCandidates = /* @__PURE__ */ new Set();
1675
- async function sync(id, source) {
1676
- const normalizedId = cleanUrl(id);
1677
- const extension = resolveSourceCandidateExtension(normalizedId);
1678
- const nextCandidates = /* @__PURE__ */ new Set();
1679
- if (CSS_SOURCE_CANDIDATE_EXTENSION_RE.test(extension)) for (const candidate of extractCssApplyCandidates(source)) nextCandidates.add(candidate);
1680
- else {
1681
- const matches = await (0, tailwindcss_patch.extractRawCandidatesWithPositions)(source, extension);
1682
- for (const match of matches) {
1683
- const candidate = match.rawCandidate;
1684
- if (typeof candidate === "string" && candidate.length > 0) nextCandidates.add(candidate);
1685
- }
1686
- }
1687
- remove(normalizedId);
1688
- if (nextCandidates.size === 0) return;
1689
- candidatesById.set(normalizedId, nextCandidates);
1690
- addCandidateSet(candidateCount, nextCandidates);
1691
- }
1692
- async function syncFile(id) {
1693
- const normalizedId = cleanUrl(id);
1694
- await sync(normalizedId, await (0, node_fs_promises.readFile)(normalizedId, "utf8"));
1695
- }
1696
- async function scanRoot({ entries, root, outDir }) {
1697
- const resolvedRoot = node_path.default.resolve(root);
1698
- const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, outDir);
1699
- const ignore = outDirIgnore ? [...DEFAULT_SCAN_IGNORE, outDirIgnore] : DEFAULT_SCAN_IGNORE;
1700
- const files = entries ? await require_source_scan.expandTailwindSourceEntries(entries, { ignore }) : await (0, fast_glob.default)(SOURCE_CANDIDATE_GLOB, {
1701
- absolute: true,
1702
- cwd: resolvedRoot,
1703
- ignore,
1704
- onlyFiles: true,
1705
- unique: true
1706
- });
1707
- await Promise.all(files.map((file) => syncFile(file)));
1708
- }
1709
- function syncInline(inlineCandidates) {
1710
- inlineIncludedCandidates = new Set(inlineCandidates?.included ?? []);
1711
- inlineExcludedCandidates = new Set(inlineCandidates?.excluded ?? []);
1712
- }
1713
- function remove(id) {
1714
- const normalizedId = cleanUrl(id);
1715
- const previousCandidates = candidatesById.get(normalizedId);
1716
- if (!previousCandidates) return;
1717
- removeCandidateSet(candidateCount, previousCandidates);
1718
- candidatesById.delete(normalizedId);
1719
- }
1720
- function values() {
1721
- const values = new Set([...candidateCount.keys(), ...inlineIncludedCandidates]);
1722
- for (const candidate of inlineExcludedCandidates) values.delete(candidate);
1723
- return values;
1724
- }
1725
- function clear() {
1726
- candidatesById.clear();
1727
- candidateCount.clear();
1728
- inlineIncludedCandidates.clear();
1729
- inlineExcludedCandidates.clear();
1730
- }
1731
- return {
1732
- sync,
1733
- syncFile,
1734
- scanRoot,
1735
- syncInline,
1736
- remove,
1737
- values,
1738
- clear
1739
- };
1740
- }
1741
- //#endregion
1742
- //#region src/bundlers/vite/source-scan.ts
1743
- const VITE_SOURCE_CANDIDATE_PATTERN = require_source_scan.createSourceScanPattern([
1744
- "js",
1745
- "jsx",
1746
- "mjs",
1747
- "cjs",
1748
- "ts",
1749
- "tsx",
1750
- "mts",
1751
- "cts",
1752
- "vue",
1753
- "uvue",
1754
- "nvue",
1755
- "svelte",
1756
- "mpx",
1757
- "html",
1758
- "wxml",
1759
- "axml",
1760
- "jxml",
1761
- "ksml",
1762
- "ttml",
1763
- "qml",
1764
- "tyml",
1765
- "xhsml",
1766
- "swan",
1767
- "css",
1768
- "wxss",
1769
- "acss",
1770
- "jxss",
1771
- "ttss",
1772
- "qss",
1773
- "tyss",
1774
- "scss",
1775
- "sass",
1776
- "less",
1777
- "styl",
1778
- "stylus"
1779
- ]);
1780
- function parseImportSourceParam(params) {
1781
- const match = /\bsource\(\s*(none|(['"])(.*?)\2)\s*\)/.exec(params);
1782
- if (!match) return;
1783
- return {
1784
- none: match[1] === "none",
1785
- sourcePath: match[3]
1786
- };
1787
- }
1788
- function isTailwindCssImport(params) {
1789
- return /^\s*(['"])tailwindcss(?:\/[^'"]*)?\1/.test(params);
1790
- }
1791
- function resolveSourceBase(base, sourcePath) {
1792
- return node_path.default.isAbsolute(sourcePath) ? sourcePath : node_path.default.resolve(base, sourcePath);
1793
- }
1794
- function resolveConfigPath(base, configPath) {
1795
- return node_path.default.isAbsolute(configPath) ? node_path.default.resolve(configPath) : node_path.default.resolve(base, configPath);
1796
- }
1797
- async function resolveConfigContentEntries(root, base) {
1798
- const configPaths = /* @__PURE__ */ new Set();
1799
- root.walkAtRules("config", (rule) => {
1800
- const configPath = require_source_scan.parseConfigParam(rule.params);
1801
- if (configPath) configPaths.add(resolveConfigPath(base, configPath));
1802
- });
1803
- const entries = [];
1804
- for (const configPath of configPaths) try {
1805
- const loaded = await (0, tailwindcss_config.loadConfig)({
1806
- config: configPath,
1807
- cwd: node_path.default.dirname(configPath)
1808
- });
1809
- entries.push(...require_source_scan.normalizeLegacyContentEntries(loaded?.config.content, node_path.default.dirname(configPath)));
1810
- } catch {}
1811
- return {
1812
- dependencies: [...configPaths],
1813
- entries
1814
- };
1815
- }
1816
- async function resolveTailwindV4EntriesFromCss(css, base) {
1817
- let root;
1818
- try {
1819
- root = postcss.default.parse(css);
1820
- } catch {
1821
- return;
1822
- }
1823
- let importSourceBase;
1824
- let hasSourceNone = false;
1825
- const [sourceEntries, configEntries] = await Promise.all([require_source_scan.resolveCssSourceEntries(root, base, VITE_SOURCE_CANDIDATE_PATTERN), resolveConfigContentEntries(root, base)]);
1826
- const entries = [...configEntries.entries, ...sourceEntries];
1827
- const inlineCandidates = require_source_scan.collectCssInlineSourceCandidates(root);
1828
- root.walkAtRules("import", (rule) => {
1829
- if (!isTailwindCssImport(rule.params)) return;
1830
- const sourceParam = parseImportSourceParam(rule.params);
1831
- if (sourceParam?.none) hasSourceNone = true;
1832
- if (sourceParam?.sourcePath) importSourceBase = resolveSourceBase(base, sourceParam.sourcePath);
1833
- });
1834
- if (importSourceBase) return {
1835
- entries: [{
1836
- base: importSourceBase,
1837
- negated: false,
1838
- pattern: VITE_SOURCE_CANDIDATE_PATTERN
1839
- }, ...entries],
1840
- explicit: true,
1841
- inlineCandidates,
1842
- dependencies: configEntries.dependencies
1843
- };
1844
- if (hasSourceNone) return {
1845
- entries,
1846
- explicit: true,
1847
- inlineCandidates,
1848
- dependencies: configEntries.dependencies
1849
- };
1850
- return entries.length > 0 ? {
1851
- entries,
1852
- explicit: true,
1853
- inlineCandidates,
1854
- dependencies: configEntries.dependencies
1855
- } : inlineCandidates.included.size > 0 || inlineCandidates.excluded.size > 0 ? {
1856
- entries: [],
1857
- explicit: true,
1858
- inlineCandidates,
1859
- dependencies: configEntries.dependencies
1860
- } : void 0;
1861
- }
1862
- async function resolveViteTailwindV4CssDependencies(css, base) {
1863
- return (await resolveTailwindV4EntriesFromCss(css, base))?.dependencies ?? [];
1864
- }
1865
- function collectExistingCssEntries(options) {
1866
- return [
1867
- ...options.cssEntries ?? [],
1868
- ...options.tailwindcss?.v4?.cssEntries ?? [],
1869
- ...options.tailwindcssPatcherOptions?.tailwindcss?.v4?.cssEntries ?? []
1870
- ].filter((item) => typeof item === "string" && item.length > 0).map((item) => node_path.default.resolve(item)).filter((item) => (0, node_fs.existsSync)(item));
1871
- }
1872
- function mergeInlineCandidates(allInlineCandidates) {
1873
- const merged = {
1874
- included: /* @__PURE__ */ new Set(),
1875
- excluded: /* @__PURE__ */ new Set()
1876
- };
1877
- for (const inlineCandidates of allInlineCandidates) {
1878
- if (!inlineCandidates) continue;
1879
- for (const candidate of inlineCandidates.included) if (!merged.excluded.has(candidate)) merged.included.add(candidate);
1880
- for (const candidate of inlineCandidates.excluded) {
1881
- merged.excluded.add(candidate);
1882
- merged.included.delete(candidate);
1883
- }
1884
- }
1885
- return merged.included.size > 0 || merged.excluded.size > 0 ? merged : void 0;
1886
- }
1887
- async function resolveViteSourceScanEntries(options, patcher) {
1888
- if (patcher.majorVersion === 3) {
1889
- const source = await require_generator.resolveTailwindV3SourceFromPatcher(patcher);
1890
- const contentEntries = require_source_scan.normalizeLegacyContentEntries(source.configObject?.content, source.config ? node_path.default.dirname(source.config) : source.cwd);
1891
- return contentEntries.length > 0 ? { entries: contentEntries } : void 0;
1892
- }
1893
- if (patcher.majorVersion === 4) {
1894
- const sourceOptions = require_generator.resolveTailwindV4SourceOptionsFromPatcher(patcher);
1895
- const cssEntries = collectExistingCssEntries(options);
1896
- const entries = [];
1897
- const cssInlineCandidates = [];
1898
- for (const cssEntry of cssEntries) {
1899
- const resolved = await resolveTailwindV4EntriesFromCss((0, node_fs.readFileSync)(cssEntry, "utf8"), node_path.default.dirname(cssEntry));
1900
- if (resolved) {
1901
- entries.push(...resolved.entries);
1902
- cssInlineCandidates.push(resolved.inlineCandidates);
1903
- }
1904
- }
1905
- const inlineCandidates = mergeInlineCandidates(cssInlineCandidates);
1906
- if (entries.length > 0 || inlineCandidates) return {
1907
- entries,
1908
- inlineCandidates
1909
- };
1910
- if (typeof sourceOptions.css === "string" && sourceOptions.css.length > 0) {
1911
- const resolved = await resolveTailwindV4EntriesFromCss(sourceOptions.css, sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd());
1912
- return resolved ? {
1913
- entries: resolved.entries,
1914
- inlineCandidates: resolved.inlineCandidates
1915
- } : void 0;
1916
- }
1917
- const source = await require_generator.resolveTailwindV4SourceFromPatcher(patcher);
1918
- const resolved = await resolveTailwindV4EntriesFromCss(source.css, source.base);
1919
- return resolved ? {
1920
- entries: resolved.entries,
1921
- inlineCandidates: resolved.inlineCandidates
1922
- } : void 0;
1923
- }
1924
- }
1925
- function toPosixPath(value) {
1926
- return value.split(node_path.default.sep).join("/");
1927
- }
1928
- function createViteSourceScanMatcher(entries) {
1929
- if (!entries?.length) return;
1930
- const positiveEntries = entries.filter((entry) => !entry.negated);
1931
- const negativeEntries = entries.filter((entry) => entry.negated);
1932
- if (positiveEntries.length === 0) return () => false;
1933
- return (file) => {
1934
- const resolvedFile = node_path.default.resolve(file);
1935
- if (!positiveEntries.some((entry) => {
1936
- const relative = toPosixPath(node_path.default.relative(node_path.default.resolve(entry.base), resolvedFile));
1937
- return relative && !relative.startsWith("../") && !node_path.default.isAbsolute(relative) && micromatch.default.isMatch(relative, entry.pattern);
1938
- })) return false;
1939
- return !negativeEntries.some((entry) => {
1940
- const relative = toPosixPath(node_path.default.relative(node_path.default.resolve(entry.base), resolvedFile));
1941
- return relative && !relative.startsWith("../") && !node_path.default.isAbsolute(relative) && micromatch.default.isMatch(relative, entry.pattern);
1942
- });
1943
- };
1944
- }
1945
- //#endregion
1946
1654
  //#region src/bundlers/vite/tailwind-basedir.ts
1947
1655
  const PACKAGE_JSON_FILE = "package.json";
1948
1656
  function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
@@ -1956,17 +1664,18 @@ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
1956
1664
  if (parent === current) break;
1957
1665
  current = parent;
1958
1666
  }
1959
- const tailwindConfigPath = require_cache.findTailwindConfig(searchRoots);
1667
+ const tailwindConfigPath = require_v3_engine.findTailwindConfig(searchRoots);
1960
1668
  if (tailwindConfigPath) return node_path.default.dirname(tailwindConfigPath);
1961
- const packageRoot = require_cache.findNearestPackageRoot(resolvedRoot);
1669
+ const packageRoot = require_v3_engine.findNearestPackageRoot(resolvedRoot);
1962
1670
  if (packageRoot && (0, node_fs.existsSync)(node_path.default.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
1963
1671
  return resolvedRoot;
1964
1672
  }
1965
1673
  //#endregion
1966
1674
  //#region src/bundlers/vite/index.ts
1967
- const debug = require_runtime_patch.createDebug();
1675
+ const debug = require_v3_engine.createDebug();
1968
1676
  const weappTailwindcssPackageDir = require_bundle_state.resolvePackageDir("weapp-tailwindcss");
1969
1677
  const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1678
+ const sourceCandidateScanSnapshotCache = /* @__PURE__ */ new Map();
1970
1679
  function normalizeSignaturePath(value) {
1971
1680
  return slash(node_path.default.resolve(value));
1972
1681
  }
@@ -1990,7 +1699,8 @@ function createSourceCandidateScanSignature(input) {
1990
1699
  roots: input.roots.map((root) => ({
1991
1700
  entries: serializeSourceEntries(root.entries),
1992
1701
  root: normalizeSignaturePath(root.root)
1993
- }))
1702
+ })),
1703
+ scanAllSources: input.scanAllSources ?? false
1994
1704
  });
1995
1705
  }
1996
1706
  /**
@@ -2018,7 +1728,8 @@ function WeappTailwindcss(options = {}) {
2018
1728
  const autoCssSourceContent = /* @__PURE__ */ new Map();
2019
1729
  let refreshRuntimeStateForAutoCssSources;
2020
1730
  let autoCssSourcesRefresh;
2021
- const registerAutoCssSource = async (id, css) => {
1731
+ let autoCssSourcesDiscovered = false;
1732
+ const registerAutoCssSource = async (id, css, options = {}) => {
2022
1733
  if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots) return;
2023
1734
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2024
1735
  if (!node_path.default.isAbsolute(file)) return;
@@ -2026,17 +1737,44 @@ function WeappTailwindcss(options = {}) {
2026
1737
  const sourceCss = require_incremental_runtime_class_set.normalizeTailwindSourceForGenerator(css, { importFallback: true });
2027
1738
  if (autoCssSourceContent.get(sourceFile) === sourceCss) return;
2028
1739
  autoCssSourceContent.set(sourceFile, sourceCss);
2029
- require_tailwindcss.upsertTailwindV4CssSource(opts, {
1740
+ const dependencies = await require_v3_engine.resolveViteTailwindV4CssDependencies(sourceCss, node_path.default.dirname(sourceFile));
1741
+ if (!require_tailwindcss.upsertTailwindV4CssSource(opts, {
2030
1742
  file: sourceFile,
1743
+ base: node_path.default.dirname(sourceFile),
2031
1744
  css: sourceCss,
2032
- dependencies: await resolveViteTailwindV4CssDependencies(sourceCss, node_path.default.dirname(sourceFile))
2033
- });
1745
+ dependencies
1746
+ })) return;
1747
+ invalidateSourceCandidateScan();
2034
1748
  debug("detected tailwindcss v4 css source from vite css module: %s", sourceFile);
1749
+ if (options.refresh === false) return;
2035
1750
  autoCssSourcesRefresh = (autoCssSourcesRefresh ?? Promise.resolve()).then(async () => {
2036
1751
  await refreshRuntimeStateForAutoCssSources?.(true);
1752
+ await syncSourceCandidateScan({ force: true });
2037
1753
  });
2038
1754
  await autoCssSourcesRefresh;
2039
1755
  };
1756
+ const discoverAndRegisterAutoCssSources = async () => {
1757
+ if (tailwindcssMajorVersion < 4 || !shouldOwnTailwindGeneration || hasInitialTailwindCssRoots || !resolvedConfig?.root) return;
1758
+ const cssEntries = await require_v3_engine.discoverTailwindV4CssEntries(resolvedConfig.root, resolvedConfig.build?.outDir);
1759
+ autoCssSourcesDiscovered = true;
1760
+ let changed = false;
1761
+ for (const cssEntry of cssEntries) {
1762
+ const sourceFile = node_path.default.resolve(cssEntry);
1763
+ const sourceCss = require_incremental_runtime_class_set.normalizeTailwindSourceForGenerator(await (0, node_fs_promises.readFile)(sourceFile, "utf8"), { importFallback: true });
1764
+ if (autoCssSourceContent.get(sourceFile) === sourceCss) continue;
1765
+ autoCssSourceContent.set(sourceFile, sourceCss);
1766
+ const resolved = await require_v3_engine.resolveTailwindV4EntriesFromCssCached(sourceCss, node_path.default.dirname(sourceFile));
1767
+ changed = require_tailwindcss.upsertTailwindV4CssSource(opts, {
1768
+ file: sourceFile,
1769
+ base: node_path.default.dirname(sourceFile),
1770
+ css: sourceCss,
1771
+ dependencies: resolved?.dependencies ?? []
1772
+ }) || changed;
1773
+ }
1774
+ if (!changed) return;
1775
+ invalidateSourceCandidateScan();
1776
+ await refreshRuntimeStateForAutoCssSources?.(true);
1777
+ };
2040
1778
  const rewritePlugins = createRewriteCssImportsPlugins({
2041
1779
  getAppType: () => opts.appType,
2042
1780
  rootImport: shouldOwnTailwindGeneration ? `${weappTailwindcssDirPosix}/generator-placeholder.css` : void 0,
@@ -2049,11 +1787,16 @@ function WeappTailwindcss(options = {}) {
2049
1787
  const customAttributesEntities = require_precheck.toCustomAttributesEntities(customAttributes);
2050
1788
  let resolvedConfig;
2051
1789
  let recordedGeneratorCandidates;
2052
- const sourceCandidateCollector = createSourceCandidateCollector();
1790
+ const sourceCandidateCollector = require_source_candidates.createSourceCandidateCollector();
1791
+ const sourceCandidateScanCache = /* @__PURE__ */ new Map();
2053
1792
  let sourceScanEntries;
2054
1793
  let sourceScanMatcher;
1794
+ let sourceScanDependencies = /* @__PURE__ */ new Set();
1795
+ let sourceScanExplicit = false;
2055
1796
  let sourceCandidateScanSignature;
1797
+ let sourceCandidateScanInvalidated = true;
2056
1798
  const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
1799
+ const pendingSourceCandidateSyncByFile = /* @__PURE__ */ new Map();
2057
1800
  const processedCssAssets = /* @__PURE__ */ new WeakSet();
2058
1801
  const processedCssAssetFiles = /* @__PURE__ */ new Set();
2059
1802
  const rememberedMainCssSources = /* @__PURE__ */ new Map();
@@ -2067,6 +1810,7 @@ function WeappTailwindcss(options = {}) {
2067
1810
  disabledDefaultTemplateHandler,
2068
1811
  debug
2069
1812
  });
1813
+ const hmrTimingRecorder = require_incremental_runtime_class_set.createHmrTimingRecorder("vite");
2070
1814
  refreshRuntimeStateForAutoCssSources = refreshRuntimeState;
2071
1815
  onLoad();
2072
1816
  const getResolvedConfig = () => resolvedConfig;
@@ -2082,8 +1826,21 @@ function WeappTailwindcss(options = {}) {
2082
1826
  };
2083
1827
  const getRecordedGeneratorCandidates = () => recordedGeneratorCandidates;
2084
1828
  const getSourceCandidates = () => sourceCandidateCollector.values();
1829
+ const getSourceCandidatesForEntries = (entries) => sourceCandidateCollector.valuesForEntries(entries);
2085
1830
  const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
1831
+ const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || node_process.default.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || node_process.default.env["WEAPP_TW_HMR_TIMING"] === "1";
1832
+ const hasSourceCandidateScanState = () => sourceCandidateScanSignature !== void 0;
1833
+ const normalizeSourceScanDependency = (file) => node_path.default.normalize(node_path.default.resolve((0, _weapp_tailwindcss_shared.cleanUrl)(file)));
1834
+ const isSourceScanDependency = (file) => sourceScanDependencies.has(normalizeSourceScanDependency(file));
1835
+ const invalidateSourceCandidateScan = () => {
1836
+ sourceCandidateScanInvalidated = true;
1837
+ };
2086
1838
  const collectSourceCandidateScanRoots = (root, entries) => {
1839
+ if (entries?.length) return [{
1840
+ entries,
1841
+ root
1842
+ }];
1843
+ if (sourceScanExplicit) return [];
2087
1844
  const roots = [{
2088
1845
  entries,
2089
1846
  root
@@ -2110,24 +1867,100 @@ function WeappTailwindcss(options = {}) {
2110
1867
  outDir
2111
1868
  })));
2112
1869
  };
1870
+ const cacheCurrentSourceCandidateScan = () => {
1871
+ if (sourceCandidateScanSignature) {
1872
+ sourceCandidateScanCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
1873
+ sourceCandidateScanSnapshotCache.set(sourceCandidateScanSignature, sourceCandidateCollector.snapshot());
1874
+ }
1875
+ };
1876
+ const shouldDiscoverAutoCssSources = () => {
1877
+ if (!autoCssSourcesDiscovered) return true;
1878
+ if (!isWatchLikeBuild()) return true;
1879
+ return sourceCandidateScanInvalidated;
1880
+ };
1881
+ async function syncSourceCandidateScan(options = {}) {
1882
+ if (!shouldOwnTailwindGeneration) return;
1883
+ if (!options.force && isWatchLikeBuild() && hasSourceCandidateScanState() && !sourceCandidateScanInvalidated) {
1884
+ debug("reuse vite source candidate scan definition for watch rebuild");
1885
+ return;
1886
+ }
1887
+ const root = resolvedConfig?.root ?? node_process.default.cwd();
1888
+ const outDir = resolvedConfig?.build?.outDir;
1889
+ const sourceScan = await require_v3_engine.resolveViteSourceScanEntries(opts, runtimeState.twPatcher, {
1890
+ outDir,
1891
+ root
1892
+ });
1893
+ sourceScanEntries = sourceScan?.entries;
1894
+ sourceScanExplicit = sourceScan?.explicit ?? false;
1895
+ sourceScanMatcher = require_v3_engine.createViteSourceScanMatcher(sourceScanEntries);
1896
+ sourceScanDependencies = new Set((sourceScan?.dependencies ?? []).map(normalizeSourceScanDependency));
1897
+ const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
1898
+ const nextScanSignature = createSourceCandidateScanSignature({
1899
+ inlineCandidates: sourceScan?.inlineCandidates,
1900
+ outDir,
1901
+ roots,
1902
+ scanAllSources: !sourceScanExplicit
1903
+ });
1904
+ if (hasSourceCandidateScanState() && sourceCandidateScanSignature === nextScanSignature) {
1905
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
1906
+ sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
1907
+ debug("reuse vite source candidate scan for watch rebuild");
1908
+ sourceCandidateScanInvalidated = false;
1909
+ return;
1910
+ }
1911
+ const cachedScan = isWatchLikeBuild() ? sourceCandidateScanCache.get(nextScanSignature) ?? sourceCandidateScanSnapshotCache.get(nextScanSignature) : void 0;
1912
+ if (cachedScan) {
1913
+ sourceCandidateCollector.restore(cachedScan);
1914
+ sourceCandidateScanSignature = nextScanSignature;
1915
+ debug("reuse cached vite source candidate scan for watch rebuild");
1916
+ sourceCandidateScanInvalidated = false;
1917
+ return;
1918
+ }
1919
+ sourceCandidateCollector.clear();
1920
+ sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
1921
+ await scanSourceCandidateRoots(roots, outDir);
1922
+ sourceCandidateScanSignature = nextScanSignature;
1923
+ sourceCandidateScanInvalidated = false;
1924
+ if (isWatchLikeBuild()) {
1925
+ sourceCandidateScanCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
1926
+ sourceCandidateScanSnapshotCache.set(nextScanSignature, sourceCandidateCollector.snapshot());
1927
+ }
1928
+ }
2113
1929
  const waitForSourceCandidateSyncs = async () => {
2114
1930
  while (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
2115
1931
  };
2116
1932
  const syncChangedSourceCandidateFile = (id) => {
2117
- if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return Promise.resolve();
1933
+ if (!shouldOwnTailwindGeneration || !require_source_candidates.isSourceCandidateRequest(id)) return Promise.resolve();
2118
1934
  const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
1935
+ if (isSourceScanDependency(file)) invalidateSourceCandidateScan();
2119
1936
  if (sourceScanMatcher && !sourceScanMatcher(file)) {
2120
1937
  sourceCandidateCollector.remove(file);
1938
+ cacheCurrentSourceCandidateScan();
1939
+ return Promise.resolve();
1940
+ }
1941
+ if (sourceScanExplicit && sourceScanEntries?.length === 0) {
1942
+ cacheCurrentSourceCandidateScan();
2121
1943
  return Promise.resolve();
2122
1944
  }
1945
+ const existingTask = pendingSourceCandidateSyncByFile.get(file);
1946
+ if (existingTask) return existingTask;
2123
1947
  const task = sourceCandidateCollector.syncFile(id).catch((error) => {
2124
1948
  debug("source candidate watch sync failed: %s %O", id, error);
1949
+ }).then(() => {
1950
+ cacheCurrentSourceCandidateScan();
2125
1951
  }).finally(() => {
2126
1952
  pendingSourceCandidateSyncs.delete(task);
1953
+ pendingSourceCandidateSyncByFile.delete(file);
2127
1954
  });
2128
1955
  pendingSourceCandidateSyncs.add(task);
1956
+ pendingSourceCandidateSyncByFile.set(file, task);
2129
1957
  return task;
2130
1958
  };
1959
+ const shouldCollectTransformedSourceCandidates = (id) => {
1960
+ if (id.search(/[?#]/) < 0) return true;
1961
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
1962
+ return !/\.(?:vue|uvue|nvue|svelte|mpx)$/i.test(file);
1963
+ };
2131
1964
  const rememberMainCssSource = (file, rawSource, cssRuntimeSignature) => {
2132
1965
  rememberedMainCssSources.set(file, rawSource);
2133
1966
  if (cssRuntimeSignature) rememberedMainCssSignatureByFile.set(file, cssRuntimeSignature);
@@ -2146,12 +1979,14 @@ function WeappTailwindcss(options = {}) {
2146
1979
  getResolvedConfig,
2147
1980
  markCssAssetProcessed,
2148
1981
  getSourceCandidates,
1982
+ getSourceCandidatesForEntries,
2149
1983
  waitForSourceCandidateSyncs,
2150
1984
  rememberMainCssSource,
2151
1985
  getRememberedMainCssSources,
2152
1986
  getRememberedMainCssSignature,
2153
1987
  setRememberedMainCssSignature,
2154
- recordGeneratorCandidates
1988
+ recordGeneratorCandidates,
1989
+ hmrTimingRecorder
2155
1990
  });
2156
1991
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
2157
1992
  opts,
@@ -2163,6 +1998,7 @@ function WeappTailwindcss(options = {}) {
2163
1998
  isCssAssetProcessed,
2164
1999
  getRecordedGeneratorCandidates,
2165
2000
  getSourceCandidates,
2001
+ getSourceCandidatesForEntries,
2166
2002
  waitForSourceCandidateSyncs,
2167
2003
  rememberMainCssSource
2168
2004
  });
@@ -2186,46 +2022,43 @@ function WeappTailwindcss(options = {}) {
2186
2022
  name: `${require_precheck.vitePluginName}:source-candidates`,
2187
2023
  enforce: "pre",
2188
2024
  async transform(code, id) {
2189
- if (!shouldOwnTailwindGeneration || !isSourceCandidateRequest(id)) return;
2190
- const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2191
- if (sourceScanMatcher && !sourceScanMatcher(file)) {
2192
- sourceCandidateCollector.remove(file);
2193
- return;
2194
- }
2195
- await sourceCandidateCollector.sync(id, code);
2025
+ if (!shouldOwnTailwindGeneration || !require_source_candidates.isSourceCandidateRequest(id) || !shouldCollectTransformedSourceCandidates(id)) return;
2026
+ return hmrTimingRecorder.measure("sourceCandidates.transform", async () => {
2027
+ const file = (0, _weapp_tailwindcss_shared.cleanUrl)(id);
2028
+ if (sourceScanMatcher && !sourceScanMatcher(file)) {
2029
+ sourceCandidateCollector.remove(file);
2030
+ cacheCurrentSourceCandidateScan();
2031
+ return;
2032
+ }
2033
+ if (sourceScanExplicit && sourceScanEntries?.length === 0) {
2034
+ cacheCurrentSourceCandidateScan();
2035
+ return;
2036
+ }
2037
+ await sourceCandidateCollector.merge(id, code);
2038
+ cacheCurrentSourceCandidateScan();
2039
+ }, { emit: false });
2196
2040
  },
2197
2041
  async watchChange(id, change) {
2198
- if (change.event === "delete") {
2199
- sourceCandidateCollector.remove(id);
2200
- return;
2201
- }
2202
- await syncChangedSourceCandidateFile(id);
2042
+ await hmrTimingRecorder.measure("sourceCandidates.watchChange", async () => {
2043
+ if (isSourceScanDependency(id)) invalidateSourceCandidateScan();
2044
+ if (change.event === "delete") {
2045
+ sourceCandidateCollector.remove(id);
2046
+ cacheCurrentSourceCandidateScan();
2047
+ return;
2048
+ }
2049
+ await syncChangedSourceCandidateFile(id);
2050
+ }, { emit: false });
2203
2051
  },
2204
2052
  async handleHotUpdate(ctx) {
2205
- await syncChangedSourceCandidateFile(ctx.file);
2053
+ await hmrTimingRecorder.measure("sourceCandidates.handleHotUpdate", async () => {
2054
+ await syncChangedSourceCandidateFile(ctx.file);
2055
+ }, { emit: false });
2206
2056
  },
2207
2057
  async buildStart() {
2208
- if (!shouldOwnTailwindGeneration) return;
2209
- const root = resolvedConfig?.root ?? node_process.default.cwd();
2210
- const outDir = resolvedConfig?.build?.outDir;
2211
- const sourceScan = await resolveViteSourceScanEntries(opts, runtimeState.twPatcher);
2212
- sourceScanEntries = sourceScan?.entries;
2213
- sourceScanMatcher = createViteSourceScanMatcher(sourceScanEntries);
2214
- const roots = collectSourceCandidateScanRoots(root, sourceScanEntries);
2215
- const nextScanSignature = createSourceCandidateScanSignature({
2216
- inlineCandidates: sourceScan?.inlineCandidates,
2217
- outDir,
2218
- roots
2219
- });
2220
- if (isWatchBuild() && sourceCandidateScanSignature === nextScanSignature) {
2221
- sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2222
- debug("reuse vite source candidate scan for watch rebuild");
2223
- return;
2224
- }
2225
- sourceCandidateCollector.clear();
2226
- sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
2227
- await scanSourceCandidateRoots(roots, outDir);
2228
- sourceCandidateScanSignature = nextScanSignature;
2058
+ await hmrTimingRecorder.measure("sourceCandidates.buildStart", async () => {
2059
+ if (shouldDiscoverAutoCssSources()) await discoverAndRegisterAutoCssSources();
2060
+ await syncSourceCandidateScan();
2061
+ }, { emit: false });
2229
2062
  }
2230
2063
  },
2231
2064
  {
@@ -2256,45 +2089,47 @@ function WeappTailwindcss(options = {}) {
2256
2089
  });
2257
2090
  },
2258
2091
  async configResolved(config) {
2259
- resolvedConfig = config;
2260
- if (shouldOwnTailwindGeneration) {
2261
- const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2262
- if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2263
- }
2264
- const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
2265
- let shouldRefreshRuntime = false;
2266
- if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2267
- const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2268
- if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2269
- const previousBasedir = opts.tailwindcssBasedir;
2270
- opts.tailwindcssBasedir = nextTailwindcssBasedir;
2271
- debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2272
- shouldRefreshRuntime = true;
2092
+ await hmrTimingRecorder.measure("configResolved", async () => {
2093
+ resolvedConfig = config;
2094
+ if (shouldOwnTailwindGeneration) {
2095
+ const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
2096
+ if (removed > 0) debug("remove official tailwind vite plugins in generator mode: %d", removed);
2273
2097
  }
2274
- }
2275
- if (!hasExplicitAppType && resolvedRoot) {
2276
- const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2277
- if (nextAppType && opts.appType !== nextAppType) {
2278
- const previousAppType = opts.appType;
2279
- opts.appType = nextAppType;
2280
- _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2281
- debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2282
- shouldRefreshRuntime = true;
2098
+ const resolvedRoot = config.root ? node_path.default.resolve(config.root) : void 0;
2099
+ let shouldRefreshRuntime = false;
2100
+ if (!hasExplicitTailwindcssBasedir && resolvedRoot) {
2101
+ const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
2102
+ if (opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
2103
+ const previousBasedir = opts.tailwindcssBasedir;
2104
+ opts.tailwindcssBasedir = nextTailwindcssBasedir;
2105
+ debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
2106
+ shouldRefreshRuntime = true;
2107
+ }
2283
2108
  }
2284
- }
2285
- if (shouldRefreshRuntime) await refreshRuntimeState(true);
2286
- if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2287
- const postcssPlugins = config.css.postcss.plugins;
2288
- if (shouldOwnTailwindGeneration) {
2289
- const removed = removeTailwindPostcssPlugins(postcssPlugins);
2290
- if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2109
+ if (!hasExplicitAppType && resolvedRoot) {
2110
+ const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot);
2111
+ if (nextAppType && opts.appType !== nextAppType) {
2112
+ const previousAppType = opts.appType;
2113
+ opts.appType = nextAppType;
2114
+ _weapp_tailwindcss_logger.logger.info("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
2115
+ debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
2116
+ shouldRefreshRuntime = true;
2117
+ }
2291
2118
  }
2292
- const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2293
- if (idx > -1) {
2294
- postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
2295
- debug("remove postcss-html-transform plugin from vite config");
2119
+ if (shouldRefreshRuntime) await refreshRuntimeState(true);
2120
+ if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
2121
+ const postcssPlugins = config.css.postcss.plugins;
2122
+ if (shouldOwnTailwindGeneration) {
2123
+ const removed = removeTailwindPostcssPlugins(postcssPlugins);
2124
+ if (removed > 0) debug("remove official tailwind postcss plugins in generator mode: %d", removed);
2125
+ }
2126
+ const idx = postcssPlugins.findIndex((x) => getPostcssPluginName(x) === "postcss-html-transform");
2127
+ if (idx > -1) {
2128
+ postcssPlugins.splice(idx, 1, (0, _weapp_tailwindcss_postcss_html_transform.default)());
2129
+ debug("remove postcss-html-transform plugin from vite config");
2130
+ }
2296
2131
  }
2297
- }
2132
+ }, { emit: false });
2298
2133
  },
2299
2134
  generateBundle: {
2300
2135
  order: "post",