weapp-tailwindcss 5.1.6 → 5.1.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 (76) hide show
  1. package/dist/bundlers/framework-selector.d.ts +26 -0
  2. package/dist/bundlers/gulp/frameworks/native/index.d.ts +6 -0
  3. package/dist/bundlers/gulp/index.d.ts +4 -4
  4. package/dist/bundlers/gulp/shared/create-native-framework-plugins.d.ts +6 -0
  5. package/dist/bundlers/vite/css-finalizer.d.ts +2 -0
  6. package/dist/bundlers/vite/frameworks/generic/index.d.ts +2 -0
  7. package/dist/bundlers/vite/frameworks/taro/index.d.ts +2 -0
  8. package/dist/bundlers/vite/frameworks/uni-app/index.d.ts +2 -0
  9. package/dist/bundlers/vite/frameworks/uni-app-x/index.d.ts +2 -0
  10. package/dist/bundlers/vite/frameworks/weapp-vite/index.d.ts +2 -0
  11. package/dist/bundlers/vite/generate-bundle/css-output-helpers.d.ts +5 -1
  12. package/dist/bundlers/vite/generate-bundle/finalize.d.ts +5 -1
  13. package/dist/bundlers/vite/generate-bundle/root-style-output.d.ts +2 -2
  14. package/dist/bundlers/vite/generate-bundle/sfc-style-source.d.ts +8 -0
  15. package/dist/bundlers/vite/generate-bundle/types.d.ts +2 -0
  16. package/dist/bundlers/vite/index.d.ts +2 -4
  17. package/dist/bundlers/vite/processed-css-assets.d.ts +5 -0
  18. package/dist/bundlers/vite/shared/create-framework-plugins.d.ts +35 -0
  19. package/dist/bundlers/vite/shared/framework-strategy.d.ts +88 -0
  20. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +1 -2
  21. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/pipeline-helpers.d.ts +11 -0
  22. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +3 -0
  23. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +1 -2
  24. package/dist/bundlers/webpack/frameworks/generic/index.d.ts +5 -0
  25. package/dist/bundlers/webpack/frameworks/index.d.ts +8 -0
  26. package/dist/bundlers/webpack/frameworks/mpx/index.d.ts +5 -0
  27. package/dist/bundlers/webpack/frameworks/taro/index.d.ts +5 -0
  28. package/dist/bundlers/webpack/frameworks/uni-app/index.d.ts +5 -0
  29. package/dist/bundlers/webpack/frameworks/weapp-vite/index.d.ts +5 -0
  30. package/dist/bundlers/webpack/shared/create-framework-plugin.d.ts +21 -0
  31. package/dist/bundlers/webpack/shared/loader-anchors.d.ts +4 -3
  32. package/dist/cli.js +8 -0
  33. package/dist/cli.mjs +8 -0
  34. package/dist/{context-BCSk_YnL.js → context-CRhUs_5e.js} +13 -4
  35. package/dist/{context-3GGqW9vw.mjs → context-CfXr3hWz.mjs} +13 -4
  36. package/dist/core.js +1 -1
  37. package/dist/core.mjs +1 -1
  38. package/dist/{generator-CqWzj2Z1.js → generator-DaaFxR5V.js} +1 -1
  39. package/dist/{generator-CoT5vu9w.mjs → generator-DugIHBgl.mjs} +1 -1
  40. package/dist/generator.js +2 -2
  41. package/dist/generator.mjs +2 -2
  42. package/dist/{gulp-Bss4wJ8t.mjs → gulp-CRjkPsbX.mjs} +22 -7
  43. package/dist/{gulp-hXE1U4Cu.js → gulp-JUfnhOOo.js} +22 -7
  44. package/dist/gulp.js +1 -1
  45. package/dist/gulp.mjs +1 -1
  46. package/dist/{hmr-timing-Cfu-4Bnf.mjs → hmr-timing-BecOXMd8.mjs} +13 -7
  47. package/dist/{hmr-timing-Df4203aI.js → hmr-timing-DcIEXnf8.js} +13 -7
  48. package/dist/index.js +4 -4
  49. package/dist/index.mjs +4 -4
  50. package/dist/postcss.js +2 -2
  51. package/dist/postcss.mjs +2 -2
  52. package/dist/presets.js +2 -2
  53. package/dist/presets.mjs +2 -2
  54. package/dist/rspack.js +1 -1
  55. package/dist/rspack.mjs +1 -1
  56. package/dist/{source-candidate-scan-signature-5Uk6U72B.js → source-candidate-scan-signature-10tvdJVC.js} +185 -98
  57. package/dist/{source-candidate-scan-signature-BbCmW975.mjs → source-candidate-scan-signature-DAg8QSgh.mjs} +162 -99
  58. package/dist/style-injector/internal.d.ts +18 -4
  59. package/dist/{tailwindcss-DYJ3HZD2.js → tailwindcss-BZjZZi60.js} +1 -1
  60. package/dist/{tailwindcss-Bjr3aphG.mjs → tailwindcss-PA2jHHpx.mjs} +1 -1
  61. package/dist/{transform-B6_y_yCB.js → transform-B0BxX3XB.js} +1 -1
  62. package/dist/{transform--155BmeJ.mjs → transform-wNEbcZeQ.mjs} +1 -1
  63. package/dist/uni-app-x/vite.d.ts +1 -0
  64. package/dist/uni-app-x/web-preflight-reset.d.ts +3 -0
  65. package/dist/{v4-engine-C9cmNlP8.js → v4-engine-BZP2462H.js} +44 -1
  66. package/dist/{v4-engine-DRQaCFMm.mjs → v4-engine-CjjWONB0.mjs} +45 -2
  67. package/dist/{vite-Baw9qNrc.js → vite-GdzlG_lx.js} +1332 -790
  68. package/dist/{vite-PdxjaqhO.mjs → vite-vf2-cDdk.mjs} +1330 -788
  69. package/dist/vite.js +1 -1
  70. package/dist/vite.mjs +1 -1
  71. package/dist/weapp-tw-css-import-rewrite-loader.js +162 -7
  72. package/dist/{webpack-BffTDmod.mjs → webpack-2s-TFhgm.mjs} +583 -238
  73. package/dist/{webpack-C9u7mfGE.js → webpack-BhM4Hqla.js} +582 -237
  74. package/dist/webpack.js +1 -1
  75. package/dist/webpack.mjs +1 -1
  76. package/package.json +3 -3
@@ -1,11 +1,11 @@
1
1
  import { resolveImplicitAppTypeFromViteRoot } from "./framework.mjs";
2
- import { $ as hasTailwindGeneratedCssMarkers, B as hasTailwindNonRootGenerationDirectives, Et as omitUndefined, G as normalizeTailwindSourceForGenerator, H as hasTailwindSourceDirectives, K as parseImportRequest, L as stripMiniProgramCssSpecificityPlaceholders, P as hasMiniProgramCssSpecificityPlaceholders, R as hasLocalCssImport, Tt as filterUnsupportedMiniProgramTailwindV4Candidates, U as normalizeTailwindConfigDirectives, V as hasTailwindRootDirectives, _ as resolveTailwindcssOptions, a as filterTailwindV4CssSourceRoots, d as normalizeCssEntries, f as findNearestPackageRoot, lt as getTailwindV4IncrementalGenerateCacheStats, o as hasConfiguredTailwindV4CssRoots, q as removeTailwindSourceDirectives, s as upsertTailwindV4CssSource, u as isTailwindV4CssEntry, w as normalizeEmptyTailwindCustomVariants, xt as resolveTailwindV4CssSourceBase, z as hasTailwindApplyDirective } from "./v4-engine-DRQaCFMm.mjs";
3
- import { a as resolveGeneratorRuntimeBranch, c as shouldUseNativeAppCssBranch, i as normalizeWeappTailwindcssGeneratorOptions, s as shouldUseMiniProgramCssBranch } from "./generator-CoT5vu9w.mjs";
2
+ import { $ as hasTailwindGeneratedCssMarkers, B as hasTailwindNonRootGenerationDirectives, Et as omitUndefined, G as normalizeTailwindSourceForGenerator, H as hasTailwindSourceDirectives, K as parseImportRequest, L as stripMiniProgramCssSpecificityPlaceholders, P as hasMiniProgramCssSpecificityPlaceholders, R as hasLocalCssImport, Tt as filterUnsupportedMiniProgramTailwindV4Candidates, U as normalizeTailwindConfigDirectives, V as hasTailwindRootDirectives, _ as resolveTailwindcssOptions, a as filterTailwindV4CssSourceRoots, d as normalizeCssEntries, f as findNearestPackageRoot, lt as getTailwindV4IncrementalGenerateCacheStats, o as hasConfiguredTailwindV4CssRoots, q as removeTailwindSourceDirectives, s as upsertTailwindV4CssSource, u as isTailwindV4CssEntry, w as normalizeEmptyTailwindCustomVariants, xt as resolveTailwindV4CssSourceBase, z as hasTailwindApplyDirective } from "./v4-engine-CjjWONB0.mjs";
3
+ import { a as resolveGeneratorRuntimeBranch, c as shouldUseNativeAppCssBranch, i as normalizeWeappTailwindcssGeneratorOptions, s as shouldUseMiniProgramCssBranch } from "./generator-DugIHBgl.mjs";
4
4
  import { o as resolveUniUtsPlatform } from "./utils-DodxWHGz.mjs";
5
- import { C as normalizeFrameworkStylePlatform, S as createDebug, _ as toCustomAttributesEntities, a as vitePluginName, l as shouldSkipJsTransform, m as replaceWxml, n as normalizeStyleHandlerMajorVersion, t as getCompilerContext, v as collectRuntimeClassSet, x as refreshTailwindRuntimeState, y as createTailwindRuntimeReadyPromise } from "./context-3GGqW9vw.mjs";
6
- import { _ as resolveViteTailwindV4CssDependencies, a as findTailwindConfig, f as createViteSourceScanMatcher, g as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions, l as getRuntimeClassSetSignature, m as discoverTailwindV4CssEntries, p as resolveViteSourceScanEntries, r as isUniAppXEnabled } from "./tailwindcss-Bjr3aphG.mjs";
7
- import { E as createCssTokenSourceMap, O as processCachedTask, T as createCssSourceTraceCacheSignature, _ as isPureLocalCssImportWrapper, a as isSourceCandidateRequest, b as scoreTailwindV4CssSourceFileMatch, d as validateCandidatesByGenerator, g as mergeMarkedUserLayerComponentsCss, h as extractMarkedUserLayerComponentsCss, m as runWithConcurrency, r as createSourceCandidateCollector, s as createBundleRuntimeClassSetManager, t as createHmrTimingRecorder, w as annotateCssSourceTrace } from "./hmr-timing-Cfu-4Bnf.mjs";
8
- import { A as isSourceStyleRequest, C as resolvePluginDisabledState, D as isHTMLRequest, E as isCSSRequest, F as createBuiltinViteStyleInjectorPlugins, M as normalizeOutputPathKey, O as normalizePath, P as toAbsoluteOutputPath, S as resolvePackageDir, T as formatPostcssSourceMap, _ as generateTailwindV4Css, a as createJsHashSalt, b as parseBundlerGeneratedCssMarkerBlocks, c as hasRuntimeAffectingSourceChanges, f as createBundleBuildState, g as createBundleModuleGraphOptions, h as applyLinkedResults, i as createCandidateSignature, j as stripRequestQuery, k as slash, l as summarizeStringDiff, m as createRuntimeAffectingSourceSignature, n as createScopedGeneratorCandidateSignature, o as createLinkedImpactSignature, p as updateBundleBuildState, r as createScopedGeneratorRuntime, s as getSnapshotHash, t as createSourceCandidateScanSignature, u as buildBundleSnapshot, v as createBundlerGeneratedCssMarker, w as cleanUrl, x as stripBundlerGeneratedCssMarkers, y as hasBundlerGeneratedCssMarker } from "./source-candidate-scan-signature-BbCmW975.mjs";
5
+ import { C as normalizeFrameworkStylePlatform, S as createDebug, _ as toCustomAttributesEntities, a as vitePluginName, l as shouldSkipJsTransform, m as replaceWxml, n as normalizeStyleHandlerMajorVersion, t as getCompilerContext, v as collectRuntimeClassSet, x as refreshTailwindRuntimeState, y as createTailwindRuntimeReadyPromise } from "./context-CfXr3hWz.mjs";
6
+ import { _ as resolveViteTailwindV4CssDependencies, a as findTailwindConfig, f as createViteSourceScanMatcher, g as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions, l as getRuntimeClassSetSignature, m as discoverTailwindV4CssEntries, p as resolveViteSourceScanEntries, r as isUniAppXEnabled } from "./tailwindcss-PA2jHHpx.mjs";
7
+ import { E as createCssTokenSourceMap, O as processCachedTask, T as createCssSourceTraceCacheSignature, _ as isPureLocalCssImportWrapper, a as isSourceCandidateRequest, b as scoreTailwindV4CssSourceFileMatch, d as validateCandidatesByGenerator, g as mergeMarkedUserLayerComponentsCss, h as extractMarkedUserLayerComponentsCss, m as runWithConcurrency, r as createSourceCandidateCollector, s as createBundleRuntimeClassSetManager, t as createHmrTimingRecorder, w as annotateCssSourceTrace } from "./hmr-timing-BecOXMd8.mjs";
8
+ import { A as hasBundlerGeneratedCssMarker, C as generateTailwindV4Css, E as normalizeOutputPathKey, F as createBuiltinViteStyleInjectorPlugins, L as viteStyleInjectorDelegates, M as stripBundlerGeneratedCssMarkers, N as resolvePackageDir, O as toAbsoluteOutputPath, P as resolvePluginDisabledState, S as createBundleModuleGraphOptions, T as stripRequestQuery, _ as isHTMLRequest, a as createJsHashSalt, b as createRuntimeAffectingSourceSignature, c as hasRuntimeAffectingSourceChanges, f as createBundleBuildState, g as isCSSRequest, h as formatPostcssSourceMap, i as createCandidateSignature, j as parseBundlerGeneratedCssMarkerBlocks, k as createBundlerGeneratedCssMarker, l as summarizeStringDiff, m as cleanUrl, n as createScopedGeneratorCandidateSignature, o as createLinkedImpactSignature, p as updateBundleBuildState, r as createScopedGeneratorRuntime, s as getSnapshotHash, t as createSourceCandidateScanSignature, u as buildBundleSnapshot, v as normalizePath, w as isSourceStyleRequest, x as applyLinkedResults, y as slash, z as resolveViteFrameworkProfile } from "./source-candidate-scan-signature-DAg8QSgh.mjs";
9
9
  import { t as logger$1 } from "./logger-BNzxZbZj.mjs";
10
10
  import fs, { existsSync, readFileSync, realpathSync } from "node:fs";
11
11
  import path from "node:path";
@@ -18,30 +18,6 @@ import micromatch from "micromatch";
18
18
  import { Buffer } from "node:buffer";
19
19
  import { logger } from "@weapp-tailwindcss/logger";
20
20
  import { parse } from "comment-json";
21
- //#region src/uni-app-x/harmony.ts
22
- function isUniAppXHarmonyOutDir(outDir) {
23
- return typeof outDir === "string" && /(?:^|[/\\])\.?app-harmony(?:[/\\]|$)/.test(outDir);
24
- }
25
- //#endregion
26
- //#region src/bundlers/vite/query.ts
27
- function parseVueRequest(id) {
28
- const [filename = id, rawQuery] = id.split(`?`, 2);
29
- const searchParams = new URLSearchParams(rawQuery);
30
- const query = Object.fromEntries(searchParams);
31
- if (query.vue != null) query.vue = true;
32
- if (query.index != null) query.index = Number(query.index);
33
- if (query.raw != null) query.raw = true;
34
- if (query.url != null) query.url = true;
35
- if (query.scoped != null) query.scoped = true;
36
- const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
37
- const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
38
- if (langType) query.lang = langType;
39
- return {
40
- filename,
41
- query
42
- };
43
- }
44
- //#endregion
45
21
  //#region src/uni-app-x/style-asset/style-value.ts
46
22
  const GEN_APP_STYLES_RE = /const\s+GenAppStyles\s*=\s*\[_uM\(\[([\s\S]*?)\]\)\]/;
47
23
  const STYLE_ENTRY_RE = /\[\s*("((?:\\.|[^"\\])+)")\s*,\s*(_pS\(_uM\(\[[\s\S]*?\]\)\))\s*\]/g;
@@ -488,426 +464,170 @@ function createUniAppXBundleAssetSourceGetter(bundle) {
488
464
  };
489
465
  }
490
466
  //#endregion
491
- //#region src/uni-app-x/style-isolation.ts
492
- const manifestCache = /* @__PURE__ */ new Map();
493
- function resolveUniAppXStyleIsolationEnabled(root) {
494
- if (!root) return false;
495
- const normalizedRoot = path.resolve(root);
496
- const cached = manifestCache.get(normalizedRoot);
497
- if (cached !== void 0) return cached;
498
- const manifestPath = path.join(normalizedRoot, "manifest.json");
499
- let enabled = false;
500
- try {
501
- enabled = `${parse(fs.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
502
- } catch {
503
- enabled = false;
467
+ //#region src/bundlers/vite/generate-bundle/configured-css-sources.ts
468
+ function collectConfiguredTailwindV4CssSources(opts) {
469
+ const runtimeCssSources = opts.tailwindcssRuntimeOptions?.tailwindcss?.v4?.cssSources ?? [];
470
+ return filterTailwindV4CssSourceRoots([...opts.tailwindcss?.v4?.cssSources ?? [], ...runtimeCssSources]) ?? [];
471
+ }
472
+ function collectExplicitTailwindV4CssEntries(opts) {
473
+ const entries = [
474
+ ...opts.cssEntries ?? [],
475
+ ...opts.tailwindcss?.v4?.cssEntries ?? [],
476
+ ...opts.tailwindcssRuntimeOptions?.tailwindcss?.v4?.cssEntries ?? []
477
+ ];
478
+ return [...new Set(entries.filter((entry) => typeof entry === "string" && entry.length > 0))];
479
+ }
480
+ function collectConfiguredTailwindV4CssSourceEntries(opts, fallbackBase) {
481
+ const entries = [];
482
+ const seen = /* @__PURE__ */ new Set();
483
+ const explicitCssEntries = collectExplicitTailwindV4CssEntries(opts);
484
+ for (const cssEntry of explicitCssEntries.length > 1 ? explicitCssEntries : []) {
485
+ if (typeof cssEntry !== "string" || cssEntry.length === 0) continue;
486
+ const resolvedFile = path.isAbsolute(cssEntry) ? path.resolve(cssEntry) : path.resolve(fallbackBase, cssEntry);
487
+ if (!existsSync(resolvedFile)) continue;
488
+ const source = readFileSync(resolvedFile, "utf8");
489
+ const key = `${resolvedFile}\0${source}`;
490
+ if (seen.has(key)) continue;
491
+ seen.add(key);
492
+ entries.push({
493
+ file: resolvedFile,
494
+ source
495
+ });
504
496
  }
505
- manifestCache.set(normalizedRoot, enabled);
506
- return enabled;
497
+ for (const cssSource of collectConfiguredTailwindV4CssSources(opts)) {
498
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0) continue;
499
+ const base = resolveTailwindV4CssSourceBase(cssSource, fallbackBase);
500
+ const file = typeof cssSource.file === "string" && cssSource.file.length > 0 ? cssSource.file : path.join(base, "tailwind.css");
501
+ const resolvedFile = path.isAbsolute(file) ? path.resolve(file) : path.resolve(base, file);
502
+ const key = `${resolvedFile}\0${cssSource.css}`;
503
+ if (seen.has(key)) continue;
504
+ seen.add(key);
505
+ entries.push({
506
+ file: resolvedFile,
507
+ source: cssSource.css
508
+ });
509
+ }
510
+ return entries;
507
511
  }
508
512
  //#endregion
509
- //#region src/uni-app-x/vite.ts
510
- let transformUVuePromise;
511
- function loadTransformUVue() {
512
- transformUVuePromise ?? (transformUVuePromise = import("./transform--155BmeJ.mjs").then((mod) => mod.transformUVue));
513
- return transformUVuePromise;
513
+ //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
514
+ function createReplayCssAsset(fileName, source) {
515
+ return {
516
+ type: "asset",
517
+ fileName,
518
+ name: void 0,
519
+ source,
520
+ needsCodeReference: false,
521
+ names: [],
522
+ originalFileName: null,
523
+ originalFileNames: []
524
+ };
514
525
  }
515
- const preprocessorLangs = /* @__PURE__ */ new Set([
516
- "scss",
517
- "sass",
518
- "less",
519
- "styl",
520
- "stylus"
521
- ]);
522
- const INLINE_LANG_RE = /lang\.([a-z]+)/i;
523
- const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
524
- const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
525
- const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
526
- const CSS_MODULE_EXPORT_RE = /^\s*export\s+default\s+(?:\{|\w|\[\])/;
527
- function isPreprocessorRequest(id, lang) {
528
- const normalizedLang = lang?.toLowerCase();
529
- if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
530
- const inlineLang = id.match(INLINE_LANG_RE)?.[1];
531
- if (inlineLang && preprocessorLangs.has(inlineLang.toLowerCase())) return true;
532
- return PREPROCESSOR_EXT_RE.test(id);
526
+ function isAddWatchFileInvalidRollupPhaseError$1(error) {
527
+ const candidate = error;
528
+ return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
533
529
  }
534
- function resolveUniAppXCssTarget(id) {
535
- return UVUE_NVUE_RE.test(cleanUrl(id)) ? "uvue" : void 0;
530
+ function registerGeneratorDependencies$1(ctx, dependencies) {
531
+ if (typeof ctx.addWatchFile !== "function") return;
532
+ for (const dependency of dependencies ?? []) try {
533
+ ctx.addWatchFile(dependency);
534
+ } catch (error) {
535
+ if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
536
+ logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
537
+ continue;
538
+ }
539
+ throw error;
540
+ }
536
541
  }
537
- function resolveUniAppXJsTransformEnabled$1(uniAppX) {
538
- return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
542
+ //#endregion
543
+ //#region src/bundlers/vite/generate-bundle/css-assets.ts
544
+ function createCssAssetEmitter(context) {
545
+ return (fileName, source) => {
546
+ if (context.emitFile) {
547
+ context.emitFile({
548
+ type: "asset",
549
+ fileName,
550
+ source
551
+ });
552
+ return;
553
+ }
554
+ return createReplayCssAsset(fileName, source);
555
+ };
539
556
  }
540
- function isCssModuleExport(code) {
541
- return CSS_MODULE_EXPORT_RE.test(code);
557
+ function resolveAssetSourceFile(asset, fallbackFile) {
558
+ return [asset.originalFileName, ...asset.originalFileNames ?? []].filter((item) => typeof item === "string" && item.length > 0)[0] ?? fallbackFile;
542
559
  }
543
- function createUniAppXPlugins(options) {
544
- const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, generateCss, jsHandler, ensureRuntimeClassSet, getResolvedConfig, uniAppX } = options;
545
- const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
546
- const utsPlatform = resolveUniUtsPlatform();
547
- const isIosPlatform = providedIosPlatform ?? utsPlatform.isAppIos;
548
- const isHarmonyPlatform = utsPlatform.isAppHarmony;
549
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
550
- let componentLocalStyleEnabled;
551
- const harmonyApplyStyleSources = /* @__PURE__ */ new Set();
552
- const harmonyApplyUtilities = /* @__PURE__ */ new Set();
553
- function rememberHarmonyApplySource(code) {
554
- const styleSources = collectUniAppXHarmonyApplyStyleSourcesFromSource(code);
555
- if (styleSources.length === 0) return;
556
- for (const styleSource of styleSources) {
557
- harmonyApplyStyleSources.add(styleSource);
558
- for (const utility of collectUniAppXHarmonyApplyUtilitiesFromSources([styleSource])) harmonyApplyUtilities.add(utility);
559
- }
560
+ //#endregion
561
+ //#region src/bundlers/vite/generate-bundle/css-output.ts
562
+ const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
563
+ const CSS_SOURCE_OUTPUT_EXT_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/i;
564
+ const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
565
+ const FALLBACK_STYLE_OUTPUT_EXTENSION = ".css";
566
+ const COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS = [
567
+ ".wxss",
568
+ ".acss",
569
+ ".ttss",
570
+ ".qss",
571
+ ".jxss",
572
+ ".tyss"
573
+ ];
574
+ function resolveCssOutputRealPath(value) {
575
+ const resolved = path.resolve(value);
576
+ let current = resolved;
577
+ const pendingSegments = [];
578
+ while (!existsSync(current)) {
579
+ const parent = path.dirname(current);
580
+ if (parent === current) return resolved;
581
+ pendingSegments.unshift(path.basename(current));
582
+ current = parent;
560
583
  }
561
- function shouldEnableComponentLocalStyle() {
562
- if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
563
- componentLocalStyleEnabled = false;
564
- return false;
565
- }
566
- if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
567
- componentLocalStyleEnabled = true;
568
- return true;
569
- }
570
- if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
571
- const root = getResolvedConfig()?.root;
572
- componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
573
- return componentLocalStyleEnabled;
584
+ try {
585
+ const realPath = realpathSync.native(current);
586
+ return pendingSegments.length > 0 ? path.join(realPath, ...pendingSegments) : realPath;
587
+ } catch {
588
+ return resolved;
574
589
  }
575
- function shouldEnableHarmonyPageLocalStyle() {
576
- return isHarmonyPlatform && resolvedUniAppXOptions.componentLocalStyles.enabled;
590
+ }
591
+ function normalizeStyleOutputExtension(value) {
592
+ if (typeof value !== "string" || value.trim().length === 0) return;
593
+ const normalized = value.trim().toLowerCase();
594
+ return normalized.startsWith(".") ? normalized : `.${normalized}`;
595
+ }
596
+ function getMatchedStyleOutputExtension(file, cssMatcher) {
597
+ const cleanFile = file.replace(/[?#].*$/, "");
598
+ if (!cssMatcher?.(cleanFile)) return;
599
+ const ext = path.extname(cleanFile);
600
+ if (!ext || ext === ".css") return;
601
+ return ext;
602
+ }
603
+ function resolveStyleOutputExtensionFromFiles(files, cssMatcher, stem) {
604
+ let extension;
605
+ for (const file of files ?? []) {
606
+ const cleanFile = file.replace(/[?#].*$/, "");
607
+ const matchedExtension = getMatchedStyleOutputExtension(cleanFile, cssMatcher);
608
+ if (!matchedExtension) continue;
609
+ if (stem && cleanFile.slice(0, -matchedExtension.length) !== stem) continue;
610
+ if (extension && extension !== matchedExtension) return;
611
+ extension = matchedExtension;
577
612
  }
578
- function isHarmonyBuildTarget() {
579
- if (resolveUniUtsPlatform().isAppHarmony) return true;
580
- return isUniAppXHarmonyOutDir(getResolvedConfig()?.build?.outDir);
581
- }
582
- async function transformStyle(code, id, query, hookContext) {
583
- const parsed = query ?? parseVueRequest(id).query;
584
- if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
585
- if (isCssModuleExport(code)) return;
586
- const shouldGenerateCss = hasTailwindSourceDirectives(code, { importFallback: true }) || hasTailwindApplyDirective(code);
587
- rememberHarmonyApplySource(code);
588
- const generatedCss = shouldGenerateCss ? await generateCss?.(id, code, hookContext) : void 0;
589
- const styleCode = typeof generatedCss === "string" && generatedCss.trim().length > 0 ? generatedCss : code;
590
- const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
591
- let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
592
- if (!styleHandlerOptions) {
593
- styleHandlerOptions = omitUndefined({
594
- isMainChunk: mainCssChunkMatcher(id, appType),
595
- uniAppXCssTarget: resolveUniAppXCssTarget(id),
596
- uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
597
- postcssOptions: { options: {
598
- from: id,
599
- map: {
600
- inline: false,
601
- annotation: false,
602
- sourcesContent: true
603
- }
604
- } }
605
- });
606
- cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
607
- }
608
- const postcssResult = await styleHandler(styleCode, styleHandlerOptions);
609
- const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
610
- for (const warning of warnings) logger$1.warn(warning.toString());
611
- const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), normalizePath(cleanUrl(id)));
612
- return {
613
- code: postcssResult.css,
614
- map: postcssMap
615
- };
616
- }
617
- }
618
- const cssPlugins = [{
619
- name: "weapp-tailwindcss:uni-app-x:css",
620
- async transform(code, id) {
621
- await runtimeState.readyPromise;
622
- return transformStyle(code, id, void 0, this);
623
- }
624
- }, {
625
- name: "weapp-tailwindcss:uni-app-x:css:pre",
626
- enforce: "pre",
627
- async transform(code, id) {
628
- await runtimeState.readyPromise;
629
- const { query } = parseVueRequest(id);
630
- const lang = query.lang;
631
- if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
632
- return transformStyle(code, id, query, this);
633
- }
634
- }];
635
- const nvuePlugin = {
636
- name: "weapp-tailwindcss:uni-app-x:nvue",
637
- enforce: "pre",
638
- async buildStart() {
639
- await ensureRuntimeClassSet(true);
640
- },
641
- async transform(code, id) {
642
- if (!UVUE_NVUE_QUERY_RE.test(id)) return;
643
- rememberHarmonyApplySource(code);
644
- const resolvedConfig = getResolvedConfig();
645
- const isServeCommand = resolvedConfig?.command === "serve";
646
- const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
647
- const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
648
- const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
649
- const transformUVue = await loadTransformUVue();
650
- const enableComponentLocalStyle = shouldEnableComponentLocalStyle();
651
- const enablePageLocalStyle = shouldEnableHarmonyPageLocalStyle();
652
- if (customAttributesEntities.length > 0 || disabledDefaultTemplateHandler || enableComponentLocalStyle || enablePageLocalStyle) return transformUVue(code, id, jsHandler, currentRuntimeSet, omitUndefined({
653
- ...customAttributesEntities.length > 0 ? { customAttributesEntities } : {},
654
- ...disabledDefaultTemplateHandler ? { disabledDefaultTemplateHandler } : {},
655
- ...enableComponentLocalStyle ? { enableComponentLocalStyle } : {},
656
- ...enablePageLocalStyle ? { enablePageLocalStyle } : {}
657
- }));
658
- return transformUVue(code, id, jsHandler, currentRuntimeSet);
659
- },
660
- async handleHotUpdate(ctx) {
661
- if (getResolvedConfig()?.command !== "serve") return;
662
- if (!UVUE_NVUE_RE.test(ctx.file)) return;
663
- await ensureRuntimeClassSet(true);
664
- },
665
- async watchChange(id) {
666
- const resolvedConfig = getResolvedConfig();
667
- if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
668
- if (!UVUE_NVUE_QUERY_RE.test(id)) return;
669
- await ensureRuntimeClassSet(true);
670
- }
671
- };
672
- const stylePlaceholderPlugin = {
673
- name: "weapp-tailwindcss:uni-app-x:style-placeholder",
674
- enforce: "post",
675
- generateBundle: {
676
- order: "post",
677
- async handler(_options, bundle) {
678
- const currentUtsPlatform = resolveUniUtsPlatform();
679
- const canInferHarmonyTarget = !currentUtsPlatform.normalized || currentUtsPlatform.isApp;
680
- const isHarmonyTarget = currentUtsPlatform.isAppHarmony || canInferHarmonyTarget && isHarmonyBuildTarget();
681
- if (!currentUtsPlatform.isApp && !isHarmonyTarget) return;
682
- const getAssetSource = createUniAppXBundleAssetSourceGetter(bundle);
683
- if (isHarmonyTarget) {
684
- const cssSources = [];
685
- const applyStyleSources = [...harmonyApplyStyleSources, ...collectUniAppXHarmonyApplyStyleSources(bundle)];
686
- const applyUtilities = /* @__PURE__ */ new Set([...harmonyApplyUtilities, ...collectUniAppXHarmonyApplyUtilities(bundle)]);
687
- if (applyStyleSources.length > 0 && applyUtilities.size > 0) {
688
- const harmonyApplyCssFile = path.resolve(getResolvedConfig()?.root ?? process$1.cwd(), "uni-app-x-harmony-apply.css");
689
- const generatedCss = await generateCss?.(harmonyApplyCssFile, createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities), this);
690
- if (typeof generatedCss === "string" && generatedCss.trim().length > 0) cssSources.push(generatedCss);
691
- }
692
- injectUniAppXHarmonyBundleStyles(bundle, {
693
- cssSources,
694
- excludeComponents: shouldEnableComponentLocalStyle()
695
- });
696
- }
697
- for (const [file, item] of Object.entries(bundle)) {
698
- if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
699
- const currentSource = String(item.source);
700
- const nextSource = injectUniAppXStylePlaceholder(file, currentSource, getAssetSource);
701
- if (nextSource !== currentSource) item.source = nextSource;
702
- }
703
- }
704
- }
705
- };
706
- return [
707
- ...cssPlugins,
708
- nvuePlugin,
709
- stylePlaceholderPlugin
710
- ];
711
- }
712
- function createUniAppXAssetTask(file, originalSource, outDir, options) {
713
- return async () => {
714
- const { cache, hashKey, createHandlerOptions, debug, getAssetSource, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
715
- const absoluteFile = toAbsoluteOutputPath(file, outDir);
716
- const rawSource = originalSource.source.toString();
717
- await processCachedTask({
718
- cache,
719
- cacheKey: file,
720
- hashKey,
721
- rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
722
- applyResult(source) {
723
- originalSource.source = source;
724
- },
725
- onCacheHit() {
726
- debug("js cache hit: %s", file);
727
- },
728
- async transform() {
729
- const currentSource = originalSource.source.toString();
730
- const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
731
- uniAppX: resolveUniAppXJsTransformEnabled$1(options.uniAppX),
732
- babelParserOptions: {
733
- plugins: ["typescript"],
734
- sourceType: "unambiguous"
735
- }
736
- }));
737
- const nextCode = injectUniAppXStylePlaceholder(file, code, getAssetSource);
738
- onUpdate(file, currentSource, nextCode);
739
- debug("js handle: %s", file);
740
- applyLinkedResults(linked);
741
- return { result: nextCode };
742
- }
743
- });
744
- };
745
- }
746
- //#endregion
747
- //#region src/bundlers/vite/generate-bundle/configured-css-sources.ts
748
- function collectConfiguredTailwindV4CssSources(opts) {
749
- const runtimeCssSources = opts.tailwindcssRuntimeOptions?.tailwindcss?.v4?.cssSources ?? [];
750
- return filterTailwindV4CssSourceRoots([...opts.tailwindcss?.v4?.cssSources ?? [], ...runtimeCssSources]) ?? [];
751
- }
752
- function collectExplicitTailwindV4CssEntries(opts) {
753
- const entries = [
754
- ...opts.cssEntries ?? [],
755
- ...opts.tailwindcss?.v4?.cssEntries ?? [],
756
- ...opts.tailwindcssRuntimeOptions?.tailwindcss?.v4?.cssEntries ?? []
757
- ];
758
- return [...new Set(entries.filter((entry) => typeof entry === "string" && entry.length > 0))];
759
- }
760
- function collectConfiguredTailwindV4CssSourceEntries(opts, fallbackBase) {
761
- const entries = [];
762
- const seen = /* @__PURE__ */ new Set();
763
- const explicitCssEntries = collectExplicitTailwindV4CssEntries(opts);
764
- for (const cssEntry of explicitCssEntries.length > 1 ? explicitCssEntries : []) {
765
- if (typeof cssEntry !== "string" || cssEntry.length === 0) continue;
766
- const resolvedFile = path.isAbsolute(cssEntry) ? path.resolve(cssEntry) : path.resolve(fallbackBase, cssEntry);
767
- if (!existsSync(resolvedFile)) continue;
768
- const source = readFileSync(resolvedFile, "utf8");
769
- const key = `${resolvedFile}\0${source}`;
770
- if (seen.has(key)) continue;
771
- seen.add(key);
772
- entries.push({
773
- file: resolvedFile,
774
- source
775
- });
776
- }
777
- for (const cssSource of collectConfiguredTailwindV4CssSources(opts)) {
778
- if (typeof cssSource.css !== "string" || cssSource.css.length === 0) continue;
779
- const base = resolveTailwindV4CssSourceBase(cssSource, fallbackBase);
780
- const file = typeof cssSource.file === "string" && cssSource.file.length > 0 ? cssSource.file : path.join(base, "tailwind.css");
781
- const resolvedFile = path.isAbsolute(file) ? path.resolve(file) : path.resolve(base, file);
782
- const key = `${resolvedFile}\0${cssSource.css}`;
783
- if (seen.has(key)) continue;
784
- seen.add(key);
785
- entries.push({
786
- file: resolvedFile,
787
- source: cssSource.css
788
- });
789
- }
790
- return entries;
791
- }
792
- //#endregion
793
- //#region src/bundlers/vite/generate-bundle/rollup-assets.ts
794
- function createReplayCssAsset(fileName, source) {
795
- return {
796
- type: "asset",
797
- fileName,
798
- name: void 0,
799
- source,
800
- needsCodeReference: false,
801
- names: [],
802
- originalFileName: null,
803
- originalFileNames: []
804
- };
805
- }
806
- function isAddWatchFileInvalidRollupPhaseError$1(error) {
807
- const candidate = error;
808
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
809
- }
810
- function registerGeneratorDependencies$1(ctx, dependencies) {
811
- if (typeof ctx.addWatchFile !== "function") return;
812
- for (const dependency of dependencies ?? []) try {
813
- ctx.addWatchFile(dependency);
814
- } catch (error) {
815
- if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
816
- logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
817
- continue;
818
- }
819
- throw error;
820
- }
821
- }
822
- //#endregion
823
- //#region src/bundlers/vite/generate-bundle/css-assets.ts
824
- function createCssAssetEmitter(context) {
825
- return (fileName, source) => {
826
- if (context.emitFile) {
827
- context.emitFile({
828
- type: "asset",
829
- fileName,
830
- source
831
- });
832
- return;
833
- }
834
- return createReplayCssAsset(fileName, source);
835
- };
836
- }
837
- function resolveAssetSourceFile(asset, fallbackFile) {
838
- return [asset.originalFileName, ...asset.originalFileNames ?? []].filter((item) => typeof item === "string" && item.length > 0)[0] ?? fallbackFile;
839
- }
840
- //#endregion
841
- //#region src/bundlers/vite/generate-bundle/css-output.ts
842
- const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
843
- const CSS_SOURCE_OUTPUT_EXT_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/i;
844
- const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
845
- const FALLBACK_STYLE_OUTPUT_EXTENSION = ".css";
846
- const COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS = [
847
- ".wxss",
848
- ".acss",
849
- ".ttss",
850
- ".qss",
851
- ".jxss",
852
- ".tyss"
853
- ];
854
- function resolveCssOutputRealPath(value) {
855
- const resolved = path.resolve(value);
856
- let current = resolved;
857
- const pendingSegments = [];
858
- while (!existsSync(current)) {
859
- const parent = path.dirname(current);
860
- if (parent === current) return resolved;
861
- pendingSegments.unshift(path.basename(current));
862
- current = parent;
863
- }
864
- try {
865
- const realPath = realpathSync.native(current);
866
- return pendingSegments.length > 0 ? path.join(realPath, ...pendingSegments) : realPath;
867
- } catch {
868
- return resolved;
869
- }
870
- }
871
- function normalizeStyleOutputExtension(value) {
872
- if (typeof value !== "string" || value.trim().length === 0) return;
873
- const normalized = value.trim().toLowerCase();
874
- return normalized.startsWith(".") ? normalized : `.${normalized}`;
875
- }
876
- function getMatchedStyleOutputExtension(file, cssMatcher) {
877
- const cleanFile = file.replace(/[?#].*$/, "");
878
- if (!cssMatcher?.(cleanFile)) return;
879
- const ext = path.extname(cleanFile);
880
- if (!ext || ext === ".css") return;
881
- return ext;
882
- }
883
- function resolveStyleOutputExtensionFromFiles(files, cssMatcher, stem) {
884
- let extension;
885
- for (const file of files ?? []) {
886
- const cleanFile = file.replace(/[?#].*$/, "");
887
- const matchedExtension = getMatchedStyleOutputExtension(cleanFile, cssMatcher);
888
- if (!matchedExtension) continue;
889
- if (stem && cleanFile.slice(0, -matchedExtension.length) !== stem) continue;
890
- if (extension && extension !== matchedExtension) return;
891
- extension = matchedExtension;
892
- }
893
- return extension;
894
- }
895
- function resolveStyleOutputExtensionFromMatcher(cssMatcher, stem) {
896
- if (!cssMatcher || !stem) return;
897
- return COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS.find((extension) => cssMatcher(`${stem}${extension}`));
898
- }
899
- function resolveStyleOutputFileFromFiles(files, cssMatcher, stem) {
900
- const cleanStem = normalizeOutputPathKey(stem);
901
- const stemSuffix = `/${cleanStem}`;
902
- const matchedFiles = /* @__PURE__ */ new Set();
903
- for (const file of files ?? []) {
904
- const cleanFile = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
905
- if (!cssMatcher?.(cleanFile)) continue;
906
- const extension = path.extname(cleanFile);
907
- if (!extension || extension === ".css") continue;
908
- const outputStem = cleanFile.slice(0, -extension.length);
909
- const outputStemSuffix = `/${outputStem}`;
910
- if (outputStem === cleanStem || outputStem.endsWith(stemSuffix) || cleanStem.endsWith(outputStemSuffix) || cleanStem.endsWith(`/${outputStem}`)) matchedFiles.add(cleanFile);
613
+ return extension;
614
+ }
615
+ function resolveStyleOutputExtensionFromMatcher(cssMatcher, stem) {
616
+ if (!cssMatcher || !stem) return;
617
+ return COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS.find((extension) => cssMatcher(`${stem}${extension}`));
618
+ }
619
+ function resolveStyleOutputFileFromFiles(files, cssMatcher, stem) {
620
+ const cleanStem = normalizeOutputPathKey(stem);
621
+ const stemSuffix = `/${cleanStem}`;
622
+ const matchedFiles = /* @__PURE__ */ new Set();
623
+ for (const file of files ?? []) {
624
+ const cleanFile = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
625
+ if (!cssMatcher?.(cleanFile)) continue;
626
+ const extension = path.extname(cleanFile);
627
+ if (!extension || extension === ".css") continue;
628
+ const outputStem = cleanFile.slice(0, -extension.length);
629
+ const outputStemSuffix = `/${outputStem}`;
630
+ if (outputStem === cleanStem || outputStem.endsWith(stemSuffix) || cleanStem.endsWith(outputStemSuffix) || cleanStem.endsWith(`/${outputStem}`)) matchedFiles.add(cleanFile);
911
631
  }
912
632
  return matchedFiles.size === 1 ? [...matchedFiles][0] : void 0;
913
633
  }
@@ -1174,18 +894,21 @@ function createRootMiniProgramOriginStyleOutputFile(file) {
1174
894
  if (/(?:^|\/)[^/]+-origin\.[^.]+$/i.test(normalized)) return normalized;
1175
895
  return normalized.replace(/(\.[^.]+)$/, "-origin$1");
1176
896
  }
1177
- function shouldKeepRootMiniProgramStyleAsImportShell(appType) {
1178
- return appType === "uni-app-vite" || appType === "uni-app-x" || appType === "taro";
897
+ function shouldKeepRootMiniProgramStyleAsImportShell(enabled) {
898
+ return enabled === true;
1179
899
  }
1180
- function shouldMoveRootMiniProgramStyleToImportShellOrigin(appType) {
1181
- return appType === "taro";
900
+ function shouldMoveRootMiniProgramStyleToImportShellOrigin(enabled) {
901
+ return enabled === true;
1182
902
  }
1183
903
  //#endregion
1184
904
  //#region src/bundlers/vite/generate-bundle/css-output-helpers.ts
1185
905
  function resolveCssBundleOutputFile(options) {
1186
- const { bundleFiles, defaultStyleOutputExtension, file, isWebGeneratorTarget, opts, shouldPreserveAppCssExtension } = options;
906
+ const { bundleFiles, defaultStyleOutputExtension, file, isWebGeneratorTarget, opts, pipelineContext, cssPipelineStrategy, shouldPreserveAppCssExtension } = options;
1187
907
  let outputFile = resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, shouldPreserveAppCssExtension, defaultStyleOutputExtension, bundleFiles);
1188
- if (outputFile === file && isRootMiniProgramStyleOutputFile$1(file) && shouldMoveRootMiniProgramStyleToImportShellOrigin(opts.appType)) outputFile = createRootMiniProgramOriginStyleOutputFile(file);
908
+ if (outputFile === file && isRootMiniProgramStyleOutputFile$1(file) && shouldMoveRootMiniProgramStyleToImportShellOrigin(cssPipelineStrategy?.shouldMoveRootMiniProgramStyleToImportShellOrigin?.({
909
+ ...pipelineContext,
910
+ file
911
+ }))) outputFile = createRootMiniProgramOriginStyleOutputFile(file);
1189
912
  return outputFile;
1190
913
  }
1191
914
  function shouldSkipRawSourceStyleAsset(outputFile, file, rawSource, assetSourceFile = file, cssMatcher) {
@@ -1223,12 +946,16 @@ function hasViteProcessedCssResultForSource(sourceFile, getViteProcessedCssAsset
1223
946
  return false;
1224
947
  }
1225
948
  function applyCssResultToBundle(options) {
1226
- const { appType, assetSourceFile, bundle, emitOrReplayCssAsset, file, originalSource, outputFile, source, viteProcessedCssAsset } = options;
949
+ const { assetSourceFile, bundle, cssPipelineStrategy, emitOrReplayCssAsset, file, originalSource, outputFile, pipelineContext, source, viteProcessedCssAsset } = options;
1227
950
  if (outputFile === file) {
1228
951
  originalSource.source = source;
1229
952
  return;
1230
953
  }
1231
- const importShellSource = isRootMiniProgramStyleOutputFile$1(file) && isRootMiniProgramStyleOutputFile$1(outputFile) && shouldKeepRootMiniProgramStyleAsImportShell(appType) ? createCssImportShell$1(file, outputFile) : void 0;
954
+ const importShellSource = isRootMiniProgramStyleOutputFile$1(file) && isRootMiniProgramStyleOutputFile$1(outputFile) && shouldKeepRootMiniProgramStyleAsImportShell(cssPipelineStrategy?.shouldKeepRootMiniProgramStyleAsImportShell?.({
955
+ ...pipelineContext,
956
+ css: source,
957
+ file
958
+ })) ? createCssImportShell$1(file, outputFile) : void 0;
1232
959
  if (bundle[file] === originalSource && originalSource.originalFileNames?.includes(assetSourceFile)) {
1233
960
  const existingOutput = bundle[outputFile];
1234
961
  if (existingOutput?.type === "asset") existingOutput.source = source;
@@ -1753,20 +1480,66 @@ const SFC_STYLE_SOURCE_EXTENSIONS = [
1753
1480
  ".svelte",
1754
1481
  ".mpx"
1755
1482
  ];
1756
- const SFC_STYLE_BLOCK_RE$1 = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
1757
- function extractSfcStyleSources(source) {
1483
+ const SFC_STYLE_BLOCK_RE$1 = /<style\b([^>]*)>([\s\S]*?)<\/style>/gi;
1484
+ const SFC_SCOPED_STYLE_ATTR_RE = /(?:^|\s)scoped(?:\s|=|$)/i;
1485
+ const SFC_LANG_STYLE_ATTR_RE = /(?:^|\s)lang(?:=(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+)))?/i;
1486
+ function extractSfcStyleBlocks(source) {
1758
1487
  const styleSources = [];
1759
1488
  SFC_STYLE_BLOCK_RE$1.lastIndex = 0;
1489
+ let index = 0;
1760
1490
  let match = SFC_STYLE_BLOCK_RE$1.exec(source);
1761
1491
  while (match !== null) {
1762
- styleSources.push(match[1] ?? "");
1492
+ const attrs = match[1] ?? "";
1493
+ styleSources.push({
1494
+ attrs,
1495
+ index,
1496
+ scoped: SFC_SCOPED_STYLE_ATTR_RE.test(attrs),
1497
+ source: match[2] ?? ""
1498
+ });
1499
+ index += 1;
1763
1500
  match = SFC_STYLE_BLOCK_RE$1.exec(source);
1764
1501
  }
1765
1502
  return styleSources;
1766
1503
  }
1504
+ function extractSfcStyleSources(source) {
1505
+ return extractSfcStyleBlocks(source).map((style) => style.source);
1506
+ }
1767
1507
  function hasSfcStyleSources(source) {
1768
1508
  return extractSfcStyleSources(source).length > 0;
1769
1509
  }
1510
+ function resolveSfcStyleHandlerSourceFile(sourceFile, styleBlocks) {
1511
+ const scopedStyleBlock = styleBlocks.find((style) => style.scoped);
1512
+ return scopedStyleBlock ? `${sourceFile}?vue&type=style&index=${scopedStyleBlock.index}&scoped=true` : sourceFile;
1513
+ }
1514
+ function normalizeSfcStyleSourceForCompare(source) {
1515
+ return source.replace(/\r\n?/g, "\n").trim();
1516
+ }
1517
+ function resolveSfcStyleBlockLang(attrs) {
1518
+ const match = SFC_LANG_STYLE_ATTR_RE.exec(attrs);
1519
+ return match?.[1] ?? match?.[2] ?? match?.[3];
1520
+ }
1521
+ function createSfcStyleRequest(sourceFile, styleBlock) {
1522
+ const params = new URLSearchParams();
1523
+ params.set("vue", "");
1524
+ params.set("type", "style");
1525
+ params.set("index", String(styleBlock.index));
1526
+ if (styleBlock.scoped) params.set("scoped", "true");
1527
+ const lang = resolveSfcStyleBlockLang(styleBlock.attrs);
1528
+ if (lang) params.set("lang", lang);
1529
+ return `${sourceFile}?${params.toString()}`;
1530
+ }
1531
+ function resolveSfcStyleRequestFromKnownSource(sourceFile, sfcSource, styleSource) {
1532
+ if (!sfcSource) return sourceFile;
1533
+ const styleBlocks = extractSfcStyleBlocks(sfcSource);
1534
+ if (styleBlocks.length === 0) return sourceFile;
1535
+ const normalizedStyleSource = normalizeSfcStyleSourceForCompare(styleSource);
1536
+ const matchedBlocks = styleBlocks.filter((styleBlock) => {
1537
+ const normalizedBlockSource = normalizeSfcStyleSourceForCompare(styleBlock.source);
1538
+ return normalizedBlockSource === normalizedStyleSource || normalizedBlockSource.includes(normalizedStyleSource) || normalizedStyleSource.includes(normalizedBlockSource);
1539
+ });
1540
+ const styleBlock = matchedBlocks.length === 1 ? matchedBlocks[0] : styleBlocks.length === 1 ? styleBlocks[0] : void 0;
1541
+ return styleBlock ? createSfcStyleRequest(sourceFile, styleBlock) : sourceFile;
1542
+ }
1770
1543
  function hasTailwindGenerationSource(source, options = {}) {
1771
1544
  const allowRootDirectives = options.allowRootDirectives !== false;
1772
1545
  return hasTailwindNonRootGenerationDirectives(source, { importFallback: true }) || allowRootDirectives && hasTailwindSourceDirectives(source, { importFallback: true }) || allowRootDirectives && hasTailwindRootDirectives(source, { importFallback: true }) || hasTailwindApplyDirective(source);
@@ -1786,7 +1559,8 @@ async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputR
1786
1559
  debug("sfc style source infer skipped: missing known source for %s -> %s", outputFile, sourceFile);
1787
1560
  return;
1788
1561
  }
1789
- const rawSource = extractSfcStyleSources(source).join("\n");
1562
+ const styleBlocks = extractSfcStyleBlocks(source);
1563
+ const rawSource = styleBlocks.map((style) => style.source).join("\n");
1790
1564
  if (!rawSource || !hasTailwindGenerationSourceForFile(sourceFile, rawSource)) {
1791
1565
  debug("sfc style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
1792
1566
  return;
@@ -1795,7 +1569,7 @@ async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputR
1795
1569
  return {
1796
1570
  outputFile,
1797
1571
  rawSource,
1798
- sourceFile
1572
+ sourceFile: resolveSfcStyleHandlerSourceFile(sourceFile, styleBlocks)
1799
1573
  };
1800
1574
  }
1801
1575
  function normalizeSfcSourceFileForCompare(file) {
@@ -1997,6 +1771,13 @@ function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, so
1997
1771
  //#endregion
1998
1772
  //#region src/bundlers/vite/processed-css-assets.ts
1999
1773
  const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
1774
+ function createCssAssetPipelineContext(options, file, bundle) {
1775
+ const context = options.createCssPipelineContext?.(file);
1776
+ return context ? {
1777
+ ...context,
1778
+ bundle
1779
+ } : void 0;
1780
+ }
2000
1781
  function isCssOutputFile(file) {
2001
1782
  return CSS_OUTPUT_FILE_RE.test(file);
2002
1783
  }
@@ -2171,14 +1952,17 @@ function removeDuplicateUnlinkedRootCssAssetsReferencedByHtml(bundle, options =
2171
1952
  return removed;
2172
1953
  }
2173
1954
  const VUE_SCOPED_ATTR_RE = /\[data-v-[^\]]+\]/gi;
1955
+ const VUE_SCOPED_CLASS_RE = /\.data-v-[\w-]+/gi;
2174
1956
  function hasVueScopedAttr(value) {
2175
1957
  VUE_SCOPED_ATTR_RE.lastIndex = 0;
2176
- const matched = VUE_SCOPED_ATTR_RE.test(value);
1958
+ VUE_SCOPED_CLASS_RE.lastIndex = 0;
1959
+ const matched = VUE_SCOPED_ATTR_RE.test(value) || VUE_SCOPED_CLASS_RE.test(value);
2177
1960
  VUE_SCOPED_ATTR_RE.lastIndex = 0;
1961
+ VUE_SCOPED_CLASS_RE.lastIndex = 0;
2178
1962
  return matched;
2179
1963
  }
2180
1964
  function normalizeCssSignatureValue(value) {
2181
- return value.replace(VUE_SCOPED_ATTR_RE, "").replace(/\s+/g, " ").replace(/\s*([>+~])\s*/g, "$1").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
1965
+ return value.replace(VUE_SCOPED_ATTR_RE, "").replace(VUE_SCOPED_CLASS_RE, "").replace(/\s+/g, " ").replace(/\s*([>+~])\s*/g, "$1").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
2182
1966
  }
2183
1967
  function createDeclarationSignature(rule) {
2184
1968
  return createDeclarationKeys(rule).sort().join(";");
@@ -2205,6 +1989,33 @@ function isLikelyTailwindGlobalRule(rule) {
2205
1989
  function isLikelyTailwindPropertyAtRule(atRule) {
2206
1990
  return atRule.name.toLowerCase() === "property" && normalizeCssSignatureValue(atRule.params).startsWith("--tw-");
2207
1991
  }
1992
+ const MINI_PROGRAM_PREFLIGHT_SELECTORS = /* @__PURE__ */ new Set([
1993
+ "view",
1994
+ "text",
1995
+ "::after",
1996
+ "::before"
1997
+ ]);
1998
+ const MINI_PROGRAM_PREFLIGHT_DECLARATIONS = /* @__PURE__ */ new Set([
1999
+ "box-sizing",
2000
+ "margin",
2001
+ "padding",
2002
+ "border"
2003
+ ]);
2004
+ function isMiniProgramTailwindPreflightDeclaration(decl) {
2005
+ return decl.prop.startsWith("--tw-") || MINI_PROGRAM_PREFLIGHT_DECLARATIONS.has(decl.prop);
2006
+ }
2007
+ function isUnscopedMiniProgramTailwindPreflightRule(rule) {
2008
+ const selectors = rule.selectors ?? [rule.selector];
2009
+ if (selectors.length === 0 || !selectors.every((selector) => {
2010
+ const normalized = normalizeCssSignatureValue(selector);
2011
+ return !hasVueScopedAttr(selector) && MINI_PROGRAM_PREFLIGHT_SELECTORS.has(normalized);
2012
+ })) return false;
2013
+ const declarations = rule.nodes?.filter((node) => node.type === "decl") ?? [];
2014
+ return declarations.length > 0 && declarations.every(isMiniProgramTailwindPreflightDeclaration);
2015
+ }
2016
+ function hasUnscopedMiniProgramTailwindPreflightRule(css) {
2017
+ return /(?:^|[{}])\s*view\s*,\s*text\s*,\s*::after\s*,\s*::before\s*\{/.test(css);
2018
+ }
2208
2019
  function collectRootScopedComparableCssCoverage(cssSources) {
2209
2020
  const rules = /* @__PURE__ */ new Set();
2210
2021
  const atRules = /* @__PURE__ */ new Set();
@@ -2246,8 +2057,9 @@ function isRuleCoveredByRootCss(rule, coverage) {
2246
2057
  function removeScopedCssCoveredByRootStyleSources(css, rootSources) {
2247
2058
  if (!hasVueScopedAttr(css)) return css;
2248
2059
  const hasScopedTailwindGeneratedCss = /tailwindcss v\d/i.test(css);
2060
+ const hasUnscopedMiniProgramPreflight = hasUnscopedMiniProgramTailwindPreflightRule(css);
2249
2061
  const coverage = collectRootScopedComparableCssCoverage(rootSources);
2250
- if (coverage.rules.size === 0 && coverage.atRules.size === 0 && !hasScopedTailwindGeneratedCss) return css;
2062
+ if (coverage.rules.size === 0 && coverage.atRules.size === 0 && !hasScopedTailwindGeneratedCss && !hasUnscopedMiniProgramPreflight) return css;
2251
2063
  try {
2252
2064
  const root = postcss.parse(css);
2253
2065
  let changed = false;
@@ -2258,7 +2070,7 @@ function removeScopedCssCoveredByRootStyleSources(css, rootSources) {
2258
2070
  }
2259
2071
  });
2260
2072
  root.walkRules((rule) => {
2261
- if (isRuleCoveredByRootCss(rule, coverage) || hasScopedTailwindGeneratedCss && isLikelyTailwindGlobalRule(rule)) {
2073
+ if (isRuleCoveredByRootCss(rule, coverage) || hasScopedTailwindGeneratedCss && isLikelyTailwindGlobalRule(rule) || isUnscopedMiniProgramTailwindPreflightRule(rule)) {
2262
2074
  rule.remove();
2263
2075
  changed = true;
2264
2076
  }
@@ -2357,11 +2169,17 @@ function isRootStyleOutputFile(file) {
2357
2169
  function isMiniProgramStyleOutputFile(file) {
2358
2170
  return /\.(?:wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i.test(file);
2359
2171
  }
2360
- function shouldPreserveMiniProgramImportShell(opts, file, css) {
2361
- return (opts.appType === "taro" || opts.appType === "uni-app-vite" || opts.appType === "uni-app-x") && isMiniProgramStyleOutputFile(file) && opts.cssMatcher(file) && isPureLocalCssImportWrapper(css);
2172
+ function shouldPreserveMiniProgramImportShell(options, bundle, file, css) {
2173
+ const context = createCssAssetPipelineContext(options, file, bundle);
2174
+ return context !== void 0 && options.cssPipelineStrategy?.shouldKeepRootMiniProgramStyleAsImportShell?.({
2175
+ ...context,
2176
+ css,
2177
+ file
2178
+ }) === true && isMiniProgramStyleOutputFile(file) && options.opts.cssMatcher(file) && isPureLocalCssImportWrapper(css);
2362
2179
  }
2363
- function resolvePreservedImportShellInjectionTarget(opts, bundle, file, css) {
2364
- if (opts.appType !== "taro") return;
2180
+ function resolvePreservedImportShellInjectionTarget(options, bundle, file, css) {
2181
+ const context = createCssAssetPipelineContext(options, file, bundle);
2182
+ if (context === void 0 || options.cssPipelineStrategy?.shouldNormalizeRootMiniProgramImportShell?.(context) !== true) return;
2365
2183
  const importedStyleFiles = collectImportedStyleFiles(css, file);
2366
2184
  if (importedStyleFiles.size !== 1) return;
2367
2185
  const [importedFile] = importedStyleFiles;
@@ -2373,15 +2191,25 @@ function resolvePreservedImportShellInjectionTarget(opts, bundle, file, css) {
2373
2191
  if (normalizeOutputPathKey(outputFile) === normalizeOutputPathKey(importedFile)) return outputFile;
2374
2192
  }
2375
2193
  }
2376
- function shouldUseCssAssetAsMainInjectionTarget(opts, file, records) {
2194
+ function shouldUseCssAssetAsMainInjectionTarget(opts, file, records, options, bundle) {
2195
+ const context = createCssAssetPipelineContext(options, file, bundle);
2377
2196
  const fileKey = normalizeOutputPathKey(file);
2378
2197
  if (!isRootStyleOutputFile(file) && records.some((record) => typeof record.outputFile === "string" && normalizeOutputPathKey(record.outputFile) === fileKey)) return true;
2379
2198
  if (!isRootStyleOutputFile(file)) return records.some((record) => record.injectIntoMain === true && typeof record.outputFile === "string" && normalizeOutputPathKey(record.outputFile) === fileKey);
2380
2199
  const matchedRootWebOutputTargets = records.map((record) => typeof record.outputFile === "string" ? normalizeOutputPathKey(record.outputFile) : void 0).filter((outputFile) => typeof outputFile === "string" && isRootStyleOutputFile(outputFile) && !isMiniProgramStyleOutputFile(outputFile)).filter((outputFile) => opts.mainCssChunkMatcher(outputFile, opts.appType));
2381
- if (opts.appType === "uni-app-vite" && !isMiniProgramStyleOutputFile(file) && matchedRootWebOutputTargets.length > 0) return matchedRootWebOutputTargets.includes(fileKey);
2200
+ if (context !== void 0 && options.cssPipelineStrategy?.shouldPreferMatchedRootWebOutputTarget?.({
2201
+ ...context,
2202
+ file,
2203
+ matchedRootWebOutputTargets
2204
+ }) === true && !isMiniProgramStyleOutputFile(file) && matchedRootWebOutputTargets.length > 0) return matchedRootWebOutputTargets.includes(fileKey);
2382
2205
  const explicitRootTargets = records.filter((record) => record.injectIntoMain === true).map((record) => typeof record.outputFile === "string" ? normalizeOutputPathKey(record.outputFile) : void 0).filter((outputFile) => typeof outputFile === "string" && isRootStyleOutputFile(outputFile) && !isMiniProgramStyleOutputFile(outputFile));
2383
2206
  const explicitWebCssTargets = records.filter((record) => record.injectIntoMain === true).map((record) => typeof record.outputFile === "string" ? normalizeOutputPathKey(record.outputFile) : void 0).filter((outputFile) => typeof outputFile === "string" && isCssOutputFile(outputFile) && !isMiniProgramStyleOutputFile(outputFile));
2384
- if (opts.appType === "uni-app-vite" && !isMiniProgramStyleOutputFile(file) && explicitWebCssTargets.length > 0) return explicitRootTargets.includes(fileKey);
2207
+ if (context !== void 0 && options.cssPipelineStrategy?.shouldPreferExplicitWebCssTargets?.({
2208
+ ...context,
2209
+ explicitRootTargets,
2210
+ explicitWebCssTargets,
2211
+ file
2212
+ }) === true && !isMiniProgramStyleOutputFile(file) && explicitWebCssTargets.length > 0) return explicitRootTargets.includes(fileKey);
2385
2213
  if (explicitRootTargets.length > 0) return explicitRootTargets.includes(fileKey);
2386
2214
  if (records.some((record) => {
2387
2215
  if (record.injectIntoMain !== true) return false;
@@ -2421,7 +2249,7 @@ function removeCoveredInjectedSourceAssets(bundle, targetFile, targetCss, record
2421
2249
  const isProcessedSource = candidateSource === record.css.trim() || candidateSource.length > 0 && containsCssAfterMinify(targetCss, candidateSource) || targetIsRootWebStyle && candidateIsRootWebStyle && candidateSource.length > 0 && !hasNonCommentCss(uncoveredCandidateSource);
2422
2250
  if (!isRecordFile && !isProcessedSource) continue;
2423
2251
  if (candidateIsRootWebStyle && !targetIsRootWebStyle) continue;
2424
- if (candidateIsRootWebStyle && !isRecordFile) continue;
2252
+ if (candidateIsRootWebStyle && !isRecordFile && !isProcessedSource) continue;
2425
2253
  if (candidateIsRootWebStyle) delete bundle[candidateFile];
2426
2254
  else clearAssetSource(candidateOutput);
2427
2255
  options.debug?.("remove injected vite-processed source css asset: %s -> %s", candidateKey, targetFile);
@@ -2473,8 +2301,22 @@ function isConfiguredTailwindV4CssEntryFile(opts, file) {
2473
2301
  const fileKey = normalizeComparableStyleFile(file);
2474
2302
  return collectConfiguredTailwindV4CssEntryFiles(opts).some((entry) => normalizeComparableStyleFile(entry) === fileKey);
2475
2303
  }
2476
- function resolveUniAppViteWebviewRootCssInjectionTarget(bundle, opts, sourceFile, outputFile) {
2477
- if (opts.appType !== "uni-app-vite" || isMiniProgramStyleOutputFile(outputFile) || !isConfiguredTailwindV4CssEntryFile(opts, sourceFile)) return;
2304
+ function resolveConfiguredCssEntryRootInjectionTarget(bundle, options, sourceFile, outputFile) {
2305
+ const opts = options.opts;
2306
+ if (opts === void 0 || isMiniProgramStyleOutputFile(outputFile) || !isConfiguredTailwindV4CssEntryFile(opts, sourceFile)) return;
2307
+ const context = createCssAssetPipelineContext(options, outputFile, bundle);
2308
+ if (context === void 0) return;
2309
+ const resolvedByStrategy = options.cssPipelineStrategy?.resolveConfiguredCssEntryRootInjectionTarget?.({
2310
+ ...context,
2311
+ bundle,
2312
+ isConfiguredCssEntryFile: (file) => isConfiguredTailwindV4CssEntryFile(opts, file),
2313
+ isMiniProgramStyleOutputFile,
2314
+ isRootStyleOutputFile,
2315
+ outputFile,
2316
+ sourceFile
2317
+ });
2318
+ if (resolvedByStrategy !== void 0) return resolvedByStrategy;
2319
+ if (options.cssPipelineStrategy?.resolveConfiguredCssEntryRootInjectionTarget == null) return;
2478
2320
  const rootCssFiles = [];
2479
2321
  const matchedRootCssFiles = [];
2480
2322
  for (const [bundleFile, output] of Object.entries(bundle)) {
@@ -2541,7 +2383,7 @@ function collectViteProcessedCssAssetResults(bundle, options) {
2541
2383
  options.markCssAssetProcessed?.(output, file);
2542
2384
  options.recordCssAssetResult?.(file, nextCss);
2543
2385
  const resolvedOutputFile = resolveViteGeneratedCssMarkerOutputFile(file, singleMarkerFile, existingAssetFiles, options.resolveViteProcessedCssOutputFile);
2544
- const webviewRootCssInjectionTarget = options.opts ? resolveUniAppViteWebviewRootCssInjectionTarget(bundle, options.opts, singleMarkerFile ?? file, resolvedOutputFile) : void 0;
2386
+ const webviewRootCssInjectionTarget = options.opts ? resolveConfiguredCssEntryRootInjectionTarget(bundle, options, singleMarkerFile ?? file, resolvedOutputFile) : void 0;
2545
2387
  const recordOutputFile = webviewRootCssInjectionTarget ?? resolvedOutputFile;
2546
2388
  if (singleMarkerFile && normalizeOutputPathKey(resolvedOutputFile) !== normalizeOutputPathKey(file) && !isRootStyleOutputFile(resolvedOutputFile) && existingAssetFiles.has(normalizeOutputPathKey(resolvedOutputFile))) {
2547
2389
  const targetAsset = findBundleAssetByOutputFile(bundle, resolvedOutputFile);
@@ -2616,10 +2458,10 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
2616
2458
  if (bundle[bundleFile] !== bundleOutput) continue;
2617
2459
  if (output.type !== "asset") continue;
2618
2460
  let file = getAssetFile$1(bundleFile, output);
2619
- if (!options.opts.cssMatcher(file) || !shouldUseCssAssetAsMainInjectionTarget(options.opts, file, viteCssResults)) continue;
2461
+ if (!options.opts.cssMatcher(file) || !shouldUseCssAssetAsMainInjectionTarget(options.opts, file, viteCssResults, options, bundle)) continue;
2620
2462
  let originalSource = readAssetSource$2(output);
2621
- if (shouldPreserveMiniProgramImportShell(options.opts, file, originalSource)) {
2622
- const importedTargetFile = resolvePreservedImportShellInjectionTarget(options.opts, bundle, file, originalSource);
2463
+ if (shouldPreserveMiniProgramImportShell(options, bundle, file, originalSource)) {
2464
+ const importedTargetFile = resolvePreservedImportShellInjectionTarget(options, bundle, file, originalSource);
2623
2465
  if (typeof importedTargetFile === "string") {
2624
2466
  options.debug?.("preserve mini-program css import shell asset: %s -> %s", file, importedTargetFile);
2625
2467
  const importedOutput = Object.entries(bundle).find(([candidateFile, candidate]) => candidate.type === "asset" && normalizeOutputPathKey(getAssetFile$1(candidateFile, candidate)) === normalizeOutputPathKey(importedTargetFile))?.[1];
@@ -2966,17 +2808,10 @@ function pruneLastCssResults(resultByFile, sourceHashByFile, activeFiles) {
2966
2808
  function readAssetSource(asset) {
2967
2809
  return typeof asset.source === "string" ? asset.source : asset.source.toString();
2968
2810
  }
2969
- function isUniAppViteWebviewAppBundle(bundleFiles) {
2970
- return bundleFiles.some((file) => path.basename(file.replace(/[?#].*$/, "")) === "app-service.js");
2971
- }
2972
- function isUniAppViteWebviewOutDir$2(outDir) {
2973
- const normalized = outDir ? path.basename(path.normalize(outDir)).trim().toLowerCase() : void 0;
2974
- return normalized === "app" || normalized === "app-plus";
2975
- }
2976
2811
  function getAssetFile(bundleFile, asset) {
2977
2812
  return asset.fileName || bundleFile;
2978
2813
  }
2979
- function finalizeUniAppViteWebviewCssCompat(bundle, options) {
2814
+ function finalizeWebviewCssCompat(bundle, options) {
2980
2815
  if (options.opts.generator?.webCompat === false) return 0;
2981
2816
  let transformed = 0;
2982
2817
  for (const [bundleFile, output] of Object.entries(bundle)) {
@@ -2989,7 +2824,7 @@ function finalizeUniAppViteWebviewCssCompat(bundle, options) {
2989
2824
  output.source = nextCss;
2990
2825
  options.recordCssAssetResult?.(file, nextCss);
2991
2826
  options.onUpdate(file, rawSource, nextCss);
2992
- options.debug("finalize uni-app vite webview css compat: %s bytes=%d", file, nextCss.length);
2827
+ options.debug("finalize webview css compat: %s bytes=%d", file, nextCss.length);
2993
2828
  transformed++;
2994
2829
  }
2995
2830
  return transformed;
@@ -3030,8 +2865,8 @@ function resolveSingleCssImportOutputFile(targetFile, css) {
3030
2865
  } catch {}
3031
2866
  return importedFile;
3032
2867
  }
3033
- function normalizeTaroRootImportShellAssets(bundle, options) {
3034
- if (options.appType !== "taro") return 0;
2868
+ function normalizeRootMiniProgramImportShellAssets(bundle, options) {
2869
+ if (!options.enabled) return 0;
3035
2870
  let updated = 0;
3036
2871
  for (const [rootBundleFile, rootOutput] of Object.entries(bundle)) {
3037
2872
  if (rootOutput.type !== "asset") continue;
@@ -3042,6 +2877,17 @@ function normalizeTaroRootImportShellAssets(bundle, options) {
3042
2877
  const originOutput = Object.entries(bundle).find(([bundleFile, output]) => output.type === "asset" && normalizeOutputPathKey(getAssetFile(bundleFile, output)) === normalizeOutputPathKey(originFile))?.[1];
3043
2878
  if (originOutput?.type !== "asset") continue;
3044
2879
  const rootSource = readAssetSource(rootOutput);
2880
+ const importedRootFile = resolveSingleCssImportOutputFile(rootFile, rootSource);
2881
+ if (importedRootFile && normalizeOutputPathKey(importedRootFile) === normalizeOutputPathKey(originFile)) {
2882
+ const nextRootSource = createCssImportShell(rootFile, originFile);
2883
+ if (rootSource === nextRootSource) continue;
2884
+ rootOutput.source = nextRootSource;
2885
+ options.recordCssAssetResult?.(rootFile, nextRootSource);
2886
+ options.onUpdate?.(rootFile, rootSource, nextRootSource);
2887
+ options.debug("normalize root css import shell request: %s -> %s", rootFile, originFile);
2888
+ updated++;
2889
+ continue;
2890
+ }
3045
2891
  if (isPureLocalCssImportWrapper(rootSource)) continue;
3046
2892
  const originSource = readAssetSource(originOutput);
3047
2893
  if (isPureLocalCssImportWrapper(originSource)) {
@@ -3056,13 +2902,13 @@ function normalizeTaroRootImportShellAssets(bundle, options) {
3056
2902
  options.recordCssAssetResult?.(originFile, rootSource);
3057
2903
  options.onUpdate?.(rootFile, rootSource, nextRootSource);
3058
2904
  options.onUpdate?.(originFile, originSource, rootSource);
3059
- options.debug("normalize taro root css import shell: %s -> %s", rootFile, originFile);
2905
+ options.debug("normalize root css import shell: %s -> %s", rootFile, originFile);
3060
2906
  updated++;
3061
2907
  }
3062
2908
  return updated;
3063
2909
  }
3064
2910
  async function finalizeGenerateBundle(options) {
3065
- const { activeProcessCacheKeys, activeProcessHashKeys, activeViteCssCacheFiles, bundle, bundleFiles, cache, cssTaskFactories, debug, defaultStyleOutputExtension, formatIteration, generatorCandidateSignature, generatorRuntime, getCssHandlerOptions, getSourceCandidateSourcesForEntries, getSourceCandidatesForEntries, getViteCssCacheStats, getViteProcessedCssAssetResults, hmrTimingRecorder, hmrTimingStartedAt, isHarmonyAppStyleTarget, isNativeAppStyleTarget, isViteProcessedCssAsset, isWebGeneratorTarget, jsAfterCss, jsTaskFactories, lastCssResultByFile, lastCssSourceHashByFile, linkedByEntry, markCssAssetProcessed, metrics, onEnd, onUpdate, opts, outDir, pendingLinkedUpdates, pruneViteCssCaches, recordCssAssetResult, recordTimingDetail, recordViteProcessedCssAssetResult, rootDir, runtime, runtimeState, shouldPreserveAppCssExtension, snapshot, sourceCandidates, sourceRoot, state, styleHandler, tasks, timingDetails, transformRuntime, transformWebTargetCss, useIncrementalMode } = options;
2911
+ const { activeProcessCacheKeys, activeProcessHashKeys, activeViteCssCacheFiles, bundle, bundleFiles, cache, cssTaskFactories, cssPipelineStrategy, createCssPipelineContext, debug, defaultStyleOutputExtension, formatIteration, generatorCandidateSignature, generatorRuntime, getCssHandlerOptions, getSourceCandidateSourcesForEntries, getSourceCandidatesForEntries, getViteCssCacheStats, getViteProcessedCssAssetResults, hmrTimingRecorder, hmrTimingStartedAt, isHarmonyAppStyleTarget, isNativeAppStyleTarget, isViteProcessedCssAsset, isWebGeneratorTarget, jsAfterCss, jsTaskFactories, lastCssResultByFile, lastCssSourceHashByFile, linkedByEntry, markCssAssetProcessed, metrics, onEnd, onUpdate, opts, outDir, pendingLinkedUpdates, pruneViteCssCaches, recordCssAssetResult, recordTimingDetail, recordViteProcessedCssAssetResult, rootDir, runtime, runtimeState, shouldPreserveAppCssExtension, snapshot, sourceCandidates, sourceRoot, state, styleHandler, tasks, timingDetails, transformRuntime, transformWebTargetCss, useIncrementalMode } = options;
3066
2912
  const tasksStart = performance.now();
3067
2913
  if (cssTaskFactories.length > 0) {
3068
2914
  const cssTask = runWithConcurrency(cssTaskFactories, resolveViteCssTaskConcurrency(useIncrementalMode, runtimeState.tailwindRuntime.majorVersion)).then(() => void 0);
@@ -3091,6 +2937,8 @@ async function finalizeGenerateBundle(options) {
3091
2937
  const syncViteProcessedCssIntoMainCssAssets = () => {
3092
2938
  collectViteProcessedCssAssetResults(bundle, {
3093
2939
  opts,
2940
+ cssPipelineStrategy,
2941
+ createCssPipelineContext,
3094
2942
  isViteProcessedCssAsset,
3095
2943
  markCssAssetProcessed,
3096
2944
  recordCssAssetResult,
@@ -3102,6 +2950,8 @@ async function finalizeGenerateBundle(options) {
3102
2950
  });
3103
2951
  return injectViteProcessedCssIntoMainCssAssets(bundle, {
3104
2952
  opts,
2953
+ cssPipelineStrategy,
2954
+ createCssPipelineContext,
3105
2955
  getViteProcessedCssAssetResults,
3106
2956
  markCssAssetProcessed,
3107
2957
  recordCssAssetResult,
@@ -3120,10 +2970,12 @@ async function finalizeGenerateBundle(options) {
3120
2970
  if (injectUniAppXHarmonyBundleStyles(bundle, { cssSources: [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css) })) debug("uni-app-x harmony bundle styles inject after css assets");
3121
2971
  syncViteProcessedCssIntoMainCssAssets();
3122
2972
  }
3123
- normalizeTaroRootImportShellAssets(bundle, {
3124
- appType: opts.appType,
2973
+ const createFinalizeCssPipelineContext = (file = "") => createCssPipelineContext?.(file);
2974
+ const finalizeCssPipelineContext = createFinalizeCssPipelineContext();
2975
+ normalizeRootMiniProgramImportShellAssets(bundle, {
3125
2976
  cssMatcher: opts.cssMatcher,
3126
2977
  debug,
2978
+ enabled: finalizeCssPipelineContext !== void 0 && cssPipelineStrategy?.shouldNormalizeRootMiniProgramImportShell?.(finalizeCssPipelineContext) === true,
3127
2979
  onUpdate,
3128
2980
  recordCssAssetResult
3129
2981
  });
@@ -3131,13 +2983,23 @@ async function finalizeGenerateBundle(options) {
3131
2983
  removeCssCoveredByRootStyleAssets(bundle, {
3132
2984
  cssMatcher: opts.cssMatcher,
3133
2985
  debug,
3134
- includeTailwindGeneratedCssAssets: opts.appType === "uni-app-vite" && isWebGeneratorTarget && isUniAppViteWebviewAppBundle(bundleFiles),
2986
+ includeTailwindGeneratedCssAssets: finalizeCssPipelineContext !== void 0 && cssPipelineStrategy?.includeTailwindGeneratedCssAssetsInRootCoverage?.({
2987
+ ...finalizeCssPipelineContext,
2988
+ bundleFiles,
2989
+ isWebGeneratorTarget,
2990
+ outDir
2991
+ }) === true,
3135
2992
  isViteProcessedCssAsset,
3136
2993
  onUpdate,
3137
2994
  recordCssAssetResult,
3138
2995
  subpackageRoots: collectMiniProgramSubpackageRoots(bundle)
3139
2996
  });
3140
- if (opts.appType === "uni-app-vite" && isWebGeneratorTarget && isUniAppViteWebviewAppBundle(Object.keys(bundle))) removeDuplicateUnlinkedRootCssAssetsReferencedByHtml(bundle, { debug });
2997
+ if (finalizeCssPipelineContext !== void 0 && cssPipelineStrategy?.shouldRemoveDuplicateUnlinkedRootCssAssetsReferencedByHtml?.({
2998
+ ...finalizeCssPipelineContext,
2999
+ bundleFiles: Object.keys(bundle),
3000
+ isWebGeneratorTarget,
3001
+ outDir
3002
+ }) === true) removeDuplicateUnlinkedRootCssAssetsReferencedByHtml(bundle, { debug });
3141
3003
  await finalizeMiniProgramCssAssets(bundle, {
3142
3004
  cssMatcher: opts.cssMatcher,
3143
3005
  debug,
@@ -3148,7 +3010,12 @@ async function finalizeGenerateBundle(options) {
3148
3010
  recordCssAssetResult,
3149
3011
  styleHandler
3150
3012
  });
3151
- if (opts.appType === "uni-app-vite" && (isWebGeneratorTarget || isUniAppViteWebviewAppBundle(Object.keys(bundle)) || isUniAppViteWebviewOutDir$2(outDir))) finalizeUniAppViteWebviewCssCompat(bundle, {
3013
+ if (finalizeCssPipelineContext !== void 0 && cssPipelineStrategy?.shouldApplyFinalWebviewCssCompat?.({
3014
+ ...finalizeCssPipelineContext,
3015
+ bundleFiles: Object.keys(bundle),
3016
+ isWebGeneratorTarget,
3017
+ outDir
3018
+ }) === true) finalizeWebviewCssCompat(bundle, {
3152
3019
  debug,
3153
3020
  onUpdate,
3154
3021
  opts,
@@ -3198,173 +3065,460 @@ async function finalizeGenerateBundle(options) {
3198
3065
  onEnd();
3199
3066
  debug("end");
3200
3067
  }
3201
- //#endregion
3202
- //#region src/bundlers/vite/generate-bundle/candidates.ts
3203
- const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
3204
- const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
3205
- const CLASS_ATTRIBUTE_RE = /\bclass\s*=\s*/g;
3206
- const MUSTACHE_OPEN = "{{";
3207
- const MUSTACHE_CLOSE = "}}";
3208
- function isUrlLikeCandidate(candidate) {
3209
- return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
3068
+ //#endregion
3069
+ //#region src/bundlers/vite/generate-bundle/candidates.ts
3070
+ const MUSTACHE_EXPRESSION_RE = /\{\{[\s\S]*?\}\}/g;
3071
+ const QUOTED_LITERAL_RE = /'([^']*)'|"([^"]*)"|`([^`]*)`/g;
3072
+ const CLASS_ATTRIBUTE_RE = /\bclass\s*=\s*/g;
3073
+ const MUSTACHE_OPEN = "{{";
3074
+ const MUSTACHE_CLOSE = "}}";
3075
+ function isUrlLikeCandidate(candidate) {
3076
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
3077
+ }
3078
+ function isArbitraryValueCandidate(candidate) {
3079
+ return candidate.includes("[") && candidate.includes("]") && !isUrlLikeCandidate(candidate.trim());
3080
+ }
3081
+ function collectClassAttributeValues(source) {
3082
+ const values = [];
3083
+ CLASS_ATTRIBUTE_RE.lastIndex = 0;
3084
+ let matched = CLASS_ATTRIBUTE_RE.exec(source);
3085
+ while (matched !== null) {
3086
+ const quoteIndex = CLASS_ATTRIBUTE_RE.lastIndex;
3087
+ const quote = source[quoteIndex];
3088
+ if (quote !== "\"" && quote !== "'") {
3089
+ matched = CLASS_ATTRIBUTE_RE.exec(source);
3090
+ continue;
3091
+ }
3092
+ let expressionDepth = 0;
3093
+ for (let index = quoteIndex + 1; index < source.length; index++) {
3094
+ if (source.startsWith(MUSTACHE_OPEN, index)) {
3095
+ expressionDepth++;
3096
+ index += 1;
3097
+ continue;
3098
+ }
3099
+ if (expressionDepth > 0 && source.startsWith(MUSTACHE_CLOSE, index)) {
3100
+ expressionDepth--;
3101
+ index += 1;
3102
+ continue;
3103
+ }
3104
+ if (expressionDepth === 0 && source[index] === quote) {
3105
+ values.push(source.slice(quoteIndex + 1, index));
3106
+ CLASS_ATTRIBUTE_RE.lastIndex = index + 1;
3107
+ break;
3108
+ }
3109
+ }
3110
+ matched = CLASS_ATTRIBUTE_RE.exec(source);
3111
+ }
3112
+ return values;
3113
+ }
3114
+ function collectUnescapedDynamicCandidates(source, allowedCandidates) {
3115
+ const matches = /* @__PURE__ */ new Set();
3116
+ const shouldFilterByAllowedCandidates = allowedCandidates !== void 0 && allowedCandidates.size > 0;
3117
+ for (const classValue of collectClassAttributeValues(source)) for (const expression of classValue.match(MUSTACHE_EXPRESSION_RE) ?? []) {
3118
+ QUOTED_LITERAL_RE.lastIndex = 0;
3119
+ let quoted = QUOTED_LITERAL_RE.exec(expression);
3120
+ while (quoted !== null) {
3121
+ const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
3122
+ for (const candidate of splitCandidateTokens(literal)) {
3123
+ const normalized = candidate.trim();
3124
+ if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
3125
+ if (shouldFilterByAllowedCandidates && !allowedCandidates.has(normalized)) continue;
3126
+ matches.add(normalized);
3127
+ }
3128
+ quoted = QUOTED_LITERAL_RE.exec(expression);
3129
+ }
3130
+ }
3131
+ return [...matches];
3132
+ }
3133
+ //#endregion
3134
+ //#region src/bundlers/vite/generate-bundle/html-processing.ts
3135
+ function processHtmlBundleEntry(options) {
3136
+ const { cache, context, debug, dynamicRetryCandidates, file, metrics, onUpdate, originalEntrySource, originalSource, rememberProcessCacheKey, resolveCurrentSourceCandidateSource, tasks, templateHandler, timeTask, transformRuntime, transformRuntimeSignature } = options;
3137
+ const rawSource = resolveCurrentSourceCandidateSource(file) ?? originalEntrySource;
3138
+ const currentRawDynamicCandidates = collectUnescapedDynamicCandidates(rawSource);
3139
+ const templateRuntime = currentRawDynamicCandidates.length > 0 ? /* @__PURE__ */ new Set([...transformRuntime, ...currentRawDynamicCandidates]) : transformRuntime;
3140
+ const templateRuntimeSignature = templateRuntime === transformRuntime ? transformRuntimeSignature : createCandidateSignature(templateRuntime);
3141
+ const htmlProcessHash = `${cache.computeHash(rawSource)}:${cache.computeHash(createRuntimeAffectingSourceSignature(rawSource, "html"))}:${templateRuntimeSignature}`;
3142
+ const cacheKey = `${file}:html:${htmlProcessHash}`;
3143
+ const hashKey = cacheKey;
3144
+ rememberProcessCacheKey(cacheKey, hashKey);
3145
+ tasks.push(timeTask("html", () => processCachedTask({
3146
+ cache,
3147
+ cacheKey,
3148
+ hashKey,
3149
+ hash: htmlProcessHash,
3150
+ applyResult(source) {
3151
+ originalSource.source = source;
3152
+ },
3153
+ onCacheHit() {
3154
+ metrics.html.cacheHits++;
3155
+ debug("html cache hit: %s", file);
3156
+ },
3157
+ async transform() {
3158
+ const start = performance.now();
3159
+ let transformed = await templateHandler(rawSource, { runtimeSet: templateRuntime });
3160
+ let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
3161
+ let retryRuntimeSet;
3162
+ if (unresolvedDynamicCandidates.length > 0) {
3163
+ const fullRuntimeSet = await context.ensureRuntimeClassSet(true);
3164
+ const allowedRetryCandidates = fullRuntimeSet.size === 0 ? unresolvedDynamicCandidates : unresolvedDynamicCandidates.filter((candidate) => dynamicRetryCandidates.has(candidate) || fullRuntimeSet.has(candidate));
3165
+ retryRuntimeSet = /* @__PURE__ */ new Set([...fullRuntimeSet, ...allowedRetryCandidates]);
3166
+ unresolvedDynamicCandidates = unresolvedDynamicCandidates.filter((candidate) => retryRuntimeSet?.has(candidate) === true);
3167
+ }
3168
+ if (retryRuntimeSet && unresolvedDynamicCandidates.length > 0) {
3169
+ logger.warn("检测到已提取 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
3170
+ transformed = await templateHandler(rawSource, { runtimeSet: retryRuntimeSet });
3171
+ unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed, retryRuntimeSet);
3172
+ if (unresolvedDynamicCandidates.length > 0) logger.warn("已提取 WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
3173
+ }
3174
+ metrics.html.elapsed += measureElapsed(start);
3175
+ metrics.html.transformed++;
3176
+ onUpdate(file, rawSource, transformed);
3177
+ debug("html handle: %s", file);
3178
+ return { result: transformed };
3179
+ }
3180
+ })));
3181
+ }
3182
+ //#endregion
3183
+ //#region src/bundlers/vite/generate-bundle/js-entries.ts
3184
+ function createJsEntryResolver(jsEntries) {
3185
+ const normalizedJsEntries = /* @__PURE__ */ new Map();
3186
+ for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
3187
+ return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
3188
+ }
3189
+ //#endregion
3190
+ //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
3191
+ function resolveUniAppXJsTransformEnabled$1(uniAppX) {
3192
+ return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
3193
+ }
3194
+ function createJsHandlerOptionsFactory(options) {
3195
+ return (absoluteFilename, extra) => ({
3196
+ ...extra,
3197
+ generateMap: false,
3198
+ filename: absoluteFilename,
3199
+ tailwindcssMajorVersion: options.getMajorVersion(),
3200
+ moduleGraph: options.moduleGraph,
3201
+ babelParserOptions: {
3202
+ ...extra?.babelParserOptions ?? {},
3203
+ sourceFilename: absoluteFilename
3204
+ }
3205
+ });
3206
+ }
3207
+ //#endregion
3208
+ //#region src/bundlers/vite/generate-bundle/js-linking.ts
3209
+ function createLinkedUpdateHelpers(options) {
3210
+ const pendingLinkedUpdates = [];
3211
+ const handleLinkedUpdate = (fileName, previous, next) => {
3212
+ options.onUpdate(fileName, previous, next);
3213
+ options.debug("js linked handle: %s", fileName);
3214
+ };
3215
+ const scheduleLinkedApply = (entry, code) => {
3216
+ pendingLinkedUpdates.push(() => {
3217
+ if (entry.output.type === "chunk") entry.output.code = code;
3218
+ else entry.output.source = code;
3219
+ });
3220
+ };
3221
+ const applyLinkedUpdates = (linked) => {
3222
+ applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
3223
+ };
3224
+ return {
3225
+ applyLinkedUpdates,
3226
+ pendingLinkedUpdates
3227
+ };
3228
+ }
3229
+ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
3230
+ if (!linked || !linkedSet) return;
3231
+ for (const id of Object.keys(linked)) {
3232
+ const linkedEntry = getJsEntry(id);
3233
+ if (linkedEntry) linkedSet.add(linkedEntry.fileName);
3234
+ }
3235
+ }
3236
+ //#endregion
3237
+ //#region src/bundlers/vite/query.ts
3238
+ function parseVueRequest(id) {
3239
+ const [filename = id, rawQuery] = id.split(`?`, 2);
3240
+ const searchParams = new URLSearchParams(rawQuery);
3241
+ const query = Object.fromEntries(searchParams);
3242
+ if (query.vue != null) query.vue = true;
3243
+ if (query.index != null) query.index = Number(query.index);
3244
+ if (query.raw != null) query.raw = true;
3245
+ if (query.url != null) query.url = true;
3246
+ if (query.scoped != null) query.scoped = true;
3247
+ const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
3248
+ const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
3249
+ if (langType) query.lang = langType;
3250
+ return {
3251
+ filename,
3252
+ query
3253
+ };
3254
+ }
3255
+ //#endregion
3256
+ //#region src/uni-app-x/harmony.ts
3257
+ function isUniAppXHarmonyOutDir(outDir) {
3258
+ return typeof outDir === "string" && /(?:^|[/\\])\.?app-harmony(?:[/\\]|$)/.test(outDir);
3259
+ }
3260
+ //#endregion
3261
+ //#region src/uni-app-x/style-isolation.ts
3262
+ const manifestCache = /* @__PURE__ */ new Map();
3263
+ function resolveUniAppXStyleIsolationEnabled(root) {
3264
+ if (!root) return false;
3265
+ const normalizedRoot = path.resolve(root);
3266
+ const cached = manifestCache.get(normalizedRoot);
3267
+ if (cached !== void 0) return cached;
3268
+ const manifestPath = path.join(normalizedRoot, "manifest.json");
3269
+ let enabled = false;
3270
+ try {
3271
+ enabled = `${parse(fs.readFileSync(manifestPath, "utf8"))["uni-app-x"]?.styleIsolationVersion ?? ""}` === "2";
3272
+ } catch {
3273
+ enabled = false;
3274
+ }
3275
+ manifestCache.set(normalizedRoot, enabled);
3276
+ return enabled;
3277
+ }
3278
+ //#endregion
3279
+ //#region src/uni-app-x/vite.ts
3280
+ let transformUVuePromise;
3281
+ function loadTransformUVue() {
3282
+ transformUVuePromise ?? (transformUVuePromise = import("./transform-wNEbcZeQ.mjs").then((mod) => mod.transformUVue));
3283
+ return transformUVuePromise;
3284
+ }
3285
+ const preprocessorLangs = /* @__PURE__ */ new Set([
3286
+ "scss",
3287
+ "sass",
3288
+ "less",
3289
+ "styl",
3290
+ "stylus"
3291
+ ]);
3292
+ const INLINE_LANG_RE = /lang\.([a-z]+)/i;
3293
+ const PREPROCESSOR_EXT_RE = /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i;
3294
+ const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
3295
+ const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
3296
+ const CSS_MODULE_EXPORT_RE = /^\s*export\s+default\s+(?:\{|\w|\[\])/;
3297
+ function isPreprocessorRequest(id, lang) {
3298
+ const normalizedLang = lang?.toLowerCase();
3299
+ if (normalizedLang && preprocessorLangs.has(normalizedLang)) return true;
3300
+ const inlineLang = id.match(INLINE_LANG_RE)?.[1];
3301
+ if (inlineLang && preprocessorLangs.has(inlineLang.toLowerCase())) return true;
3302
+ return PREPROCESSOR_EXT_RE.test(id);
3303
+ }
3304
+ function resolveUniAppXCssTarget(id) {
3305
+ return UVUE_NVUE_RE.test(cleanUrl(id)) ? "uvue" : void 0;
3210
3306
  }
3211
- function isArbitraryValueCandidate(candidate) {
3212
- return candidate.includes("[") && candidate.includes("]") && !isUrlLikeCandidate(candidate.trim());
3307
+ function resolveUniAppXJsTransformEnabled(uniAppX) {
3308
+ return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
3213
3309
  }
3214
- function collectClassAttributeValues(source) {
3215
- const values = [];
3216
- CLASS_ATTRIBUTE_RE.lastIndex = 0;
3217
- let matched = CLASS_ATTRIBUTE_RE.exec(source);
3218
- while (matched !== null) {
3219
- const quoteIndex = CLASS_ATTRIBUTE_RE.lastIndex;
3220
- const quote = source[quoteIndex];
3221
- if (quote !== "\"" && quote !== "'") {
3222
- matched = CLASS_ATTRIBUTE_RE.exec(source);
3223
- continue;
3310
+ function isCssModuleExport(code) {
3311
+ return CSS_MODULE_EXPORT_RE.test(code);
3312
+ }
3313
+ function createUniAppXPlugins(options) {
3314
+ const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, runtimeState, styleHandler, generateCss, jsHandler, ensureRuntimeClassSet, getResolvedConfig, isEnabled = () => true, uniAppX } = options;
3315
+ const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
3316
+ const utsPlatform = resolveUniUtsPlatform();
3317
+ const isIosPlatform = providedIosPlatform ?? utsPlatform.isAppIos;
3318
+ const isHarmonyPlatform = utsPlatform.isAppHarmony;
3319
+ const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
3320
+ let componentLocalStyleEnabled;
3321
+ const harmonyApplyStyleSources = /* @__PURE__ */ new Set();
3322
+ const harmonyApplyUtilities = /* @__PURE__ */ new Set();
3323
+ function rememberHarmonyApplySource(code) {
3324
+ const styleSources = collectUniAppXHarmonyApplyStyleSourcesFromSource(code);
3325
+ if (styleSources.length === 0) return;
3326
+ for (const styleSource of styleSources) {
3327
+ harmonyApplyStyleSources.add(styleSource);
3328
+ for (const utility of collectUniAppXHarmonyApplyUtilitiesFromSources([styleSource])) harmonyApplyUtilities.add(utility);
3224
3329
  }
3225
- let expressionDepth = 0;
3226
- for (let index = quoteIndex + 1; index < source.length; index++) {
3227
- if (source.startsWith(MUSTACHE_OPEN, index)) {
3228
- expressionDepth++;
3229
- index += 1;
3230
- continue;
3231
- }
3232
- if (expressionDepth > 0 && source.startsWith(MUSTACHE_CLOSE, index)) {
3233
- expressionDepth--;
3234
- index += 1;
3235
- continue;
3236
- }
3237
- if (expressionDepth === 0 && source[index] === quote) {
3238
- values.push(source.slice(quoteIndex + 1, index));
3239
- CLASS_ATTRIBUTE_RE.lastIndex = index + 1;
3240
- break;
3241
- }
3330
+ }
3331
+ function shouldEnableComponentLocalStyle() {
3332
+ if (!resolvedUniAppXOptions.componentLocalStyles.enabled) {
3333
+ componentLocalStyleEnabled = false;
3334
+ return false;
3242
3335
  }
3243
- matched = CLASS_ATTRIBUTE_RE.exec(source);
3336
+ if (!resolvedUniAppXOptions.componentLocalStyles.onlyWhenStyleIsolationVersion2) {
3337
+ componentLocalStyleEnabled = true;
3338
+ return true;
3339
+ }
3340
+ if (componentLocalStyleEnabled !== void 0) return componentLocalStyleEnabled;
3341
+ const root = getResolvedConfig()?.root;
3342
+ componentLocalStyleEnabled = resolveUniAppXStyleIsolationEnabled(root);
3343
+ return componentLocalStyleEnabled;
3244
3344
  }
3245
- return values;
3246
- }
3247
- function collectUnescapedDynamicCandidates(source, allowedCandidates) {
3248
- const matches = /* @__PURE__ */ new Set();
3249
- const shouldFilterByAllowedCandidates = allowedCandidates !== void 0 && allowedCandidates.size > 0;
3250
- for (const classValue of collectClassAttributeValues(source)) for (const expression of classValue.match(MUSTACHE_EXPRESSION_RE) ?? []) {
3251
- QUOTED_LITERAL_RE.lastIndex = 0;
3252
- let quoted = QUOTED_LITERAL_RE.exec(expression);
3253
- while (quoted !== null) {
3254
- const literal = quoted[1] ?? quoted[2] ?? quoted[3] ?? "";
3255
- for (const candidate of splitCandidateTokens(literal)) {
3256
- const normalized = candidate.trim();
3257
- if (!normalized || !isArbitraryValueCandidate(normalized)) continue;
3258
- if (shouldFilterByAllowedCandidates && !allowedCandidates.has(normalized)) continue;
3259
- matches.add(normalized);
3345
+ function shouldEnableHarmonyPageLocalStyle() {
3346
+ return isHarmonyPlatform && resolvedUniAppXOptions.componentLocalStyles.enabled;
3347
+ }
3348
+ function isHarmonyBuildTarget() {
3349
+ if (resolveUniUtsPlatform().isAppHarmony) return true;
3350
+ return isUniAppXHarmonyOutDir(getResolvedConfig()?.build?.outDir);
3351
+ }
3352
+ async function transformStyle(code, id, query, hookContext) {
3353
+ const parsed = query ?? parseVueRequest(id).query;
3354
+ if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
3355
+ if (isCssModuleExport(code)) return;
3356
+ const shouldGenerateCss = hasTailwindSourceDirectives(code, { importFallback: true }) || hasTailwindApplyDirective(code);
3357
+ rememberHarmonyApplySource(code);
3358
+ const generatedCss = shouldGenerateCss ? await generateCss?.(id, code, hookContext) : void 0;
3359
+ const styleCode = typeof generatedCss === "string" && generatedCss.trim().length > 0 ? generatedCss : code;
3360
+ const cacheKey = `${mainCssChunkMatcher(id, appType) ? "1" : "0"}:${id}`;
3361
+ let styleHandlerOptions = cssHandlerOptionsCache.get(cacheKey);
3362
+ if (!styleHandlerOptions) {
3363
+ styleHandlerOptions = omitUndefined({
3364
+ isMainChunk: mainCssChunkMatcher(id, appType),
3365
+ uniAppXCssTarget: resolveUniAppXCssTarget(id),
3366
+ uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
3367
+ postcssOptions: { options: {
3368
+ from: id,
3369
+ map: {
3370
+ inline: false,
3371
+ annotation: false,
3372
+ sourcesContent: true
3373
+ }
3374
+ } }
3375
+ });
3376
+ cssHandlerOptionsCache.set(cacheKey, styleHandlerOptions);
3260
3377
  }
3261
- quoted = QUOTED_LITERAL_RE.exec(expression);
3378
+ const postcssResult = await styleHandler(styleCode, styleHandlerOptions);
3379
+ const warnings = typeof postcssResult.warnings === "function" ? postcssResult.warnings() : [];
3380
+ for (const warning of warnings) logger$1.warn(warning.toString());
3381
+ const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), normalizePath(cleanUrl(id)));
3382
+ return {
3383
+ code: postcssResult.css,
3384
+ map: postcssMap
3385
+ };
3262
3386
  }
3263
3387
  }
3264
- return [...matches];
3265
- }
3266
- //#endregion
3267
- //#region src/bundlers/vite/generate-bundle/html-processing.ts
3268
- function processHtmlBundleEntry(options) {
3269
- const { cache, context, debug, dynamicRetryCandidates, file, metrics, onUpdate, originalEntrySource, originalSource, rememberProcessCacheKey, resolveCurrentSourceCandidateSource, tasks, templateHandler, timeTask, transformRuntime, transformRuntimeSignature } = options;
3270
- const rawSource = resolveCurrentSourceCandidateSource(file) ?? originalEntrySource;
3271
- const currentRawDynamicCandidates = collectUnescapedDynamicCandidates(rawSource);
3272
- const templateRuntime = currentRawDynamicCandidates.length > 0 ? /* @__PURE__ */ new Set([...transformRuntime, ...currentRawDynamicCandidates]) : transformRuntime;
3273
- const templateRuntimeSignature = templateRuntime === transformRuntime ? transformRuntimeSignature : createCandidateSignature(templateRuntime);
3274
- const htmlProcessHash = `${cache.computeHash(rawSource)}:${cache.computeHash(createRuntimeAffectingSourceSignature(rawSource, "html"))}:${templateRuntimeSignature}`;
3275
- const cacheKey = `${file}:html:${htmlProcessHash}`;
3276
- const hashKey = cacheKey;
3277
- rememberProcessCacheKey(cacheKey, hashKey);
3278
- tasks.push(timeTask("html", () => processCachedTask({
3279
- cache,
3280
- cacheKey,
3281
- hashKey,
3282
- hash: htmlProcessHash,
3283
- applyResult(source) {
3284
- originalSource.source = source;
3388
+ const cssPlugins = [{
3389
+ name: "weapp-tailwindcss:uni-app-x:css",
3390
+ async transform(code, id) {
3391
+ if (!isEnabled()) return;
3392
+ await runtimeState.readyPromise;
3393
+ return transformStyle(code, id, void 0, this);
3394
+ }
3395
+ }, {
3396
+ name: "weapp-tailwindcss:uni-app-x:css:pre",
3397
+ enforce: "pre",
3398
+ async transform(code, id) {
3399
+ if (!isEnabled()) return;
3400
+ await runtimeState.readyPromise;
3401
+ const { query } = parseVueRequest(id);
3402
+ const lang = query.lang;
3403
+ if (isIosPlatform && isPreprocessorRequest(id, lang)) return;
3404
+ return transformStyle(code, id, query, this);
3405
+ }
3406
+ }];
3407
+ const nvuePlugin = {
3408
+ name: "weapp-tailwindcss:uni-app-x:nvue",
3409
+ enforce: "pre",
3410
+ async buildStart() {
3411
+ if (!isEnabled()) return;
3412
+ await ensureRuntimeClassSet(true);
3285
3413
  },
3286
- onCacheHit() {
3287
- metrics.html.cacheHits++;
3288
- debug("html cache hit: %s", file);
3414
+ async transform(code, id) {
3415
+ if (!isEnabled()) return;
3416
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
3417
+ rememberHarmonyApplySource(code);
3418
+ const resolvedConfig = getResolvedConfig();
3419
+ const isServeCommand = resolvedConfig?.command === "serve";
3420
+ const isWatchBuild = resolvedConfig?.command === "build" && !!resolvedConfig.build?.watch;
3421
+ const isNonWatchBuild = resolvedConfig?.command === "build" && !resolvedConfig.build?.watch;
3422
+ const currentRuntimeSet = isServeCommand || isWatchBuild || isNonWatchBuild ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
3423
+ const transformUVue = await loadTransformUVue();
3424
+ const enableComponentLocalStyle = shouldEnableComponentLocalStyle();
3425
+ const enablePageLocalStyle = shouldEnableHarmonyPageLocalStyle();
3426
+ if (customAttributesEntities.length > 0 || disabledDefaultTemplateHandler || enableComponentLocalStyle || enablePageLocalStyle) return transformUVue(code, id, jsHandler, currentRuntimeSet, omitUndefined({
3427
+ ...customAttributesEntities.length > 0 ? { customAttributesEntities } : {},
3428
+ ...disabledDefaultTemplateHandler ? { disabledDefaultTemplateHandler } : {},
3429
+ ...enableComponentLocalStyle ? { enableComponentLocalStyle } : {},
3430
+ ...enablePageLocalStyle ? { enablePageLocalStyle } : {}
3431
+ }));
3432
+ return transformUVue(code, id, jsHandler, currentRuntimeSet);
3289
3433
  },
3290
- async transform() {
3291
- const start = performance.now();
3292
- let transformed = await templateHandler(rawSource, { runtimeSet: templateRuntime });
3293
- let unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed);
3294
- let retryRuntimeSet;
3295
- if (unresolvedDynamicCandidates.length > 0) {
3296
- const fullRuntimeSet = await context.ensureRuntimeClassSet(true);
3297
- const allowedRetryCandidates = fullRuntimeSet.size === 0 ? unresolvedDynamicCandidates : unresolvedDynamicCandidates.filter((candidate) => dynamicRetryCandidates.has(candidate) || fullRuntimeSet.has(candidate));
3298
- retryRuntimeSet = /* @__PURE__ */ new Set([...fullRuntimeSet, ...allowedRetryCandidates]);
3299
- unresolvedDynamicCandidates = unresolvedDynamicCandidates.filter((candidate) => retryRuntimeSet?.has(candidate) === true);
3300
- }
3301
- if (retryRuntimeSet && unresolvedDynamicCandidates.length > 0) {
3302
- logger.warn("检测到已提取 WXML 动态类名未完成转译,已回退到完整 runtimeSet 重试: %s -> %O", file, unresolvedDynamicCandidates);
3303
- transformed = await templateHandler(rawSource, { runtimeSet: retryRuntimeSet });
3304
- unresolvedDynamicCandidates = collectUnescapedDynamicCandidates(transformed, retryRuntimeSet);
3305
- if (unresolvedDynamicCandidates.length > 0) logger.warn("已提取 WXML 动态类名在完整 runtimeSet 重试后仍未完成转译: %s -> %O", file, unresolvedDynamicCandidates);
3434
+ async handleHotUpdate(ctx) {
3435
+ if (!isEnabled()) return;
3436
+ if (getResolvedConfig()?.command !== "serve") return;
3437
+ if (!UVUE_NVUE_RE.test(ctx.file)) return;
3438
+ await ensureRuntimeClassSet(true);
3439
+ },
3440
+ async watchChange(id) {
3441
+ if (!isEnabled()) return;
3442
+ const resolvedConfig = getResolvedConfig();
3443
+ if (resolvedConfig?.command !== "build" || !resolvedConfig.build?.watch) return;
3444
+ if (!UVUE_NVUE_QUERY_RE.test(id)) return;
3445
+ await ensureRuntimeClassSet(true);
3446
+ }
3447
+ };
3448
+ const stylePlaceholderPlugin = {
3449
+ name: "weapp-tailwindcss:uni-app-x:style-placeholder",
3450
+ enforce: "post",
3451
+ generateBundle: {
3452
+ order: "post",
3453
+ async handler(_options, bundle) {
3454
+ if (!isEnabled()) return;
3455
+ const currentUtsPlatform = resolveUniUtsPlatform();
3456
+ const canInferHarmonyTarget = !currentUtsPlatform.normalized || currentUtsPlatform.isApp;
3457
+ const isHarmonyTarget = currentUtsPlatform.isAppHarmony || canInferHarmonyTarget && isHarmonyBuildTarget();
3458
+ if (!currentUtsPlatform.isApp && !isHarmonyTarget) return;
3459
+ const getAssetSource = createUniAppXBundleAssetSourceGetter(bundle);
3460
+ if (isHarmonyTarget) {
3461
+ const cssSources = [];
3462
+ const applyStyleSources = [...harmonyApplyStyleSources, ...collectUniAppXHarmonyApplyStyleSources(bundle)];
3463
+ const applyUtilities = /* @__PURE__ */ new Set([...harmonyApplyUtilities, ...collectUniAppXHarmonyApplyUtilities(bundle)]);
3464
+ if (applyStyleSources.length > 0 && applyUtilities.size > 0) {
3465
+ const harmonyApplyCssFile = path.resolve(getResolvedConfig()?.root ?? process$1.cwd(), "uni-app-x-harmony-apply.css");
3466
+ const generatedCss = await generateCss?.(harmonyApplyCssFile, createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities), this);
3467
+ if (typeof generatedCss === "string" && generatedCss.trim().length > 0) cssSources.push(generatedCss);
3468
+ }
3469
+ injectUniAppXHarmonyBundleStyles(bundle, {
3470
+ cssSources,
3471
+ excludeComponents: shouldEnableComponentLocalStyle()
3472
+ });
3473
+ }
3474
+ for (const [file, item] of Object.entries(bundle)) {
3475
+ if (item.type !== "asset" || !file.endsWith(".uvue.ts")) continue;
3476
+ const currentSource = String(item.source);
3477
+ const nextSource = injectUniAppXStylePlaceholder(file, currentSource, getAssetSource);
3478
+ if (nextSource !== currentSource) item.source = nextSource;
3479
+ }
3306
3480
  }
3307
- metrics.html.elapsed += measureElapsed(start);
3308
- metrics.html.transformed++;
3309
- onUpdate(file, rawSource, transformed);
3310
- debug("html handle: %s", file);
3311
- return { result: transformed };
3312
- }
3313
- })));
3314
- }
3315
- //#endregion
3316
- //#region src/bundlers/vite/generate-bundle/js-entries.ts
3317
- function createJsEntryResolver(jsEntries) {
3318
- const normalizedJsEntries = /* @__PURE__ */ new Map();
3319
- for (const [id, entry] of jsEntries) normalizedJsEntries.set(normalizeOutputPathKey(id), entry);
3320
- return (id) => jsEntries.get(id) ?? normalizedJsEntries.get(normalizeOutputPathKey(id));
3321
- }
3322
- //#endregion
3323
- //#region src/bundlers/vite/generate-bundle/js-handler-options.ts
3324
- function resolveUniAppXJsTransformEnabled(uniAppX) {
3325
- return uniAppX === void 0 ? true : isUniAppXEnabled(uniAppX);
3326
- }
3327
- function createJsHandlerOptionsFactory(options) {
3328
- return (absoluteFilename, extra) => ({
3329
- ...extra,
3330
- generateMap: false,
3331
- filename: absoluteFilename,
3332
- tailwindcssMajorVersion: options.getMajorVersion(),
3333
- moduleGraph: options.moduleGraph,
3334
- babelParserOptions: {
3335
- ...extra?.babelParserOptions ?? {},
3336
- sourceFilename: absoluteFilename
3337
3481
  }
3338
- });
3339
- }
3340
- //#endregion
3341
- //#region src/bundlers/vite/generate-bundle/js-linking.ts
3342
- function createLinkedUpdateHelpers(options) {
3343
- const pendingLinkedUpdates = [];
3344
- const handleLinkedUpdate = (fileName, previous, next) => {
3345
- options.onUpdate(fileName, previous, next);
3346
- options.debug("js linked handle: %s", fileName);
3347
3482
  };
3348
- const scheduleLinkedApply = (entry, code) => {
3349
- pendingLinkedUpdates.push(() => {
3350
- if (entry.output.type === "chunk") entry.output.code = code;
3351
- else entry.output.source = code;
3483
+ return [
3484
+ ...cssPlugins,
3485
+ nvuePlugin,
3486
+ stylePlaceholderPlugin
3487
+ ];
3488
+ }
3489
+ function createUniAppXAssetTask(file, originalSource, outDir, options) {
3490
+ return async () => {
3491
+ const { cache, hashKey, createHandlerOptions, debug, getAssetSource, jsHandler, onUpdate, runtimeSet, applyLinkedResults } = options;
3492
+ const absoluteFile = toAbsoluteOutputPath(file, outDir);
3493
+ const rawSource = originalSource.source.toString();
3494
+ await processCachedTask({
3495
+ cache,
3496
+ cacheKey: file,
3497
+ hashKey,
3498
+ rawSource: options.hashSalt ? `${rawSource}\n/*${options.hashSalt}*/` : rawSource,
3499
+ applyResult(source) {
3500
+ originalSource.source = source;
3501
+ },
3502
+ onCacheHit() {
3503
+ debug("js cache hit: %s", file);
3504
+ },
3505
+ async transform() {
3506
+ const currentSource = originalSource.source.toString();
3507
+ const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
3508
+ uniAppX: resolveUniAppXJsTransformEnabled(options.uniAppX),
3509
+ babelParserOptions: {
3510
+ plugins: ["typescript"],
3511
+ sourceType: "unambiguous"
3512
+ }
3513
+ }));
3514
+ const nextCode = injectUniAppXStylePlaceholder(file, code, getAssetSource);
3515
+ onUpdate(file, currentSource, nextCode);
3516
+ debug("js handle: %s", file);
3517
+ applyLinkedResults(linked);
3518
+ return { result: nextCode };
3519
+ }
3352
3520
  });
3353
3521
  };
3354
- const applyLinkedUpdates = (linked) => {
3355
- applyLinkedResults(linked, options.jsEntries, handleLinkedUpdate, scheduleLinkedApply);
3356
- };
3357
- return {
3358
- applyLinkedUpdates,
3359
- pendingLinkedUpdates
3360
- };
3361
- }
3362
- function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
3363
- if (!linked || !linkedSet) return;
3364
- for (const id of Object.keys(linked)) {
3365
- const linkedEntry = getJsEntry(id);
3366
- if (linkedEntry) linkedSet.add(linkedEntry.fileName);
3367
- }
3368
3522
  }
3369
3523
  //#endregion
3370
3524
  //#region src/bundlers/vite/generate-bundle/js-processing.ts
@@ -3472,7 +3626,7 @@ function processJsBundleEntry(options) {
3472
3626
  }
3473
3627
  const currentSource = originalEntrySource;
3474
3628
  const precheckOptions = createHandlerOptions(path.resolve(outDir, file), {
3475
- uniAppX: resolveUniAppXJsTransformEnabled(uniAppX),
3629
+ uniAppX: resolveUniAppXJsTransformEnabled$1(uniAppX),
3476
3630
  babelParserOptions: {
3477
3631
  plugins: ["typescript"],
3478
3632
  sourceType: "unambiguous"
@@ -4140,27 +4294,6 @@ function createTransformFilterSignature(options) {
4140
4294
  return [`include:${createRuleSignature(options?.include)}`, `exclude:${createRuleSignature(options?.exclude)}`].join(";");
4141
4295
  }
4142
4296
  //#endregion
4143
- //#region src/bundlers/vite/uni-app-x-css-options.ts
4144
- function resolveUniAppXNativeCssHandlerOptions(opts) {
4145
- const uniUtsPlatform = resolveUniUtsPlatform();
4146
- if (!shouldUseNativeAppCssBranch(resolveGeneratorRuntimeBranch(normalizeWeappTailwindcssGeneratorOptions(opts.generator, {
4147
- appType: opts.appType,
4148
- platform: opts.cssOptions?.platform ?? opts.platform,
4149
- uniAppX: resolveUniAppXOptions(opts.uniAppX),
4150
- uniUtsPlatform
4151
- }), {
4152
- appType: opts.appType,
4153
- platform: opts.cssOptions?.platform ?? opts.platform,
4154
- uniAppX: resolveUniAppXOptions(opts.uniAppX),
4155
- uniUtsPlatform
4156
- })) || !isUniAppXEnabled(opts.uniAppX)) return {};
4157
- return {
4158
- uniAppX: true,
4159
- uniAppXCssTarget: "uvue",
4160
- uniAppXUnsupported: resolveUniAppXOptions(opts.uniAppX).uvueUnsupported
4161
- };
4162
- }
4163
- //#endregion
4164
4297
  //#region src/bundlers/vite/weapp-vite-config.ts
4165
4298
  function resolveSourceRootCandidate(root, value) {
4166
4299
  if (typeof value !== "string" || value.trim().length === 0) return;
@@ -4222,16 +4355,35 @@ function inferPlatformFromViteOutDir$1(outDir) {
4222
4355
  const normalized = segment.trim().toLowerCase();
4223
4356
  if (normalized === "h5" || normalized === "web" || normalized === "app" || normalized === "app-plus" || normalized.startsWith("app-") || normalized.startsWith("mp-") || normalized.startsWith("quickapp-webview")) return normalized;
4224
4357
  }
4225
- function isUniAppViteWebviewOutDir$1(outDir) {
4226
- const normalized = outDir ? path.basename(path.normalize(outDir)).trim().toLowerCase() : void 0;
4227
- return normalized === "app" || normalized === "app-plus";
4228
- }
4229
4358
  function createGenerateBundleHook(context) {
4230
4359
  const state = createBundleBuildState();
4231
4360
  const lastCssResultByFile = /* @__PURE__ */ new Map();
4232
4361
  const lastCssSourceHashByFile = /* @__PURE__ */ new Map();
4233
4362
  let currentOutDir;
4234
4363
  let currentSubpackageRoots;
4364
+ const createInitialCssPipelineContext = (file) => {
4365
+ const resolvedConfig = context.getResolvedConfig();
4366
+ const platform = context.opts.cssOptions?.platform ?? context.opts.platform ?? inferPlatformFromViteOutDir$1(resolvedConfig?.build?.outDir);
4367
+ const currentGeneratorOptions = normalizeWeappTailwindcssGeneratorOptions(context.opts.generator, {
4368
+ appType: context.opts.appType,
4369
+ platform,
4370
+ tailwindcssMajorVersion: context.runtimeState.tailwindRuntime.majorVersion,
4371
+ uniAppX: context.opts.uniAppX
4372
+ });
4373
+ return {
4374
+ currentGeneratorBranch: resolveGeneratorRuntimeBranch(currentGeneratorOptions, {
4375
+ appType: context.opts.appType,
4376
+ platform,
4377
+ tailwindcssMajorVersion: context.runtimeState.tailwindRuntime.majorVersion,
4378
+ uniAppX: context.opts.uniAppX
4379
+ }),
4380
+ currentGeneratorOptions,
4381
+ file,
4382
+ opts: context.opts,
4383
+ resolvedConfig,
4384
+ resolveStylePlatform: () => platform
4385
+ };
4386
+ };
4235
4387
  const cssHandlerOptions = createCssHandlerOptionsCache({
4236
4388
  getAppType: () => context.opts.appType,
4237
4389
  mainCssChunkMatcher: context.opts.mainCssChunkMatcher,
@@ -4239,7 +4391,7 @@ function createGenerateBundleHook(context) {
4239
4391
  getOutputRoot: () => currentOutDir,
4240
4392
  getExtraOptions: (file) => ({
4241
4393
  ...resolveViteCssHandlerExtraOptions(file),
4242
- ...resolveUniAppXNativeCssHandlerOptions(context.opts),
4394
+ ...context.cssPipelineStrategy?.getCssHandlerExtraOptions?.(createInitialCssPipelineContext(file)) ?? {},
4243
4395
  ...currentSubpackageRoots && isSubpackageOutputFile(file, currentSubpackageRoots) ? { isMainChunk: false } : {}
4244
4396
  })
4245
4397
  });
@@ -4270,18 +4422,27 @@ function createGenerateBundleHook(context) {
4270
4422
  uniAppX,
4271
4423
  uniUtsPlatform
4272
4424
  });
4425
+ const cssPipelineContext = {
4426
+ bundle,
4427
+ currentGeneratorBranch: generatorBranch,
4428
+ currentGeneratorOptions: generatorOptions,
4429
+ opts,
4430
+ resolvedConfig,
4431
+ resolveStylePlatform: () => generatorPlatform
4432
+ };
4273
4433
  const isWebGeneratorTarget = generatorBranch.isWeb;
4274
- const shouldApplyWebviewSafeSelectors = opts.appType === "uni-app-vite" && isUniAppViteWebviewOutDir$1(resolvedConfig?.build?.outDir);
4275
- const shouldApplyWebviewCssCompat = isWebGeneratorTarget || shouldApplyWebviewSafeSelectors;
4434
+ const shouldApplyWebCssCompat = context.cssPipelineStrategy?.shouldApplyWebCssCompat?.(cssPipelineContext) === true;
4276
4435
  const transformWebTargetCss = (css) => {
4277
- const compatCss = isWebGeneratorTarget ? transformWebCssCompat(css, generatorOptions.webCompat) : shouldApplyWebviewCssCompat ? transformWebCssCompat(css, generatorOptions.webCompat ?? true) : css;
4278
- return shouldApplyWebviewSafeSelectors ? transformWebCssSafeSelectors(compatCss, { escapeMap: opts.escapeMap }) : compatCss;
4436
+ return context.cssPipelineStrategy?.transformGeneratedCss?.(css, {
4437
+ ...cssPipelineContext,
4438
+ defaultWebCssCompat: (value) => transformWebCssCompat(value, isWebGeneratorTarget ? generatorOptions.webCompat : generatorOptions.webCompat ?? true),
4439
+ removeScopedPreflight: (value) => value,
4440
+ shouldApplyWebCssCompat
4441
+ }) ?? (shouldApplyWebCssCompat ? transformWebCssCompat(css, isWebGeneratorTarget ? generatorOptions.webCompat : generatorOptions.webCompat ?? true) : css);
4279
4442
  };
4280
- const isUniAppXStyleTarget = opts.appType === "uni-app-x";
4281
- const isNativeAppStyleTarget = isUniAppXStyleTarget && uniUtsPlatform.isApp;
4282
- const canInferHarmonyAppStyleTarget = isUniAppXStyleTarget && (!uniUtsPlatform.normalized || uniUtsPlatform.isApp);
4283
- const isHarmonyAppStyleTarget = isUniAppXStyleTarget && (uniUtsPlatform.isAppHarmony || canInferHarmonyAppStyleTarget && (isUniAppXHarmonyBundle(bundle) || isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir)));
4284
- const shouldPreserveAppCssExtension = isNativeAppStyleTarget || isHarmonyAppStyleTarget;
4443
+ const isNativeAppStyleTarget = context.cssPipelineStrategy?.isNativeAppStyleTarget?.(cssPipelineContext) === true;
4444
+ const isHarmonyAppStyleTarget = context.cssPipelineStrategy?.isHarmonyAppStyleTarget?.(cssPipelineContext) === true;
4445
+ const shouldPreserveAppCssExtension = context.cssPipelineStrategy?.shouldPreserveStyleOutputExtension?.(cssPipelineContext) ?? (isNativeAppStyleTarget || isHarmonyAppStyleTarget);
4285
4446
  const shouldGenerateWebCssByGenerator = isWebGeneratorTarget;
4286
4447
  const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
4287
4448
  const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process$1.cwd();
@@ -4296,6 +4457,8 @@ function createGenerateBundleHook(context) {
4296
4457
  if (subpackageRoots) currentSubpackageRoots = subpackageRoots;
4297
4458
  collectViteProcessedCssAssetResults(bundle, {
4298
4459
  opts,
4460
+ cssPipelineStrategy: context.cssPipelineStrategy,
4461
+ createCssPipelineContext: () => cssPipelineContext,
4299
4462
  isViteProcessedCssAsset,
4300
4463
  markCssAssetProcessed,
4301
4464
  recordCssAssetResult,
@@ -4360,20 +4523,32 @@ function createGenerateBundleHook(context) {
4360
4523
  ...Array.isArray(runtimeTailwindcssOptions?.v4?.cssEntries) ? runtimeTailwindcssOptions.v4.cssEntries : [],
4361
4524
  ...Array.isArray(tailwindRuntimeOptions?.v4?.cssEntries) ? tailwindRuntimeOptions.v4.cssEntries : []
4362
4525
  ].filter((file) => typeof file === "string" && file.length > 0).map(normalizeConfiguredTailwindV4CssEntryFileKey));
4363
- const resolveUniAppViteWebviewRootCssInjectionTarget = (sourceFile, outputFile) => {
4364
- if (opts.appType !== "uni-app-vite" || !outputFile.replace(/[?#].*$/, "").endsWith(".css") || typeof sourceFile !== "string" || !configuredTailwindV4ExplicitCssEntryFileKeysForScope.has(normalizeConfiguredTailwindV4CssEntryFileKey(sourceFile))) return;
4365
- const rootCssFiles = bundleFiles.filter((file) => {
4366
- const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
4367
- return opts.cssMatcher(file) && normalized.endsWith(".css") && !normalized.includes("/");
4526
+ const isRootStyleOutputFile = (file) => {
4527
+ const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
4528
+ return normalized.endsWith(".css") && !normalized.includes("/");
4529
+ };
4530
+ const isMiniProgramStyleOutputFile = (file) => /\.(?:wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i.test(file);
4531
+ const resolveConfiguredCssEntryRootInjectionTarget = (sourceFile, outputFile) => {
4532
+ if (!outputFile.replace(/[?#].*$/, "").endsWith(".css") || typeof sourceFile !== "string" || !configuredTailwindV4ExplicitCssEntryFileKeysForScope.has(normalizeConfiguredTailwindV4CssEntryFileKey(sourceFile))) return;
4533
+ return context.cssPipelineStrategy?.resolveConfiguredCssEntryRootInjectionTarget?.({
4534
+ ...cssPipelineContext,
4535
+ bundle,
4536
+ isConfiguredCssEntryFile: (file) => typeof file === "string" && configuredTailwindV4ExplicitCssEntryFileKeysForScope.has(normalizeConfiguredTailwindV4CssEntryFileKey(file)),
4537
+ isMiniProgramStyleOutputFile,
4538
+ isRootStyleOutputFile,
4539
+ outputFile,
4540
+ sourceFile
4368
4541
  });
4369
- const matchedRootCssFiles = rootCssFiles.filter((file) => getCssHandlerOptions(file).isMainChunk);
4370
- if (matchedRootCssFiles.length === 1) return matchedRootCssFiles[0];
4371
- if (matchedRootCssFiles.length > 1) return;
4372
- return rootCssFiles.length === 1 ? rootCssFiles[0] : void 0;
4373
4542
  };
4374
4543
  const resolveConfiguredTailwindV4CssEntryOutputFile = (sourceFile) => resolveViteCssPipelineOutputFile(sourceFile, opts, rootDir, isWebGeneratorTarget, shouldPreserveAppCssExtension, sourceRoot, defaultStyleOutputExtension, bundleFiles);
4375
- const selectUniAppViteWebviewRootCssSourceEntry = (outputFile, entries) => {
4376
- if (opts.appType !== "uni-app-vite" || !isWebGeneratorTarget || !opts.cssMatcher(outputFile) || normalizeOutputPathKey(outputFile.replace(/[?#].*$/, "")).includes("/")) return;
4544
+ const selectConfiguredRootCssSourceEntry = (outputFile, entries, originalFileNames) => {
4545
+ const matchedOriginalEntry = entries.find((entry) => originalFileNames?.some((originalFile) => normalizeConfiguredTailwindV4CssEntryFileKey(originalFile) === normalizeConfiguredTailwindV4CssEntryFileKey(entry.file)) === true);
4546
+ if (matchedOriginalEntry && outputFile.replace(/[?#].*$/, "").endsWith(".css")) return matchedOriginalEntry;
4547
+ if (!(context.cssPipelineStrategy?.shouldSelectConfiguredCssEntryRootSource?.({
4548
+ ...cssPipelineContext,
4549
+ isRootStyleOutputFile,
4550
+ outputFile
4551
+ }) === true || cssPipelineContext.currentGeneratorBranch.isWeb && opts.cssMatcher(outputFile) && isRootStyleOutputFile(outputFile))) return;
4377
4552
  const generationEntries = entries.filter((entry) => hasTailwindGenerationSource(entry.source));
4378
4553
  if (generationEntries.length <= 1) return generationEntries[0];
4379
4554
  const rootOutputEntries = generationEntries.filter((entry) => {
@@ -4546,10 +4721,18 @@ function createGenerateBundleHook(context) {
4546
4721
  getMajorVersion: () => runtimeState.tailwindRuntime.majorVersion,
4547
4722
  moduleGraph: moduleGraphOptions
4548
4723
  });
4549
- const createHandlerOptions = (absoluteFilename, extra) => createBaseHandlerOptions(absoluteFilename, shouldApplyWebviewSafeSelectors ? {
4550
- needEscaped: true,
4551
- ...extra
4552
- } : extra);
4724
+ const resolveFrameworkJsHandlerOptions = (absoluteFilename) => context.cssPipelineStrategy?.getServeJsHandlerOptions?.({
4725
+ ...cssPipelineContext,
4726
+ file: absoluteFilename
4727
+ });
4728
+ const createHandlerOptions = (absoluteFilename, extra) => {
4729
+ const frameworkExtra = resolveFrameworkJsHandlerOptions(absoluteFilename);
4730
+ return createBaseHandlerOptions(absoluteFilename, frameworkExtra || extra ? {
4731
+ ...frameworkExtra,
4732
+ ...extra
4733
+ } : void 0);
4734
+ };
4735
+ const shouldTransformJsBundle = !isWebGeneratorTarget || context.cssPipelineStrategy?.shouldTransformServeJs?.(cssPipelineContext) === true;
4553
4736
  const linkedByEntry = useIncrementalMode ? /* @__PURE__ */ new Map() : void 0;
4554
4737
  const sharedCssResultCache = /* @__PURE__ */ new Map();
4555
4738
  const activeProcessCacheKeys = /* @__PURE__ */ new Set();
@@ -4606,12 +4789,18 @@ function createGenerateBundleHook(context) {
4606
4789
  metrics.css.total++;
4607
4790
  const assetSourceFile = resolveAssetSourceFile(originalSource, file);
4608
4791
  const rawSource = normalizeRelativeCssConfigDirectives(originalEntrySource, assetSourceFile, outDir, opts);
4792
+ const cssPipelineContext = {
4793
+ ...createInitialCssPipelineContext(file),
4794
+ bundle
4795
+ };
4609
4796
  let outputFile = resolveCssBundleOutputFile({
4610
4797
  bundleFiles,
4798
+ cssPipelineStrategy: context.cssPipelineStrategy,
4611
4799
  defaultStyleOutputExtension,
4612
4800
  file,
4613
4801
  isWebGeneratorTarget,
4614
4802
  opts,
4803
+ pipelineContext: cssPipelineContext,
4615
4804
  shouldPreserveAppCssExtension
4616
4805
  });
4617
4806
  const resolveMatchedOutputFileForCurrentAsset = createMatchedCssSourceOutputResolver({
@@ -4620,6 +4809,13 @@ function createGenerateBundleHook(context) {
4620
4809
  originalFileNames: originalSource.originalFileNames,
4621
4810
  resolveOutputFileFromMatchedCssSource: resolveMatchedCssSourceOutputFile
4622
4811
  });
4812
+ const configuredOriginalSourceEntry = outputFile.replace(/[?#].*$/, "").endsWith(".css") ? getConfiguredTailwindV4CssSourceEntries().find((entry) => originalSource.originalFileNames?.some((originalFile) => normalizeConfiguredTailwindV4CssEntryFileKey(originalFile) === normalizeConfiguredTailwindV4CssEntryFileKey(entry.file)) === true) : void 0;
4813
+ const configuredOriginalOutputFile = configuredOriginalSourceEntry ? resolveMatchedOutputFileForCurrentAsset(configuredOriginalSourceEntry.file) : void 0;
4814
+ let resolvedFromConfiguredOriginalCssEntry = false;
4815
+ if (configuredOriginalOutputFile && normalizeOutputPathKey(configuredOriginalOutputFile) !== normalizeOutputPathKey(outputFile)) {
4816
+ outputFile = configuredOriginalOutputFile;
4817
+ resolvedFromConfiguredOriginalCssEntry = true;
4818
+ }
4623
4819
  activeViteCssCacheFiles.add(normalizeViteCssCacheKey(outputFile));
4624
4820
  if (shouldSkipRawSourceStyleAsset(outputFile, file, rawSource, assetSourceFile, opts.cssMatcher)) {
4625
4821
  delete bundle[file];
@@ -4631,13 +4827,14 @@ function createGenerateBundleHook(context) {
4631
4827
  let resolvedFromTemporaryCssAsset = false;
4632
4828
  const applyCssResult = (source) => {
4633
4829
  applyCssResultToBundle({
4634
- appType: opts.appType,
4635
4830
  assetSourceFile,
4636
4831
  bundle,
4832
+ cssPipelineStrategy: context.cssPipelineStrategy,
4637
4833
  emitOrReplayCssAsset,
4638
4834
  file,
4639
4835
  originalSource,
4640
4836
  outputFile,
4837
+ pipelineContext: cssPipelineContext,
4641
4838
  source,
4642
4839
  viteProcessedCssAsset
4643
4840
  });
@@ -4704,7 +4901,7 @@ function createGenerateBundleHook(context) {
4704
4901
  if (!hasUsableRememberedTailwindSource) {
4705
4902
  const configuredTailwindV4CssSourceEntries = getConfiguredTailwindV4CssSourceEntries();
4706
4903
  const inferredSourceStyle = resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outDir, sourceRoot, getCssSource, getSourceCandidateSources, configuredTailwindV4CssSourceEntries.map((entry) => [entry.file, entry.source]), debug);
4707
- const inferredWebviewRootSourceEntry = inferredSourceStyle ? void 0 : selectUniAppViteWebviewRootCssSourceEntry(outputFile, configuredTailwindV4CssSourceEntries);
4904
+ const inferredWebviewRootSourceEntry = inferredSourceStyle ? void 0 : selectConfiguredRootCssSourceEntry(outputFile, configuredTailwindV4CssSourceEntries, originalSource.originalFileNames);
4708
4905
  const inferredWebviewRootSourceStyle = inferredWebviewRootSourceEntry ? {
4709
4906
  outputFile,
4710
4907
  rawSource: inferredWebviewRootSourceEntry.source,
@@ -4792,7 +4989,7 @@ function createGenerateBundleHook(context) {
4792
4989
  const hasSameOutputRememberedTailwindGenerationSource = hasRememberedTailwindGenerationSource && rememberedCssSource != null && normalizeOutputPathKey(rememberedCssSource.outputFile) === normalizeOutputPathKey(outputFile);
4793
4990
  const hasStaleViteProcessedCssSource = vitePipelineCssAsset && hasDifferentRememberedCssSource && (hasCurrentTailwindGenerationDirective || hasRememberedApplyDirective || hasRememberedTailwindGenerationSource);
4794
4991
  const generatorSourceFile = vitePipelineCssAsset ? rememberedCssSource?.sourceFile ?? assetSourceFile : assetSourceFile;
4795
- const webviewRootCssInjectionTarget = vitePipelineCssAsset ? resolveUniAppViteWebviewRootCssInjectionTarget(generatorSourceFile, outputFile) : void 0;
4992
+ const webviewRootCssInjectionTarget = vitePipelineCssAsset ? resolveConfiguredCssEntryRootInjectionTarget(generatorSourceFile, outputFile) : void 0;
4796
4993
  const usesConfiguredTailwindV4FallbackSource = rememberedCssSource != null && normalizeOutputPathKey(rememberedCssSource.outputFile) === normalizeOutputPathKey(outputFile) && normalizeOutputPathKey(rememberedCssSource.sourceFile.replace(/[?#].*$/, "")) !== normalizeOutputPathKey(file);
4797
4994
  if (vitePipelineCssAsset && outputCssHandlerOptions.isMainChunk !== true && configuredTailwindV4CssSourceFileKeysForScope.has(normalizeConfiguredTailwindV4CssEntryFileKey(generatorSourceFile))) {
4798
4995
  usedConfiguredTailwindV4CssSourceFiles.add(normalizeOutputPathKey(generatorSourceFile));
@@ -4833,7 +5030,7 @@ function createGenerateBundleHook(context) {
4833
5030
  const shouldRefreshViteProcessedCssByCandidates = viteProcessedCssAsset && useIncrementalMode && state.generatorCandidateSignature !== void 0 && generatorCandidatesChanged;
4834
5031
  const vitePipelineCssInjectionOutputFile = webviewRootCssInjectionTarget ?? outputFile;
4835
5032
  const shouldRecordVitePipelineCssByOutput = normalizeOutputPathKey(vitePipelineCssInjectionOutputFile) === normalizeOutputPathKey(outputFile);
4836
- const shouldInjectVitePipelineCssIntoMain = vitePipelineCssAsset && outputCssHandlerOptions.isMainChunk !== true && (webviewRootCssInjectionTarget != null || shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions));
5033
+ const shouldInjectVitePipelineCssIntoMain = vitePipelineCssAsset && !resolvedFromConfiguredOriginalCssEntry && outputCssHandlerOptions.isMainChunk !== true && (webviewRootCssInjectionTarget != null || shouldInjectCssIntoMainFromOutput(outputFile, generatorSourceFile, outputCssHandlerOptions));
4837
5034
  const shouldTrackGeneratorRuntime = hasStaleViteProcessedCssSource || shouldRegenerateMainPackageCssWithScopedCandidates || hasCurrentTailwindGenerationDirective || hasSameOutputRememberedTailwindGenerationSource || shouldProcessTailwindGeneration && (!useIncrementalMode || cssHandlerOptions.isMainChunk || processFiles.css.has(file) || runtimeLinkedCssFiles.has(file) || runtimeLinkedCssFiles.has(outputFile) || shouldRegenerateCollectedViteCss || hasRuntimeAffectingChanges && (alreadyProcessedCssAsset || vitePipelineCssAsset));
4838
5035
  const shouldPreserveCollectedViteCssAsset = !shouldRegenerateCollectedViteCss && (state.generatorCandidateSignature === void 0 || !generatorCandidatesChanged) && (collectedBundlerGeneratedCssFiles.has(file) || hasBundlerGeneratedCssMarker(rawSource));
4839
5036
  const strippedViteProcessedCss = stripBundlerGeneratedCssMarkers(rawSource);
@@ -4979,7 +5176,7 @@ function createGenerateBundleHook(context) {
4979
5176
  continue;
4980
5177
  }
4981
5178
  if (type !== "js") continue;
4982
- if (isWebGeneratorTarget && !shouldApplyWebviewSafeSelectors) {
5179
+ if (!shouldTransformJsBundle) {
4983
5180
  debug("js skip web target: %s", file);
4984
5181
  continue;
4985
5182
  }
@@ -5061,6 +5258,8 @@ function createGenerateBundleHook(context) {
5061
5258
  bundleFiles,
5062
5259
  cache,
5063
5260
  cssTaskFactories,
5261
+ cssPipelineStrategy: context.cssPipelineStrategy,
5262
+ createCssPipelineContext: () => cssPipelineContext,
5064
5263
  debug,
5065
5264
  defaultStyleOutputExtension,
5066
5265
  formatIteration: useIncrementalMode ? state.iteration : 0,
@@ -5134,9 +5333,9 @@ function registerGeneratorDependencies(ctx, dependencies) {
5134
5333
  throw error;
5135
5334
  }
5136
5335
  }
5137
- function createCssHandlerOptions(opts, majorVersion, file) {
5336
+ function createCssHandlerOptions(opts, majorVersion, file, extraOptions = {}) {
5138
5337
  return {
5139
- ...resolveUniAppXNativeCssHandlerOptions(opts),
5338
+ ...extraOptions,
5140
5339
  cssPreflight: opts.cssPreflight,
5141
5340
  isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
5142
5341
  postcssOptions: { options: { from: file } },
@@ -5161,13 +5360,15 @@ function shouldFinalizeProcessedCssAsset(opts, file) {
5161
5360
  function collectViteProcessedCssSources(getViteProcessedCssAssetResults) {
5162
5361
  return [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css);
5163
5362
  }
5164
- function isUniAppViteWebviewOutDir(outDir) {
5165
- const normalized = outDir ? path.basename(path.normalize(outDir)).trim().toLowerCase() : void 0;
5166
- return normalized === "app" || normalized === "app-plus";
5167
- }
5168
- function finalizeWebCss(css, enabled, webCompat, options = {}) {
5169
- const compatCss = enabled ? transformWebCssCompat(css, webCompat) : css;
5170
- return options.safeSelectors ? transformWebCssSafeSelectors(compatCss, { escapeMap: options.escapeMap }) : compatCss;
5363
+ function finalizeWebCss(css, context, cssPipelineStrategy) {
5364
+ const shouldApplyWebCssCompat = cssPipelineStrategy?.shouldApplyWebCssCompat?.(context) === true;
5365
+ const defaultWebCssCompat = (value) => transformWebCssCompat(value, context.currentGeneratorBranch.isWeb ? context.currentGeneratorOptions.webCompat : context.currentGeneratorOptions.webCompat ?? true);
5366
+ return cssPipelineStrategy?.transformGeneratedCss?.(css, {
5367
+ ...context,
5368
+ defaultWebCssCompat,
5369
+ removeScopedPreflight: (value) => value,
5370
+ shouldApplyWebCssCompat
5371
+ }) ?? (shouldApplyWebCssCompat ? defaultWebCssCompat(css) : css);
5171
5372
  }
5172
5373
  function createViteCssFinalizerOutputPlugin(context) {
5173
5374
  return {
@@ -5176,7 +5377,7 @@ function createViteCssFinalizerOutputPlugin(context) {
5176
5377
  generateBundle: {
5177
5378
  order: "post",
5178
5379
  async handler(_options, bundle) {
5179
- const { opts, runtimeState, ensureRuntimeClassSet, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
5380
+ const { opts, runtimeState, ensureRuntimeClassSet, cssPipelineStrategy, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset } = context;
5180
5381
  const resolvedConfig = getResolvedConfig();
5181
5382
  const uniUtsPlatform = resolveUniUtsPlatform();
5182
5383
  const generatorPlatform = opts.cssOptions?.platform ?? opts.platform ?? inferPlatformFromViteOutDir(resolvedConfig?.build?.outDir);
@@ -5195,11 +5396,16 @@ function createViteCssFinalizerOutputPlugin(context) {
5195
5396
  uniUtsPlatform
5196
5397
  });
5197
5398
  const isWebGeneratorTarget = generatorBranch.isWeb;
5198
- const shouldApplyWebviewSafeSelectors = opts.appType === "uni-app-vite" && isUniAppViteWebviewOutDir(resolvedConfig?.build?.outDir);
5199
- const isUniAppXStyleTarget = opts.appType === "uni-app-x";
5200
- const canInferHarmonyAppStyleTarget = isUniAppXStyleTarget && (!uniUtsPlatform.normalized || uniUtsPlatform.isApp);
5201
- const isHarmonyAppStyleTarget = isUniAppXStyleTarget && (uniUtsPlatform.isAppHarmony || canInferHarmonyAppStyleTarget && (isUniAppXHarmonyBundle(bundle) || isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir)));
5202
- const isNativeAppStyleTarget = isUniAppXStyleTarget && (uniUtsPlatform.isApp || isHarmonyAppStyleTarget);
5399
+ const createCssPipelineContext = (_file) => ({
5400
+ bundle,
5401
+ currentGeneratorBranch: generatorBranch,
5402
+ currentGeneratorOptions: generatorOptions,
5403
+ opts,
5404
+ resolvedConfig,
5405
+ resolveStylePlatform: () => generatorPlatform
5406
+ });
5407
+ const isHarmonyAppStyleTarget = cssPipelineStrategy?.isHarmonyAppStyleTarget?.(createCssPipelineContext("")) === true;
5408
+ const isNativeAppStyleTarget = cssPipelineStrategy?.isNativeAppStyleTarget?.(createCssPipelineContext("")) === true;
5203
5409
  if (resolvedConfig?.command !== "build" && !isNativeAppStyleTarget) return;
5204
5410
  const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process$1.cwd();
5205
5411
  const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType) ?? resolveSourceRootFromBundleGraph(resolvedConfig, bundle);
@@ -5211,28 +5417,32 @@ function createViteCssFinalizerOutputPlugin(context) {
5211
5417
  const collectViteProcessedCssAssets = () => {
5212
5418
  collectViteProcessedCssAssetResults(bundle, {
5213
5419
  opts,
5420
+ cssPipelineStrategy,
5421
+ createCssPipelineContext,
5214
5422
  isViteProcessedCssAsset,
5215
5423
  markCssAssetProcessed,
5216
5424
  recordCssAssetResult,
5217
5425
  recordViteProcessedCssAssetResult,
5218
5426
  resolveViteProcessedCssOutputFile: (file) => resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget, isNativeAppStyleTarget, sourceRoot, resolveMiniProgramStyleOutputExtension({ files: Object.keys(bundle) }), Object.keys(bundle)),
5219
- transformCss: (css) => finalizeWebCss(css, generatorBranch.isWeb, generatorOptions.webCompat, {
5220
- escapeMap: opts.escapeMap,
5221
- safeSelectors: shouldApplyWebviewSafeSelectors
5222
- }),
5427
+ transformCss: (css, file) => finalizeWebCss(css, {
5428
+ ...createCssPipelineContext(file),
5429
+ file
5430
+ }, cssPipelineStrategy),
5223
5431
  debug
5224
5432
  });
5225
5433
  };
5226
5434
  const injectViteProcessedCssIntoMainCss = () => {
5227
5435
  return injectViteProcessedCssIntoMainCssAssets(bundle, {
5228
5436
  opts,
5437
+ cssPipelineStrategy,
5438
+ createCssPipelineContext,
5229
5439
  getViteProcessedCssAssetResults,
5230
5440
  markCssAssetProcessed,
5231
5441
  recordCssAssetResult,
5232
- transformCss: (css) => finalizeWebCss(css, generatorBranch.isWeb, generatorOptions.webCompat, {
5233
- escapeMap: opts.escapeMap,
5234
- safeSelectors: shouldApplyWebviewSafeSelectors
5235
- }),
5442
+ transformCss: (css, file) => finalizeWebCss(css, {
5443
+ ...createCssPipelineContext(file),
5444
+ file
5445
+ }, cssPipelineStrategy),
5236
5446
  debug,
5237
5447
  onUpdate: opts.onUpdate
5238
5448
  });
@@ -5244,7 +5454,10 @@ function createViteCssFinalizerOutputPlugin(context) {
5244
5454
  const applyStyleSources = collectUniAppXHarmonyApplyStyleSources(bundle);
5245
5455
  if (applyUtilities.size === 0 || applyStyleSources.length === 0) return cssSources;
5246
5456
  const harmonyRuntime = /* @__PURE__ */ new Set([...runtime, ...applyUtilities]);
5247
- const harmonyCssHandlerOptions = createCssHandlerOptions(opts, runtimeState.tailwindRuntime.majorVersion, "uni-app-x-harmony-apply.css");
5457
+ const harmonyCssHandlerOptions = createCssHandlerOptions(opts, runtimeState.tailwindRuntime.majorVersion, "uni-app-x-harmony-apply.css", cssPipelineStrategy?.getCssHandlerExtraOptions?.({
5458
+ ...createCssPipelineContext("uni-app-x-harmony-apply.css"),
5459
+ file: "uni-app-x-harmony-apply.css"
5460
+ }) ?? {});
5248
5461
  const generated = await generateTailwindV4Css({
5249
5462
  opts,
5250
5463
  runtimeState,
@@ -5279,10 +5492,10 @@ function createViteCssFinalizerOutputPlugin(context) {
5279
5492
  await injectHarmonyBundleStyles(getRecordedGeneratorCandidates?.() ?? getSourceCandidates?.() ?? await ensureRuntimeClassSet());
5280
5493
  collectViteProcessedCssAssets();
5281
5494
  injectViteProcessedCssIntoMainCss();
5282
- normalizeTaroRootImportShellAssets(bundle, {
5283
- appType: opts.appType,
5495
+ normalizeRootMiniProgramImportShellAssets(bundle, {
5284
5496
  cssMatcher: opts.cssMatcher,
5285
5497
  debug,
5498
+ enabled: cssPipelineStrategy?.shouldNormalizeRootMiniProgramImportShell?.(createCssPipelineContext("")) === true,
5286
5499
  onUpdate: opts.onUpdate,
5287
5500
  recordCssAssetResult
5288
5501
  });
@@ -5297,17 +5510,20 @@ function createViteCssFinalizerOutputPlugin(context) {
5297
5510
  const file = output.fileName || bundleFile;
5298
5511
  const rawSource = output.source.toString();
5299
5512
  if (isViteProcessedCssAsset?.(output, file)) {
5300
- const nextCss = annotateCss(finalizeWebCss(stripBundlerGeneratedCssMarkers(rawSource), generatorBranch.isWeb, generatorOptions.webCompat, {
5301
- escapeMap: opts.escapeMap,
5302
- safeSelectors: shouldApplyWebviewSafeSelectors
5303
- }));
5513
+ const nextCss = annotateCss(finalizeWebCss(stripBundlerGeneratedCssMarkers(rawSource), {
5514
+ ...createCssPipelineContext(file),
5515
+ file
5516
+ }, cssPipelineStrategy));
5304
5517
  output.source = nextCss;
5305
5518
  markCssAssetProcessed(output, file);
5306
5519
  recordCssAssetResult?.(file, nextCss);
5307
5520
  debug("css finalizer skip vite-processed css: %s", file);
5308
5521
  return;
5309
5522
  }
5310
- const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.tailwindRuntime.majorVersion, file);
5523
+ const cssHandlerOptions = createCssHandlerOptions(opts, runtimeState.tailwindRuntime.majorVersion, file, cssPipelineStrategy?.getCssHandlerExtraOptions?.({
5524
+ ...createCssPipelineContext(file),
5525
+ file
5526
+ }) ?? {});
5311
5527
  const cssUserHandlerOptions = {
5312
5528
  ...cssHandlerOptions,
5313
5529
  isMainChunk: false
@@ -5316,7 +5532,10 @@ function createViteCssFinalizerOutputPlugin(context) {
5316
5532
  const rememberedMainCssSource = processed && cssHandlerOptions.isMainChunk ? getRememberedMainCssSource?.(file) : void 0;
5317
5533
  const generatorRawSource = rememberedMainCssSource?.rawSource ?? rawSource;
5318
5534
  const generatorSourceFile = rememberedMainCssSource?.sourceFile ?? file;
5319
- const generatorCssHandlerOptions = rememberedMainCssSource ? createCssHandlerOptions(opts, runtimeState.tailwindRuntime.majorVersion, generatorSourceFile) : cssHandlerOptions;
5535
+ const generatorCssHandlerOptions = rememberedMainCssSource ? createCssHandlerOptions(opts, runtimeState.tailwindRuntime.majorVersion, generatorSourceFile, cssPipelineStrategy?.getCssHandlerExtraOptions?.({
5536
+ ...createCssPipelineContext(generatorSourceFile),
5537
+ file: generatorSourceFile
5538
+ }) ?? {}) : cssHandlerOptions;
5320
5539
  const generatorCssUserHandlerOptions = rememberedMainCssSource ? {
5321
5540
  ...generatorCssHandlerOptions,
5322
5541
  isMainChunk: false
@@ -5335,10 +5554,10 @@ function createViteCssFinalizerOutputPlugin(context) {
5335
5554
  styleHandler: opts.styleHandler,
5336
5555
  debug
5337
5556
  }) : void 0;
5338
- const nextCss = annotateCss(generated?.css ?? (generatorBranch.isWeb ? finalizeWebCss(rawSource, true, generatorOptions.webCompat, {
5339
- escapeMap: opts.escapeMap,
5340
- safeSelectors: shouldApplyWebviewSafeSelectors
5341
- }) : (await opts.styleHandler(rawSource, cssHandlerOptions)).css));
5557
+ const nextCss = annotateCss(generated?.css ?? (generatorBranch.isWeb ? finalizeWebCss(rawSource, {
5558
+ ...createCssPipelineContext(file),
5559
+ file
5560
+ }, cssPipelineStrategy) : (await opts.styleHandler(rawSource, cssHandlerOptions)).css));
5342
5561
  if (generated) {
5343
5562
  registerGeneratorDependencies(this, generated.dependencies);
5344
5563
  debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
@@ -5353,10 +5572,10 @@ function createViteCssFinalizerOutputPlugin(context) {
5353
5572
  await injectHarmonyBundleStyles(generatorRuntime);
5354
5573
  collectViteProcessedCssAssets();
5355
5574
  injectViteProcessedCssIntoMainCss();
5356
- normalizeTaroRootImportShellAssets(bundle, {
5357
- appType: opts.appType,
5575
+ normalizeRootMiniProgramImportShellAssets(bundle, {
5358
5576
  cssMatcher: opts.cssMatcher,
5359
5577
  debug,
5578
+ enabled: cssPipelineStrategy?.shouldNormalizeRootMiniProgramImportShell?.(createCssPipelineContext("")) === true,
5360
5579
  onUpdate: opts.onUpdate,
5361
5580
  recordCssAssetResult
5362
5581
  });
@@ -6037,6 +6256,12 @@ function isViteServeCssRootRequest(id, command) {
6037
6256
  function isViteCssHmrModule(code, id, command) {
6038
6257
  return isViteServeStyleRequest(id, command) && VITE_CSS_HMR_MODULE_RE.test(code) && /[?&](?:direct|vue)(?:&|$)/.test(id);
6039
6258
  }
6259
+ function hasViteServeCssGenerationDirective(code) {
6260
+ return hasTailwindRootDirectives(code) || hasTailwindSourceDirectives(code, { importFallback: true }) || hasTailwindApplyDirective(code);
6261
+ }
6262
+ function hasViteServeCssRootDirective(code) {
6263
+ return hasTailwindRootDirectives(code);
6264
+ }
6040
6265
  function createViteServeCssGenerationPlugins(options) {
6041
6266
  return [{
6042
6267
  name: `${vitePluginName}:generate:serve`,
@@ -6061,7 +6286,8 @@ function createViteServeCssGenerationPlugins(options) {
6061
6286
  if (!options.shouldGenerate() || !isViteCssHmrModule(code, id, options.getCommand())) return;
6062
6287
  const extracted = extractViteCssHmrModuleCss(code);
6063
6288
  if (!extracted) return;
6064
- await options.onTailwindRootCss?.(id, extracted.css);
6289
+ if (!hasViteServeCssGenerationDirective(extracted.css)) return;
6290
+ if (hasViteServeCssRootDirective(extracted.css)) await options.onTailwindRootCss?.(id, extracted.css);
6065
6291
  const generatedCss = await options.generateCss(id, extracted.css, this);
6066
6292
  if (generatedCss === void 0 || generatedCss === extracted.css) return;
6067
6293
  const nextCode = replaceViteCssHmrModuleCss(code, generatedCss);
@@ -6120,7 +6346,7 @@ function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
6120
6346
  return resolvedRoot;
6121
6347
  }
6122
6348
  //#endregion
6123
- //#region src/bundlers/vite/index.ts
6349
+ //#region src/bundlers/vite/shared/create-framework-plugins.ts
6124
6350
  const debug = createDebug();
6125
6351
  const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
6126
6352
  const weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
@@ -6159,23 +6385,22 @@ function inferPlatformFromOutDir(outDir) {
6159
6385
  function isWebOrNativeAppPlatform(platform) {
6160
6386
  return platform === "h5" || platform === "web" || platform?.startsWith("web-") === true || platform === "app" || platform === "app-plus" || platform?.startsWith("app-") === true;
6161
6387
  }
6162
- function isUniAppViteWebviewStylePlatform(platform) {
6163
- return platform === "app" || platform === "app-plus";
6388
+ function applyViteWebCssCompat(css, options) {
6389
+ return transformWebCssCompat(css, options.compat);
6164
6390
  }
6165
- function applyUniAppViteWebviewCssCompat(css, options) {
6166
- const compatCss = transformWebCssCompat(css, options.compat);
6167
- return options.safeSelectors ? transformWebCssSafeSelectors(compatCss, { escapeMap: options.escapeMap }) : compatCss;
6391
+ function isInternalUserDefinedOptions(options) {
6392
+ return typeof options.onLoad === "function" && typeof options.mainCssChunkMatcher === "function" && typeof options.tailwindRuntime === "object" && typeof options.refreshTailwindcssRuntime === "function";
6168
6393
  }
6169
6394
  /**
6170
- * @name WeappTailwindcss
6171
- * @description uni-app vite / uni-app-x 版本插件
6172
- * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
6395
+ * Vite 各框架分支共享的组合工厂。框架分支只负责选择和拥有各自入口,公共稳定能力放在这里复用。
6173
6396
  */
6174
- function WeappTailwindcss(options = {}) {
6175
- const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
6176
- const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
6177
- const rawCssEntries = collectConfiguredCssEntries(options);
6178
- const opts = getCompilerContext({
6397
+ function createViteFrameworkPlugins(options = {}, frameworkBranch) {
6398
+ debug("create vite framework plugins framework=%s", frameworkBranch.frameworkName);
6399
+ const rawOptions = options.__internalViteRawOptions ?? options;
6400
+ const hasExplicitAppType = typeof options.__internalViteRawExplicitAppType === "boolean" ? options.__internalViteRawExplicitAppType : typeof options.appType === "string" && options.appType.trim().length > 0;
6401
+ const hasExplicitTailwindcssBasedir = typeof options.__internalViteRawExplicitTailwindcssBasedir === "boolean" ? options.__internalViteRawExplicitTailwindcssBasedir : typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
6402
+ const rawCssEntries = collectConfiguredCssEntries(rawOptions);
6403
+ const opts = isInternalUserDefinedOptions(options) ? options : getCompilerContext({
6179
6404
  ...options,
6180
6405
  __internalDeferMissingCssEntriesWarning: true
6181
6406
  });
@@ -6196,7 +6421,9 @@ function WeappTailwindcss(options = {}) {
6196
6421
  const { disabled, customAttributes, onLoad, mainCssChunkMatcher, styleHandler, jsHandler, tailwindRuntime, refreshTailwindcssRuntime, uniAppX, disabledDefaultTemplateHandler, styleInjector } = opts;
6197
6422
  const initialTailwindRuntime = tailwindRuntime;
6198
6423
  const refreshTailwindRuntime = refreshTailwindcssRuntime;
6199
- const uniAppXEnabled = isUniAppXEnabled(uniAppX);
6424
+ const frameworkCssPipelineStrategy = frameworkBranch.cssPipelineStrategy;
6425
+ const uniAppXEnabled = frameworkBranch.isRuntimeClassSetFeatureEnabled?.({ uniAppX }) === true;
6426
+ const shouldEnableFrameworkExtraPlugins = () => frameworkBranch.createExtraPlugins !== void 0;
6200
6427
  const disabledOptions = resolvePluginDisabledState(disabled);
6201
6428
  const tailwindcssMajorVersion = initialTailwindRuntime.majorVersion ?? 0;
6202
6429
  if (!disabledOptions.plugin && tailwindcssMajorVersion !== 4) throw new Error("weapp-tailwindcss/vite 新生成管线仅支持 Tailwind CSS v4,请升级 tailwindcss 或停留在旧版 weapp-tailwindcss。");
@@ -6225,6 +6452,14 @@ function WeappTailwindcss(options = {}) {
6225
6452
  tailwindcssMajorVersion,
6226
6453
  uniAppX
6227
6454
  });
6455
+ const createCssPipelineContext = (overrides = {}) => ({
6456
+ currentGeneratorBranch: resolveCurrentGeneratorBranch(),
6457
+ currentGeneratorOptions: resolveCurrentGeneratorOptions(),
6458
+ opts,
6459
+ resolvedConfig,
6460
+ resolveStylePlatform: resolveViteStylePlatform,
6461
+ ...overrides
6462
+ });
6228
6463
  const initialGeneratorBranch = resolveCurrentGeneratorBranch();
6229
6464
  const transformEarlyMiniProgramCss = (code) => {
6230
6465
  const platform = resolveViteStylePlatform();
@@ -6241,8 +6476,8 @@ function WeappTailwindcss(options = {}) {
6241
6476
  };
6242
6477
  const shouldInferAppType = !hasExplicitAppType && !initialGeneratorBranch.isWeb;
6243
6478
  const hasInitialTailwindCssRoots = hasConfiguredTailwindV4CssRoots({
6244
- ...options,
6245
- cssEntries: opts.cssEntries ?? options.cssEntries
6479
+ ...rawOptions,
6480
+ cssEntries: opts.cssEntries ?? rawOptions.cssEntries
6246
6481
  });
6247
6482
  const autoCssSourceContent = /* @__PURE__ */ new Map();
6248
6483
  const transientAutoCssSources = /* @__PURE__ */ new Map();
@@ -6558,10 +6793,6 @@ function WeappTailwindcss(options = {}) {
6558
6793
  const isUniViteProject = () => {
6559
6794
  return resolvedConfig?.plugins?.some((plugin) => plugin.name.includes("uni")) ?? false;
6560
6795
  };
6561
- const isHarmonyAppBuildTarget = () => {
6562
- if (resolveUniUtsPlatform().isAppHarmony) return true;
6563
- return isUniAppXHarmonyOutDir(resolvedConfig?.build?.outDir);
6564
- };
6565
6796
  const matchesViteProcessedCssSource = (candidate) => {
6566
6797
  const normalized = normalizeViteProcessedCssFile(candidate);
6567
6798
  return viteProcessedCssSourceFiles.has(normalized);
@@ -6581,7 +6812,10 @@ function WeappTailwindcss(options = {}) {
6581
6812
  getOutputRoot: () => resolvedConfig?.build?.outDir ? path.resolve(resolvedConfig.root, resolvedConfig.build.outDir) : resolvedConfig?.root,
6582
6813
  getExtraOptions: (file) => ({
6583
6814
  ...resolveViteCssHandlerExtraOptions(file),
6584
- ...resolveUniAppXNativeCssHandlerOptions(opts)
6815
+ ...frameworkCssPipelineStrategy?.getCssHandlerExtraOptions?.({
6816
+ ...createCssPipelineContext(),
6817
+ file
6818
+ }) ?? {}
6585
6819
  }),
6586
6820
  getDynamicCssOptions: () => ({ cssPreflight: opts.cssPreflight })
6587
6821
  });
@@ -6594,20 +6828,24 @@ function WeappTailwindcss(options = {}) {
6594
6828
  await runtimeState.readyPromise;
6595
6829
  await waitForSourceCandidateSyncs();
6596
6830
  const file = cleanUrl(id);
6597
- const requestFile = isCSSRequest(id) ? id : file;
6831
+ const requestFile = isCSSRequest(id) ? id === file ? resolveSfcStyleRequestFromKnownSource(file, cssMemory.getKnownSfcSource(file), code) : id : file;
6598
6832
  if (!isCSSRequest(requestFile) || opts.htmlMatcher(file) || isHTMLRequest(file)) return;
6599
6833
  const generatorCode = normalizeEmptyTailwindCustomVariants(code);
6600
6834
  const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process$1.cwd();
6601
- const isHarmonyAppStyleTarget = isHarmonyAppBuildTarget();
6602
- const isNativeAppStyleTarget = opts.appType === "uni-app-x" && (resolveUniUtsPlatform().isApp || isHarmonyAppStyleTarget);
6603
- const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType);
6604
6835
  const currentGeneratorOptions = resolveCurrentGeneratorOptions();
6605
6836
  const currentGeneratorBranch = resolveCurrentGeneratorBranch();
6606
- const outputFile = resolveViteCssPipelineOutputFile(requestFile, opts, rootDir, currentGeneratorBranch.isWeb, isNativeAppStyleTarget, sourceRoot);
6837
+ const cssPipelineContext = createCssPipelineContext({
6838
+ currentGeneratorBranch,
6839
+ currentGeneratorOptions
6840
+ });
6841
+ const shouldPreserveStyleOutputExtension = frameworkCssPipelineStrategy?.shouldPreserveStyleOutputExtension?.(cssPipelineContext) ?? frameworkCssPipelineStrategy?.isNativeAppStyleTarget?.(cssPipelineContext) === true;
6842
+ const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType);
6843
+ const outputFile = resolveViteCssPipelineOutputFile(requestFile, opts, rootDir, currentGeneratorBranch.isWeb, shouldPreserveStyleOutputExtension, sourceRoot);
6607
6844
  const runtime = getRecordedGeneratorCandidates() ?? getSourceCandidates() ?? await ensureRuntimeClassSet();
6845
+ const sourceCssHandlerOptions = transformCssHandlerOptions.getCssHandlerOptions(requestFile);
6608
6846
  const outputCssHandlerOptions = transformCssHandlerOptions.getCssHandlerOptions(outputFile);
6609
6847
  const cssHandlerOptions = {
6610
- ...transformCssHandlerOptions.getCssHandlerOptions(file),
6848
+ ...sourceCssHandlerOptions,
6611
6849
  isMainChunk: outputCssHandlerOptions.isMainChunk
6612
6850
  };
6613
6851
  const transientCssSource = transientAutoCssSources.get(file) ?? (hasTailwindRootDirectives(generatorCode, { importFallback: currentGeneratorOptions.importFallback }) || hasTailwindSourceDirectives(generatorCode, { importFallback: currentGeneratorOptions.importFallback }) || hasTailwindApplyDirective(generatorCode) ? {
@@ -6615,7 +6853,11 @@ function WeappTailwindcss(options = {}) {
6615
6853
  css: generatorCode,
6616
6854
  file: path.resolve(file)
6617
6855
  } : void 0);
6618
- const shouldDeferEmptyScopedCssSource = transientCssSource == null && !(opts.appType === "uni-app-x" && !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(generatorCode));
6856
+ const shouldDeferEmptyScopedCssSource = transientCssSource == null && (frameworkCssPipelineStrategy?.shouldDeferEmptyScopedCssSource?.({
6857
+ ...cssPipelineContext,
6858
+ cssHandlerOptions,
6859
+ generatorCode
6860
+ }) ?? true);
6619
6861
  const generated = await generateTailwindV4Css({
6620
6862
  opts,
6621
6863
  runtimeState,
@@ -6624,7 +6866,7 @@ function WeappTailwindcss(options = {}) {
6624
6866
  file,
6625
6867
  outputFile,
6626
6868
  cssHandlerOptions,
6627
- cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(file),
6869
+ cssUserHandlerOptions: transformCssHandlerOptions.getCssUserHandlerOptions(requestFile),
6628
6870
  cssSources: transientCssSource ? [transientCssSource] : void 0,
6629
6871
  getSourceCandidatesForEntries,
6630
6872
  generatorPlatform: resolveGeneratorPlatform(),
@@ -6636,12 +6878,13 @@ function WeappTailwindcss(options = {}) {
6636
6878
  });
6637
6879
  if (!generated) return;
6638
6880
  const finalizedCss = finalizeViteMiniProgramCss(generated.css);
6639
- const isUniAppViteWebviewPlatform = opts.appType === "uni-app-vite" && isUniAppViteWebviewStylePlatform(resolveViteStylePlatform());
6640
- const tracedCss = annotateCssSourceTrace(removeScopedTailwindPreflightCss(currentGeneratorBranch.isWeb || isUniAppViteWebviewPlatform ? applyUniAppViteWebviewCssCompat(finalizedCss, {
6641
- compat: currentGeneratorOptions.webCompat ?? true,
6642
- escapeMap: opts.escapeMap,
6643
- safeSelectors: isUniAppViteWebviewPlatform
6644
- }) : finalizedCss), {
6881
+ const shouldApplyWebCssCompat = currentGeneratorBranch.isWeb || frameworkCssPipelineStrategy?.shouldApplyWebCssCompat?.(cssPipelineContext) === true;
6882
+ const tracedCss = annotateCssSourceTrace(frameworkCssPipelineStrategy?.transformGeneratedCss?.(finalizedCss, {
6883
+ ...cssPipelineContext,
6884
+ defaultWebCssCompat: (css) => applyViteWebCssCompat(css, { compat: currentGeneratorOptions.webCompat ?? true }),
6885
+ removeScopedPreflight: removeScopedTailwindPreflightCss,
6886
+ shouldApplyWebCssCompat
6887
+ }) ?? removeScopedTailwindPreflightCss(shouldApplyWebCssCompat ? applyViteWebCssCompat(finalizedCss, { compat: currentGeneratorOptions.webCompat ?? true }) : finalizedCss), {
6645
6888
  opts,
6646
6889
  tokenSources: createCssTokenSourceMap(getSourceCandidateSourcesForEntries(void 0), opts)
6647
6890
  });
@@ -6656,7 +6899,7 @@ function WeappTailwindcss(options = {}) {
6656
6899
  injectIntoMain: shouldInjectGeneratedCssIntoMain,
6657
6900
  outputFile
6658
6901
  });
6659
- if (isNativeAppStyleTarget && outputFile.endsWith(".css")) hookContext?.emitFile?.({
6902
+ if (shouldPreserveStyleOutputExtension && outputFile.endsWith(".css")) hookContext?.emitFile?.({
6660
6903
  type: "asset",
6661
6904
  fileName: outputFile,
6662
6905
  source: tracedCss
@@ -6667,9 +6910,9 @@ function WeappTailwindcss(options = {}) {
6667
6910
  cssMemory.rememberCssSource({
6668
6911
  outputFile,
6669
6912
  rawSource: code,
6670
- sourceFile: id
6913
+ sourceFile: requestFile
6671
6914
  });
6672
- debug("css generated for vite postcss pipeline: %s bytes=%d", file, tracedCss.length);
6915
+ debug("css generated for vite postcss pipeline: %s bytes=%d", requestFile, tracedCss.length);
6673
6916
  return `${createBundlerGeneratedCssMarker("vite", normalizeViteProcessedCssFile(file))}\n${tracedCss}`;
6674
6917
  };
6675
6918
  const rewritePlugins = createRewriteCssImportsPlugins({
@@ -6715,12 +6958,14 @@ function WeappTailwindcss(options = {}) {
6715
6958
  recordGeneratorCandidates,
6716
6959
  pruneViteCssCaches,
6717
6960
  getViteCssCacheStats,
6718
- hmrTimingRecorder
6961
+ hmrTimingRecorder,
6962
+ cssPipelineStrategy: frameworkCssPipelineStrategy
6719
6963
  });
6720
6964
  const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
6721
6965
  opts,
6722
6966
  runtimeState,
6723
6967
  ensureRuntimeClassSet,
6968
+ cssPipelineStrategy: frameworkCssPipelineStrategy,
6724
6969
  debug,
6725
6970
  getResolvedConfig,
6726
6971
  markCssAssetProcessed,
@@ -6741,25 +6986,25 @@ function WeappTailwindcss(options = {}) {
6741
6986
  }),
6742
6987
  getRememberedMainCssSource: cssMemory.getRememberedCssSourceEntry
6743
6988
  });
6744
- const isIosPlatform = resolveUniUtsPlatform().isAppIos;
6989
+ const extraPluginPlatform = frameworkBranch.getExtraPluginPlatform?.() ?? {};
6745
6990
  const prepareTailwindGeneration = async () => {
6746
6991
  if (shouldDiscoverAutoCssSources()) await discoverAndRegisterAutoCssSources();
6747
6992
  await syncSourceCandidateScan();
6748
6993
  };
6749
- const uniAppXPlugins = uniAppXEnabled ? createUniAppXPlugins({
6750
- appType: opts.appType ?? "uni-app-x",
6994
+ const extraPlugins = frameworkBranch.createExtraPlugins?.({
6751
6995
  customAttributesEntities,
6752
6996
  disabledDefaultTemplateHandler,
6753
- isIosPlatform,
6997
+ ensureRuntimeClassSet,
6998
+ generateCss: generateTailwindCssForVitePipeline,
6999
+ getResolvedConfig,
7000
+ isEnabled: shouldEnableFrameworkExtraPlugins,
7001
+ isIosPlatform: extraPluginPlatform.isIosPlatform === true,
7002
+ jsHandler,
6754
7003
  mainCssChunkMatcher,
6755
7004
  runtimeState,
6756
7005
  styleHandler,
6757
- generateCss: generateTailwindCssForVitePipeline,
6758
- jsHandler,
6759
- ensureRuntimeClassSet,
6760
- getResolvedConfig,
6761
7006
  uniAppX
6762
- }) : void 0;
7007
+ }) ?? [];
6763
7008
  const plugins = [
6764
7009
  ...rewritePlugins,
6765
7010
  {
@@ -6858,10 +7103,13 @@ function WeappTailwindcss(options = {}) {
6858
7103
  shouldGenerate: () => shouldOwnTailwindGeneration
6859
7104
  }),
6860
7105
  createViteServeJsTransformPlugin({
6861
- createHandlerOptions: (file) => serveJsHandlerOptions(file, opts.appType === "uni-app-vite" && isUniAppViteWebviewStylePlatform(resolveViteStylePlatform()) ? { needEscaped: true } : void 0),
7106
+ createHandlerOptions: (file) => serveJsHandlerOptions(file, frameworkCssPipelineStrategy?.getServeJsHandlerOptions?.({
7107
+ ...createCssPipelineContext(),
7108
+ file
7109
+ })),
6862
7110
  getCommand: () => resolvedConfig?.command,
6863
7111
  jsHandler,
6864
- shouldTransform: () => shouldOwnTailwindGeneration && (!resolveCurrentGeneratorBranch().isWeb || opts.appType === "uni-app-vite" && isUniAppViteWebviewStylePlatform(resolveViteStylePlatform())),
7112
+ shouldTransform: () => shouldOwnTailwindGeneration && (frameworkCssPipelineStrategy?.shouldTransformServeJs?.(createCssPipelineContext()) ?? !resolveCurrentGeneratorBranch().isWeb),
6865
7113
  transformRuntime: ensureRuntimeClassSet
6866
7114
  }),
6867
7115
  {
@@ -6936,10 +7184,304 @@ function WeappTailwindcss(options = {}) {
6936
7184
  }
6937
7185
  }
6938
7186
  ];
6939
- if (uniAppXPlugins) plugins.push(...uniAppXPlugins);
7187
+ plugins.push(...extraPlugins);
6940
7188
  plugins.push(cssFinalizerOutputPlugin);
6941
- plugins.push(...createBuiltinViteStyleInjectorPlugins(styleInjector, () => opts.appType));
7189
+ plugins.push(...createBuiltinViteStyleInjectorPlugins(styleInjector, () => frameworkBranch.styleInjectorDelegate));
6942
7190
  return plugins;
6943
7191
  }
6944
7192
  //#endregion
7193
+ //#region src/bundlers/vite/frameworks/generic/index.ts
7194
+ function createGenericVitePlugins(options = {}) {
7195
+ return createViteFrameworkPlugins(options, {
7196
+ frameworkName: "generic",
7197
+ styleInjectorDelegate: viteStyleInjectorDelegates.generic
7198
+ });
7199
+ }
7200
+ //#endregion
7201
+ //#region src/bundlers/vite/frameworks/taro/index.ts
7202
+ const taroCssPipelineStrategy = {
7203
+ shouldKeepRootMiniProgramStyleAsImportShell() {
7204
+ return true;
7205
+ },
7206
+ shouldMoveRootMiniProgramStyleToImportShellOrigin() {
7207
+ return true;
7208
+ },
7209
+ shouldNormalizeRootMiniProgramImportShell() {
7210
+ return true;
7211
+ }
7212
+ };
7213
+ function createTaroAlipayBrowserslistAssetPlugin() {
7214
+ return {
7215
+ name: "weapp-tailwindcss:taro-alipay-browserslist-asset",
7216
+ enforce: "pre",
7217
+ generateBundle(_options, bundle) {
7218
+ if (process$1.env.TARO_ENV !== "alipay") return;
7219
+ bundle[".browserslistrc"] = {
7220
+ type: "asset",
7221
+ fileName: ".browserslistrc",
7222
+ source: "defaults and fully supports es6-module"
7223
+ };
7224
+ }
7225
+ };
7226
+ }
7227
+ function createTaroVitePlugins(options = {}) {
7228
+ return [createTaroAlipayBrowserslistAssetPlugin(), ...createViteFrameworkPlugins(options, {
7229
+ frameworkName: "taro",
7230
+ cssPipelineStrategy: taroCssPipelineStrategy,
7231
+ styleInjectorDelegate: viteStyleInjectorDelegates.taro
7232
+ })];
7233
+ }
7234
+ //#endregion
7235
+ //#region src/bundlers/vite/frameworks/uni-app/index.ts
7236
+ function isUniAppWebviewStylePlatform(platform) {
7237
+ return platform === "app" || platform === "app-plus";
7238
+ }
7239
+ function isUniAppWebviewAppBundle(bundleFiles) {
7240
+ return bundleFiles.some((file) => path.basename(file.replace(/[?#].*$/, "")) === "app-service.js");
7241
+ }
7242
+ function isUniAppWebviewOutDir(outDir) {
7243
+ const normalized = outDir ? path.basename(path.normalize(outDir)).trim().toLowerCase() : void 0;
7244
+ return normalized === "app" || normalized === "app-plus";
7245
+ }
7246
+ const uniAppCssPipelineStrategy = {
7247
+ getServeJsHandlerOptions(context) {
7248
+ return isUniAppWebviewStylePlatform(context.resolveStylePlatform()) ? { needEscaped: true } : void 0;
7249
+ },
7250
+ shouldApplyWebCssCompat(context) {
7251
+ return isUniAppWebviewStylePlatform(context.resolveStylePlatform());
7252
+ },
7253
+ includeTailwindGeneratedCssAssetsInRootCoverage(context) {
7254
+ return context.isWebGeneratorTarget && isUniAppWebviewAppBundle(context.bundleFiles);
7255
+ },
7256
+ resolveConfiguredCssEntryRootInjectionTarget(context) {
7257
+ if (context.isMiniProgramStyleOutputFile(context.outputFile) || !context.isConfiguredCssEntryFile(context.sourceFile)) return;
7258
+ const rootCssFiles = [];
7259
+ const matchedRootCssFiles = [];
7260
+ for (const [bundleFile, output] of Object.entries(context.bundle)) {
7261
+ if (output.type !== "asset") continue;
7262
+ const file = output.fileName || bundleFile;
7263
+ if (!context.opts.cssMatcher(file) || !context.isRootStyleOutputFile(file) || context.isMiniProgramStyleOutputFile(file)) continue;
7264
+ rootCssFiles.push(file);
7265
+ if (context.opts.mainCssChunkMatcher(file, context.opts.appType)) matchedRootCssFiles.push(file);
7266
+ }
7267
+ if (matchedRootCssFiles.length === 1) return matchedRootCssFiles[0];
7268
+ if (matchedRootCssFiles.length > 1) return;
7269
+ return rootCssFiles.length === 1 ? rootCssFiles[0] : void 0;
7270
+ },
7271
+ shouldApplyFinalWebviewCssCompat(context) {
7272
+ return isUniAppWebviewAppBundle(context.bundleFiles) || isUniAppWebviewOutDir(context.outDir);
7273
+ },
7274
+ shouldKeepRootMiniProgramStyleAsImportShell() {
7275
+ return true;
7276
+ },
7277
+ shouldPreferExplicitWebCssTargets() {
7278
+ return true;
7279
+ },
7280
+ shouldPreferMatchedRootWebOutputTarget() {
7281
+ return true;
7282
+ },
7283
+ shouldRemoveDuplicateUnlinkedRootCssAssetsReferencedByHtml(context) {
7284
+ return context.isWebGeneratorTarget && isUniAppWebviewAppBundle(context.bundleFiles);
7285
+ },
7286
+ shouldSelectConfiguredCssEntryRootSource(context) {
7287
+ return context.currentGeneratorBranch.isWeb && context.opts.cssMatcher(context.outputFile) && context.isRootStyleOutputFile(context.outputFile);
7288
+ },
7289
+ shouldTransformServeJs(context) {
7290
+ return !context.currentGeneratorBranch.isWeb || isUniAppWebviewStylePlatform(context.resolveStylePlatform());
7291
+ },
7292
+ transformGeneratedCss(css, context) {
7293
+ const webCss = context.shouldApplyWebCssCompat ? transformWebCssCompat(css, context.currentGeneratorBranch.isWeb ? context.currentGeneratorOptions.webCompat : context.currentGeneratorOptions.webCompat ?? true) : css;
7294
+ const safeCss = isUniAppWebviewStylePlatform(context.resolveStylePlatform()) ? transformWebCssSafeSelectors(webCss, { escapeMap: context.opts.escapeMap }) : webCss;
7295
+ return context.removeScopedPreflight(safeCss);
7296
+ }
7297
+ };
7298
+ function createUniAppVitePlugins(options = {}) {
7299
+ return createViteFrameworkPlugins(options, {
7300
+ frameworkName: "uni-app",
7301
+ cssPipelineStrategy: uniAppCssPipelineStrategy,
7302
+ styleInjectorDelegate: viteStyleInjectorDelegates.uniApp
7303
+ });
7304
+ }
7305
+ const UNI_APP_X_WEB_PREFLIGHT_RESET_CSS = [`/* weapp-tailwindcss uni-app-x web preflight reset */`, `${[
7306
+ "uni-ad-draw",
7307
+ "uni-ad-fullscreen-video",
7308
+ "uni-ad-interactive",
7309
+ "uni-ad-interstitial",
7310
+ "uni-ad-rewarded-video",
7311
+ "uni-ad",
7312
+ "uni-animation-view",
7313
+ "uni-audio",
7314
+ "uni-block",
7315
+ "uni-button",
7316
+ "uni-camera",
7317
+ "uni-canvas",
7318
+ "uni-checkbox-group",
7319
+ "uni-checkbox",
7320
+ "uni-cover-image",
7321
+ "uni-cover-view",
7322
+ "uni-custom-tab-bar",
7323
+ "uni-editor",
7324
+ "uni-form",
7325
+ "uni-icon",
7326
+ "uni-image",
7327
+ "uni-input",
7328
+ "uni-label",
7329
+ "uni-list-item",
7330
+ "uni-list-view",
7331
+ "uni-live-player",
7332
+ "uni-live-pusher",
7333
+ "uni-map",
7334
+ "uni-match-media",
7335
+ "uni-movable-area",
7336
+ "uni-movable-view",
7337
+ "uni-navigation-bar",
7338
+ "uni-navigator",
7339
+ "uni-open-data",
7340
+ "uni-page-meta",
7341
+ "uni-picker-view",
7342
+ "uni-picker",
7343
+ "uni-progress",
7344
+ "uni-radio-group",
7345
+ "uni-radio",
7346
+ "uni-rich-text",
7347
+ "uni-scroll-view",
7348
+ "uni-slider",
7349
+ "uni-sticky-header",
7350
+ "uni-sticky-section",
7351
+ "uni-swiper-item",
7352
+ "uni-swiper",
7353
+ "uni-switch",
7354
+ "uni-template",
7355
+ "uni-text",
7356
+ "uni-textarea",
7357
+ "uni-unicloud-db",
7358
+ "uni-video",
7359
+ "uni-view",
7360
+ "uni-web-view"
7361
+ ].map((tag) => `uni-app ${tag}`).join(", ")}{border-width:0;}`].join("\n");
7362
+ const TAILWIND_PREFLIGHT_BORDER_RE = /\bborder\s*:\s*0(?:px)?\s+solid\b/;
7363
+ function withUniAppXWebPreflightReset(css, enabled) {
7364
+ if (!enabled || css.includes("weapp-tailwindcss uni-app-x web preflight reset") || !TAILWIND_PREFLIGHT_BORDER_RE.test(css)) return css;
7365
+ return css.length > 0 ? `${UNI_APP_X_WEB_PREFLIGHT_RESET_CSS}\n${css}` : UNI_APP_X_WEB_PREFLIGHT_RESET_CSS;
7366
+ }
7367
+ //#endregion
7368
+ //#region src/bundlers/vite/uni-app-x-css-options.ts
7369
+ function resolveUniAppXNativeCssHandlerOptions(opts) {
7370
+ const uniUtsPlatform = resolveUniUtsPlatform();
7371
+ if (!shouldUseNativeAppCssBranch(resolveGeneratorRuntimeBranch(normalizeWeappTailwindcssGeneratorOptions(opts.generator, {
7372
+ appType: opts.appType,
7373
+ platform: opts.cssOptions?.platform ?? opts.platform,
7374
+ uniAppX: resolveUniAppXOptions(opts.uniAppX),
7375
+ uniUtsPlatform
7376
+ }), {
7377
+ appType: opts.appType,
7378
+ platform: opts.cssOptions?.platform ?? opts.platform,
7379
+ uniAppX: resolveUniAppXOptions(opts.uniAppX),
7380
+ uniUtsPlatform
7381
+ })) || !isUniAppXEnabled(opts.uniAppX)) return {};
7382
+ return {
7383
+ uniAppX: true,
7384
+ uniAppXCssTarget: "uvue",
7385
+ uniAppXUnsupported: resolveUniAppXOptions(opts.uniAppX).uvueUnsupported
7386
+ };
7387
+ }
7388
+ //#endregion
7389
+ //#region src/bundlers/vite/frameworks/uni-app-x/index.ts
7390
+ function isUniAppXNativeAppStyleTarget() {
7391
+ return resolveUniUtsPlatform().isApp;
7392
+ }
7393
+ function isUniAppXHarmonyAppStyleTarget(context) {
7394
+ const uniUtsPlatform = resolveUniUtsPlatform();
7395
+ const canInferHarmonyAppStyleTarget = !uniUtsPlatform.normalized || uniUtsPlatform.isApp;
7396
+ return uniUtsPlatform.isAppHarmony || canInferHarmonyAppStyleTarget && (context.bundle != null && isUniAppXHarmonyBundle(context.bundle) || isUniAppXHarmonyOutDir(context.resolvedConfig?.build?.outDir));
7397
+ }
7398
+ const uniAppXCssPipelineStrategy = {
7399
+ getCssHandlerExtraOptions(context) {
7400
+ return resolveUniAppXNativeCssHandlerOptions(context.opts);
7401
+ },
7402
+ isNativeAppStyleTarget() {
7403
+ return isUniAppXNativeAppStyleTarget();
7404
+ },
7405
+ isHarmonyAppStyleTarget(context) {
7406
+ return isUniAppXHarmonyAppStyleTarget(context);
7407
+ },
7408
+ shouldPreserveStyleOutputExtension(context) {
7409
+ return isUniAppXNativeAppStyleTarget() || isUniAppXHarmonyAppStyleTarget(context);
7410
+ },
7411
+ shouldKeepRootMiniProgramStyleAsImportShell() {
7412
+ return true;
7413
+ },
7414
+ shouldDeferEmptyScopedCssSource(context) {
7415
+ if (!context.cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(context.generatorCode)) return false;
7416
+ return true;
7417
+ },
7418
+ transformGeneratedCss(css, context) {
7419
+ const webCss = context.shouldApplyWebCssCompat ? context.defaultWebCssCompat(css) : css;
7420
+ return withUniAppXWebPreflightReset(context.removeScopedPreflight(webCss), context.currentGeneratorBranch.isWeb);
7421
+ }
7422
+ };
7423
+ function createUniAppXVitePlugins(options = {}) {
7424
+ return createViteFrameworkPlugins(options, {
7425
+ frameworkName: "uni-app-x",
7426
+ cssPipelineStrategy: uniAppXCssPipelineStrategy,
7427
+ getExtraPluginPlatform: () => ({ isIosPlatform: resolveUniUtsPlatform().isAppIos }),
7428
+ styleInjectorDelegate: viteStyleInjectorDelegates.uniApp,
7429
+ isRuntimeClassSetFeatureEnabled: () => true,
7430
+ createExtraPlugins: (context) => createUniAppXPlugins({
7431
+ appType: "uni-app-x",
7432
+ customAttributesEntities: context.customAttributesEntities,
7433
+ disabledDefaultTemplateHandler: context.disabledDefaultTemplateHandler,
7434
+ ensureRuntimeClassSet: context.ensureRuntimeClassSet,
7435
+ generateCss: context.generateCss,
7436
+ getResolvedConfig: context.getResolvedConfig,
7437
+ isEnabled: context.isEnabled,
7438
+ isIosPlatform: context.isIosPlatform,
7439
+ jsHandler: context.jsHandler,
7440
+ mainCssChunkMatcher: context.mainCssChunkMatcher,
7441
+ runtimeState: context.runtimeState,
7442
+ styleHandler: context.styleHandler,
7443
+ uniAppX: context.uniAppX
7444
+ })
7445
+ });
7446
+ }
7447
+ //#endregion
7448
+ //#region src/bundlers/vite/frameworks/weapp-vite/index.ts
7449
+ function createWeappVitePlugins(options = {}) {
7450
+ return createViteFrameworkPlugins(options, {
7451
+ frameworkName: "weapp-vite",
7452
+ styleInjectorDelegate: viteStyleInjectorDelegates.generic
7453
+ });
7454
+ }
7455
+ //#endregion
7456
+ //#region src/bundlers/vite/index.ts
7457
+ /**
7458
+ * @name WeappTailwindcss
7459
+ * @description Vite 入口只负责早期识别框架分支,具体插件组合由各 framework 目录拥有。
7460
+ * @link https://tw.icebreaker.top/docs/quick-start/frameworks/uni-app-vite
7461
+ */
7462
+ function WeappTailwindcss(options = {}) {
7463
+ const hasExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
7464
+ const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
7465
+ const opts = getCompilerContext({
7466
+ ...options,
7467
+ __internalDeferMissingCssEntriesWarning: true
7468
+ });
7469
+ opts.__internalViteRawOptions = options;
7470
+ opts.__internalViteRawExplicitAppType = hasExplicitAppType;
7471
+ opts.__internalViteRawExplicitTailwindcssBasedir = hasExplicitTailwindcssBasedir;
7472
+ switch (resolveViteFrameworkProfile({
7473
+ appType: opts.appType,
7474
+ detectEnv: true,
7475
+ env: process$1.env,
7476
+ root: opts.tailwindcssBasedir ?? process$1.cwd(),
7477
+ uniAppX: opts.uniAppX
7478
+ }).frameworkName) {
7479
+ case "taro": return createTaroVitePlugins(opts);
7480
+ case "uni-app": return createUniAppVitePlugins(opts);
7481
+ case "uni-app-x": return createUniAppXVitePlugins(opts);
7482
+ case "weapp-vite": return createWeappVitePlugins(opts);
7483
+ default: return createGenericVitePlugins(opts);
7484
+ }
7485
+ }
7486
+ //#endregion
6945
7487
  export { WeappTailwindcss as t };