weapp-tailwindcss 5.0.6 → 5.0.7

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 (103) hide show
  1. package/dist/{bundle-state-CFgzVHFP.js → bundle-state-BzwPS-UI.js} +2 -1
  2. package/dist/{bundle-state-CdNXQl-o.mjs → bundle-state-ChcOKb9w.mjs} +2 -1
  3. package/dist/bundlers/gulp/index.d.ts +3 -4
  4. package/dist/bundlers/gulp/module-graph.d.ts +2 -0
  5. package/dist/bundlers/gulp/runtime-snapshot.d.ts +5 -0
  6. package/dist/bundlers/gulp/vinyl-transform.d.ts +3 -0
  7. package/dist/bundlers/shared/css-cleanup.d.ts +1 -1
  8. package/dist/bundlers/shared/css-source-trace.d.ts +20 -0
  9. package/dist/bundlers/shared/generator-css/directives/fallback.d.ts +11 -0
  10. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +56 -0
  11. package/dist/bundlers/shared/generator-css/local-imports.d.ts +7 -0
  12. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +1 -1
  13. package/dist/bundlers/shared/generator-css/types.d.ts +27 -0
  14. package/dist/bundlers/shared/generator-css/user-css.d.ts +26 -0
  15. package/dist/bundlers/shared/generator-css/validate.d.ts +5 -0
  16. package/dist/bundlers/shared/generator-css.d.ts +4 -32
  17. package/dist/bundlers/vite/css-finalizer.d.ts +3 -0
  18. package/dist/bundlers/vite/generate-bundle/css-config-directives.d.ts +2 -0
  19. package/dist/bundlers/vite/generate-bundle/css-output.d.ts +14 -0
  20. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +11 -0
  21. package/dist/bundlers/vite/generate-bundle/sfc-style-source.d.ts +9 -0
  22. package/dist/bundlers/vite/generate-bundle/style-matching.d.ts +5 -0
  23. package/dist/bundlers/vite/generate-bundle/subpackages.d.ts +7 -0
  24. package/dist/bundlers/vite/generate-bundle/types.d.ts +68 -0
  25. package/dist/bundlers/vite/generate-bundle.d.ts +4 -62
  26. package/dist/bundlers/vite/incremental-runtime-class-set/entries.d.ts +4 -0
  27. package/dist/bundlers/vite/incremental-runtime-class-set/escaped-candidates.d.ts +2 -0
  28. package/dist/bundlers/vite/incremental-runtime-class-set/v3-candidates.d.ts +13 -0
  29. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +1 -0
  30. package/dist/bundlers/vite/processed-css-assets/css-rules.d.ts +17 -0
  31. package/dist/bundlers/vite/processed-css-assets.d.ts +2 -0
  32. package/dist/bundlers/vite/source-candidates/scan-root.d.ts +10 -0
  33. package/dist/bundlers/vite/source-candidates/script.d.ts +7 -0
  34. package/dist/bundlers/vite/source-candidates/tailwind-v3-default-extractor.d.ts +1 -0
  35. package/dist/bundlers/vite/source-candidates.d.ts +8 -3
  36. package/dist/bundlers/vite/source-scan/css-entries.d.ts +20 -0
  37. package/dist/bundlers/vite/source-scan/dependencies.d.ts +2 -0
  38. package/dist/bundlers/vite/source-scan.d.ts +2 -12
  39. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/helpers.d.ts +48 -0
  40. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -20
  41. package/dist/cli.js +69 -69
  42. package/dist/cli.mjs +69 -69
  43. package/dist/core.js +1 -1
  44. package/dist/core.mjs +1 -1
  45. package/dist/{defaults-BPUuNYcD.js → defaults-Boc26eel.js} +1 -0
  46. package/dist/{defaults-8xrgzxFY.mjs → defaults-DH0ZQRhy.mjs} +1 -0
  47. package/dist/defaults.js +1 -1
  48. package/dist/defaults.mjs +1 -1
  49. package/dist/{generator-C56PJYxA.js → generator-6yF8wjxR.js} +1 -1
  50. package/dist/{generator-Bgn4m8An.mjs → generator-BON6M1bL.mjs} +1 -1
  51. package/dist/generator.js +2 -2
  52. package/dist/generator.mjs +2 -2
  53. package/dist/gulp-_7p1Z2vc.js +473 -0
  54. package/dist/gulp-oE-Byqk6.mjs +463 -0
  55. package/dist/gulp.js +4 -414
  56. package/dist/gulp.mjs +1 -406
  57. package/dist/{incremental-runtime-class-set-Bmzdjlk0.js → hmr-timing-BKQNRxHr.js} +1205 -449
  58. package/dist/{incremental-runtime-class-set-BEYHQkZc.mjs → hmr-timing-BVTGf5ch.mjs} +1169 -467
  59. package/dist/index.js +5 -5
  60. package/dist/index.mjs +5 -5
  61. package/dist/{postcss-B7QNe78h.js → postcss-BTIunhWl.js} +7 -7
  62. package/dist/{postcss-BgINK7Nm.mjs → postcss-BtmrrZ31.mjs} +4 -4
  63. package/dist/postcss.js +1 -1
  64. package/dist/postcss.mjs +1 -1
  65. package/dist/{precheck-Copn2SqE.mjs → precheck-CZjr87m_.mjs} +19 -5
  66. package/dist/{precheck-CyPbGn38.js → precheck-fhIkzCSU.js} +19 -5
  67. package/dist/presets.js +2 -2
  68. package/dist/presets.mjs +2 -2
  69. package/dist/tailwindcss/source-scan/inline-source.d.ts +7 -0
  70. package/dist/tailwindcss/source-scan.d.ts +2 -7
  71. package/dist/tailwindcss/v3-engine/generator/cache-key.d.ts +3 -0
  72. package/dist/tailwindcss/v3-engine/generator/content.d.ts +10 -0
  73. package/dist/tailwindcss/v3-engine/generator/runtime-ready.d.ts +2 -0
  74. package/dist/tailwindcss/v4-engine/generator/css-compat.d.ts +2 -0
  75. package/dist/tailwindcss/v4-engine/generator/rpx-candidates.d.ts +6 -0
  76. package/dist/tailwindcss/v4-engine/generator/scan-sources.d.ts +2 -0
  77. package/dist/tailwindcss/v4-engine/types.d.ts +1 -1
  78. package/dist/{tailwindcss-C0Zgo3Es.mjs → tailwindcss-bbQUg25J.mjs} +2 -2
  79. package/dist/{tailwindcss-Tw6CSVHL.js → tailwindcss-vswd1gc3.js} +2 -2
  80. package/dist/{transform-95ivJthq.js → transform-CReJxxh_.js} +11 -2
  81. package/dist/{transform-DgCFGtQR.mjs → transform-DEsFlG9k.mjs} +11 -2
  82. package/dist/types/typedoc-tailwindcss-patch.d.ts +4 -2
  83. package/dist/types/user-defined-options/general.d.ts +5 -0
  84. package/dist/uni-app-x/component-local-style.d.ts +1 -0
  85. package/dist/uni-app-x/harmony.d.ts +1 -0
  86. package/dist/uni-app-x/style-asset/style-value.d.ts +16 -0
  87. package/dist/uni-app-x/style-asset.d.ts +20 -0
  88. package/dist/uni-app-x/transform.d.ts +1 -0
  89. package/dist/uni-app-x/vite.d.ts +1 -0
  90. package/dist/{v3-engine-6FVAcrZl.js → v3-engine-CEMXFegG.js} +758 -708
  91. package/dist/{v3-engine-Ji6AXPh2.mjs → v3-engine-CdIwmHuc.mjs} +756 -706
  92. package/dist/{vite-Bw6LOXvf.js → vite-0jFbh9hx.js} +1797 -386
  93. package/dist/{vite-ChZ2cbn4.mjs → vite-C7BGAlCE.mjs} +1779 -369
  94. package/dist/vite.js +1 -1
  95. package/dist/vite.mjs +1 -1
  96. package/dist/weapp-tw-css-import-rewrite-loader.js +1104 -980
  97. package/dist/{webpack-CMJ7iqN7.mjs → webpack-Dx6_eg5k.mjs} +96 -36
  98. package/dist/{webpack-nn3P8_S_.js → webpack-aEuDoYfQ.js} +105 -44
  99. package/dist/webpack.js +1 -1
  100. package/dist/webpack.mjs +1 -1
  101. package/package.json +7 -6
  102. package/dist/source-candidates-BODCmzz5.mjs +0 -355
  103. package/dist/source-candidates-Caf2GDvx.js +0 -374
@@ -1,13 +1,16 @@
1
- import { A as normalizeTailwindV3CssEntrySource, B as splitTailwindV4GeneratedCssBySourceOrder, E as hasTailwindSourceDirectives, F as createCssAppend, G as prependConfigDirective, H as stripTailwindBanner, I as hasTailwindGeneratedCss, L as hasTailwindGeneratedCssMarkers, M as removeTailwindSourceDirectives, N as resolveCssEntrySource, O as normalizeTailwindSourceDirectives, P as VITE_MARKER_RE, R as splitGeneratorPlaceholderCssBySourceOrder, S as resolveTailwindV4SourceOptionsFromPatcher, T as hasTailwindRootDirectives, U as stripTailwindBanners, V as stripGeneratorPlaceholderMarkers, W as normalizeConfigDirective, X as loadTailwindV4DesignSystem, Y as filterUnsupportedMiniProgramTailwindV4Candidates, gt as omitUndefined, h as resolveTailwindV4EntriesFromCss, j as parseImportRequest, l as getRuntimeClassSetSignature, lt as createDebug, n as resolveTailwindV3SourceFromPatcher, r as resolveTailwindV3SourceOptionsFromPatcher, rt as normalizeLegacyContentEntries, st as resolveTailwindV4CssSourceBase, t as resolveTailwindV3Source, w as hasTailwindApplyDirective, x as resolveTailwindV4SourceFromPatcher, y as resolveTailwindV4Source$1, z as splitTailwindGeneratedCssByBanner } from "./v3-engine-Ji6AXPh2.mjs";
2
- import { i as normalizeWeappTailwindcssGeneratorOptions, t as createWeappTailwindcssGenerator } from "./generator-Bgn4m8An.mjs";
3
- import { p as replaceWxml, r as resolveStyleOptionsFromContext } from "./precheck-Copn2SqE.mjs";
4
- import { r as isUniAppXEnabled } from "./tailwindcss-C0Zgo3Es.mjs";
5
- import { existsSync, readFileSync } from "node:fs";
1
+ import { A as normalizeTailwindV3CssEntrySource, B as splitTailwindV4GeneratedCssBySourceOrder, E as hasTailwindSourceDirectives, F as createCssAppend, G as prependConfigDirective, H as stripTailwindBanner, I as hasTailwindGeneratedCss, L as hasTailwindGeneratedCssMarkers, M as removeTailwindSourceDirectives, N as resolveCssEntrySource, O as normalizeTailwindSourceDirectives, P as VITE_MARKER_RE, Q as FULL_SOURCE_SCAN_EXTENSION_RE, R as splitGeneratorPlaceholderCssBySourceOrder, S as resolveTailwindV4SourceOptionsFromPatcher, T as hasTailwindRootDirectives, U as stripTailwindBanners, V as stripGeneratorPlaceholderMarkers, W as normalizeConfigDirective, X as loadTailwindV4DesignSystem, Y as filterUnsupportedMiniProgramTailwindV4Candidates, at as resolveSourceScanPath, g as resolveTailwindV4EntriesFromCss, j as parseImportRequest, l as getRuntimeClassSetSignature, lt as createDebug, n as resolveTailwindV3SourceFromPatcher, nt as normalizeLegacyContentEntries, ot as resolveTailwindV4CssSourceBase, r as resolveTailwindV3SourceOptionsFromPatcher, st as toPosixPath$1, t as resolveTailwindV3Source, tt as isFileMatchedByTailwindSourceEntries, w as hasTailwindApplyDirective, x as resolveTailwindV4SourceFromPatcher, y as resolveTailwindV4Source$1, yt as omitUndefined, z as splitTailwindGeneratedCssByBanner } from "./v3-engine-CdIwmHuc.mjs";
2
+ import { i as normalizeWeappTailwindcssGeneratorOptions, t as createWeappTailwindcssGenerator } from "./generator-BON6M1bL.mjs";
3
+ import { h as traverse, m as babelParse, p as replaceWxml, r as resolveStyleOptionsFromContext } from "./precheck-CZjr87m_.mjs";
4
+ import { r as isUniAppXEnabled } from "./tailwindcss-bbQUg25J.mjs";
5
+ import { createRequire } from "node:module";
6
6
  import postcss from "postcss";
7
- import { extractRawCandidatesWithPositions, extractSourceCandidates, extractValidCandidates, resolveValidTailwindV4Candidates } from "tailwindcss-patch";
7
+ import { extractRawCandidatesWithPositions, extractSourceCandidates, extractValidCandidates, resolveProjectSourceFiles, resolveValidTailwindV4Candidates, splitCandidateTokens } from "tailwindcss-patch";
8
8
  import process from "node:process";
9
+ import { existsSync, readFileSync } from "node:fs";
9
10
  import path from "node:path";
10
- import { finalizeMiniProgramCss, removeUnsupportedMiniProgramAtRules } from "@weapp-tailwindcss/postcss";
11
+ import { readFile } from "node:fs/promises";
12
+ import { finalizeMiniProgramCss, pruneMiniProgramGeneratedCss, removeUnsupportedMiniProgramAtRules } from "@weapp-tailwindcss/postcss";
13
+ import { MappingChars2String, unescape } from "@weapp-core/escape";
11
14
  //#region src/bundlers/shared/cache.ts
12
15
  async function processCachedTask({ cache, cacheKey, hashKey = cacheKey, rawSource, hash, readCache, applyResult, transform, onCacheHit }) {
13
16
  let cacheHit = false;
@@ -27,6 +30,199 @@ async function processCachedTask({ cache, cacheKey, hashKey = cacheKey, rawSourc
27
30
  if (!cacheHit) await applyResult(result, { cacheHit: false });
28
31
  }
29
32
  //#endregion
33
+ //#region src/bundlers/shared/css-source-trace.ts
34
+ const CSS_SOURCE_TRACE_COMMENT_RE = /^\s*tokens:\s/;
35
+ const TAILWIND_GENERATED_CONTAINER_TRACE_COMMENT_RE = /^\s*tokens:\s*container\s*<=\s*<tailwind generated>\s*$/i;
36
+ function normalizeSelectorTokenCandidate(candidate) {
37
+ return candidate.replace(/(?<!\\)\\:/g, ":").replace(/(?<!\\)\\\//g, "/");
38
+ }
39
+ function normalizeSourcePath(source, root) {
40
+ const resolvedRoot = path.resolve(root);
41
+ const resolvedSource = path.resolve(source);
42
+ const relative = path.relative(resolvedRoot, resolvedSource);
43
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return relative.split(path.sep).join("/");
44
+ return source.split(path.sep).join("/");
45
+ }
46
+ function getSourceTraceRoot(opts) {
47
+ const configured = opts.cssSourceTrace;
48
+ if (configured && typeof configured === "object" && configured.root) return configured.root;
49
+ return opts.tailwindcssBasedir ?? process.cwd();
50
+ }
51
+ function isCssSourceTraceEnabled(opts) {
52
+ return opts.cssSourceTrace === true || typeof opts.cssSourceTrace === "object" && opts.cssSourceTrace !== null;
53
+ }
54
+ function createCssTokenSourceMap(sourcesByToken, opts) {
55
+ const root = getSourceTraceRoot(opts);
56
+ const tokenSources = /* @__PURE__ */ new Map();
57
+ for (const [token, sources] of [...sourcesByToken.entries()].sort(([a], [b]) => a.localeCompare(b))) {
58
+ const source = {
59
+ token,
60
+ sources: [...sources].map((file) => normalizeSourcePath(file, root)).sort()
61
+ };
62
+ tokenSources.set(token, source);
63
+ const escaped = replaceWxml(token, { escapeMap: opts.escapeMap });
64
+ tokenSources.set(escaped, source);
65
+ tokenSources.set(escaped.replaceAll("\\", ""), source);
66
+ }
67
+ return tokenSources;
68
+ }
69
+ function createCssSourceTraceCacheSignature(tokenSources, opts) {
70
+ if (!isCssSourceTraceEnabled(opts)) return "css-source-trace:0";
71
+ if (!tokenSources?.size) return "css-source-trace:1:empty";
72
+ return `css-source-trace:1:${[...tokenSources.values()].map(({ token, sources }) => `${token}<=${sources.join(",")}`).sort().join("|")}`;
73
+ }
74
+ function getTokenSource(tokenSources, token) {
75
+ return tokenSources.get(token);
76
+ }
77
+ function collectRuleSourceTokens(rule, tokenSources) {
78
+ const tokens = /* @__PURE__ */ new Map();
79
+ for (const selector of rule.selectors) {
80
+ const classMatches = selector.matchAll(/\.((?:\\.|[^\s.#:[{>,])*)/g);
81
+ for (const match of classMatches) {
82
+ const rawCandidate = match[1];
83
+ if (!rawCandidate) continue;
84
+ const candidates = [normalizeSelectorTokenCandidate(rawCandidate), rawCandidate];
85
+ for (const candidate of candidates) {
86
+ const source = getTokenSource(tokenSources, candidate);
87
+ if (!source) continue;
88
+ tokens.set(source.token, source);
89
+ break;
90
+ }
91
+ }
92
+ }
93
+ return tokens;
94
+ }
95
+ function removeTracedTailwindGeneratedContainerRules(root) {
96
+ root.walkRules((rule) => {
97
+ if (!rule.selectors || rule.selectors.length !== 1 || rule.selectors[0] !== ".container") return;
98
+ const previous = rule.prev();
99
+ if (previous?.type !== "comment" || !TAILWIND_GENERATED_CONTAINER_TRACE_COMMENT_RE.test(previous.text)) return;
100
+ previous.remove();
101
+ rule.remove();
102
+ });
103
+ }
104
+ function annotateCssSourceTrace(css, options) {
105
+ if (!isCssSourceTraceEnabled(options.opts) || !options.tokenSources?.size) return css;
106
+ try {
107
+ const root = postcss.parse(css);
108
+ root.walkComments((comment) => {
109
+ if (CSS_SOURCE_TRACE_COMMENT_RE.test(comment.text)) comment.remove();
110
+ });
111
+ root.walkRules((rule) => {
112
+ const tokens = collectRuleSourceTokens(rule, options.tokenSources);
113
+ if (tokens.size === 0 || !rule.parent) return;
114
+ const lines = [...tokens.values()].map(({ token, sources }) => {
115
+ return `${token} <= ${sources.length > 0 ? sources.join(", ") : "<tailwind generated>"}`;
116
+ });
117
+ const comment = postcss.comment({ text: `tokens: ${lines.join(" | ")}` });
118
+ if (rule.raws.before !== void 0) comment.raws.before = rule.raws.before;
119
+ rule.raws.before = "\n";
120
+ rule.parent.insertBefore(rule, comment);
121
+ });
122
+ removeTracedTailwindGeneratedContainerRules(root);
123
+ return root.toString();
124
+ } catch {
125
+ return css;
126
+ }
127
+ }
128
+ //#endregion
129
+ //#region src/bundlers/shared/generator-css/generation-helpers.ts
130
+ function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight, options = {}) {
131
+ if (target !== "weapp") return css;
132
+ return finalizeMiniProgramCss(css, {
133
+ cssPreflight: majorVersion === 4 && options.injectPreflight !== false ? cssPreflight : void 0,
134
+ isTailwindcssV4: majorVersion === 4,
135
+ preservePseudoContentInit: majorVersion === 3
136
+ });
137
+ }
138
+ function shouldInjectMiniProgramPreflightForGeneratorCss(opts, options) {
139
+ if (options.cssHandlerOptions.uniAppX === true && options.cssHandlerOptions.uniAppXCssTarget === "uvue") return false;
140
+ if (!options.isolateCurrentCssCandidates) return true;
141
+ return isUniAppXEnabled(opts.uniAppX) && Boolean(options.localImports?.trim());
142
+ }
143
+ function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
144
+ if (options.isolateCssSource && options.currentCssCandidates?.length) return new Set([...scopedRuntime, ...options.currentCssCandidates]);
145
+ if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.matchedCssSourceFile || options.isolateCssSource && scopedRuntime.size === 0) return scopedRuntime;
146
+ return new Set([...scopedRuntime, ...runtime]);
147
+ }
148
+ function shouldIsolateScopedCssSource(source, sourceEntries) {
149
+ return Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile) || sourceEntries !== void 0 && sourceEntries.length > 0;
150
+ }
151
+ function shouldIsolateCurrentTailwindV4CssCandidates(majorVersion, cssHandlerOptions, options) {
152
+ return majorVersion === 4 && !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(options.rawSource) && !hasTailwindRootDirectives(options.rawSource) && !options.hasGeneratedCss && !options.hasGeneratedMarkers;
153
+ }
154
+ function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
155
+ if (majorVersion !== 4) return false;
156
+ if (target === "web") return true;
157
+ if (isolateCssSource) return false;
158
+ return generatorRuntime.size === 0;
159
+ }
160
+ function shouldAppendWebBundleCssFallback(target, options) {
161
+ return target === "web" && !options.hasMatchedCssSourceFile && !options.hasSourceDirectives;
162
+ }
163
+ function isEmptyCssSourceOrderParts(parts) {
164
+ return parts.before.trim().length === 0 && parts.after.trim().length === 0;
165
+ }
166
+ function resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorStyleOptions) {
167
+ const preflightStyleOptions = {
168
+ cssPreflight: opts.cssPreflight,
169
+ cssPreflightRange: opts.cssPreflightRange
170
+ };
171
+ return {
172
+ ...resolveStyleOptionsFromContext(opts),
173
+ atRules: opts.atRules,
174
+ uniAppXCssTarget: opts.uniAppXCssTarget,
175
+ uniAppXUnsupported: opts.uniAppXUnsupported,
176
+ ...cssHandlerOptions,
177
+ ...preflightStyleOptions,
178
+ ...generatorStyleOptions
179
+ };
180
+ }
181
+ function createCssSourceOrderAppend$1(base, extra) {
182
+ if (!base) return extra;
183
+ if (!extra) return base;
184
+ if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
185
+ return `${base}\n${extra}`;
186
+ }
187
+ function shouldFinalizeMarkedUserLayerComponentsCss(file) {
188
+ return !/\.(?:vue|svelte|astro|scss|sass|less|styl)(?:[?#].*)?$/i.test(file);
189
+ }
190
+ function splitRawSourceByGeneratedCssOrder(rawSource, rawTailwindCss) {
191
+ const placeholderParts = splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss);
192
+ if (placeholderParts) return placeholderParts;
193
+ const exactParts = splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss);
194
+ if (exactParts) return exactParts;
195
+ return splitTailwindGeneratedCssByBanner(rawSource);
196
+ }
197
+ function shouldUseGeneratorForCurrentCss(majorVersion, cssHandlerOptions, options) {
198
+ const hasApplyDirectives = hasTailwindApplyDirective(options.rawSource);
199
+ return options.hasGeneratedCss || options.hasGeneratedMarkers || options.hasSourceDirectives || majorVersion === 4 && hasApplyDirectives || cssHandlerOptions.isMainChunk;
200
+ }
201
+ function createRuntimeWithCurrentCssCandidates(runtime, currentCssCandidates, isolateCurrentCssCandidates) {
202
+ return isolateCurrentCssCandidates ? new Set(currentCssCandidates) : currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
203
+ }
204
+ function mergeGeneratorResults(generatedResults) {
205
+ const firstGenerated = generatedResults[0];
206
+ if (!firstGenerated) return;
207
+ if (generatedResults.length === 1) return firstGenerated;
208
+ const incrementalCssResults = generatedResults.map((item) => item.incrementalCss).filter((css) => typeof css === "string");
209
+ const incrementalRawCssResults = generatedResults.map((item) => item.incrementalRawCss).filter((css) => typeof css === "string");
210
+ return {
211
+ ...firstGenerated,
212
+ css: generatedResults.map((item) => item.css).join("\n"),
213
+ rawCss: generatedResults.map((item) => item.rawCss).join("\n"),
214
+ incrementalCss: incrementalCssResults.length === generatedResults.length ? incrementalCssResults.filter(Boolean).join("\n") : void 0,
215
+ incrementalRawCss: incrementalRawCssResults.length === generatedResults.length ? incrementalRawCssResults.filter(Boolean).join("\n") : void 0,
216
+ classSet: new Set(generatedResults.flatMap((item) => [...item.classSet])),
217
+ dependencies: [...new Set(generatedResults.flatMap((item) => item.dependencies))],
218
+ sources: generatedResults.flatMap((item) => item.sources)
219
+ };
220
+ }
221
+ const SUPPORTED_GENERATOR_MAJOR_VERSIONS$1 = new Set([3, 4]);
222
+ function isSupportedGeneratorMajorVersion(majorVersion) {
223
+ return SUPPORTED_GENERATOR_MAJOR_VERSIONS$1.has(majorVersion ?? 0);
224
+ }
225
+ //#endregion
30
226
  //#region src/bundlers/shared/generator-css/legacy-selectors.ts
31
227
  const CLASS_SELECTOR_RE = /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i;
32
228
  const MINI_PROGRAM_THEME_SCOPE_SELECTORS = new Set([
@@ -263,13 +459,6 @@ function isPathWithinRoot$1(file, root) {
263
459
  const relative = path.relative(root, file);
264
460
  return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
265
461
  }
266
- function countCommonSuffixSegments(a, b) {
267
- const aSegments = a.split("/").filter(Boolean);
268
- const bSegments = b.split("/").filter(Boolean);
269
- let count = 0;
270
- while (count < aSegments.length && count < bSegments.length && aSegments[aSegments.length - 1 - count] === bSegments[bSegments.length - 1 - count]) count++;
271
- return count;
272
- }
273
462
  function collectOutputMatchBases(file, sourceOptions) {
274
463
  const normalizedFile = file.replace(/[?#].*$/, "");
275
464
  const roots = [
@@ -304,7 +493,7 @@ function isMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
304
493
  const normalizedRoot = path.resolve(root);
305
494
  if (isPathWithinRoot$1(normalizedSourceFile, normalizedRoot)) addSourceBase(path.relative(normalizedRoot, normalizedSourceFile));
306
495
  }
307
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`) || countCommonSuffixSegments(outputBase, sourceBase) >= 2) return true;
496
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`)) return true;
308
497
  return false;
309
498
  }
310
499
  function scoreMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
@@ -322,13 +511,9 @@ function scoreMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
322
511
  if (isPathWithinRoot$1(normalizedSourceFile, normalizedRoot)) addSourceBase(path.relative(normalizedRoot, normalizedSourceFile));
323
512
  }
324
513
  let bestScore = 0;
325
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) {
326
- const commonSuffixSegments = countCommonSuffixSegments(outputBase, sourceBase);
327
- if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
328
- else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
329
- else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
330
- else if (commonSuffixSegments >= 2) bestScore = Math.max(bestScore, 100 + commonSuffixSegments);
331
- }
514
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
515
+ else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
516
+ else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
332
517
  return bestScore;
333
518
  }
334
519
  function collectMatchedConfiguredSourceFiles(file, sourceOptions) {
@@ -487,7 +672,7 @@ function canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) {
487
672
  return true;
488
673
  }
489
674
  function shouldResolveSourceSideCssEntry(rawSource) {
490
- return rawSource.includes("@apply") || hasTailwindGeneratedCss(rawSource) || hasTailwindGeneratedCssMarkers(rawSource);
675
+ return rawSource.includes("@apply") || hasTailwindRootDirectives(rawSource, { importFallback: true }) || hasTailwindSourceDirectives(rawSource, { importFallback: true }) || hasTailwindGeneratedCss(rawSource) || hasTailwindGeneratedCssMarkers(rawSource);
491
676
  }
492
677
  function shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) {
493
678
  return Boolean(sourceSideEntrySource) && !hasTailwindSourceDirectives(rawSource, { importFallback: true });
@@ -532,17 +717,6 @@ function collectCssSourceMatchBases(file, roots) {
532
717
  } else for (const root of resolvedRoots) addBase(path.resolve(root, normalizedFile));
533
718
  return bases;
534
719
  }
535
- function hasMatchingCssSourceBase(outputBases, sourceBases) {
536
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`)) return true;
537
- return false;
538
- }
539
- function isMatchingTailwindV4CssSourceFile(file, cssSourceFile, sourceOptions) {
540
- return hasMatchingCssSourceBase(collectCssSourceMatchBases(file, [
541
- sourceOptions.outputRoot,
542
- sourceOptions.projectRoot,
543
- sourceOptions.cwd
544
- ]), collectCssSourceMatchBases(cssSourceFile, [sourceOptions.projectRoot, sourceOptions.cwd]));
545
- }
546
720
  function scoreTailwindV4CssSourceFileMatch(file, cssSourceFile, sourceOptions) {
547
721
  const outputBases = collectCssSourceMatchBases(file, [
548
722
  sourceOptions.outputRoot,
@@ -629,12 +803,29 @@ async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOpt
629
803
  if (!cssSources?.length) return;
630
804
  const normalizedRawSource = normalizeCssSourceForCompare(rawSource);
631
805
  const sourceFile = resolvePostcssSourceFile(cssHandlerOptions);
632
- const matchingSource = cssSources.find((cssSource) => {
633
- if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return false;
634
- if (sourceFile && typeof cssSource.file === "string" && path.resolve(sourceFile) === path.resolve(cssSource.file)) return true;
635
- if (typeof cssSource.file === "string" && isMatchingTailwindV4CssSourceFile(file, cssSource.file, sourceOptions)) return true;
636
- return normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource;
637
- });
806
+ const matches = cssSources.map((cssSource, index) => {
807
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return;
808
+ if (sourceFile && typeof cssSource.file === "string" && path.resolve(sourceFile) === path.resolve(cssSource.file)) return {
809
+ cssSource,
810
+ index,
811
+ score: 1e6
812
+ };
813
+ if (typeof cssSource.file === "string") {
814
+ const pathScore = scoreTailwindV4CssSourceFileMatch(file, cssSource.file, sourceOptions);
815
+ if (pathScore > 0) return {
816
+ cssSource,
817
+ index,
818
+ score: pathScore
819
+ };
820
+ }
821
+ if (normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource) return {
822
+ cssSource,
823
+ index,
824
+ score: 1
825
+ };
826
+ }).filter((match) => Boolean(match)).sort((a, b) => b.score - a.score || a.index - b.index);
827
+ const bestScore = matches[0]?.score;
828
+ const matchingSource = bestScore && matches.filter((match) => match.score === bestScore).length === 1 ? matches[0]?.cssSource : void 0;
638
829
  if (!matchingSource) return;
639
830
  return resolveSingleTailwindV4CssSource(matchingSource, sourceOptions, { matched: true });
640
831
  }
@@ -706,7 +897,10 @@ function createTailwindV4CssSourceResolver(sourceOptions, generatorOptions) {
706
897
  async function resolveTailwindV4SourceSideEntrySource(resolvedEntrySource, sourceOptions, generatorOptions, file) {
707
898
  if (!resolvedEntrySource) return;
708
899
  const resolvedSourceOptions = omitUndefined(sourceOptions);
709
- const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, resolvedSourceOptions);
900
+ const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, {
901
+ ...resolvedSourceOptions,
902
+ sourceFile: resolvedEntrySource.file
903
+ });
710
904
  const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions);
711
905
  return withMatchedSourceSideMetadata(await resolveTailwindV4Source$1(createSingleTailwindV4SourceOptions(resolvedSourceOptions, {
712
906
  base: resolvedEntrySource.base,
@@ -737,7 +931,25 @@ function withMatchedSourceSideMetadata(source, resolvedEntrySource) {
737
931
  }
738
932
  function createTailwindV4ApplyReferenceSource(css, sourceOptions) {
739
933
  if (!hasTailwindApplyDirective(css) || hasTailwindRootDirectives(css)) return css;
740
- return `@import "${sourceOptions.packageName ?? "tailwindcss"}" source(none);\n${css}`;
934
+ const utilities = collectTailwindApplyUtilities(css);
935
+ return [
936
+ `@import "${sourceOptions.packageName ?? "tailwindcss"}" source(none);`,
937
+ utilities.length > 0 ? `@source inline(${JSON.stringify(utilities.join(" "))});` : void 0,
938
+ css
939
+ ].filter(Boolean).join("\n");
940
+ }
941
+ function collectTailwindApplyUtilities(css) {
942
+ let root;
943
+ try {
944
+ root = postcss.parse(css);
945
+ } catch {
946
+ return [];
947
+ }
948
+ const utilities = /* @__PURE__ */ new Set();
949
+ root.walkAtRules("apply", (rule) => {
950
+ for (const utility of splitCandidateTokens(rule.params)) utilities.add(utility);
951
+ });
952
+ return [...utilities].sort();
741
953
  }
742
954
  async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions) {
743
955
  const base = resolveCssSourceBase(file, cssHandlerOptions);
@@ -850,11 +1062,15 @@ async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, fi
850
1062
  return resolved ? [resolved] : [];
851
1063
  }
852
1064
  const matchedCssEntrySource = sourceOptions ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
1065
+ if (matchedCssEntrySource) return [generatorOptions?.config ? {
1066
+ ...matchedCssEntrySource,
1067
+ css: prependConfigDirective(matchedCssEntrySource.css, generatorOptions.config)
1068
+ } : matchedCssEntrySource];
1069
+ const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource((shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) && (sourceOptions.cssEntries?.length ?? 0) <= 1) && canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
1070
+ if (sourceSideCssSource) return [sourceSideCssSource];
853
1071
  const matchedCssSource = await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions);
854
1072
  const candidateMatchedCssSource = await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions);
855
- const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource((shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) && (sourceOptions.cssEntries?.length ?? 0) <= 1) && canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
856
1073
  const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource;
857
- if (sourceSideCssSource) return [sourceSideCssSource];
858
1074
  if (preferredCssEntrySource) return [generatorOptions?.config ? {
859
1075
  ...preferredCssEntrySource,
860
1076
  css: prependConfigDirective(preferredCssEntrySource.css, generatorOptions.config)
@@ -1032,6 +1248,27 @@ function resolveLegacyCompatCssSource(rawSource) {
1032
1248
  setLimitedCacheValue(legacyCompatSourceCache, rawSource, resolved);
1033
1249
  return resolved;
1034
1250
  }
1251
+ function removeMiniProgramContainerCompatCss(css) {
1252
+ try {
1253
+ const root = postcss.parse(css);
1254
+ let removed = false;
1255
+ root.walkRules((rule) => {
1256
+ if (rule.selectors?.length === 1 && rule.selectors[0] === ".container") {
1257
+ rule.remove();
1258
+ removed = true;
1259
+ }
1260
+ });
1261
+ root.walkAtRules((atRule) => {
1262
+ if (atRule.nodes && atRule.nodes.length === 0) {
1263
+ atRule.remove();
1264
+ removed = true;
1265
+ }
1266
+ });
1267
+ return removed ? root.toString() : css;
1268
+ } catch {
1269
+ return css;
1270
+ }
1271
+ }
1035
1272
  function hasContainerConfigToken(rawSource) {
1036
1273
  return rawSource.includes("@config") && /\bcontainer\b/.test(rawSource);
1037
1274
  }
@@ -1060,7 +1297,8 @@ function hasConfiguredContainerCompatSources(sources) {
1060
1297
  return sources.some((source) => hasConfiguredContainerCompatSource(source));
1061
1298
  }
1062
1299
  async function appendLegacyCompatCss(css, rawSource, generatorTarget, styleHandler, cssHandlerOptions, generatorStyleOptions) {
1063
- const compatSource = removeGeneratedSelectorCompatCss(resolveLegacyCompatCssSource(rawSource), css);
1300
+ const resolvedCompatSource = resolveLegacyCompatCssSource(rawSource);
1301
+ const compatSource = removeGeneratedSelectorCompatCss(generatorTarget === "weapp" ? removeMiniProgramContainerCompatCss(resolvedCompatSource) : resolvedCompatSource, css);
1064
1302
  if (compatSource.trim().length === 0) return css;
1065
1303
  if (generatorTarget !== "weapp") return createCssAppend(css, compatSource);
1066
1304
  const styleOptions = {
@@ -1078,6 +1316,7 @@ async function appendLegacyCompatCss(css, rawSource, generatorTarget, styleHandl
1078
1316
  return createCssAppend(css, cleanedCompatCss);
1079
1317
  }
1080
1318
  async function appendLegacyContainerCompatCss(css, rawSource, file, runtime, configuredContainerCompat, generatorTarget, styleHandler, cssHandlerOptions, generatorStyleOptions) {
1319
+ if (generatorTarget === "weapp") return css;
1081
1320
  const compatSource = resolveLegacyCompatCssSource(rawSource);
1082
1321
  const shouldAppendContainer = runtime.has("container") || hasConfiguredContainerCompat(rawSource, file, cssHandlerOptions) || configuredContainerCompat || collectGeneratedSelectors(compatSource).has(".container");
1083
1322
  if (generatorTarget !== "weapp" || !shouldAppendContainer || collectGeneratedSelectors(css).has(".container")) return css;
@@ -1140,128 +1379,97 @@ function inheritLegacyUnitConvertedDeclarations(css, legacyCss) {
1140
1379
  }
1141
1380
  }
1142
1381
  //#endregion
1143
- //#region src/bundlers/shared/generator-css/user-layer-order.ts
1144
- const USER_LAYER_COMPONENTS_START = "/*! weapp-tailwindcss layer components start */";
1145
- const USER_LAYER_COMPONENTS_END = "/*! weapp-tailwindcss layer components end */";
1146
- const UTILITY_LAYER_INSERTION_RES = [
1147
- /(^|\n)\.(?:fixed|absolute|relative|sticky|static)\s*\{/,
1148
- /(^|\n)\.(?:block|inline-block|inline|flex|inline-flex|grid|hidden)\s*\{/,
1149
- /(^|\n)\.(?:m|mx|my|mt|mr|mb|ml|p|px|py|pt|pr|pb|pl)-/,
1150
- /(^|\n)\.(?:w|h|min-w|min-h|max-w|max-h)-/,
1151
- /(^|\n)\.(?:bg|text|border|rounded|shadow|opacity|transition|transform|translate|scale|rotate|gap|items|justify|content)-/
1152
- ];
1153
- function appendCss(base, extra) {
1382
+ //#region src/bundlers/shared/generator-css/local-imports.ts
1383
+ const REMOTE_IMPORT_RE = /^(?:https?:)?\/\//i;
1384
+ function createCssSourceOrderAppend(base, extra) {
1154
1385
  if (!base) return extra;
1155
1386
  if (!extra) return base;
1156
1387
  if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1157
1388
  return `${base}\n${extra}`;
1158
1389
  }
1159
- function removeFirstCssOccurrence(css, chunk) {
1160
- const trimmed = chunk.trim();
1161
- if (!trimmed) return css;
1162
- const index = css.indexOf(trimmed);
1163
- if (index === -1) return css;
1164
- return appendCss(css.slice(0, index).trimEnd(), css.slice(index + trimmed.length).trimStart());
1390
+ function isLocalImportRequest(request) {
1391
+ return request.length > 0 && !request.startsWith("#") && !request.startsWith("tailwindcss") && !request.startsWith("weapp-tailwindcss") && !request.startsWith("data:") && !REMOTE_IMPORT_RE.test(request);
1165
1392
  }
1166
- function collectSelectorsFromCss(css) {
1167
- const selectors = /* @__PURE__ */ new Set();
1393
+ function isPureLocalCssImportWrapper(css) {
1394
+ let hasImport = false;
1168
1395
  try {
1169
- postcss.parse(css).walkRules((rule) => {
1170
- for (const selector of rule.selectors ?? [rule.selector]) {
1171
- const normalized = selector.trim();
1172
- if (normalized) selectors.add(normalized);
1173
- }
1174
- });
1175
- } catch {}
1176
- return selectors;
1396
+ const root = postcss.parse(css);
1397
+ for (const node of root.nodes) {
1398
+ if (node.type === "comment") continue;
1399
+ if (node.type !== "atrule" || node.name !== "import") return false;
1400
+ const request = parseImportRequest(node.params);
1401
+ if (!request || !isLocalImportRequest(request)) return false;
1402
+ hasImport = true;
1403
+ }
1404
+ } catch {
1405
+ return false;
1406
+ }
1407
+ return hasImport;
1177
1408
  }
1178
- function matchesLayerSelector(selector, layerSelector) {
1179
- if (selector === layerSelector) return true;
1180
- if (!selector.startsWith(layerSelector)) return false;
1181
- const next = selector[layerSelector.length];
1182
- return next === ":" || next === "[";
1409
+ function cleanLocalCssImportWrapperTailwindDirectives(css) {
1410
+ let hasLocalImport = false;
1411
+ let hasTailwindDirective = false;
1412
+ try {
1413
+ const root = postcss.parse(css);
1414
+ for (const node of root.nodes) {
1415
+ if (node.type === "comment") continue;
1416
+ if (node.type === "atrule" && node.name === "import") {
1417
+ const request = parseImportRequest(node.params);
1418
+ if (!request || !isLocalImportRequest(request)) return;
1419
+ hasLocalImport = true;
1420
+ continue;
1421
+ }
1422
+ if (node.type === "atrule" && node.name === "source") {
1423
+ hasTailwindDirective = true;
1424
+ continue;
1425
+ }
1426
+ return;
1427
+ }
1428
+ } catch {
1429
+ return;
1430
+ }
1431
+ return hasLocalImport && hasTailwindDirective ? prefixLocalCssImportsWithWebpackIgnore(removeTailwindSourceDirectives(css)) : void 0;
1183
1432
  }
1184
- function removeCssRulesForSelectors(css, layerCss) {
1185
- const selectors = [...collectSelectorsFromCss(layerCss)];
1186
- if (selectors.length === 0) return css;
1433
+ function prefixLocalCssImportsWithWebpackIgnore(css) {
1187
1434
  try {
1188
1435
  const root = postcss.parse(css);
1189
- root.walkRules((rule) => {
1190
- if ((rule.selectors ?? [rule.selector]).some((selector) => selectors.some((layerSelector) => matchesLayerSelector(selector.trim(), layerSelector)))) rule.remove();
1436
+ root.walkAtRules("import", (atRule) => {
1437
+ const request = parseImportRequest(atRule.params);
1438
+ if (request && isLocalImportRequest(request)) atRule.raws.before = `${atRule.raws.before ?? ""}/* webpackIgnore: true */\n`;
1191
1439
  });
1192
1440
  return root.toString();
1193
1441
  } catch {
1194
- return removeFirstCssOccurrence(css, layerCss);
1442
+ return css;
1195
1443
  }
1196
1444
  }
1197
- function wrapUserLayerComponentsCss(css) {
1198
- return css.trim().length > 0 ? `${USER_LAYER_COMPONENTS_START}\n${css}\n${USER_LAYER_COMPONENTS_END}` : css;
1199
- }
1200
- function extractMarkedUserLayerComponentsCss(css) {
1201
- const layers = [];
1202
- let rest = "";
1203
- let cursor = 0;
1204
- while (cursor < css.length) {
1205
- const startIndex = css.indexOf(USER_LAYER_COMPONENTS_START, cursor);
1206
- if (startIndex === -1) {
1207
- rest += css.slice(cursor);
1208
- break;
1445
+ function splitLocalCssImports(source) {
1446
+ try {
1447
+ const root = postcss.parse(source);
1448
+ const importRoot = postcss.root();
1449
+ let changed = false;
1450
+ for (const node of [...root.nodes]) {
1451
+ if (node.type !== "atrule" || node.name !== "import") continue;
1452
+ const request = parseImportRequest(node.params);
1453
+ if (!request || !isLocalImportRequest(request)) continue;
1454
+ importRoot.append(node.clone());
1455
+ node.remove();
1456
+ changed = true;
1209
1457
  }
1210
- rest += css.slice(cursor, startIndex);
1211
- const contentStart = startIndex + 47;
1212
- const endIndex = css.indexOf(USER_LAYER_COMPONENTS_END, contentStart);
1213
- if (endIndex === -1) {
1214
- rest += css.slice(startIndex);
1215
- break;
1216
- }
1217
- const layerCss = css.slice(contentStart, endIndex).trim();
1218
- if (layerCss) layers.push(layerCss);
1219
- cursor = endIndex + 45;
1220
- }
1221
- return {
1222
- layers,
1223
- rest
1224
- };
1225
- }
1226
- function findUtilityLayerInsertionIndex(css) {
1227
- let index = -1;
1228
- for (const pattern of UTILITY_LAYER_INSERTION_RES) {
1229
- const match = pattern.exec(css);
1230
- if (!match) continue;
1231
- const nextIndex = match.index + (match[1]?.length ?? 0);
1232
- index = index === -1 ? nextIndex : Math.min(index, nextIndex);
1458
+ const imports = importRoot.nodes.filter((node) => node.type === "atrule" && node.name === "import").map((node) => `@import ${node.params};`).join("\n");
1459
+ return changed ? {
1460
+ imports,
1461
+ source: root.toString()
1462
+ } : void 0;
1463
+ } catch {
1464
+ return;
1233
1465
  }
1234
- return index;
1235
- }
1236
- function reorderMarkedUserLayerComponentsCss(css) {
1237
- if (!css.includes(USER_LAYER_COMPONENTS_START)) return css;
1238
- const { layers, rest } = extractMarkedUserLayerComponentsCss(css);
1239
- if (layers.length === 0) return rest;
1240
- const layerCss = layers.join("\n");
1241
- const insertionIndex = findUtilityLayerInsertionIndex(rest);
1242
- if (insertionIndex === -1) return appendCss(rest, layerCss);
1243
- return appendCss(appendCss(rest.slice(0, insertionIndex), layerCss), rest.slice(insertionIndex));
1244
1466
  }
1245
- function mergeMarkedUserLayerComponentsCss(baseCss, markedCss) {
1246
- if (!markedCss.includes(USER_LAYER_COMPONENTS_START)) return {
1247
- css: baseCss,
1248
- merged: false
1249
- };
1250
- const { layers } = extractMarkedUserLayerComponentsCss(markedCss);
1251
- if (layers.length === 0) return {
1252
- css: baseCss,
1253
- merged: false
1254
- };
1255
- const layerCss = layers.join("\n");
1256
- return {
1257
- css: reorderMarkedUserLayerComponentsCss(appendCss(removeCssRulesForSelectors(baseCss, layerCss), wrapUserLayerComponentsCss(layerCss))),
1258
- merged: true
1259
- };
1467
+ function restoreLocalCssImports(css, imports) {
1468
+ if (!imports?.trim()) return css;
1469
+ return createCssSourceOrderAppend(imports, css);
1260
1470
  }
1261
1471
  //#endregion
1262
- //#region src/bundlers/shared/generator-css.ts
1263
- const SUPPORTED_GENERATOR_MAJOR_VERSIONS = new Set([3, 4]);
1264
- const REMOTE_IMPORT_RE = /^(?:https?:)?\/\//i;
1472
+ //#region src/bundlers/shared/generator-css/user-css.ts
1265
1473
  const TAILWIND_V4_GENERATOR_AT_RULES = new Set([
1266
1474
  "config",
1267
1475
  "custom-variant",
@@ -1271,30 +1479,6 @@ const TAILWIND_V4_GENERATOR_AT_RULES = new Set([
1271
1479
  "utility",
1272
1480
  "variant"
1273
1481
  ]);
1274
- function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight, options = {}) {
1275
- if (target !== "weapp") return css;
1276
- return finalizeMiniProgramCss(css, {
1277
- cssPreflight: majorVersion === 4 && options.injectPreflight !== false ? cssPreflight : void 0,
1278
- isTailwindcssV4: majorVersion === 4,
1279
- preservePseudoContentInit: majorVersion === 3
1280
- });
1281
- }
1282
- function shouldInjectMiniProgramPreflightForGeneratorCss(opts, options) {
1283
- if (options.cssHandlerOptions.uniAppX === true && options.cssHandlerOptions.uniAppXCssTarget === "uvue") return false;
1284
- if (!options.isolateCurrentCssCandidates) return true;
1285
- return isUniAppXEnabled(opts.uniAppX) && Boolean(options.localImports?.trim());
1286
- }
1287
- function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
1288
- if (options.isolateCssSource && options.currentCssCandidates?.length) return new Set([...scopedRuntime, ...options.currentCssCandidates]);
1289
- if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.matchedCssSourceFile || options.isolateCssSource && scopedRuntime.size === 0) return scopedRuntime;
1290
- return new Set([...scopedRuntime, ...runtime]);
1291
- }
1292
- function shouldIsolateScopedCssSource(source, sourceEntries) {
1293
- return Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile) || sourceEntries !== void 0 && sourceEntries.length > 0;
1294
- }
1295
- function shouldIsolateCurrentTailwindV4CssCandidates(majorVersion, cssHandlerOptions, options) {
1296
- return majorVersion === 4 && !cssHandlerOptions.isMainChunk && hasTailwindApplyDirective(options.rawSource) && !hasTailwindRootDirectives(options.rawSource) && !options.hasGeneratedCss && !options.hasGeneratedMarkers;
1297
- }
1298
1482
  function removeTailwindApplyAtRules(source) {
1299
1483
  if (!source.includes("@apply")) return source;
1300
1484
  try {
@@ -1332,34 +1516,6 @@ function removeTailwindV4GeneratorAtRules(source) {
1332
1516
  return source;
1333
1517
  }
1334
1518
  }
1335
- function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
1336
- if (majorVersion !== 4 || isolateCssSource) return false;
1337
- return target === "web" || generatorRuntime.size === 0;
1338
- }
1339
- function shouldAppendWebBundleCssFallback(target, options) {
1340
- return target === "web" && !options.hasMatchedCssSourceFile && !options.hasSourceDirectives;
1341
- }
1342
- function isEmptyCssSourceOrderParts(parts) {
1343
- return parts.before.trim().length === 0 && parts.after.trim().length === 0;
1344
- }
1345
- function resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorStyleOptions) {
1346
- const preflightStyleOptions = {
1347
- cssPreflight: opts.cssPreflight,
1348
- cssPreflightRange: opts.cssPreflightRange
1349
- };
1350
- return {
1351
- ...resolveStyleOptionsFromContext(opts),
1352
- atRules: opts.atRules,
1353
- uniAppXCssTarget: opts.uniAppXCssTarget,
1354
- uniAppXUnsupported: opts.uniAppXUnsupported,
1355
- ...cssHandlerOptions,
1356
- ...preflightStyleOptions,
1357
- ...generatorStyleOptions
1358
- };
1359
- }
1360
- function isLocalImportRequest(request) {
1361
- return request.length > 0 && !request.startsWith("#") && !request.startsWith("tailwindcss") && !request.startsWith("weapp-tailwindcss") && !request.startsWith("data:") && !REMOTE_IMPORT_RE.test(request);
1362
- }
1363
1519
  function isCommentOnlyCss(source) {
1364
1520
  try {
1365
1521
  const root = postcss.parse(source);
@@ -1394,22 +1550,6 @@ function stripUnmatchedTailwindSourceMediaCloseFragments(source) {
1394
1550
  return stripLeadingTailwindSourceMediaCloseFragment(source).replace(/\s*\}\s*$/, "");
1395
1551
  }
1396
1552
  }
1397
- function createCssSourceOrderAppend(base, extra) {
1398
- if (!base) return extra;
1399
- if (!extra) return base;
1400
- if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1401
- return `${base}\n${extra}`;
1402
- }
1403
- function shouldFinalizeMarkedUserLayerComponentsCss(file) {
1404
- return !/\.(?:vue|svelte|astro|scss|sass|less|styl)(?:[?#].*)?$/i.test(file);
1405
- }
1406
- function splitRawSourceByGeneratedCssOrder(rawSource, rawTailwindCss) {
1407
- const placeholderParts = splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss);
1408
- if (placeholderParts) return placeholderParts;
1409
- const exactParts = splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss);
1410
- if (exactParts) return exactParts;
1411
- return splitTailwindGeneratedCssByBanner(rawSource);
1412
- }
1413
1553
  function splitUserCssLayerBlocks(source) {
1414
1554
  if (!source.includes("@layer")) return {
1415
1555
  layer: "",
@@ -1561,84 +1701,157 @@ async function transformGeneratorUserCss(source, options) {
1561
1701
  });
1562
1702
  return removeUnsupportedMiniProgramAtRules(css);
1563
1703
  }
1564
- function isPureLocalCssImportWrapper(css) {
1565
- let hasImport = false;
1566
- try {
1567
- const root = postcss.parse(css);
1568
- for (const node of root.nodes) {
1569
- if (node.type === "comment") continue;
1570
- if (node.type !== "atrule" || node.name !== "import") return false;
1571
- const request = parseImportRequest(node.params);
1572
- if (!request || !isLocalImportRequest(request)) return false;
1573
- hasImport = true;
1574
- }
1575
- } catch {
1576
- return false;
1577
- }
1578
- return hasImport;
1704
+ //#endregion
1705
+ //#region src/bundlers/shared/generator-css/user-layer-order.ts
1706
+ const USER_LAYER_COMPONENTS_START = "/*! weapp-tailwindcss layer components start */";
1707
+ const USER_LAYER_COMPONENTS_END = "/*! weapp-tailwindcss layer components end */";
1708
+ const UTILITY_LAYER_INSERTION_RES = [
1709
+ /(^|\n)\.(?:fixed|absolute|relative|sticky|static)\s*\{/,
1710
+ /(^|\n)\.(?:block|inline-block|inline|flex|inline-flex|grid|hidden)\s*\{/,
1711
+ /(^|\n)\.(?:m|mx|my|mt|mr|mb|ml|p|px|py|pt|pr|pb|pl)-/,
1712
+ /(^|\n)\.(?:w|h|min-w|min-h|max-w|max-h)-/,
1713
+ /(^|\n)\.(?:bg|text|border|rounded|shadow|opacity|transition|transform|translate|scale|rotate|gap|items|justify|content)-/
1714
+ ];
1715
+ function appendCss(base, extra) {
1716
+ if (!base) return extra;
1717
+ if (!extra) return base;
1718
+ if (/\s$/.test(base) || /^\s/.test(extra)) return `${base}${extra}`;
1719
+ return `${base}\n${extra}`;
1579
1720
  }
1580
- function cleanLocalCssImportWrapperTailwindDirectives(css) {
1581
- let hasLocalImport = false;
1582
- let hasTailwindDirective = false;
1721
+ function removeFirstCssOccurrence(css, chunk) {
1722
+ const trimmed = chunk.trim();
1723
+ if (!trimmed) return css;
1724
+ const index = css.indexOf(trimmed);
1725
+ if (index === -1) return css;
1726
+ return appendCss(css.slice(0, index).trimEnd(), css.slice(index + trimmed.length).trimStart());
1727
+ }
1728
+ function collectSelectorsFromCss(css) {
1729
+ const selectors = /* @__PURE__ */ new Set();
1583
1730
  try {
1584
- const root = postcss.parse(css);
1585
- for (const node of root.nodes) {
1586
- if (node.type === "comment") continue;
1587
- if (node.type === "atrule" && node.name === "import") {
1588
- const request = parseImportRequest(node.params);
1589
- if (!request || !isLocalImportRequest(request)) return;
1590
- hasLocalImport = true;
1591
- continue;
1592
- }
1593
- if (node.type === "atrule" && node.name === "source") {
1594
- hasTailwindDirective = true;
1595
- continue;
1731
+ postcss.parse(css).walkRules((rule) => {
1732
+ for (const selector of rule.selectors ?? [rule.selector]) {
1733
+ const normalized = selector.trim();
1734
+ if (normalized) selectors.add(normalized);
1596
1735
  }
1597
- return;
1598
- }
1599
- } catch {
1600
- return;
1601
- }
1602
- return hasLocalImport && hasTailwindDirective ? prefixLocalCssImportsWithWebpackIgnore(removeTailwindSourceDirectives(css)) : void 0;
1736
+ });
1737
+ } catch {}
1738
+ return selectors;
1603
1739
  }
1604
- function prefixLocalCssImportsWithWebpackIgnore(css) {
1740
+ function matchesLayerSelector(selector, layerSelector) {
1741
+ if (selector === layerSelector) return true;
1742
+ if (!selector.startsWith(layerSelector)) return false;
1743
+ const next = selector[layerSelector.length];
1744
+ return next === ":" || next === "[";
1745
+ }
1746
+ function removeCssRulesForSelectors(css, layerCss) {
1747
+ const selectors = [...collectSelectorsFromCss(layerCss)];
1748
+ if (selectors.length === 0) return css;
1605
1749
  try {
1606
1750
  const root = postcss.parse(css);
1607
- root.walkAtRules("import", (atRule) => {
1608
- const request = parseImportRequest(atRule.params);
1609
- if (request && isLocalImportRequest(request)) atRule.raws.before = `${atRule.raws.before ?? ""}/* webpackIgnore: true */\n`;
1751
+ root.walkRules((rule) => {
1752
+ if ((rule.selectors ?? [rule.selector]).some((selector) => selectors.some((layerSelector) => matchesLayerSelector(selector.trim(), layerSelector)))) rule.remove();
1610
1753
  });
1611
1754
  return root.toString();
1612
1755
  } catch {
1613
- return css;
1756
+ return removeFirstCssOccurrence(css, layerCss);
1614
1757
  }
1615
1758
  }
1616
- function splitLocalCssImports(source) {
1617
- try {
1618
- const root = postcss.parse(source);
1619
- const importRoot = postcss.root();
1620
- let changed = false;
1621
- for (const node of [...root.nodes]) {
1622
- if (node.type !== "atrule" || node.name !== "import") continue;
1623
- const request = parseImportRequest(node.params);
1624
- if (!request || !isLocalImportRequest(request)) continue;
1625
- importRoot.append(node.clone());
1626
- node.remove();
1627
- changed = true;
1759
+ function wrapUserLayerComponentsCss(css) {
1760
+ return css.trim().length > 0 ? `${USER_LAYER_COMPONENTS_START}\n${css}\n${USER_LAYER_COMPONENTS_END}` : css;
1761
+ }
1762
+ function extractMarkedUserLayerComponentsCss(css) {
1763
+ const layers = [];
1764
+ let rest = "";
1765
+ let cursor = 0;
1766
+ while (cursor < css.length) {
1767
+ const startIndex = css.indexOf(USER_LAYER_COMPONENTS_START, cursor);
1768
+ if (startIndex === -1) {
1769
+ rest += css.slice(cursor);
1770
+ break;
1628
1771
  }
1629
- const imports = importRoot.nodes.filter((node) => node.type === "atrule" && node.name === "import").map((node) => `@import ${node.params};`).join("\n");
1630
- return changed ? {
1631
- imports,
1632
- source: root.toString()
1633
- } : void 0;
1634
- } catch {
1635
- return;
1772
+ rest += css.slice(cursor, startIndex);
1773
+ const contentStart = startIndex + 47;
1774
+ const endIndex = css.indexOf(USER_LAYER_COMPONENTS_END, contentStart);
1775
+ if (endIndex === -1) {
1776
+ rest += css.slice(startIndex);
1777
+ break;
1778
+ }
1779
+ const layerCss = css.slice(contentStart, endIndex).trim();
1780
+ if (layerCss) layers.push(layerCss);
1781
+ cursor = endIndex + 45;
1782
+ }
1783
+ return {
1784
+ layers,
1785
+ rest
1786
+ };
1787
+ }
1788
+ function findUtilityLayerInsertionIndex(css) {
1789
+ let index = -1;
1790
+ for (const pattern of UTILITY_LAYER_INSERTION_RES) {
1791
+ const match = pattern.exec(css);
1792
+ if (!match) continue;
1793
+ const nextIndex = match.index + (match[1]?.length ?? 0);
1794
+ index = index === -1 ? nextIndex : Math.min(index, nextIndex);
1636
1795
  }
1796
+ return index;
1637
1797
  }
1638
- function restoreLocalCssImports(css, imports) {
1639
- if (!imports?.trim()) return css;
1640
- return createCssSourceOrderAppend(imports, css);
1798
+ function reorderMarkedUserLayerComponentsCss(css) {
1799
+ if (!css.includes(USER_LAYER_COMPONENTS_START)) return css;
1800
+ const { layers, rest } = extractMarkedUserLayerComponentsCss(css);
1801
+ if (layers.length === 0) return rest;
1802
+ const layerCss = layers.join("\n");
1803
+ const insertionIndex = findUtilityLayerInsertionIndex(rest);
1804
+ if (insertionIndex === -1) return appendCss(rest, layerCss);
1805
+ return appendCss(appendCss(rest.slice(0, insertionIndex), layerCss), rest.slice(insertionIndex));
1641
1806
  }
1807
+ function mergeMarkedUserLayerComponentsCss(baseCss, markedCss) {
1808
+ if (!markedCss.includes(USER_LAYER_COMPONENTS_START)) return {
1809
+ css: baseCss,
1810
+ merged: false
1811
+ };
1812
+ const { layers } = extractMarkedUserLayerComponentsCss(markedCss);
1813
+ if (layers.length === 0) return {
1814
+ css: baseCss,
1815
+ merged: false
1816
+ };
1817
+ const layerCss = layers.join("\n");
1818
+ return {
1819
+ css: reorderMarkedUserLayerComponentsCss(appendCss(removeCssRulesForSelectors(baseCss, layerCss), wrapUserLayerComponentsCss(layerCss))),
1820
+ merged: true
1821
+ };
1822
+ }
1823
+ //#endregion
1824
+ //#region src/bundlers/shared/generator-css/validate.ts
1825
+ const SUPPORTED_GENERATOR_MAJOR_VERSIONS = new Set([3, 4]);
1826
+ async function validateCandidatesByGenerator(options) {
1827
+ const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState } = options;
1828
+ const majorVersion = runtimeState.twPatcher.majorVersion;
1829
+ if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || candidates.size === 0) return /* @__PURE__ */ new Set();
1830
+ const generatorOptions = {
1831
+ ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
1832
+ bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
1833
+ };
1834
+ const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, {
1835
+ cssEntries: opts.cssEntries,
1836
+ runtime: candidates
1837
+ });
1838
+ const classSets = await Promise.all(sources.map(async (source) => {
1839
+ const generator = createWeappTailwindcssGenerator(source);
1840
+ if (generatorOptions.bareArbitraryValues === void 0 || generatorOptions.bareArbitraryValues === false) {
1841
+ if (typeof generator.validateCandidates === "function") return generator.validateCandidates(candidates);
1842
+ }
1843
+ return (await generator.generate({
1844
+ bareArbitraryValues: generatorOptions.bareArbitraryValues,
1845
+ candidates,
1846
+ target: "tailwind"
1847
+ })).classSet;
1848
+ }));
1849
+ const classSet = new Set(classSets.flatMap((item) => [...item]));
1850
+ debug("tailwind generator validated candidates: %s candidates=%d classSet=%d", file, candidates.size, classSet.size);
1851
+ return classSet;
1852
+ }
1853
+ //#endregion
1854
+ //#region src/bundlers/shared/generator-css.ts
1642
1855
  async function generateCssByGenerator(options) {
1643
1856
  const { opts, runtimeState, runtime, rawSource, file, cssHandlerOptions, cssUserHandlerOptions, getSourceCandidatesForEntries, styleHandler, debug } = options;
1644
1857
  const generatorOptions = {
@@ -1661,8 +1874,13 @@ async function generateCssByGenerator(options) {
1661
1874
  const hasGeneratedCss = hasTailwindGeneratedCss(generatorRawSource);
1662
1875
  const hasSourceDirectives = hasTailwindSourceDirectives(generatorRawSource, { importFallback: generatorOptions.importFallback });
1663
1876
  const hasGeneratedMarkers = hasTailwindGeneratedCssMarkers(generatorRawSource);
1664
- const shouldGenerateCurrentCss = hasGeneratedCss || hasGeneratedMarkers || hasSourceDirectives || cssHandlerOptions.isMainChunk;
1665
- if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
1877
+ const shouldGenerateCurrentCss = shouldUseGeneratorForCurrentCss(majorVersion, cssHandlerOptions, {
1878
+ hasGeneratedCss,
1879
+ hasGeneratedMarkers,
1880
+ hasSourceDirectives,
1881
+ rawSource: generatorRawSource
1882
+ });
1883
+ if (!isSupportedGeneratorMajorVersion(majorVersion) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
1666
1884
  try {
1667
1885
  await runtimeState.readyPromise;
1668
1886
  const currentCssCandidates = majorVersion === 4 ? await extractSourceCandidates(generatorRawSource, "css", { ...generatorOptions.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: generatorOptions.bareArbitraryValues } }) : [];
@@ -1671,7 +1889,7 @@ async function generateCssByGenerator(options) {
1671
1889
  hasGeneratedMarkers,
1672
1890
  rawSource: generatorRawSource
1673
1891
  });
1674
- const runtimeWithCurrentCss = isolateCurrentCssCandidates ? new Set(currentCssCandidates) : currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
1892
+ const runtimeWithCurrentCss = createRuntimeWithCurrentCssCandidates(runtime, currentCssCandidates, isolateCurrentCssCandidates);
1675
1893
  const sources = await resolveGeneratorSources(majorVersion, runtimeState, generatorRawSource, file, cssHandlerOptions, generatorOptions, {
1676
1894
  cssEntries: opts.cssEntries,
1677
1895
  getSourceCandidatesForEntries,
@@ -1679,12 +1897,13 @@ async function generateCssByGenerator(options) {
1679
1897
  });
1680
1898
  const generatorStyleOptions = resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorOptions.styleOptions);
1681
1899
  const configuredContainerCompat = hasConfiguredContainerCompatSources(sources);
1682
- const generatedResults = (await Promise.all(sources.map(async (source) => {
1900
+ const generated = mergeGeneratorResults((await Promise.all(sources.map(async (source) => {
1683
1901
  const generator = createWeappTailwindcssGenerator(source);
1684
1902
  const sourceEntries = getSourceCandidatesForEntries && (majorVersion === 3 || majorVersion === 4) ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
1685
1903
  const scopedRuntime = sourceEntries ? getSourceCandidatesForEntries?.(sourceEntries) : void 0;
1686
1904
  const isolateCssSource = shouldIsolateScopedCssSource(source, sourceEntries);
1687
- const matchedCssSourceFile = Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile);
1905
+ const sourceMetadata = source.__weappTailwindcssMeta;
1906
+ const matchedCssSourceFile = Boolean(sourceMetadata?.matchedCssSourceFile);
1688
1907
  if (options.deferEmptyScopedCssSource && isolateCssSource && scopedRuntime?.size === 0 && currentCssCandidates.length === 0 && !cssHandlerOptions.isMainChunk) {
1689
1908
  debug("defer empty scoped css source generation: %s", file);
1690
1909
  return;
@@ -1706,21 +1925,8 @@ async function generateCssByGenerator(options) {
1706
1925
  tailwindcssV3Compatibility: generatorOptions.tailwindcssV3Compatibility,
1707
1926
  target: generatorOptions.target
1708
1927
  });
1709
- }))).filter((item) => Boolean(item));
1710
- const firstGenerated = generatedResults[0];
1711
- if (!firstGenerated) return;
1712
- const incrementalCssResults = generatedResults.map((item) => item.incrementalCss).filter((css) => typeof css === "string");
1713
- const incrementalRawCssResults = generatedResults.map((item) => item.incrementalRawCss).filter((css) => typeof css === "string");
1714
- const generated = generatedResults.length === 1 ? firstGenerated : {
1715
- ...firstGenerated,
1716
- css: generatedResults.map((item) => item.css).join("\n"),
1717
- rawCss: generatedResults.map((item) => item.rawCss).join("\n"),
1718
- incrementalCss: incrementalCssResults.length === generatedResults.length ? incrementalCssResults.filter(Boolean).join("\n") : void 0,
1719
- incrementalRawCss: incrementalRawCssResults.length === generatedResults.length ? incrementalRawCssResults.filter(Boolean).join("\n") : void 0,
1720
- classSet: new Set(generatedResults.flatMap((item) => [...item.classSet])),
1721
- dependencies: [...new Set(generatedResults.flatMap((item) => item.dependencies))],
1722
- sources: generatedResults.flatMap((item) => item.sources)
1723
- };
1928
+ }))).filter((item) => Boolean(item)));
1929
+ if (!generated) return;
1724
1930
  debug("tailwind generator result: %s rawBytes=%d cssBytes=%d candidates=%d", file, generated.rawCss.length, generated.css.length, generated.classSet.size);
1725
1931
  if ((generated.target !== "weapp" || !hasUserCssLayerBlocks(generatorRawSource)) && typeof options.previousCss === "string" && typeof generated.incrementalCss === "string") {
1726
1932
  const incrementalCss = stripTailwindBanner(generated.incrementalCss);
@@ -1757,13 +1963,13 @@ async function generateCssByGenerator(options) {
1757
1963
  const beforeUserCss = await transformGeneratorUserCss(orderedExtraCss.before, userCssOptions);
1758
1964
  const afterLayerUserCss = await transformGeneratorUserCss(afterLayerParts.layer, userCssOptions);
1759
1965
  const afterUserCss = await transformGeneratorUserCss(afterLayerParts.rest, userCssOptions);
1760
- css = createCssSourceOrderAppend(createCssSourceOrderAppend(createCssSourceOrderAppend(beforeUserCss, generated.target === "weapp" ? wrapUserLayerComponentsCss(afterLayerUserCss) : afterLayerUserCss), css), afterUserCss);
1966
+ css = createCssSourceOrderAppend$1(createCssSourceOrderAppend$1(createCssSourceOrderAppend$1(beforeUserCss, generated.target === "weapp" ? wrapUserLayerComponentsCss(afterLayerUserCss) : afterLayerUserCss), css), afterUserCss);
1761
1967
  if (isEmptyCssSourceOrderParts(orderedExtraCss) && shouldAppendWebBundleCssFallback(generated.target, {
1762
1968
  hasSourceDirectives,
1763
1969
  hasMatchedCssSourceFile
1764
1970
  })) {
1765
1971
  const userCss = await transformGeneratorUserCss(userCssRawSource, userCssOptions);
1766
- css = createCssSourceOrderAppend(css, userCss);
1972
+ css = createCssSourceOrderAppend$1(css, userCss);
1767
1973
  }
1768
1974
  if (generated.target === "weapp" && shouldAppendMatchedCssSourceCompat) {
1769
1975
  if (shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
@@ -1801,7 +2007,7 @@ async function generateCssByGenerator(options) {
1801
2007
  rest: css
1802
2008
  } : extractGeneratedCssForUserLayerSelectors(css, layerParts.layer);
1803
2009
  if (layerCss.layer.trim().length > 0) {
1804
- css = createCssSourceOrderAppend(wrapUserLayerComponentsCss(layerCss.layer), layerCss.rest);
2010
+ css = createCssSourceOrderAppend$1(wrapUserLayerComponentsCss(layerCss.layer), layerCss.rest);
1805
2011
  if (shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
1806
2012
  }
1807
2013
  }
@@ -1815,7 +2021,7 @@ async function generateCssByGenerator(options) {
1815
2021
  styleHandler,
1816
2022
  importFallback: generatorOptions.importFallback
1817
2023
  });
1818
- css = createCssSourceOrderAppend(css, userCss);
2024
+ css = createCssSourceOrderAppend$1(css, userCss);
1819
2025
  }
1820
2026
  if (hasMatchedCssSourceFile && generated.target === "weapp") {
1821
2027
  if (!isolateCurrentCssCandidates && !shouldFilterApplyOnlyCss) css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
@@ -1831,7 +2037,7 @@ async function generateCssByGenerator(options) {
1831
2037
  styleHandler,
1832
2038
  importFallback: generatorOptions.importFallback
1833
2039
  });
1834
- css = createCssSourceOrderAppend(css, userCss);
2040
+ css = createCssSourceOrderAppend$1(css, userCss);
1835
2041
  }
1836
2042
  return {
1837
2043
  css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
@@ -1845,132 +2051,26 @@ async function generateCssByGenerator(options) {
1845
2051
  };
1846
2052
  }
1847
2053
  if (!shouldFilterApplyOnlyCss) {
1848
- css = await appendLegacyCompatCss(css, userCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1849
- css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
1850
- }
1851
- return {
1852
- css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
1853
- cssHandlerOptions,
1854
- isolateCurrentCssCandidates,
1855
- localImports: localImportParts?.imports
1856
- }) }), localImportParts?.imports),
1857
- target: generated.target,
1858
- source: "generator",
1859
- dependencies: generated.dependencies
1860
- };
1861
- } catch (error) {
1862
- debug("tailwind direct css generation failed: %s %O", file, error);
1863
- throw error;
1864
- }
1865
- }
1866
- async function validateCandidatesByGenerator(options) {
1867
- const { candidates, cssHandlerOptions, debug, file, opts, rawSource, runtimeState } = options;
1868
- const majorVersion = runtimeState.twPatcher.majorVersion;
1869
- if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || candidates.size === 0) return /* @__PURE__ */ new Set();
1870
- const generatorOptions = {
1871
- ...normalizeWeappTailwindcssGeneratorOptions(opts.generator),
1872
- bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues
1873
- };
1874
- const sources = await resolveGeneratorSources(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, {
1875
- cssEntries: opts.cssEntries,
1876
- runtime: candidates
1877
- });
1878
- const classSets = await Promise.all(sources.map(async (source) => {
1879
- const generator = createWeappTailwindcssGenerator(source);
1880
- if (generatorOptions.bareArbitraryValues === void 0 || generatorOptions.bareArbitraryValues === false) {
1881
- if (typeof generator.validateCandidates === "function") return generator.validateCandidates(candidates);
1882
- }
1883
- return (await generator.generate({
1884
- bareArbitraryValues: generatorOptions.bareArbitraryValues,
1885
- candidates,
1886
- target: "tailwind"
1887
- })).classSet;
1888
- }));
1889
- const classSet = new Set(classSets.flatMap((item) => [...item]));
1890
- debug("tailwind generator validated candidates: %s candidates=%d classSet=%d", file, candidates.size, classSet.size);
1891
- return classSet;
1892
- }
1893
- //#endregion
1894
- //#region src/bundlers/shared/hmr-timing.ts
1895
- function shouldEmitHmrTiming() {
1896
- return process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
1897
- }
1898
- function shouldEmitHumanReadableTiming() {
1899
- return process.env["WEAPP_TW_HMR_TIMING"] === "1" && process.env["WEAPP_TW_HMR_TIMING_LOG"] !== "0";
1900
- }
1901
- function emitHmrTiming(bundler, phase, durationMs, details = {}) {
1902
- if (!shouldEmitHmrTiming()) return;
1903
- const serializableDetails = { ...details };
1904
- delete serializableDetails.emit;
1905
- const payload = {
1906
- bundler,
1907
- phase,
1908
- durationMs: Math.max(0, Math.round(durationMs)),
1909
- ...serializableDetails,
1910
- ...typeof details.wallMs === "number" ? { wallMs: Math.max(0, Math.round(details.wallMs)) } : {}
1911
- };
1912
- process.stdout.write(`[weapp-tailwindcss:hmr] ${JSON.stringify(payload)}\n`);
1913
- if (shouldEmitHumanReadableTiming()) {
1914
- const fileSuffix = details.file ? ` file=${details.file}` : "";
1915
- if (details.metric === "total") {
1916
- const hooks = details.hooks ? Object.entries(details.hooks).map(([hook, summary]) => `${hook}=${Math.max(0, Math.round(summary.durationMs))}ms/${summary.count}`).join(", ") : "";
1917
- const hookSuffix = hooks ? ` (${hooks})` : "";
1918
- const wallSuffix = typeof payload.wallMs === "number" ? ` wall=${payload.wallMs}ms` : "";
1919
- process.stdout.write(`[weapp-tailwindcss] ${bundler}:weapp-tailwindcss 总耗时 ${payload.durationMs}ms${wallSuffix}${hookSuffix}\n`);
1920
- return;
1921
- }
1922
- process.stdout.write(`[weapp-tailwindcss] ${bundler}:${phase} 耗时 ${payload.durationMs}ms${fileSuffix}\n`);
1923
- }
1924
- }
1925
- function createHmrTimingRecorder(bundler) {
1926
- const session = {
1927
- hooks: {},
1928
- totalMs: 0
1929
- };
1930
- const record = (phase, durationMs, details = {}) => {
1931
- const roundedDuration = Math.max(0, Math.round(durationMs));
1932
- if (session.startedAt === void 0) session.startedAt = performance.now() - Math.max(0, durationMs);
1933
- session.totalMs += Math.max(0, durationMs);
1934
- const current = session.hooks[phase] ?? {
1935
- count: 0,
1936
- durationMs: 0,
1937
- maxMs: 0
1938
- };
1939
- current.count += 1;
1940
- current.durationMs += roundedDuration;
1941
- current.maxMs = Math.max(current.maxMs, roundedDuration);
1942
- session.hooks[phase] = current;
1943
- if (details.emit !== false) emitHmrTiming(bundler, phase, durationMs, details);
1944
- };
1945
- const measure = async (phase, task, details = {}) => {
1946
- const startedAt = performance.now();
1947
- try {
1948
- return await task();
1949
- } finally {
1950
- record(phase, performance.now() - startedAt, details);
1951
- }
1952
- };
1953
- const emitTotal = (phase = "total") => {
1954
- if (session.totalMs <= 0) return;
1955
- const wallMs = session.startedAt === void 0 ? session.totalMs : performance.now() - session.startedAt;
1956
- emitHmrTiming(bundler, phase, session.totalMs, {
1957
- hooks: session.hooks,
1958
- metric: "total",
1959
- wallMs
1960
- });
1961
- session.hooks = {};
1962
- delete session.startedAt;
1963
- session.totalMs = 0;
1964
- };
1965
- return {
1966
- emitTotal,
1967
- measure,
1968
- record
1969
- };
2054
+ css = await appendLegacyCompatCss(css, userCssRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2055
+ css = await appendLegacyContainerCompatCss(css, userCssRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
2056
+ }
2057
+ return {
2058
+ css: restoreLocalCssImports(finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight, { injectPreflight: shouldInjectMiniProgramPreflightForGeneratorCss(opts, {
2059
+ cssHandlerOptions,
2060
+ isolateCurrentCssCandidates,
2061
+ localImports: localImportParts?.imports
2062
+ }) }), localImportParts?.imports),
2063
+ target: generated.target,
2064
+ source: "generator",
2065
+ dependencies: generated.dependencies
2066
+ };
2067
+ } catch (error) {
2068
+ debug("tailwind direct css generation failed: %s %O", file, error);
2069
+ throw error;
2070
+ }
1970
2071
  }
1971
2072
  //#endregion
1972
- //#region src/bundlers/vite/incremental-runtime-class-set.ts
1973
- const debug = createDebug("[vite:runtime-set] ");
2073
+ //#region src/bundlers/vite/incremental-runtime-class-set/entries.ts
1974
2074
  const EXTENSION_DOT_PREFIX_RE = /^\./;
1975
2075
  const VENDOR_CHUNK_BASENAME_RE = /^(?:vendor|vendors|chunk-vendors|common_vendor)(?:[.-]|$)/i;
1976
2076
  const COMMON_VENDOR_CHUNK_RE = /^(?:common|static|assets|chunks?)\/(?:vendor|vendors|chunk-vendors|common_vendor|runtime)(?:[.-]|$)/i;
@@ -2005,17 +2105,6 @@ function isRuntimeCandidateEntry(entry) {
2005
2105
  if (entry.output.facadeModuleId && !isDependencyModuleId(entry.output.facadeModuleId)) return true;
2006
2106
  return collectChunkModuleIds(entry).some((id) => !isDependencyModuleId(id));
2007
2107
  }
2008
- function createExtractOptions(context, source, bareArbitraryValues) {
2009
- return {
2010
- cwd: context.projectRoot,
2011
- base: context.base,
2012
- baseFallbacks: context.baseFallbacks,
2013
- css: context.css,
2014
- content: source,
2015
- extension: "html",
2016
- bareArbitraryValues
2017
- };
2018
- }
2019
2108
  function createRuntimeEntries(snapshot) {
2020
2109
  return snapshot.entries.filter(isRuntimeCandidateEntry);
2021
2110
  }
@@ -2028,37 +2117,54 @@ function resolveEntryExtension(entry) {
2028
2117
  if (ext.length > 0) return ext;
2029
2118
  return "js";
2030
2119
  }
2031
- function createCandidateValidationSource(candidates) {
2032
- return [...new Set(candidates)].sort().join("\n");
2033
- }
2034
- function removeCandidateSet(candidateCountByClass, candidates) {
2035
- for (const className of candidates) {
2036
- const count = candidateCountByClass.get(className);
2037
- if (count == null) continue;
2038
- if (count <= 1) {
2039
- candidateCountByClass.delete(className);
2120
+ //#endregion
2121
+ //#region src/bundlers/vite/incremental-runtime-class-set/escaped-candidates.ts
2122
+ const ESCAPED_CLASS_TOKEN_RE = /[\w-]+_[A-Z][\w-]*/gi;
2123
+ const TAILWIND_RESTORED_CANDIDATE_SIGNAL_RE = /[[\]:/#!.]/;
2124
+ const MAX_RESTORED_CANDIDATE_VARIANTS = 512;
2125
+ function createEscapeFragments(escapeMap) {
2126
+ return [...new Set(Object.values(escapeMap).filter(Boolean))].sort((a, b) => b.length - a.length);
2127
+ }
2128
+ function hasEscapeFragment(token, escapeFragments) {
2129
+ return escapeFragments.some((fragment) => token.includes(fragment));
2130
+ }
2131
+ function createAmbiguousRestoredRuntimeCandidates(token, escapeMap, escapeFragments) {
2132
+ if (!hasEscapeFragment(token, escapeFragments)) return [];
2133
+ const unescapedByFragment = new Map(Object.entries(escapeMap).map(([char, fragment]) => [fragment, char]));
2134
+ let variants = [""];
2135
+ let index = 0;
2136
+ while (index < token.length) {
2137
+ const fragment = escapeFragments.find((item) => token.startsWith(item, index));
2138
+ if (!fragment) {
2139
+ variants = variants.map((item) => item + token[index]);
2140
+ index += 1;
2040
2141
  continue;
2041
2142
  }
2042
- candidateCountByClass.set(className, count - 1);
2143
+ const nextVariants = [];
2144
+ const unescaped = unescapedByFragment.get(fragment);
2145
+ for (const variant of variants) {
2146
+ nextVariants.push(variant + fragment);
2147
+ if (unescaped) nextVariants.push(variant + unescaped);
2148
+ if (nextVariants.length >= MAX_RESTORED_CANDIDATE_VARIANTS) break;
2149
+ }
2150
+ variants = nextVariants;
2151
+ index += fragment.length;
2043
2152
  }
2153
+ variants.push(unescape(token, { map: escapeMap }));
2154
+ return [...new Set(variants)].filter((restored) => restored !== token && TAILWIND_RESTORED_CANDIDATE_SIGNAL_RE.test(restored) && !/\s/.test(restored));
2044
2155
  }
2045
- function addCandidateSet(candidateCountByClass, candidates) {
2046
- for (const className of candidates) {
2047
- const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
2048
- candidateCountByClass.set(className, nextCount);
2156
+ function collectEscapedRuntimeCandidates(source, escapeMap, escapeFragments) {
2157
+ const candidates = /* @__PURE__ */ new Set();
2158
+ ESCAPED_CLASS_TOKEN_RE.lastIndex = 0;
2159
+ let match = ESCAPED_CLASS_TOKEN_RE.exec(source);
2160
+ while (match) {
2161
+ for (const restored of createAmbiguousRestoredRuntimeCandidates(match[0], escapeMap, escapeFragments)) candidates.add(restored);
2162
+ match = ESCAPED_CLASS_TOKEN_RE.exec(source);
2049
2163
  }
2164
+ return candidates;
2050
2165
  }
2051
- function createRuntimeClassSet(baseClassSet, candidateCountByClass) {
2052
- return new Set([...baseClassSet, ...candidateCountByClass.keys()]);
2053
- }
2054
- function createNonSourceBaseClassSet(baseClassSet, candidateCountByClass) {
2055
- const nextBaseClassSet = new Set(baseClassSet);
2056
- for (const candidate of candidateCountByClass.keys()) nextBaseClassSet.delete(candidate);
2057
- return nextBaseClassSet;
2058
- }
2059
- function isUrlLikeCandidate(candidate) {
2060
- return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
2061
- }
2166
+ //#endregion
2167
+ //#region src/bundlers/vite/incremental-runtime-class-set/v3-candidates.ts
2062
2168
  const TAILWIND_V3_ARBITRARY_UTILITY_PREFIXES = new Set([
2063
2169
  "accent",
2064
2170
  "animate",
@@ -2137,6 +2243,9 @@ const TAILWIND_V3_ARBITRARY_UTILITY_PREFIXES = new Set([
2137
2243
  "w",
2138
2244
  "z"
2139
2245
  ]);
2246
+ function isUrlLikeCandidate(candidate) {
2247
+ return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
2248
+ }
2140
2249
  function getBaseUtilityCandidate(candidate) {
2141
2250
  let bracketDepth = 0;
2142
2251
  let lastVariantSeparator = -1;
@@ -2231,10 +2340,54 @@ function isRawCandidateInRanges(start, ranges) {
2231
2340
  function isRawCandidateAllowedForV3(source, candidate, start, extension, knownSourceCandidates, highConfidenceLiteralRanges = []) {
2232
2341
  return isHighConfidenceV3Candidate(candidate) || knownSourceCandidates?.has(candidate) === true || isRawCandidateInClassContext(source, start, extension) || isRawCandidateInRanges(start, highConfidenceLiteralRanges);
2233
2342
  }
2343
+ //#endregion
2344
+ //#region src/bundlers/vite/incremental-runtime-class-set.ts
2345
+ const debug = createDebug("[vite:runtime-set] ");
2346
+ function createExtractOptions(context, source, bareArbitraryValues) {
2347
+ return {
2348
+ cwd: context.projectRoot,
2349
+ base: context.base,
2350
+ baseFallbacks: context.baseFallbacks,
2351
+ css: context.css,
2352
+ content: source,
2353
+ extension: "html",
2354
+ ...bareArbitraryValues === void 0 ? {} : { bareArbitraryValues }
2355
+ };
2356
+ }
2357
+ function createCandidateValidationSource(candidates) {
2358
+ return [...new Set(candidates)].sort().join("\n");
2359
+ }
2360
+ function removeCandidateSet$1(candidateCountByClass, candidates) {
2361
+ for (const className of candidates) {
2362
+ const count = candidateCountByClass.get(className);
2363
+ if (count == null) continue;
2364
+ if (count <= 1) {
2365
+ candidateCountByClass.delete(className);
2366
+ continue;
2367
+ }
2368
+ candidateCountByClass.set(className, count - 1);
2369
+ }
2370
+ }
2371
+ function addCandidateSet$1(candidateCountByClass, candidates) {
2372
+ for (const className of candidates) {
2373
+ const nextCount = (candidateCountByClass.get(className) ?? 0) + 1;
2374
+ candidateCountByClass.set(className, nextCount);
2375
+ }
2376
+ }
2377
+ function createRuntimeClassSet(baseClassSet, candidateCountByClass) {
2378
+ return new Set([...baseClassSet, ...candidateCountByClass.keys()]);
2379
+ }
2380
+ function createNonSourceBaseClassSet(baseClassSet, candidateCountByClass) {
2381
+ const nextBaseClassSet = new Set(baseClassSet);
2382
+ for (const candidate of candidateCountByClass.keys()) nextBaseClassSet.delete(candidate);
2383
+ return nextBaseClassSet;
2384
+ }
2234
2385
  function createBundleRuntimeClassSetManager(options = {}) {
2235
2386
  const customExtractCandidates = options.extractCandidates;
2236
2387
  const extractCandidates = customExtractCandidates ?? extractValidCandidates;
2237
2388
  const extractRawCandidates = options.extractRawCandidates ?? extractRawCandidatesWithPositions;
2389
+ const escapeMap = options.escapeMap ?? MappingChars2String;
2390
+ const escapeFragments = createEscapeFragments(escapeMap);
2238
2391
  let baseClassSet = /* @__PURE__ */ new Set();
2239
2392
  const candidateCountByClass = /* @__PURE__ */ new Map();
2240
2393
  const candidatesByFile = /* @__PURE__ */ new Map();
@@ -2260,7 +2413,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2260
2413
  return designSystemPromise;
2261
2414
  }
2262
2415
  function populateCandidateValidityCacheFromDesignSystem(designSystem, unknownCandidates) {
2263
- const validCandidates = resolveValidTailwindV4Candidates(designSystem, unknownCandidates, { bareArbitraryValues: options.bareArbitraryValues });
2416
+ const validCandidates = resolveValidTailwindV4Candidates(designSystem, unknownCandidates, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
2264
2417
  for (const candidate of unknownCandidates) candidateValidityCache.set(candidate, validCandidates.has(candidate));
2265
2418
  }
2266
2419
  async function validateUnknownCandidates(patcher, unknownCandidates) {
@@ -2294,6 +2447,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2294
2447
  candidates.add(candidate);
2295
2448
  }
2296
2449
  }
2450
+ if (patcher.majorVersion === 4) for (const candidate of collectEscapedRuntimeCandidates(entry.source, escapeMap, escapeFragments)) candidates.add(candidate);
2297
2451
  return candidates;
2298
2452
  }
2299
2453
  async function sync(patcher, snapshot, options = {}) {
@@ -2312,7 +2466,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2312
2466
  const canUseBaseWithoutInitialFullScan = Boolean(fullRebuild && !hadTrackedRuntimeFiles && options.skipInitialFullScanWithBase === true && nextBaseClassSet && nextBaseClassSet.size > 0);
2313
2467
  for (const [file, previousCandidates] of candidatesByFile) {
2314
2468
  if (currentRuntimeFiles.has(file) || snapshot.hasOmittedKnownFiles) continue;
2315
- removeCandidateSet(candidateCountByClass, previousCandidates);
2469
+ removeCandidateSet$1(candidateCountByClass, previousCandidates);
2316
2470
  candidatesByFile.delete(file);
2317
2471
  }
2318
2472
  const changedRuntimeFiles = canUseBaseWithoutInitialFullScan ? [...collectChangedRuntimeFiles(snapshot)] : fullRebuild ? [...runtimeEntriesByFile.keys()] : [...collectChangedRuntimeFiles(snapshot)];
@@ -2334,7 +2488,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2334
2488
  for (const file of changedRuntimeFiles) {
2335
2489
  const nextRawCandidates = rawCandidatesByFile.get(file);
2336
2490
  const previousCandidates = candidatesByFile.get(file);
2337
- if (previousCandidates) removeCandidateSet(candidateCountByClass, previousCandidates);
2491
+ if (previousCandidates) removeCandidateSet$1(candidateCountByClass, previousCandidates);
2338
2492
  if (!nextRawCandidates || nextRawCandidates.size === 0) {
2339
2493
  candidatesByFile.delete(file);
2340
2494
  continue;
@@ -2345,7 +2499,7 @@ function createBundleRuntimeClassSetManager(options = {}) {
2345
2499
  candidatesByFile.delete(file);
2346
2500
  continue;
2347
2501
  }
2348
- addCandidateSet(candidateCountByClass, nextCandidates);
2502
+ addCandidateSet$1(candidateCountByClass, nextCandidates);
2349
2503
  candidatesByFile.set(file, nextCandidates);
2350
2504
  }
2351
2505
  if (nextBaseClassSet) baseClassSet = canUseBaseWithoutInitialFullScan ? new Set(nextBaseClassSet) : createNonSourceBaseClassSet(nextBaseClassSet, candidateCountByClass);
@@ -2359,4 +2513,552 @@ function createBundleRuntimeClassSetManager(options = {}) {
2359
2513
  };
2360
2514
  }
2361
2515
  //#endregion
2362
- export { validateCandidatesByGenerator as a, generateCssByGenerator as i, createHmrTimingRecorder as n, mergeMarkedUserLayerComponentsCss as o, emitHmrTiming as r, processCachedTask as s, createBundleRuntimeClassSetManager as t };
2516
+ //#region src/bundlers/vite/source-candidates/scan-root.ts
2517
+ const TAILWIND_V4_IGNORED_CONTENT_DIRS = [
2518
+ ".git",
2519
+ ".hg",
2520
+ ".jj",
2521
+ ".next",
2522
+ ".parcel-cache",
2523
+ ".pnpm-store",
2524
+ ".svelte-kit",
2525
+ ".svn",
2526
+ ".turbo",
2527
+ ".venv",
2528
+ ".vercel",
2529
+ ".yarn",
2530
+ "__pycache__",
2531
+ "node_modules",
2532
+ "venv"
2533
+ ];
2534
+ const TAILWIND_V4_IGNORED_EXTENSIONS = [
2535
+ "css",
2536
+ "less",
2537
+ "postcss",
2538
+ "pcss",
2539
+ "lock",
2540
+ "sass",
2541
+ "scss",
2542
+ "styl",
2543
+ "stylus",
2544
+ "log",
2545
+ "wxss",
2546
+ "acss",
2547
+ "jxss",
2548
+ "ttss",
2549
+ "qss",
2550
+ "tyss"
2551
+ ];
2552
+ const TAILWIND_V4_IGNORED_FILES = [
2553
+ "package-lock.json",
2554
+ "pnpm-lock.yaml",
2555
+ "bun.lockb",
2556
+ ".gitignore",
2557
+ ".env",
2558
+ ".env.*"
2559
+ ];
2560
+ function resolveOutDirIgnorePattern(root, outDir) {
2561
+ if (!outDir) return;
2562
+ const relative = path.relative(root, path.resolve(root, outDir));
2563
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return;
2564
+ return `${toPosixPath$1(relative)}/**`;
2565
+ }
2566
+ function normalizeScanEntries(root, entries, outDirIgnore) {
2567
+ const hasPositiveEntry = entries?.some((entry) => !entry.negated) === true;
2568
+ const scanEntries = entries?.length ? hasPositiveEntry ? entries : [{
2569
+ base: root,
2570
+ pattern: "**/*",
2571
+ negated: false
2572
+ }, ...entries] : void 0;
2573
+ if (!outDirIgnore) return scanEntries;
2574
+ return [...scanEntries ?? [{
2575
+ base: root,
2576
+ pattern: "**/*",
2577
+ negated: false
2578
+ }], {
2579
+ base: root,
2580
+ pattern: outDirIgnore,
2581
+ negated: true
2582
+ }];
2583
+ }
2584
+ function shouldApplyDefaultIgnoredSources(entries) {
2585
+ return entries?.length === void 0 ? false : entries.length > 0 && entries.every((entry) => entry.negated);
2586
+ }
2587
+ function createDefaultIgnoredSources(root, outDirIgnore, entries, explicit) {
2588
+ return [...!explicit || shouldApplyDefaultIgnoredSources(entries) ? [
2589
+ ...TAILWIND_V4_IGNORED_CONTENT_DIRS.map((pattern) => ({
2590
+ base: root,
2591
+ pattern: `**/${pattern}/**`,
2592
+ negated: true
2593
+ })),
2594
+ ...TAILWIND_V4_IGNORED_EXTENSIONS.map((extension) => ({
2595
+ base: root,
2596
+ pattern: `**/*.${extension}`,
2597
+ negated: true
2598
+ })),
2599
+ ...TAILWIND_V4_IGNORED_FILES.map((pattern) => ({
2600
+ base: root,
2601
+ pattern: `**/${pattern}`,
2602
+ negated: true
2603
+ }))
2604
+ ] : [], ...outDirIgnore ? [{
2605
+ base: root,
2606
+ pattern: outDirIgnore,
2607
+ negated: true
2608
+ }] : []];
2609
+ }
2610
+ function resolveSourceCandidateScanFiles(options) {
2611
+ const resolvedRoot = path.resolve(options.root);
2612
+ const outDirIgnore = resolveOutDirIgnorePattern(resolvedRoot, options.outDir);
2613
+ const scanEntries = normalizeScanEntries(resolvedRoot, options.entries, outDirIgnore);
2614
+ const ignoredSources = createDefaultIgnoredSources(resolvedRoot, outDirIgnore, options.entries, options.explicit);
2615
+ return resolveProjectSourceFiles({
2616
+ cwd: resolvedRoot,
2617
+ ...scanEntries === void 0 ? {} : { sources: scanEntries },
2618
+ ...ignoredSources.length > 0 ? { ignoredSources } : {},
2619
+ filter: options.filter
2620
+ });
2621
+ }
2622
+ //#endregion
2623
+ //#region src/bundlers/vite/source-candidates/script.ts
2624
+ const SCRIPT_SOURCE_CANDIDATE_EXTENSIONS = new Set([
2625
+ "js",
2626
+ "jsx",
2627
+ "mjs",
2628
+ "cjs",
2629
+ "ts",
2630
+ "tsx",
2631
+ "mts",
2632
+ "cts"
2633
+ ]);
2634
+ const CLASS_LIKE_NAME_RE = /class/i;
2635
+ function getPropertyName(node) {
2636
+ if (!node) return;
2637
+ if (node.type === "Identifier") return node.name;
2638
+ if (node.type === "StringLiteral") return node.value;
2639
+ }
2640
+ function isClassLikeStringPath(path) {
2641
+ const parent = path.parentPath;
2642
+ if (!parent) return false;
2643
+ if (parent.isVariableDeclarator?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.id) ?? "");
2644
+ if (parent.isObjectProperty?.() || parent.isObjectMethod?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.key) ?? "");
2645
+ if (parent.isAssignmentExpression?.()) {
2646
+ const left = parent.node.left;
2647
+ if (left?.type === "Identifier") return CLASS_LIKE_NAME_RE.test(left.name);
2648
+ if (left?.type === "MemberExpression") return CLASS_LIKE_NAME_RE.test(getPropertyName(left.property) ?? "");
2649
+ }
2650
+ if (parent.isJSXAttribute?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.name) ?? "");
2651
+ return false;
2652
+ }
2653
+ function isTemplateElementInClassLikePath(path) {
2654
+ const templateLiteralPath = path.parentPath;
2655
+ if (!templateLiteralPath?.isTemplateLiteral?.()) return false;
2656
+ const parent = templateLiteralPath.parentPath;
2657
+ if (!parent) return false;
2658
+ if (parent.isVariableDeclarator?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.id) ?? "");
2659
+ if (parent.isObjectProperty?.() || parent.isObjectMethod?.()) return CLASS_LIKE_NAME_RE.test(getPropertyName(parent.node.key) ?? "");
2660
+ if (parent.isAssignmentExpression?.()) {
2661
+ const left = parent.node.left;
2662
+ if (left?.type === "Identifier") return CLASS_LIKE_NAME_RE.test(left.name);
2663
+ if (left?.type === "MemberExpression") return CLASS_LIKE_NAME_RE.test(getPropertyName(left.property) ?? "");
2664
+ }
2665
+ return false;
2666
+ }
2667
+ async function extractScriptStringCandidates(source, extension, options) {
2668
+ if (!SCRIPT_SOURCE_CANDIDATE_EXTENSIONS.has(extension)) return [];
2669
+ const values = /* @__PURE__ */ new Set();
2670
+ try {
2671
+ traverse(babelParse(source, {
2672
+ cache: true,
2673
+ cacheKey: `vite-source-candidates:${extension}`,
2674
+ plugins: ["jsx", "typescript"],
2675
+ sourceType: "unambiguous"
2676
+ }), {
2677
+ noScope: true,
2678
+ StringLiteral(path) {
2679
+ if (isClassLikeStringPath(path)) values.add(path.node.value);
2680
+ },
2681
+ TemplateElement(path) {
2682
+ if (isTemplateElementInClassLikePath(path)) values.add(path.node.value.raw);
2683
+ }
2684
+ });
2685
+ } catch {
2686
+ return [];
2687
+ }
2688
+ const candidates = /* @__PURE__ */ new Set();
2689
+ for (const value of values) {
2690
+ const extractedCandidates = options.extractor ? await options.extractor(value, "html") : await extractSourceCandidates(value, "html", { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } });
2691
+ for (const candidate of extractedCandidates) candidates.add(candidate);
2692
+ }
2693
+ return candidates;
2694
+ }
2695
+ //#endregion
2696
+ //#region src/bundlers/vite/source-candidates/tailwind-v3-default-extractor.ts
2697
+ const require = createRequire(import.meta.url);
2698
+ const TAILWIND_V3_HTML_TOKEN_CANDIDATES = new Set([
2699
+ "/block",
2700
+ "/div",
2701
+ "/span",
2702
+ "/template",
2703
+ "/text",
2704
+ "/view",
2705
+ "class",
2706
+ "className",
2707
+ "div",
2708
+ "hover-class",
2709
+ "span",
2710
+ "template",
2711
+ "text",
2712
+ "view"
2713
+ ]);
2714
+ function createTailwindV3DefaultExtractor() {
2715
+ try {
2716
+ const defaultExtractorModule = require("tailwindcss/lib/lib/defaultExtractor");
2717
+ const resolveConfigModule = require("tailwindcss/resolveConfig");
2718
+ const resolveConfig = resolveConfigModule.default ?? resolveConfigModule;
2719
+ const extractor = (defaultExtractorModule.defaultExtractor ?? defaultExtractorModule.default ?? defaultExtractorModule)({ tailwindConfig: resolveConfig({ content: [] }) });
2720
+ return (source) => new Set(extractor(source).filter((candidate) => !TAILWIND_V3_HTML_TOKEN_CANDIDATES.has(candidate)));
2721
+ } catch {
2722
+ return;
2723
+ }
2724
+ }
2725
+ //#endregion
2726
+ //#region src/bundlers/vite/source-candidates.ts
2727
+ const CLEAN_URL_RE = /[?#].*$/;
2728
+ const sourceCandidateContentCache = /* @__PURE__ */ new Map();
2729
+ function cleanUrl(id) {
2730
+ return resolveSourceScanPath(id.replace(CLEAN_URL_RE, ""));
2731
+ }
2732
+ function resolveSourceCandidateExtension(id) {
2733
+ const normalized = cleanUrl(id);
2734
+ return /\.([^.\\/]+)$/.exec(normalized)?.[1] ?? "html";
2735
+ }
2736
+ function createSourceCandidateContentCacheKey(extension, source, bareArbitraryValues, extractor) {
2737
+ return `${extension}\0${JSON.stringify(bareArbitraryValues ?? false)}\0${extractor ? "custom" : "default"}\0${source}`;
2738
+ }
2739
+ async function extractCandidates(source, extension, options) {
2740
+ const candidates = options.extractor ? new Set(await options.extractor(source, extension)) : new Set(await extractSourceCandidates(source, extension, { ...options.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: options.bareArbitraryValues } }));
2741
+ const scriptCandidates = await extractScriptStringCandidates(source, extension, options);
2742
+ for (const candidate of scriptCandidates) candidates.add(candidate);
2743
+ return candidates;
2744
+ }
2745
+ function isSourceCandidateRequest(id) {
2746
+ return FULL_SOURCE_SCAN_EXTENSION_RE.test(cleanUrl(id));
2747
+ }
2748
+ function removeCandidateSet(candidateCount, candidates) {
2749
+ for (const candidate of candidates) {
2750
+ const count = candidateCount.get(candidate);
2751
+ if (count == null) continue;
2752
+ if (count <= 1) {
2753
+ candidateCount.delete(candidate);
2754
+ continue;
2755
+ }
2756
+ candidateCount.set(candidate, count - 1);
2757
+ }
2758
+ }
2759
+ function addCandidateSet(candidateCount, candidates) {
2760
+ for (const candidate of candidates) candidateCount.set(candidate, (candidateCount.get(candidate) ?? 0) + 1);
2761
+ }
2762
+ function createSourceCandidateCollector(options = {}) {
2763
+ const candidatesById = /* @__PURE__ */ new Map();
2764
+ const scanCandidatesById = /* @__PURE__ */ new Map();
2765
+ const transformCandidatesById = /* @__PURE__ */ new Map();
2766
+ const cssCandidatesById = /* @__PURE__ */ new Map();
2767
+ const sourceById = /* @__PURE__ */ new Map();
2768
+ const candidateCount = /* @__PURE__ */ new Map();
2769
+ let inlineIncludedCandidates = /* @__PURE__ */ new Set();
2770
+ let inlineExcludedCandidates = /* @__PURE__ */ new Set();
2771
+ async function sync(id, source) {
2772
+ const normalizedId = cleanUrl(id);
2773
+ sourceById.set(normalizedId, source);
2774
+ const extension = resolveSourceCandidateExtension(normalizedId);
2775
+ const contentCacheKey = createSourceCandidateContentCacheKey(extension, source, options.bareArbitraryValues, options.extractor);
2776
+ const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2777
+ if (cachedCandidates) {
2778
+ replaceScanLayer(normalizedId, new Set(cachedCandidates));
2779
+ return;
2780
+ }
2781
+ const nextCandidates = await extractCandidates(source, extension, options);
2782
+ sourceCandidateContentCache.set(contentCacheKey, [...nextCandidates]);
2783
+ replaceScanLayer(normalizedId, nextCandidates);
2784
+ }
2785
+ async function syncCss(id, source) {
2786
+ const normalizedId = cleanUrl(id);
2787
+ const contentCacheKey = createSourceCandidateContentCacheKey("css", source, options.bareArbitraryValues, options.extractor);
2788
+ const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2789
+ if (cachedCandidates) {
2790
+ replaceCssLayer(normalizedId, new Set(cachedCandidates));
2791
+ return;
2792
+ }
2793
+ const nextCandidates = await extractCandidates(source, "css", options);
2794
+ sourceCandidateContentCache.set(contentCacheKey, [...nextCandidates]);
2795
+ replaceCssLayer(normalizedId, nextCandidates);
2796
+ }
2797
+ async function merge(id, source) {
2798
+ const normalizedId = cleanUrl(id);
2799
+ const extension = resolveSourceCandidateExtension(normalizedId);
2800
+ const contentCacheKey = createSourceCandidateContentCacheKey(extension, source, options.bareArbitraryValues, options.extractor);
2801
+ const cachedCandidates = sourceCandidateContentCache.get(contentCacheKey);
2802
+ const extractedCandidates = cachedCandidates ? new Set(cachedCandidates) : await extractCandidates(source, extension, options);
2803
+ if (!cachedCandidates) sourceCandidateContentCache.set(contentCacheKey, [...extractedCandidates]);
2804
+ replaceTransformLayer(normalizedId, extractedCandidates);
2805
+ }
2806
+ async function syncFile(id) {
2807
+ const normalizedId = cleanUrl(id);
2808
+ await sync(normalizedId, await readFile(normalizedId, "utf8"));
2809
+ }
2810
+ async function syncCurrentFile(id) {
2811
+ const normalizedId = cleanUrl(id);
2812
+ transformCandidatesById.delete(normalizedId);
2813
+ await syncFile(normalizedId);
2814
+ }
2815
+ async function scanRoot({ entries, explicit, root, outDir }) {
2816
+ const files = await resolveSourceCandidateScanFiles({
2817
+ entries,
2818
+ explicit,
2819
+ filter: isSourceCandidateRequest,
2820
+ outDir,
2821
+ root
2822
+ });
2823
+ await Promise.all(files.map((file) => syncFile(resolveSourceScanPath(file))));
2824
+ }
2825
+ function replaceFinal(id, nextCandidates) {
2826
+ const normalizedId = cleanUrl(id);
2827
+ const previousCandidates = candidatesById.get(normalizedId);
2828
+ if (previousCandidates) {
2829
+ removeCandidateSet(candidateCount, previousCandidates);
2830
+ candidatesById.delete(normalizedId);
2831
+ }
2832
+ if (nextCandidates.size === 0) return;
2833
+ candidatesById.set(normalizedId, nextCandidates);
2834
+ addCandidateSet(candidateCount, nextCandidates);
2835
+ }
2836
+ function replaceScanLayer(id, nextCandidates) {
2837
+ const normalizedId = cleanUrl(id);
2838
+ if (nextCandidates.size === 0) scanCandidatesById.delete(normalizedId);
2839
+ else scanCandidatesById.set(normalizedId, nextCandidates);
2840
+ recompute(normalizedId);
2841
+ }
2842
+ function replaceTransformLayer(id, nextCandidates) {
2843
+ const normalizedId = cleanUrl(id);
2844
+ if (nextCandidates.size === 0) transformCandidatesById.delete(normalizedId);
2845
+ else transformCandidatesById.set(normalizedId, nextCandidates);
2846
+ recompute(normalizedId);
2847
+ }
2848
+ function replaceCssLayer(id, nextCandidates) {
2849
+ const normalizedId = cleanUrl(id);
2850
+ if (nextCandidates.size === 0) cssCandidatesById.delete(normalizedId);
2851
+ else cssCandidatesById.set(normalizedId, nextCandidates);
2852
+ recompute(normalizedId);
2853
+ }
2854
+ function recompute(id) {
2855
+ const normalizedId = cleanUrl(id);
2856
+ replaceFinal(normalizedId, new Set([
2857
+ ...scanCandidatesById.get(normalizedId) ?? [],
2858
+ ...transformCandidatesById.get(normalizedId) ?? [],
2859
+ ...cssCandidatesById.get(normalizedId) ?? []
2860
+ ]));
2861
+ }
2862
+ function syncInline(inlineCandidates) {
2863
+ inlineIncludedCandidates = new Set(inlineCandidates?.included ?? []);
2864
+ inlineExcludedCandidates = new Set(inlineCandidates?.excluded ?? []);
2865
+ }
2866
+ function remove(id) {
2867
+ const normalizedId = cleanUrl(id);
2868
+ scanCandidatesById.delete(normalizedId);
2869
+ transformCandidatesById.delete(normalizedId);
2870
+ cssCandidatesById.delete(normalizedId);
2871
+ sourceById.delete(normalizedId);
2872
+ const previousCandidates = candidatesById.get(normalizedId);
2873
+ if (!previousCandidates) return;
2874
+ removeCandidateSet(candidateCount, previousCandidates);
2875
+ candidatesById.delete(normalizedId);
2876
+ }
2877
+ function source(id) {
2878
+ return sourceById.get(cleanUrl(id));
2879
+ }
2880
+ function values() {
2881
+ const values = new Set([...candidateCount.keys(), ...inlineIncludedCandidates]);
2882
+ for (const candidate of inlineExcludedCandidates) values.delete(candidate);
2883
+ return values;
2884
+ }
2885
+ function valuesForEntries(entries, options = {}) {
2886
+ if (entries === void 0) {
2887
+ if (!options.excludeEntries?.length) return values();
2888
+ }
2889
+ const filtered = /* @__PURE__ */ new Set();
2890
+ for (const [id, candidates] of candidatesById) {
2891
+ if (entries !== void 0 && !isFileMatchedByTailwindSourceEntries(id, entries)) continue;
2892
+ if (options.excludeEntries?.length && isFileMatchedByTailwindSourceEntries(id, options.excludeEntries)) continue;
2893
+ for (const candidate of candidates) filtered.add(candidate);
2894
+ }
2895
+ for (const candidate of inlineIncludedCandidates) filtered.add(candidate);
2896
+ for (const candidate of inlineExcludedCandidates) filtered.delete(candidate);
2897
+ return filtered;
2898
+ }
2899
+ function sourcesForEntries(entries, options = {}) {
2900
+ const sources = /* @__PURE__ */ new Map();
2901
+ const addCandidateSource = (candidate, id) => {
2902
+ let candidateSources = sources.get(candidate);
2903
+ if (!candidateSources) {
2904
+ candidateSources = /* @__PURE__ */ new Set();
2905
+ sources.set(candidate, candidateSources);
2906
+ }
2907
+ if (id) candidateSources.add(id);
2908
+ };
2909
+ for (const [id, candidates] of candidatesById) {
2910
+ if (entries !== void 0 && !isFileMatchedByTailwindSourceEntries(id, entries)) continue;
2911
+ if (options.excludeEntries?.length && isFileMatchedByTailwindSourceEntries(id, options.excludeEntries)) continue;
2912
+ for (const candidate of candidates) addCandidateSource(candidate, id);
2913
+ }
2914
+ for (const candidate of inlineIncludedCandidates) addCandidateSource(candidate, void 0);
2915
+ for (const candidate of inlineExcludedCandidates) sources.delete(candidate);
2916
+ return sources;
2917
+ }
2918
+ function clear() {
2919
+ candidatesById.clear();
2920
+ scanCandidatesById.clear();
2921
+ transformCandidatesById.clear();
2922
+ cssCandidatesById.clear();
2923
+ sourceById.clear();
2924
+ candidateCount.clear();
2925
+ inlineIncludedCandidates.clear();
2926
+ inlineExcludedCandidates.clear();
2927
+ }
2928
+ function snapshot() {
2929
+ return {
2930
+ candidatesById: [...candidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2931
+ cssCandidatesById: [...cssCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2932
+ scanCandidatesById: [...scanCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2933
+ sourceById: [...sourceById.entries()],
2934
+ transformCandidatesById: [...transformCandidatesById.entries()].map(([id, candidates]) => [id, [...candidates]]),
2935
+ inlineExcludedCandidates: [...inlineExcludedCandidates],
2936
+ inlineIncludedCandidates: [...inlineIncludedCandidates]
2937
+ };
2938
+ }
2939
+ function restore(snapshot) {
2940
+ clear();
2941
+ inlineExcludedCandidates = new Set(snapshot.inlineExcludedCandidates);
2942
+ inlineIncludedCandidates = new Set(snapshot.inlineIncludedCandidates);
2943
+ const scanEntries = snapshot.scanCandidatesById ?? snapshot.candidatesById;
2944
+ for (const [id, candidates] of scanEntries) {
2945
+ const candidateSet = new Set(candidates);
2946
+ if (candidateSet.size === 0) continue;
2947
+ scanCandidatesById.set(id, candidateSet);
2948
+ }
2949
+ for (const [id, candidates] of snapshot.transformCandidatesById ?? []) {
2950
+ const candidateSet = new Set(candidates);
2951
+ if (candidateSet.size === 0) continue;
2952
+ transformCandidatesById.set(id, candidateSet);
2953
+ }
2954
+ for (const [id, candidates] of snapshot.cssCandidatesById ?? []) {
2955
+ const candidateSet = new Set(candidates);
2956
+ if (candidateSet.size === 0) continue;
2957
+ cssCandidatesById.set(id, candidateSet);
2958
+ }
2959
+ for (const [id, candidates] of snapshot.candidatesById) {
2960
+ const candidateSet = new Set(candidates);
2961
+ if (candidateSet.size === 0) continue;
2962
+ candidatesById.set(id, candidateSet);
2963
+ addCandidateSet(candidateCount, candidateSet);
2964
+ }
2965
+ for (const [id, source] of snapshot.sourceById ?? []) sourceById.set(id, source);
2966
+ }
2967
+ return {
2968
+ sync,
2969
+ syncCss,
2970
+ merge,
2971
+ syncFile,
2972
+ syncCurrentFile,
2973
+ scanRoot,
2974
+ syncInline,
2975
+ remove,
2976
+ source,
2977
+ values,
2978
+ valuesForEntries,
2979
+ sourcesForEntries,
2980
+ snapshot,
2981
+ restore,
2982
+ clear
2983
+ };
2984
+ }
2985
+ //#endregion
2986
+ //#region src/bundlers/shared/hmr-timing.ts
2987
+ function shouldEmitHmrTiming() {
2988
+ return process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
2989
+ }
2990
+ function shouldEmitHumanReadableTiming() {
2991
+ return process.env["WEAPP_TW_HMR_TIMING"] === "1" && process.env["WEAPP_TW_HMR_TIMING_LOG"] !== "0";
2992
+ }
2993
+ function emitHmrTiming(bundler, phase, durationMs, details = {}) {
2994
+ if (!shouldEmitHmrTiming()) return;
2995
+ const serializableDetails = { ...details };
2996
+ delete serializableDetails.emit;
2997
+ const payload = {
2998
+ bundler,
2999
+ phase,
3000
+ durationMs: Math.max(0, Math.round(durationMs)),
3001
+ ...serializableDetails,
3002
+ ...typeof details.wallMs === "number" ? { wallMs: Math.max(0, Math.round(details.wallMs)) } : {}
3003
+ };
3004
+ process.stdout.write(`[weapp-tailwindcss:hmr] ${JSON.stringify(payload)}\n`);
3005
+ if (shouldEmitHumanReadableTiming()) {
3006
+ const fileSuffix = details.file ? ` file=${details.file}` : "";
3007
+ if (details.metric === "total") {
3008
+ const hooks = details.hooks ? Object.entries(details.hooks).map(([hook, summary]) => `${hook}=${Math.max(0, Math.round(summary.durationMs))}ms/${summary.count}`).join(", ") : "";
3009
+ const hookSuffix = hooks ? ` (${hooks})` : "";
3010
+ const wallSuffix = typeof payload.wallMs === "number" ? ` wall=${payload.wallMs}ms` : "";
3011
+ process.stdout.write(`[weapp-tailwindcss] ${bundler}:weapp-tailwindcss 总耗时 ${payload.durationMs}ms${wallSuffix}${hookSuffix}\n`);
3012
+ return;
3013
+ }
3014
+ process.stdout.write(`[weapp-tailwindcss] ${bundler}:${phase} 耗时 ${payload.durationMs}ms${fileSuffix}\n`);
3015
+ }
3016
+ }
3017
+ function createHmrTimingRecorder(bundler) {
3018
+ const session = {
3019
+ hooks: {},
3020
+ totalMs: 0
3021
+ };
3022
+ const record = (phase, durationMs, details = {}) => {
3023
+ const roundedDuration = Math.max(0, Math.round(durationMs));
3024
+ if (session.startedAt === void 0) session.startedAt = performance.now() - Math.max(0, durationMs);
3025
+ session.totalMs += Math.max(0, durationMs);
3026
+ const current = session.hooks[phase] ?? {
3027
+ count: 0,
3028
+ durationMs: 0,
3029
+ maxMs: 0
3030
+ };
3031
+ current.count += 1;
3032
+ current.durationMs += roundedDuration;
3033
+ current.maxMs = Math.max(current.maxMs, roundedDuration);
3034
+ session.hooks[phase] = current;
3035
+ if (details.emit !== false) emitHmrTiming(bundler, phase, durationMs, details);
3036
+ };
3037
+ const measure = async (phase, task, details = {}) => {
3038
+ const startedAt = performance.now();
3039
+ try {
3040
+ return await task();
3041
+ } finally {
3042
+ record(phase, performance.now() - startedAt, details);
3043
+ }
3044
+ };
3045
+ const emitTotal = (phase = "total") => {
3046
+ if (session.totalMs <= 0) return;
3047
+ const wallMs = session.startedAt === void 0 ? session.totalMs : performance.now() - session.startedAt;
3048
+ emitHmrTiming(bundler, phase, session.totalMs, {
3049
+ hooks: session.hooks,
3050
+ metric: "total",
3051
+ wallMs
3052
+ });
3053
+ session.hooks = {};
3054
+ delete session.startedAt;
3055
+ session.totalMs = 0;
3056
+ };
3057
+ return {
3058
+ emitTotal,
3059
+ measure,
3060
+ record
3061
+ };
3062
+ }
3063
+ //#endregion
3064
+ export { isCssSourceTraceEnabled as _, createTailwindV3DefaultExtractor as a, validateCandidatesByGenerator as c, isPureLocalCssImportWrapper as d, finalizeMiniProgramCss as f, createCssTokenSourceMap as g, createCssSourceTraceCacheSignature as h, isSourceCandidateRequest as i, extractMarkedUserLayerComponentsCss as l, annotateCssSourceTrace as m, emitHmrTiming as n, createBundleRuntimeClassSetManager as o, pruneMiniProgramGeneratedCss as p, createSourceCandidateCollector as r, generateCssByGenerator as s, createHmrTimingRecorder as t, mergeMarkedUserLayerComponentsCss as u, processCachedTask as v };