weapp-tailwindcss 5.0.1 → 5.0.2

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 (54) hide show
  1. package/dist/{bundle-state-CBF5YX1m.js → bundle-state-Bvj01pW7.js} +35 -3
  2. package/dist/{bundle-state-CQmxxx0R.mjs → bundle-state-DY3eq4Gz.mjs} +24 -4
  3. package/dist/bundlers/shared/generated-css-marker.d.ts +6 -0
  4. package/dist/bundlers/shared/generator-css/directives.d.ts +1 -0
  5. package/dist/bundlers/shared/generator-css/source-files.d.ts +11 -5
  6. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +2 -0
  7. package/dist/bundlers/shared/generator-css.d.ts +1 -0
  8. package/dist/bundlers/vite/bundle-state.d.ts +5 -1
  9. package/dist/bundlers/vite/css-finalizer.d.ts +12 -3
  10. package/dist/bundlers/vite/generate-bundle.d.ts +22 -6
  11. package/dist/bundlers/vite/processed-css-assets.d.ts +10 -2
  12. package/dist/bundlers/vite/source-candidates.d.ts +2 -0
  13. package/dist/bundlers/webpack/loaders/watch-dependencies.d.ts +8 -0
  14. package/dist/cli.js +1 -0
  15. package/dist/cli.mjs +1 -0
  16. package/dist/core.js +1 -1
  17. package/dist/core.mjs +1 -1
  18. package/dist/{generator-CvmsIQFI.js → generator-Bd1LntD3.js} +1 -1
  19. package/dist/{generator-DDtsUvkH.mjs → generator-DRHWC1t-.mjs} +1 -1
  20. package/dist/generator.js +2 -2
  21. package/dist/generator.mjs +2 -2
  22. package/dist/gulp.js +16 -10
  23. package/dist/gulp.mjs +14 -8
  24. package/dist/{incremental-runtime-class-set-BffodqHh.js → incremental-runtime-class-set-Bl18sFqt.js} +540 -694
  25. package/dist/{incremental-runtime-class-set-DArodvWs.mjs → incremental-runtime-class-set-CAEuUesH.mjs} +495 -619
  26. package/dist/index.js +4 -4
  27. package/dist/index.mjs +4 -4
  28. package/dist/{postcss-BzNYQUOH.mjs → postcss-CJrmfXvi.mjs} +4 -4
  29. package/dist/{postcss-DE0TOtV9.js → postcss-DfnqZ4Bm.js} +4 -4
  30. package/dist/postcss.js +1 -1
  31. package/dist/postcss.mjs +1 -1
  32. package/dist/{precheck-BzYPm-EG.js → precheck-Bj5ReSOU.js} +2 -2
  33. package/dist/{precheck-jZvTVXXG.mjs → precheck-CUr1DYyy.mjs} +2 -2
  34. package/dist/presets.js +2 -2
  35. package/dist/presets.mjs +2 -2
  36. package/dist/{source-candidates-BuTlMabx.mjs → source-candidates-D7b-Jzsx.mjs} +44 -11
  37. package/dist/{source-candidates-CxoIaS88.js → source-candidates-DQxvGPSw.js} +49 -10
  38. package/dist/tailwindcss/source-scan.d.ts +3 -1
  39. package/dist/{tailwindcss-CCZcu0lr.mjs → tailwindcss-D5RogwtV.mjs} +2 -2
  40. package/dist/{tailwindcss-DZckITp1.js → tailwindcss-jvoYizzX.js} +7 -1
  41. package/dist/{v3-engine-DGBhUnjn.mjs → v3-engine-BCUGX3gX.mjs} +637 -31
  42. package/dist/{v3-engine-M6Aqru5T.js → v3-engine-CmIF_gsq.js} +768 -30
  43. package/dist/{vite-DgRkWVPG.js → vite-D1ZdgbWa.js} +533 -290
  44. package/dist/{vite-BBcQIJpD.mjs → vite-jBTi5CwO.mjs} +532 -289
  45. package/dist/vite.js +1 -1
  46. package/dist/vite.mjs +1 -1
  47. package/dist/{runtime-registry-DpcR3IHI.js → watch-dependencies-zwx4EhBn.js} +39 -0
  48. package/dist/weapp-tw-css-import-rewrite-loader.js +1932 -1621
  49. package/dist/weapp-tw-runtime-classset-loader.js +6 -6
  50. package/dist/{webpack-D43aMQzO.mjs → webpack-CChDqRrl.mjs} +6 -6
  51. package/dist/{webpack-D-gb4ZvO.js → webpack-vk2uqSnK.js} +7 -7
  52. package/dist/webpack.js +1 -1
  53. package/dist/webpack.mjs +1 -1
  54. package/package.json +2 -2
@@ -2,23 +2,23 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_runtime_registry = require("./runtime-registry-DpcR3IHI.js");
5
+ const require_watch_dependencies = require("./watch-dependencies-zwx4EhBn.js");
6
6
  let node_buffer = require("node:buffer");
7
7
  let node_process = require("node:process");
8
- node_process = require_runtime_registry.__toESM(node_process);
8
+ node_process = require_watch_dependencies.__toESM(node_process);
9
9
  let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
10
+ let node_fs = require("node:fs");
11
+ node_fs = require_watch_dependencies.__toESM(node_fs);
10
12
  let node_path = require("node:path");
11
- node_path = require_runtime_registry.__toESM(node_path);
13
+ node_path = require_watch_dependencies.__toESM(node_path);
12
14
  let node_util = require("node:util");
13
15
  let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
14
16
  let tailwindcss_patch = require("tailwindcss-patch");
15
- let node_fs = require("node:fs");
16
- node_fs = require_runtime_registry.__toESM(node_fs);
17
17
  let node_module = require("node:module");
18
18
  let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
19
19
  let node_url = require("node:url");
20
20
  let debug = require("debug");
21
- debug = require_runtime_registry.__toESM(debug);
21
+ debug = require_watch_dependencies.__toESM(debug);
22
22
  let node_fs_promises = require("node:fs/promises");
23
23
  require("fast-glob");
24
24
  let tailwindcss_config = require("tailwindcss-config");
@@ -26,7 +26,7 @@ require("micromatch");
26
26
  let _weapp_core_escape = require("@weapp-core/escape");
27
27
  require("magic-string");
28
28
  let _babel_traverse = require("@babel/traverse");
29
- _babel_traverse = require_runtime_registry.__toESM(_babel_traverse);
29
+ _babel_traverse = require_watch_dependencies.__toESM(_babel_traverse);
30
30
  require("@babel/parser");
31
31
  require("@babel/types");
32
32
  require("@ast-core/escape");
@@ -365,7 +365,7 @@ function compileCssMacroConditionalComments(css, options) {
365
365
  const platformTokens = createPlatformTokenSet(resolveCssMacroPlatform(options));
366
366
  if (platformTokens.size === 0 || !css.includes("#if")) return css;
367
367
  try {
368
- const root = require_runtime_registry.postcss_default.parse(css);
368
+ const root = require_watch_dependencies.postcss_default.parse(css);
369
369
  const transformContainer = (container) => {
370
370
  const stack = [];
371
371
  for (const node of [...container.nodes ?? []]) {
@@ -420,7 +420,7 @@ function hasCssMacroTailwindV4Directive(css) {
420
420
  if (!css?.includes("css-macro")) return false;
421
421
  try {
422
422
  let found = false;
423
- require_runtime_registry.postcss_default.parse(css).walkAtRules("plugin", (rule) => {
423
+ require_watch_dependencies.postcss_default.parse(css).walkAtRules("plugin", (rule) => {
424
424
  if (isCssMacroPluginRequest(parseCssPluginRequest(rule.params))) found = true;
425
425
  });
426
426
  return found;
@@ -458,7 +458,7 @@ function hasCssMacroStyleOptions(options) {
458
458
  return Boolean(options?.[CSS_MACRO_STYLE_OPTIONS_MARKER]);
459
459
  }
460
460
  async function transformCssMacroCss(css, options) {
461
- const result = (await require_runtime_registry.postcss_default([creator()]).process(css, { from: void 0 })).css;
461
+ const result = (await require_watch_dependencies.postcss_default([creator()]).process(css, { from: void 0 })).css;
462
462
  return compileCssMacroConditionalComments(result, options);
463
463
  }
464
464
  //#endregion
@@ -948,7 +948,7 @@ function collectCssInlineSourceCandidates(root) {
948
948
  excluded
949
949
  };
950
950
  }
951
- function normalizeLegacyContentEntries(content, base) {
951
+ function normalizeLegacyContentEntries(content, base, options = {}) {
952
952
  if (typeof content === "string") {
953
953
  const negated = content.startsWith("!");
954
954
  return [{
@@ -957,8 +957,8 @@ function normalizeLegacyContentEntries(content, base) {
957
957
  pattern: normalizeGlobPattern(negated ? content.slice(1) : content)
958
958
  }];
959
959
  }
960
- if (Array.isArray(content)) return content.flatMap((item) => normalizeLegacyContentEntries(item, base));
961
- if (isLegacyContentObject$1(content)) return normalizeLegacyContentEntries(content.files, base);
960
+ if (Array.isArray(content)) return content.flatMap((item) => normalizeLegacyContentEntries(item, base, options));
961
+ if (isLegacyContentObject$1(content)) return normalizeLegacyContentEntries(content.files, content.relative && options.relativeBase ? options.relativeBase : base, options);
962
962
  return [];
963
963
  }
964
964
  async function pathExistsAsDirectory(file) {
@@ -1968,7 +1968,7 @@ function resolveStyleOptions$1(source, options) {
1968
1968
  function collectCustomPropertyValues(css) {
1969
1969
  const values = /* @__PURE__ */ new Map();
1970
1970
  try {
1971
- require_runtime_registry.postcss_default.parse(css).walkDecls((decl) => {
1971
+ require_watch_dependencies.postcss_default.parse(css).walkDecls((decl) => {
1972
1972
  if (decl.prop.startsWith("--")) values.set(decl.prop, decl.value.trim());
1973
1973
  });
1974
1974
  } catch {}
@@ -2003,9 +2003,10 @@ function parseImportSourceParam$1(params) {
2003
2003
  };
2004
2004
  }
2005
2005
  function isTailwindCssImport$1(params) {
2006
- return /^\s*(['"])tailwindcss(?:\/[^'"]*)?\1/.test(params);
2006
+ const specifier = parseCssImportSpecifier$2(params);
2007
+ return specifier === "tailwindcss" || specifier?.startsWith("tailwindcss/") || specifier?.replaceAll("\\", "/").endsWith("/tailwindcss/index.css");
2007
2008
  }
2008
- function parseCssImportSpecifier$1(params) {
2009
+ function parseCssImportSpecifier$2(params) {
2009
2010
  const value = params.trim();
2010
2011
  const quoted = /^(['"])(.*?)\1/.exec(value);
2011
2012
  if (quoted) return quoted[2];
@@ -2013,7 +2014,7 @@ function parseCssImportSpecifier$1(params) {
2013
2014
  return url?.[2] ?? url?.[3];
2014
2015
  }
2015
2016
  function isTailwindCssPreflightImport(params) {
2016
- const specifier = parseCssImportSpecifier$1(params);
2017
+ const specifier = parseCssImportSpecifier$2(params);
2017
2018
  return specifier === "tailwindcss/preflight.css" || specifier === "tailwindcss/preflight";
2018
2019
  }
2019
2020
  function hasImportLayerOption(params) {
@@ -2023,7 +2024,7 @@ function removeUnlayeredTailwindV4PreflightImports(css) {
2023
2024
  if (!css.includes("preflight")) return css;
2024
2025
  let root;
2025
2026
  try {
2026
- root = require_runtime_registry.postcss_default.parse(css);
2027
+ root = require_watch_dependencies.postcss_default.parse(css);
2027
2028
  } catch {
2028
2029
  return css;
2029
2030
  }
@@ -2059,7 +2060,7 @@ async function resolveCssDefinedScanSources(source) {
2059
2060
  const from = source.dependencies[0];
2060
2061
  let root;
2061
2062
  try {
2062
- root = require_runtime_registry.postcss_default.parse(source.css, { from });
2063
+ root = require_watch_dependencies.postcss_default.parse(source.css, { from });
2063
2064
  } catch {
2064
2065
  return;
2065
2066
  }
@@ -2102,7 +2103,7 @@ function removeUnsupportedThemeVendorKeyframes(css) {
2102
2103
  if (!css.includes("@theme") || !css.includes("@-")) return css;
2103
2104
  let root;
2104
2105
  try {
2105
- root = require_runtime_registry.postcss_default.parse(css);
2106
+ root = require_watch_dependencies.postcss_default.parse(css);
2106
2107
  } catch {
2107
2108
  return css;
2108
2109
  }
@@ -2248,189 +2249,217 @@ function createTailwindV4Engine(source) {
2248
2249
  };
2249
2250
  }
2250
2251
  //#endregion
2251
- //#region src/tailwindcss/v4-engine/source.ts
2252
- function isPostcssPluginImportTarget(value) {
2253
- if (!value) return false;
2254
- return value === "@tailwindcss/postcss" || value.includes("/postcss");
2252
+ //#region src/bundlers/shared/generator-css/config-directive.ts
2253
+ function quoteCssString(value) {
2254
+ return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
2255
2255
  }
2256
- function uniqueDefined(values) {
2257
- return [...new Set(values.filter((value) => typeof value === "string" && value.length > 0))];
2256
+ function toCssPath(value) {
2257
+ return value.replaceAll("\\", "/");
2258
2258
  }
2259
- function getProjectRoot$1(patcher) {
2260
- return patcher.options?.projectRoot ?? node_process.default.cwd();
2259
+ function prependConfigDirective(css, config) {
2260
+ if (!config || /@config\s+/.test(css)) return css;
2261
+ return `@config "${quoteCssString(toCssPath(config))}";\n${css}`;
2261
2262
  }
2262
- function resolveBase(value, fallback) {
2263
- return value === void 0 ? fallback : node_path.default.isAbsolute(value) ? node_path.default.resolve(value) : node_path.default.resolve(fallback, value);
2263
+ function normalizeConfigDirective(css, config) {
2264
+ if (!config || !/@config\s+/.test(css)) return css;
2265
+ return css.replace(/@config\s+(["'])(.+?)\1\s*;?/, `@config "${quoteCssString(toCssPath(config))}";`);
2264
2266
  }
2265
- function resolveConfigDir(config, projectRoot) {
2266
- if (!config) return;
2267
- const configPath = node_path.default.isAbsolute(config) ? config : node_path.default.resolve(projectRoot, config);
2268
- return node_path.default.dirname(configPath);
2267
+ //#endregion
2268
+ //#region src/bundlers/shared/generator-css/markers.ts
2269
+ const TAILWIND_V4_BANNER_RE = /\/\*!\s*tailwindcss v4\./;
2270
+ const TAILWIND_GENERATED_CSS_MARKER_RE = /\/\*!\s*tailwindcss v|@property\s+--tw-|--tw-|:not\(#\\#\)|\.[^,{]*(?:\\:|\\\[|\\#)|(?::host|page|\.tw-root|wx-root-portal-content)[^{]*\{[^}]*--(?:color|spacing|text|font-weight|radius)-/;
2271
+ const GENERATOR_PLACEHOLDER_MARKER_RE = /\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\//i;
2272
+ const GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE = /\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\/\s*/gi;
2273
+ const TAILWIND_BANNER_PREFIX_RE = /^\/\*!\s*tailwindcss v[^*]*\*\/\s*/i;
2274
+ const TAILWIND_BANNER_RE = /\/\*!\s*tailwindcss v[^*]*\*\//i;
2275
+ const TAILWIND_BANNER_GLOBAL_RE = /\/\*!\s*tailwindcss v[^*]*\*\/\s*/gi;
2276
+ const VITE_MARKER_RE = /\/\*\$vite\$:[^*]*\*\//g;
2277
+ function createCssAppend(base, extra) {
2278
+ if (!base) return extra;
2279
+ if (!extra) return base;
2280
+ return `${base}\n${extra}`;
2269
2281
  }
2270
- function isBarePackageSpecifier(specifier) {
2271
- return !specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.includes("\\") && !/^[a-z][a-z\d+.-]*:/i.test(specifier);
2282
+ function splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss) {
2283
+ const trimmedRaw = rawSource.trim();
2284
+ const trimmedTailwind = rawTailwindCss.trim();
2285
+ if (trimmedRaw === trimmedTailwind) return {
2286
+ before: "",
2287
+ after: ""
2288
+ };
2289
+ if (trimmedTailwind.startsWith(trimmedRaw)) return {
2290
+ before: "",
2291
+ after: ""
2292
+ };
2293
+ const start = rawSource.indexOf(rawTailwindCss);
2294
+ if (start === -1) return;
2295
+ return {
2296
+ before: rawSource.slice(0, start),
2297
+ after: rawSource.slice(start + rawTailwindCss.length)
2298
+ };
2272
2299
  }
2273
- function parseCssImportSpecifier(params) {
2274
- const value = params.trim();
2275
- const quoted = /^(['"])(.*?)\1/.exec(value);
2276
- if (quoted) {
2277
- const specifier = quoted[2];
2278
- if (specifier === void 0) return;
2279
- return {
2280
- quote: quoted[1],
2281
- raw: quoted[0],
2282
- specifier
2283
- };
2300
+ function splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss) {
2301
+ const match = GENERATOR_PLACEHOLDER_MARKER_RE.exec(rawSource);
2302
+ if (!match || match.index === void 0) return;
2303
+ let afterStart = match.index + match[0].length;
2304
+ while (/\s/.test(rawSource[afterStart] ?? "")) afterStart++;
2305
+ if (rawTailwindCss && rawSource.slice(afterStart).startsWith(rawTailwindCss)) {
2306
+ afterStart += rawTailwindCss.length;
2307
+ while (/\s/.test(rawSource[afterStart] ?? "")) afterStart++;
2284
2308
  }
2285
- const url = /^url\(\s*(?:(['"])(.*?)\1|([^'")\s]+))\s*\)/.exec(value);
2286
- if (!url) return;
2287
- const specifier = url[2] ?? url[3];
2288
- if (specifier === void 0) return;
2289
2309
  return {
2290
- quote: url[1],
2291
- raw: url[0],
2292
- specifier
2310
+ before: rawSource.slice(0, match.index),
2311
+ after: rawSource.slice(afterStart)
2293
2312
  };
2294
2313
  }
2295
- function quoteCssImportSpecifier(specifier, quote = "\"") {
2296
- return `${quote}${specifier.replaceAll("\\", "\\\\").replaceAll(quote, `\\${quote}`)}${quote}`;
2314
+ function splitTailwindGeneratedCssByBanner(rawSource, start) {
2315
+ const match = start === void 0 ? TAILWIND_BANNER_RE.exec(rawSource) : { index: start };
2316
+ if (!match || match.index === void 0) return;
2317
+ return {
2318
+ before: rawSource.slice(0, match.index),
2319
+ after: [...rawSource.slice(match.index).matchAll(VITE_MARKER_RE)].map((item) => item[0]).join("\n")
2320
+ };
2297
2321
  }
2298
- function createTailwindV4CssImportSpecifierSet(packageName) {
2299
- const specifiers = new Set(["tailwindcss"]);
2300
- if (packageName && isBarePackageSpecifier(packageName)) specifiers.add(packageName);
2301
- return specifiers;
2322
+ function stripTailwindBanner(css) {
2323
+ return css.replace(TAILWIND_BANNER_PREFIX_RE, "");
2302
2324
  }
2303
- function normalizeTailwindV4CssPackageImports(css, packageName) {
2304
- if (!css.includes("tailwindcss")) return css;
2305
- let root;
2306
- try {
2307
- root = require_runtime_registry.postcss_default.parse(css);
2308
- } catch {
2309
- return css;
2310
- }
2311
- const importSpecifiers = createTailwindV4CssImportSpecifierSet(packageName);
2312
- let changed = false;
2313
- root.walkAtRules("import", (rule) => {
2314
- const parsed = parseCssImportSpecifier(rule.params);
2315
- if (!parsed || !importSpecifiers.has(parsed.specifier)) return;
2316
- rule.params = rule.params.replace(parsed.raw, quoteCssImportSpecifier(`${parsed.specifier}/index.css`, parsed.quote));
2317
- changed = true;
2318
- });
2319
- return changed ? root.toString() : css;
2325
+ function stripTailwindBanners(css) {
2326
+ return css.replace(TAILWIND_BANNER_GLOBAL_RE, "");
2320
2327
  }
2321
- function resolveTailwindCssImportTarget(patcher) {
2322
- const configuredPackageName = resolveTailwindcssOptions(patcher.options)?.packageName;
2323
- if (typeof configuredPackageName === "string" && configuredPackageName.length > 0 && !isPostcssPluginImportTarget(configuredPackageName)) return configuredPackageName;
2324
- const packageName = patcher.packageInfo?.name;
2325
- if (typeof packageName === "string" && packageName.length > 0 && !isPostcssPluginImportTarget(packageName)) return packageName;
2326
- return "tailwindcss";
2328
+ function stripGeneratorPlaceholderMarkers(css) {
2329
+ return css.replace(GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE, "");
2327
2330
  }
2328
- function readTailwindV4Options(patcher) {
2329
- return resolveTailwindcssOptions(patcher.options)?.v4 ?? patcher.options?.tailwind?.v4;
2331
+ function hasTailwindGeneratedCss(rawSource) {
2332
+ return TAILWIND_V4_BANNER_RE.test(rawSource);
2330
2333
  }
2331
- function isRawTailwindcssPatchOptions(options) {
2332
- return Boolean(options && "tailwindcss" in options);
2334
+ function hasTailwindGeneratedCssMarkers(rawSource) {
2335
+ return TAILWIND_GENERATED_CSS_MARKER_RE.test(rawSource) || GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource);
2333
2336
  }
2334
- function resolvePatchTailwindV4SourceOptions(patcher) {
2335
- if (patcher.options) {
2336
- const projectRoot = getProjectRoot$1(patcher);
2337
- const tailwindOptions = resolveTailwindcssOptions(patcher.options);
2338
- const tailwindV4Options = readTailwindV4Options(patcher);
2339
- const cwd = resolveBase(tailwindOptions?.cwd, projectRoot);
2340
- const configuredBase = tailwindV4Options?.configuredBase ?? (isRawTailwindcssPatchOptions(patcher.options) ? tailwindV4Options?.base : void 0);
2341
- const baseFallbacks = uniqueDefined([
2342
- configuredBase,
2343
- cwd,
2344
- projectRoot,
2345
- resolveConfigDir(tailwindOptions?.config, projectRoot)
2346
- ]);
2347
- return {
2348
- projectRoot,
2349
- cwd,
2350
- ...configuredBase === void 0 ? {} : { base: configuredBase },
2351
- baseFallbacks,
2352
- ...tailwindV4Options?.css === void 0 ? {} : { css: tailwindV4Options.css },
2353
- ...tailwindV4Options?.cssSources === void 0 ? {} : { cssSources: tailwindV4Options.cssSources },
2354
- ...tailwindV4Options?.cssEntries === void 0 ? {} : { cssEntries: tailwindV4Options.cssEntries },
2355
- packageName: resolveTailwindCssImportTarget(patcher)
2356
- };
2357
- }
2358
- return {
2359
- projectRoot: getProjectRoot$1(patcher),
2360
- packageName: resolveTailwindCssImportTarget(patcher)
2361
- };
2337
+ //#endregion
2338
+ //#region src/bundlers/shared/generator-css/directives.ts
2339
+ const TAILWIND_REMOVABLE_SOURCE_DIRECTIVE_NAMES = new Set([
2340
+ "config",
2341
+ "custom-variant",
2342
+ "layer",
2343
+ "plugin",
2344
+ "reference",
2345
+ "source",
2346
+ "tailwind",
2347
+ "theme",
2348
+ "utility",
2349
+ "variant"
2350
+ ]);
2351
+ const TAILWIND_ROOT_DIRECTIVE_NAMES = new Set([
2352
+ "config",
2353
+ "custom-variant",
2354
+ "plugin",
2355
+ "source",
2356
+ "tailwind",
2357
+ "theme",
2358
+ "utility",
2359
+ "variant"
2360
+ ]);
2361
+ const TAILWIND_ROOT_DIRECTIVE_RE = /@(?:import\s+(?:url\(\s*)?["']?tailwindcss4?(?:\/[^"')\s]*)?|(?:use|forward)\s+(?:url\(\s*)?["']?tailwindcss4?(?:\/[^"')\s]*)?|tailwind|config|custom-variant|plugin|source|theme|utility|variant)\b/;
2362
+ const TAILWIND_EXTRACTABLE_DIRECTIVE_RE = /^\s*@(?:import|use|forward|tailwind|config|source|reference|plugin)\b[\s\S]*?(?:;|$)/;
2363
+ const TAILWIND_EXTRACTABLE_LAYER_STATEMENT_RE = /^\s*@layer\s[^;{]+;\s*$/;
2364
+ const TAILWIND_EXTRACTABLE_BLOCK_START_RE = /^\s*@(?:layer|theme|utility|variant|custom-variant)\b[\s\S]*\{/;
2365
+ const TAILWIND_V3_SUBPATH_IMPORT_LAYERS = new Map([
2366
+ ["tailwindcss/base", "base"],
2367
+ ["tailwindcss/components", "components"],
2368
+ ["tailwindcss/utilities", "utilities"]
2369
+ ]);
2370
+ function parseImportRequest(params) {
2371
+ return /^(?:url\(\s*)?(["']?)([^"')\s]+)\1\s*\)?/.exec(params.trim())?.[2];
2362
2372
  }
2363
- function resolveTailwindV4SourceOptionsFromPatcher(patcher) {
2364
- const tailwindV4Options = readTailwindV4Options(patcher);
2365
- return omitUndefined({
2366
- ...resolvePatchTailwindV4SourceOptions(patcher),
2367
- sources: tailwindV4Options?.sources
2368
- });
2373
+ function parseConfigRequest(params) {
2374
+ return /^(["'])(.+)\1\s*;?$/.exec(params.trim())?.[2];
2369
2375
  }
2370
- function resolveTailwindV4Source(options) {
2371
- return (0, tailwindcss_patch.resolveTailwindV4Source)(options?.css === void 0 ? options : {
2372
- ...options,
2373
- css: normalizeTailwindV4CssPackageImports(options.css, options.packageName)
2374
- });
2376
+ function isPackageJsonImportRequest$1(request) {
2377
+ return typeof request === "string" && request.startsWith("#");
2375
2378
  }
2376
- async function resolveTailwindV4SourceFromPatcher(patcher) {
2377
- return resolveTailwindV4Source(resolveTailwindV4SourceOptionsFromPatcher(patcher));
2379
+ function isWeappTailwindcssImportRequest(request) {
2380
+ return request === "weapp-tailwindcss" || request?.startsWith("weapp-tailwindcss/");
2378
2381
  }
2379
- //#endregion
2380
- //#region src/bundlers/vite/static-config-content.ts
2381
- function skipWhitespaceAndComments(source, start) {
2382
- let index = start;
2383
- while (index < source.length) {
2384
- const char = source[index];
2385
- if (/\s/.test(char ?? "")) {
2386
- index += 1;
2387
- continue;
2382
+ function normalizeTailwindImportRequest(request, options = {}) {
2383
+ if (options.importFallback && isWeappTailwindcssImportRequest(request)) return request.replace(/^weapp-tailwindcss/, "tailwindcss");
2384
+ return request;
2385
+ }
2386
+ function replaceImportRequest(params, request, replacement) {
2387
+ const index = params.indexOf(request);
2388
+ if (index === -1) return params;
2389
+ return `${params.slice(0, index)}${replacement}${params.slice(index + request.length)}`;
2390
+ }
2391
+ function normalizeTailwindImportAtRules(root, options = {}) {
2392
+ if (!options.importFallback) return false;
2393
+ let changed = false;
2394
+ const seenCanonicalImports = /* @__PURE__ */ new Set();
2395
+ root.walkAtRules("import", (node) => {
2396
+ const request = parseImportRequest(node.params);
2397
+ const normalizedRequest = normalizeTailwindImportRequest(request, options);
2398
+ if (!normalizedRequest || !isTailwindImportRequest(normalizedRequest)) return;
2399
+ const normalizedParams = request && normalizedRequest !== request ? replaceImportRequest(node.params, request, normalizedRequest) : node.params;
2400
+ const normalizedKey = normalizedParams.trim();
2401
+ if (seenCanonicalImports.has(normalizedKey)) {
2402
+ node.remove();
2403
+ changed = true;
2404
+ return;
2388
2405
  }
2389
- if (char === "/" && source[index + 1] === "/") {
2390
- index += 2;
2391
- while (index < source.length && source[index] !== "\n") index += 1;
2392
- continue;
2406
+ seenCanonicalImports.add(normalizedKey);
2407
+ if (normalizedParams !== node.params) {
2408
+ node.params = normalizedParams;
2409
+ changed = true;
2393
2410
  }
2394
- if (char === "/" && source[index + 1] === "*") {
2395
- index += 2;
2396
- while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) index += 1;
2397
- index = Math.min(index + 2, source.length);
2398
- continue;
2411
+ });
2412
+ return changed;
2413
+ }
2414
+ function normalizeTailwindDirectiveLine(line, options = {}) {
2415
+ const trimmed = line.trimStart();
2416
+ if (/^@(?:use|forward)\b/.test(trimmed)) {
2417
+ const request = parseImportRequest(trimmed.replace(/^@(?:use|forward)\b/, ""));
2418
+ if (isTailwindImportRequest(request) || options.importFallback && isWeappTailwindcssImportRequest(request)) {
2419
+ const normalizedRequest = normalizeTailwindImportRequest(request, options);
2420
+ return replaceImportRequest(line.replace(/^(\s*)@(?:use|forward)\b/, "$1@import"), request, normalizedRequest);
2399
2421
  }
2400
- break;
2422
+ return line;
2401
2423
  }
2402
- return index;
2424
+ if (!options.importFallback || !trimmed.startsWith("@import")) return line;
2425
+ const request = parseImportRequest(trimmed.replace(/^@import\b/, ""));
2426
+ if (!request || !isWeappTailwindcssImportRequest(request)) return line;
2427
+ return replaceImportRequest(line, request, request.replace(/^weapp-tailwindcss/, "tailwindcss"));
2403
2428
  }
2404
- function readQuotedString(source, start) {
2405
- const quote = source[start];
2406
- if (quote !== "\"" && quote !== "'") return;
2407
- let value = "";
2408
- for (let index = start + 1; index < source.length; index++) {
2409
- const char = source[index];
2410
- if (char === "\\") {
2411
- const next = source[index + 1];
2412
- if (next === void 0) return;
2413
- value += next;
2414
- index += 1;
2415
- continue;
2429
+ function extractTailwindDirectiveLines(rawSource, options = {}) {
2430
+ const directives = [];
2431
+ const seenImports = /* @__PURE__ */ new Set();
2432
+ for (const line of stripGeneratorPlaceholderMarkers(rawSource).split(/\r?\n/)) {
2433
+ const trimmed = line.trim();
2434
+ if (!trimmed || trimmed.startsWith("//")) continue;
2435
+ const directive = TAILWIND_EXTRACTABLE_DIRECTIVE_RE.exec(line)?.[0] ?? TAILWIND_EXTRACTABLE_LAYER_STATEMENT_RE.exec(line)?.[0];
2436
+ if (!directive) continue;
2437
+ const normalized = normalizeTailwindDirectiveLine(directive.trimEnd(), options);
2438
+ const normalizedTrimmed = normalized.trim();
2439
+ if (options.removeConfig && normalizedTrimmed.startsWith("@config")) continue;
2440
+ const request = /^@(?:import|use|forward)\b/.test(normalizedTrimmed) ? parseImportRequest(normalizedTrimmed.replace(/^@(?:import|use|forward)\b/, "")) : void 0;
2441
+ if (request && !isTailwindImportRequest(request) && !isPackageJsonImportRequest$1(request)) continue;
2442
+ if (/^@(?:import|use|forward)\b/.test(normalizedTrimmed) && !request) continue;
2443
+ if (request && isTailwindImportRequest(request)) {
2444
+ const key = normalizedTrimmed;
2445
+ if (seenImports.has(key)) continue;
2446
+ seenImports.add(key);
2416
2447
  }
2417
- if (char === quote) return {
2418
- end: index + 1,
2419
- value
2420
- };
2421
- value += char;
2448
+ directives.push(normalized);
2422
2449
  }
2450
+ return directives;
2423
2451
  }
2424
- function readIdentifier(source, start) {
2425
- return /^[A-Z_$][\w$]*/i.exec(source.slice(start))?.[0];
2426
- }
2427
- function findMatchingBracket(source, start, open, close) {
2428
- let depth = 0;
2452
+ function stripPreprocessorLineComment(line) {
2429
2453
  let quote;
2430
- for (let index = start; index < source.length; index++) {
2431
- const char = source[index];
2454
+ let escaped = false;
2455
+ for (let index = 0; index < line.length; index++) {
2456
+ const char = line[index];
2457
+ if (escaped) {
2458
+ escaped = false;
2459
+ continue;
2460
+ }
2432
2461
  if (char === "\\") {
2433
- index += 1;
2462
+ escaped = true;
2434
2463
  continue;
2435
2464
  }
2436
2465
  if (quote) {
@@ -2441,1428 +2470,1500 @@ function findMatchingBracket(source, start, open, close) {
2441
2470
  quote = char;
2442
2471
  continue;
2443
2472
  }
2444
- if (char === "`") return;
2445
- if (char === open) {
2446
- depth += 1;
2447
- continue;
2448
- }
2449
- if (char === close) {
2450
- depth -= 1;
2451
- if (depth === 0) return index;
2452
- }
2473
+ if (char === "/" && line[index + 1] === "/" && (index === 0 || /\s/.test(line[index - 1]))) return line.slice(0, index).trimEnd();
2453
2474
  }
2475
+ return line;
2454
2476
  }
2455
- function findContentPropertyValue(source) {
2456
- let index = 0;
2457
- while (index < source.length) {
2458
- const nextIndex = source.indexOf("content", index);
2459
- if (nextIndex === -1) return;
2460
- const previous = source[nextIndex - 1];
2461
- const next = source[nextIndex + 7];
2462
- if (previous && /[\w$]/.test(previous) || next && /[\w$]/.test(next)) {
2463
- index = nextIndex + 7;
2477
+ function countBlockBraceDelta(line) {
2478
+ let quote;
2479
+ let escaped = false;
2480
+ let delta = 0;
2481
+ for (let index = 0; index < line.length; index++) {
2482
+ const char = line[index];
2483
+ if (escaped) {
2484
+ escaped = false;
2464
2485
  continue;
2465
2486
  }
2466
- let colonIndex = skipWhitespaceAndComments(source, nextIndex + 7);
2467
- if (source[colonIndex] !== ":") {
2468
- index = nextIndex + 7;
2487
+ if (char === "\\") {
2488
+ escaped = true;
2469
2489
  continue;
2470
2490
  }
2471
- colonIndex = skipWhitespaceAndComments(source, colonIndex + 1);
2472
- return { start: colonIndex };
2473
- }
2474
- }
2475
- function parseStaticContentArray(source, start) {
2476
- if (source[start] !== "[") return;
2477
- const value = [];
2478
- let index = skipWhitespaceAndComments(source, start + 1);
2479
- while (index < source.length) {
2480
- if (source[index] === "]") return {
2481
- end: index + 1,
2482
- value
2483
- };
2484
- const parsed = parseStaticContentValue(source, index);
2485
- if (!parsed) return;
2486
- value.push(parsed.value);
2487
- index = skipWhitespaceAndComments(source, parsed.end);
2488
- if (source[index] === ",") {
2489
- index = skipWhitespaceAndComments(source, index + 1);
2491
+ if (quote) {
2492
+ if (char === quote) quote = void 0;
2490
2493
  continue;
2491
2494
  }
2492
- if (source[index] === "]") continue;
2493
- return;
2495
+ if (char === "\"" || char === "'") {
2496
+ quote = char;
2497
+ continue;
2498
+ }
2499
+ if (char === "{") delta++;
2500
+ else if (char === "}") delta--;
2494
2501
  }
2502
+ return delta;
2495
2503
  }
2496
- function parseStaticContentObject(source, start) {
2497
- if (source[start] !== "{") return;
2498
- const end = findMatchingBracket(source, start, "{", "}");
2499
- if (end === void 0) return;
2500
- let index = skipWhitespaceAndComments(source, start + 1);
2501
- let files;
2502
- while (index < end) {
2503
- let key;
2504
- const quotedKey = readQuotedString(source, index);
2505
- if (quotedKey) {
2506
- key = quotedKey.value;
2507
- index = quotedKey.end;
2508
- } else {
2509
- key = readIdentifier(source, index);
2510
- if (!key) return;
2511
- index += key.length;
2512
- }
2513
- index = skipWhitespaceAndComments(source, index);
2514
- if (source[index] !== ":") return;
2515
- index = skipWhitespaceAndComments(source, index + 1);
2516
- const parsedValue = parseStaticContentValue(source, index);
2517
- if (!parsedValue) return;
2518
- if (key === "files") files = parsedValue.value;
2519
- index = skipWhitespaceAndComments(source, parsedValue.end);
2520
- if (source[index] === ",") {
2521
- index = skipWhitespaceAndComments(source, index + 1);
2504
+ function extractTailwindFallbackBlocks(rawSource) {
2505
+ const blocks = [];
2506
+ let current;
2507
+ let depth = 0;
2508
+ for (const rawLine of stripGeneratorPlaceholderMarkers(rawSource).split(/\r?\n/)) {
2509
+ const line = stripPreprocessorLineComment(rawLine);
2510
+ if (!line.trim()) continue;
2511
+ if (!current) {
2512
+ if (!TAILWIND_EXTRACTABLE_BLOCK_START_RE.test(line)) continue;
2513
+ current = [line];
2514
+ depth = countBlockBraceDelta(line);
2515
+ if (depth <= 0) {
2516
+ blocks.push(current.join("\n"));
2517
+ current = void 0;
2518
+ depth = 0;
2519
+ }
2522
2520
  continue;
2523
2521
  }
2524
- if (index < end) return;
2522
+ current.push(line);
2523
+ depth += countBlockBraceDelta(line);
2524
+ if (depth <= 0) {
2525
+ blocks.push(current.join("\n"));
2526
+ current = void 0;
2527
+ depth = 0;
2528
+ }
2525
2529
  }
2526
- return files === void 0 ? void 0 : {
2527
- end: end + 1,
2528
- value: { files }
2529
- };
2530
+ return blocks;
2530
2531
  }
2531
- function parseStaticContentValue(source, start) {
2532
- const index = skipWhitespaceAndComments(source, start);
2533
- const quoted = readQuotedString(source, index);
2534
- if (quoted) return quoted;
2535
- if (source[index] === "[") return parseStaticContentArray(source, index);
2536
- if (source[index] === "{") return parseStaticContentObject(source, index);
2532
+ function extractTailwindSourceForPostcssFallback(rawSource, options = {}) {
2533
+ const directives = [...extractTailwindDirectiveLines(rawSource, options), ...extractTailwindFallbackBlocks(rawSource)];
2534
+ return directives.length > 0 ? directives.join("\n") : void 0;
2537
2535
  }
2538
- function readStaticConfigContent(configPath) {
2539
- let source;
2540
- try {
2541
- source = (0, node_fs.readFileSync)(configPath, "utf8");
2542
- } catch {
2543
- return;
2536
+ function extractConfigRequestFromSource(rawSource) {
2537
+ for (const line of rawSource.split(/\r?\n/)) {
2538
+ const match = /^\s*@config\b([\s\S]*?)(?:;|$)/.exec(line);
2539
+ const request = match ? parseConfigRequest(match[1] ?? "") : void 0;
2540
+ if (request) return request;
2544
2541
  }
2545
- const contentProperty = findContentPropertyValue(source);
2546
- if (!contentProperty) return;
2547
- return parseStaticContentValue(source, contentProperty.start)?.value;
2548
2542
  }
2549
- //#endregion
2550
- //#region src/bundlers/vite/source-scan.ts
2551
- const VITE_SOURCE_CANDIDATE_PATTERN = FULL_SOURCE_SCAN_PATTERN;
2552
- function parseImportSourceParam(params) {
2553
- const match = /\bsource\(\s*(none|(['"])(.*?)\2)\s*\)/.exec(params);
2554
- if (!match) return;
2555
- return {
2556
- none: match[1] === "none",
2557
- sourcePath: match[3]
2558
- };
2543
+ function resolveConfigPath$1(base, configPath) {
2544
+ if (node_path.default.isAbsolute(configPath) || isPackageJsonImportRequest$1(configPath)) return node_path.default.isAbsolute(configPath) ? configPath : void 0;
2545
+ return node_path.default.resolve(base, configPath);
2559
2546
  }
2560
- function isTailwindCssImport(params) {
2561
- return /^\s*(['"])tailwindcss(?:\/[^'"]*)?\1/.test(params);
2547
+ function hasPreprocessorOnlySyntax(rawSource) {
2548
+ return /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@[\w-]+\s*:|@(?:mixin|include|function|use|forward)\b)/.test(rawSource);
2562
2549
  }
2563
- function resolveSourceBase(base, sourcePath) {
2564
- return node_path.default.isAbsolute(sourcePath) ? sourcePath : node_path.default.resolve(base, sourcePath);
2550
+ function normalizeTailwindSourceForGenerator(rawSource, options = {}) {
2551
+ return hasPreprocessorOnlySyntax(rawSource) ? extractTailwindSourceForPostcssFallback(rawSource, options) ?? rawSource : rawSource;
2565
2552
  }
2566
- function resolveConfigPath(base, configPath) {
2567
- if (node_path.default.isAbsolute(configPath)) return node_path.default.resolve(configPath);
2568
- let current = node_path.default.resolve(base);
2569
- while (true) {
2570
- const candidate = node_path.default.resolve(current, configPath);
2571
- if ((0, node_fs.existsSync)(candidate)) return candidate;
2572
- const parent = node_path.default.dirname(current);
2573
- if (parent === current) break;
2574
- current = parent;
2553
+ function normalizeTailwindV3CssEntrySource(rawSource) {
2554
+ try {
2555
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
2556
+ let changed = false;
2557
+ root.walkAtRules("import", (node) => {
2558
+ const layer = TAILWIND_V3_SUBPATH_IMPORT_LAYERS.get(parseImportRequest(node.params) ?? "");
2559
+ if (!layer) return;
2560
+ node.replaceWith(require_watch_dependencies.postcss_default.atRule({
2561
+ name: "tailwind",
2562
+ params: layer
2563
+ }));
2564
+ changed = true;
2565
+ });
2566
+ return changed ? root.toString() : rawSource;
2567
+ } catch {
2568
+ return rawSource;
2575
2569
  }
2576
- return node_path.default.resolve(base, configPath);
2577
2570
  }
2578
- async function resolveConfigContentEntries(root, base) {
2579
- const configPaths = /* @__PURE__ */ new Set();
2580
- root.walkAtRules("config", (rule) => {
2581
- const configPath = parseConfigParam$1(rule.params);
2582
- if (configPath) configPaths.add(resolveConfigPath(base, configPath));
2583
- });
2584
- const entries = [];
2585
- for (const configPath of configPaths) {
2586
- const staticContent = readStaticConfigContent(configPath);
2587
- if (staticContent !== void 0) {
2588
- entries.push(...normalizeLegacyContentEntries(staticContent, node_path.default.dirname(configPath)));
2589
- continue;
2590
- }
2591
- try {
2592
- const loaded = await (0, tailwindcss_config.loadConfig)({
2593
- config: configPath,
2594
- cwd: node_path.default.dirname(configPath)
2595
- });
2596
- entries.push(...normalizeLegacyContentEntries(loaded?.config.content, node_path.default.dirname(configPath)));
2597
- } catch {}
2598
- }
2599
- return {
2600
- dependencies: [...configPaths],
2601
- entries
2602
- };
2603
- }
2604
- async function resolveTailwindV4EntriesFromCss(css, base) {
2605
- let root;
2571
+ function normalizeTailwindSourceDirectives(rawSource, options = {}) {
2572
+ if (!options.importFallback) return rawSource;
2606
2573
  try {
2607
- root = require_runtime_registry.postcss_default.parse(css);
2574
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
2575
+ return normalizeTailwindImportAtRules(root, options) ? root.toString() : rawSource;
2608
2576
  } catch {
2609
- return;
2577
+ return extractTailwindSourceForPostcssFallback(rawSource, options) ?? rawSource;
2610
2578
  }
2611
- let importSourceBase;
2612
- let hasSourceNone = false;
2613
- let hasTailwindCssImport = false;
2614
- const [sourceEntries, configEntries] = await Promise.all([resolveCssSourceEntries(root, base, VITE_SOURCE_CANDIDATE_PATTERN), resolveConfigContentEntries(root, base)]);
2615
- const entries = [...configEntries.entries, ...sourceEntries];
2616
- const hasPositiveEntries = entries.some((entry) => !entry.negated);
2617
- const inlineCandidates = collectCssInlineSourceCandidates(root);
2618
- root.walkAtRules("import", (rule) => {
2619
- if (!isTailwindCssImport(rule.params)) return;
2620
- hasTailwindCssImport = true;
2621
- const sourceParam = parseImportSourceParam(rule.params);
2622
- if (sourceParam?.none) hasSourceNone = true;
2623
- if (sourceParam?.sourcePath) importSourceBase = resolveSourceBase(base, sourceParam.sourcePath);
2624
- });
2625
- if (importSourceBase) return {
2626
- entries: [{
2627
- base: importSourceBase,
2628
- negated: false,
2629
- pattern: VITE_SOURCE_CANDIDATE_PATTERN
2630
- }, ...entries],
2631
- explicit: true,
2632
- inlineCandidates,
2633
- dependencies: configEntries.dependencies
2634
- };
2635
- if (hasSourceNone) return {
2636
- entries,
2637
- explicit: true,
2638
- inlineCandidates,
2639
- dependencies: configEntries.dependencies
2640
- };
2641
- if (hasPositiveEntries) return {
2642
- entries,
2643
- explicit: true,
2644
- inlineCandidates,
2645
- dependencies: configEntries.dependencies
2646
- };
2647
- if (inlineCandidates.included.size > 0 || inlineCandidates.excluded.size > 0) return {
2648
- entries: [],
2649
- explicit: true,
2650
- inlineCandidates,
2651
- dependencies: configEntries.dependencies
2652
- };
2653
- return hasTailwindCssImport ? {
2654
- entries,
2655
- explicit: false,
2656
- inlineCandidates,
2657
- dependencies: configEntries.dependencies
2658
- } : void 0;
2659
2579
  }
2660
- //#endregion
2661
- //#region src/tailwindcss/runtime/cache.ts
2662
- const runtimeSignaturePatchersSymbol = Symbol.for("weapp-tailwindcss.runtimeSignaturePatchers");
2663
- //#endregion
2664
- //#region src/tailwindcss/runtime-patch.ts
2665
- const debug$2 = createDebug("[tailwindcss:runtime-patch] ");
2666
- const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
2667
- const runtimePatchPromiseCache = /* @__PURE__ */ new WeakMap();
2668
- function getNestedPatchers(twPatcher) {
2669
- const nested = twPatcher[runtimeSignaturePatchersSymbol];
2670
- return Array.isArray(nested) && nested.length > 0 ? nested : void 0;
2580
+ function isTailwindImportRequest(request) {
2581
+ return request === "tailwindcss" || request === "tailwindcss4" || request?.startsWith("tailwindcss/") || request?.startsWith("tailwindcss4/");
2671
2582
  }
2672
- function shouldApplyRuntimePatch(twPatcher) {
2673
- return twPatcher.majorVersion === 3 && typeof twPatcher.patch === "function";
2583
+ function isTailwindImportAtRule(node, options = {}) {
2584
+ if (node.name === "tailwind") return true;
2585
+ if (node.name !== "import" && node.name !== "use" && node.name !== "forward") return false;
2586
+ return isTailwindImportRequest(normalizeTailwindImportRequest(parseImportRequest(node.params), options));
2674
2587
  }
2675
- function clearTailwindcssRequireCache(twPatcher) {
2676
- const rootPath = twPatcher.packageInfo?.rootPath;
2677
- if (!rootPath) return;
2678
- const normalizedRoot = node_path.default.resolve(rootPath);
2679
- let count = 0;
2680
- for (const id of Object.keys(require$1.cache)) {
2681
- const normalizedId = node_path.default.resolve(id);
2682
- if (normalizedId === normalizedRoot || normalizedId.startsWith(`${normalizedRoot}${node_path.default.sep}`)) {
2683
- delete require$1.cache[id];
2684
- count += 1;
2685
- }
2686
- }
2687
- if (count > 0) debug$2("clear tailwindcss require cache after runtime patch, count=%d root=%s", count, normalizedRoot);
2588
+ function isTailwindSourceDirective(node, options = {}) {
2589
+ if (node.type !== "atrule") return false;
2590
+ const atRule = node;
2591
+ if (isTailwindImportAtRule(atRule, options)) return true;
2592
+ if (atRule.name === "import" && isPackageJsonImportRequest$1(parseImportRequest(atRule.params))) return true;
2593
+ if (atRule.name === "layer") return !atRule.nodes || atRule.nodes.length === 0;
2594
+ return TAILWIND_REMOVABLE_SOURCE_DIRECTIVE_NAMES.has(atRule.name);
2688
2595
  }
2689
- async function ensureTailwindcssRuntimePatch(twPatcher, options = {}) {
2690
- const nestedPatchers = getNestedPatchers(twPatcher);
2691
- if (nestedPatchers) {
2692
- await Promise.all(nestedPatchers.map((patcher) => ensureTailwindcssRuntimePatch(patcher)));
2693
- return;
2694
- }
2695
- if (!shouldApplyRuntimePatch(twPatcher)) return;
2696
- const cached = runtimePatchPromiseCache.get(twPatcher);
2697
- if (cached) {
2698
- await cached;
2699
- if (options.clearRequireCache) clearTailwindcssRequireCache(twPatcher);
2700
- return;
2701
- }
2702
- const task = Promise.resolve().then(async () => {
2703
- debug$2("apply tailwindcss runtime patch, package=%s version=%s root=%s", twPatcher.packageInfo?.name ?? "tailwindcss", twPatcher.packageInfo?.version ?? "unknown", twPatcher.packageInfo?.rootPath ?? "unknown");
2704
- await twPatcher.patch?.();
2705
- if (options.clearRequireCache) clearTailwindcssRequireCache(twPatcher);
2706
- }).catch((error) => {
2707
- runtimePatchPromiseCache.delete(twPatcher);
2708
- throw error;
2709
- });
2710
- runtimePatchPromiseCache.set(twPatcher, task);
2711
- return task;
2596
+ function hasGeneratedCssArtifacts(rawSource) {
2597
+ return hasTailwindGeneratedCssMarkers(rawSource) && !GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource);
2712
2598
  }
2713
- //#endregion
2714
- //#region src/tailwindcss/v3-engine/miniprogram.ts
2715
- const defaultStyleHandler = (0, _weapp_tailwindcss_postcss.createStyleHandler)({
2716
- cssChildCombinatorReplaceValue: ["view", "text"],
2717
- cssRemoveHoverPseudoClass: true,
2718
- isMainChunk: true,
2719
- majorVersion: 3
2720
- });
2721
- const MINI_PROGRAM_V3_PREFLIGHT_SELECTORS = new Set([
2722
- "view,text,:before,:after",
2723
- "view,text,:after,:before",
2724
- "view,text,::before,::after",
2725
- "view,text,::after,::before"
2726
- ]);
2727
- const V3_PREFLIGHT_RESET_PROPS = new Set([
2728
- "box-sizing",
2729
- "border",
2730
- "border-width",
2731
- "border-style",
2732
- "border-color",
2733
- "margin",
2734
- "padding"
2735
- ]);
2736
- function normalizeSelector(selector) {
2737
- return selector.trim().replace(/\s+/g, "");
2599
+ function isTailwindGenerationDirective(node, options = {}) {
2600
+ if (node.type !== "atrule") return false;
2601
+ const atRule = node;
2602
+ const request = atRule.name === "import" ? parseImportRequest(atRule.params) : atRule.name === "config" || atRule.name === "plugin" || atRule.name === "reference" ? parseConfigRequest(atRule.params) : void 0;
2603
+ return isTailwindImportAtRule(atRule, options) || isPackageJsonImportRequest$1(request) || atRule.name === "apply" || !options.ignoreLayer && atRule.name === "layer" || atRule.name === "config" || atRule.name === "source";
2738
2604
  }
2739
- function isMiniProgramV3PreflightRule(rule) {
2740
- return MINI_PROGRAM_V3_PREFLIGHT_SELECTORS.has(normalizeSelector(rule.selector));
2605
+ function removeTailwindSourceDirectives(rawSource, options = {}) {
2606
+ try {
2607
+ const source = hasPreprocessorOnlySyntax(rawSource) ? extractTailwindSourceForPostcssFallback(rawSource, options) : stripGeneratorPlaceholderMarkers(rawSource);
2608
+ if (!source) return "";
2609
+ const root = require_watch_dependencies.postcss_default.parse(source);
2610
+ let removed = false;
2611
+ root.walk((node) => {
2612
+ if (isTailwindSourceDirective(node, options)) {
2613
+ node.remove();
2614
+ removed = true;
2615
+ }
2616
+ });
2617
+ return removed ? root.toString() : source;
2618
+ } catch {
2619
+ return stripGeneratorPlaceholderMarkers(rawSource);
2620
+ }
2741
2621
  }
2742
- function hasResetDeclaration(rule) {
2743
- let found = false;
2744
- rule.walkDecls((decl) => {
2745
- if (V3_PREFLIGHT_RESET_PROPS.has(decl.prop)) found = true;
2746
- });
2747
- return found;
2622
+ function hasTailwindSourceDirectives(rawSource, options = {}) {
2623
+ try {
2624
+ if (GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource)) return true;
2625
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
2626
+ let found = false;
2627
+ const ignoreLayer = hasGeneratedCssArtifacts(rawSource);
2628
+ root.walk((node) => {
2629
+ if (isTailwindGenerationDirective(node, {
2630
+ ...options,
2631
+ ignoreLayer
2632
+ })) {
2633
+ found = true;
2634
+ return false;
2635
+ }
2636
+ });
2637
+ return found;
2638
+ } catch {
2639
+ return extractTailwindDirectiveLines(rawSource, options).length > 0;
2640
+ }
2748
2641
  }
2749
- function createPreflightDeclarations(cssPreflight) {
2750
- if (!cssPreflight || typeof cssPreflight !== "object") return [];
2751
- return Object.entries(cssPreflight).filter((entry) => entry[1] !== false).map(([prop, value]) => require_runtime_registry.postcss_default.decl({
2752
- prop,
2753
- value: value.toString()
2754
- }));
2642
+ function hasTailwindRootDirectives(rawSource, options = {}) {
2643
+ if (!TAILWIND_ROOT_DIRECTIVE_RE.test(rawSource) && !(options.importFallback && rawSource.includes("weapp-tailwindcss"))) return false;
2644
+ try {
2645
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
2646
+ let found = false;
2647
+ root.walkAtRules((node) => {
2648
+ const request = node.name === "import" ? parseImportRequest(node.params) : node.name === "config" || node.name === "plugin" ? parseConfigRequest(node.params) : void 0;
2649
+ if (isTailwindImportAtRule(node, options) || isPackageJsonImportRequest$1(request) || TAILWIND_ROOT_DIRECTIVE_NAMES.has(node.name)) {
2650
+ found = true;
2651
+ return false;
2652
+ }
2653
+ });
2654
+ return found;
2655
+ } catch {
2656
+ return extractTailwindDirectiveLines(rawSource, options).length > 0;
2657
+ }
2755
2658
  }
2756
- function ensureMiniProgramV3PreflightReset(css, cssPreflight) {
2757
- const declarations = createPreflightDeclarations(cssPreflight);
2758
- if (declarations.length === 0) return css;
2659
+ function hasTailwindApplyDirective(rawSource) {
2660
+ if (!rawSource.includes("@apply")) return false;
2759
2661
  try {
2760
- const root = require_runtime_registry.postcss_default.parse(css);
2761
- let targetRule;
2762
- let hasReset = false;
2763
- root.walkRules((rule) => {
2764
- if (!isMiniProgramV3PreflightRule(rule)) return;
2765
- targetRule ??= rule;
2766
- if (hasResetDeclaration(rule)) hasReset = true;
2662
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
2663
+ let found = false;
2664
+ root.walkAtRules("apply", () => {
2665
+ found = true;
2666
+ return false;
2767
2667
  });
2768
- if (!targetRule || hasReset) return css;
2769
- targetRule.append(...declarations.map((decl) => decl.clone()));
2770
- return root.toString();
2668
+ return found;
2771
2669
  } catch {
2772
- return css;
2670
+ return false;
2773
2671
  }
2774
2672
  }
2775
- async function transformTailwindV3CssToWeapp(css, options) {
2776
- const result = await defaultStyleHandler(hasCssMacroStyleOptions(options) ? await transformCssMacroCss(css, options) : css, {
2777
- cssChildCombinatorReplaceValue: ["view", "text"],
2778
- cssRemoveHoverPseudoClass: true,
2779
- isMainChunk: true,
2780
- majorVersion: 3,
2781
- ...options
2782
- });
2783
- const pruneOptions = {
2784
- preservePreflight: true,
2785
- preserveConditionalComments: hasCssMacroStyleOptions(options)
2786
- };
2787
- return ensureMiniProgramV3PreflightReset((0, _weapp_tailwindcss_postcss.pruneMiniProgramGeneratedCss)(result.css, pruneOptions), options?.cssPreflight);
2788
- }
2789
- async function transformTailwindV3CssByTarget(css, target, options) {
2790
- if (target === "weapp") return transformTailwindV3CssToWeapp(css, options);
2791
- return hasCssMacroStyleOptions(options) ? transformCssMacroCss(css, options) : css;
2673
+ function resolveCssEntrySource(rawSource, base, options = {}) {
2674
+ try {
2675
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
2676
+ const normalizedImports = normalizeTailwindImportAtRules(root, options);
2677
+ let found = false;
2678
+ let config;
2679
+ let configRequest;
2680
+ let removedConfig = false;
2681
+ const removeConfig = options.removeConfig ?? true;
2682
+ const ignoreLayer = hasGeneratedCssArtifacts(rawSource);
2683
+ root.walk((node) => {
2684
+ if (isTailwindGenerationDirective(node, {
2685
+ ...options,
2686
+ ignoreLayer
2687
+ })) found = true;
2688
+ if (node.type === "atrule" && node.name === "config") {
2689
+ const configPath = parseConfigRequest(node.params);
2690
+ if (configPath && !config) {
2691
+ configRequest = configPath;
2692
+ config = resolveConfigPath$1(base, configPath);
2693
+ }
2694
+ if (removeConfig) {
2695
+ node.remove();
2696
+ removedConfig = true;
2697
+ }
2698
+ }
2699
+ });
2700
+ if (!found) return;
2701
+ if (hasPreprocessorOnlySyntax(rawSource)) {
2702
+ const css = extractTailwindSourceForPostcssFallback(rawSource, {
2703
+ ...options,
2704
+ removeConfig
2705
+ });
2706
+ if (css) return {
2707
+ css,
2708
+ config,
2709
+ configRequest,
2710
+ base
2711
+ };
2712
+ }
2713
+ return {
2714
+ css: removedConfig || normalizedImports ? root.toString() : rawSource,
2715
+ config,
2716
+ configRequest,
2717
+ base
2718
+ };
2719
+ } catch {
2720
+ const css = extractTailwindSourceForPostcssFallback(rawSource, options);
2721
+ const configRequest = extractConfigRequestFromSource(rawSource);
2722
+ const config = configRequest ? resolveConfigPath$1(base, configRequest) : void 0;
2723
+ return css ? {
2724
+ css,
2725
+ config,
2726
+ configRequest,
2727
+ base
2728
+ } : void 0;
2729
+ }
2792
2730
  }
2793
2731
  //#endregion
2794
- //#region src/tailwindcss/v3-engine/generator.ts
2795
- const runtimeReadyPromiseCache = /* @__PURE__ */ new Map();
2796
- const incrementalGenerateCache = /* @__PURE__ */ new Map();
2797
- function isLegacyContentObject(value) {
2798
- return typeof value === "object" && value !== null && "files" in value;
2732
+ //#region src/tailwindcss/v4-engine/source.ts
2733
+ const require$2 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
2734
+ function isCssEntryPoint(file) {
2735
+ return typeof file === "string" && node_path.default.basename(file) === "index.css" && (0, node_fs.existsSync)(file);
2799
2736
  }
2800
- function createRawContentEntries(candidates, sources) {
2801
- const entries = [];
2802
- const candidateContent = [...candidates].join(" ");
2803
- if (candidateContent.length > 0) entries.push({
2804
- raw: candidateContent,
2805
- extension: "html"
2806
- });
2807
- for (const source of sources) entries.push({
2808
- raw: source.content,
2809
- extension: source.extension ?? "html"
2810
- });
2811
- return entries;
2737
+ function resolvePackageCssEntryPoint(specifier) {
2738
+ try {
2739
+ const resolved = require$2.resolve(specifier);
2740
+ if (isCssEntryPoint(resolved)) return resolved;
2741
+ } catch {}
2742
+ const packageName = specifier.replace(/\/index\.css$/, "");
2743
+ if (packageName !== "tailwindcss") return;
2744
+ try {
2745
+ const packageJson = require$2.resolve(`${packageName}/package.json`);
2746
+ const cssEntry = node_path.default.resolve(node_path.default.dirname(packageJson), "index.css");
2747
+ if (isCssEntryPoint(cssEntry)) return cssEntry;
2748
+ } catch {}
2749
+ try {
2750
+ let current = node_path.default.dirname(require$2.resolve("tailwindcss-patch"));
2751
+ while (true) {
2752
+ const cssEntry = node_path.default.resolve(current, "..", "tailwindcss", "index.css");
2753
+ if (isCssEntryPoint(cssEntry)) return cssEntry;
2754
+ const parent = node_path.default.dirname(current);
2755
+ if (parent === current) break;
2756
+ current = parent;
2757
+ }
2758
+ } catch {}
2812
2759
  }
2813
- function createChangedContentEntries(candidates, sources) {
2814
- return createRawContentEntries(candidates, sources).map((entry) => ({
2815
- content: entry.raw,
2816
- extension: entry.extension
2817
- }));
2760
+ function isPostcssPluginImportTarget(value) {
2761
+ if (!value) return false;
2762
+ return value === "@tailwindcss/postcss" || value.includes("/postcss");
2818
2763
  }
2819
- function collectCandidates(candidates) {
2820
- return new Set(candidates ?? []);
2764
+ function uniqueDefined(values) {
2765
+ return [...new Set(values.filter((value) => typeof value === "string" && value.length > 0))];
2821
2766
  }
2822
- function normalizeBareArbitraryValueCandidate(candidate, bareArbitraryValues) {
2823
- return (0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(candidate, bareArbitraryValues)?.canonicalCandidate ?? candidate;
2767
+ function getProjectRoot$1(patcher) {
2768
+ return patcher.options?.projectRoot ?? node_process.default.cwd();
2824
2769
  }
2825
- function normalizeBareArbitraryValueCandidates(candidates, bareArbitraryValues) {
2826
- const normalized = /* @__PURE__ */ new Set();
2827
- const restoreCandidates = /* @__PURE__ */ new Map();
2828
- for (const candidate of candidates) {
2829
- const normalizedCandidate = normalizeBareArbitraryValueCandidate(candidate, bareArbitraryValues);
2830
- normalized.add(normalizedCandidate);
2831
- if (normalizedCandidate !== candidate) restoreCandidates.set(normalizedCandidate, candidate);
2770
+ function resolveBase(value, fallback) {
2771
+ return value === void 0 ? fallback : node_path.default.isAbsolute(value) ? node_path.default.resolve(value) : node_path.default.resolve(fallback, value);
2772
+ }
2773
+ function resolveConfigDir(config, projectRoot) {
2774
+ if (!config) return;
2775
+ const configPath = node_path.default.isAbsolute(config) ? config : node_path.default.resolve(projectRoot, config);
2776
+ return node_path.default.dirname(configPath);
2777
+ }
2778
+ function isBarePackageSpecifier(specifier) {
2779
+ return !specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.includes("\\") && !/^[a-z][a-z\d+.-]*:/i.test(specifier);
2780
+ }
2781
+ function parseCssImportSpecifier$1(params) {
2782
+ const value = params.trim();
2783
+ const quoted = /^(['"])(.*?)\1/.exec(value);
2784
+ if (quoted) {
2785
+ const specifier = quoted[2];
2786
+ if (specifier === void 0) return;
2787
+ return {
2788
+ quote: quoted[1],
2789
+ raw: quoted[0],
2790
+ specifier
2791
+ };
2832
2792
  }
2793
+ const url = /^url\(\s*(?:(['"])(.*?)\1|([^'")\s]+))\s*\)/.exec(value);
2794
+ if (!url) return;
2795
+ const specifier = url[2] ?? url[3];
2796
+ if (specifier === void 0) return;
2833
2797
  return {
2834
- candidates: normalized,
2835
- restoreCandidates
2798
+ quote: url[1],
2799
+ raw: url[0],
2800
+ specifier
2836
2801
  };
2837
2802
  }
2838
- async function collectSourceBareArbitraryValueCandidates(sources, bareArbitraryValues) {
2839
- if (!(0, tailwindcss_patch.isBareArbitraryValuesEnabled)(bareArbitraryValues)) return [];
2840
- const candidates = /* @__PURE__ */ new Set();
2841
- for (const source of sources ?? []) for (const candidate of await (0, tailwindcss_patch.extractSourceCandidates)(source.content, source.extension ?? "html", { bareArbitraryValues })) if ((0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(candidate, bareArbitraryValues)) candidates.add(candidate);
2842
- return [...candidates];
2803
+ function quoteCssImportSpecifier(specifier, quote = "\"") {
2804
+ return `${quote}${specifier.replaceAll("\\", "\\\\").replaceAll(quote, `\\${quote}`)}${quote}`;
2843
2805
  }
2844
- function escapeCssClassSelector(className) {
2845
- return className.replace(/[^\w-]/g, (char) => `\\${char}`);
2806
+ function createTailwindV4CssImportSpecifierSet(packageName) {
2807
+ const specifiers = new Set(["tailwindcss"]);
2808
+ if (packageName && isBarePackageSpecifier(packageName)) specifiers.add(packageName);
2809
+ return specifiers;
2846
2810
  }
2847
- function restoreBareArbitraryValueCssSelectors(css, originalCandidates, bareArbitraryValues, escapeClassName) {
2848
- if (!(0, tailwindcss_patch.isBareArbitraryValuesEnabled)(bareArbitraryValues)) return css;
2849
- let restored = css;
2850
- for (const originalCandidate of originalCandidates) {
2851
- const canonical = (0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(originalCandidate, bareArbitraryValues)?.canonicalCandidate;
2852
- if (canonical) restored = restored.split(`.${escapeClassName(canonical)}`).join(`.${escapeCssClassSelector(originalCandidate)}`);
2811
+ function normalizeTailwindV4CssPackageImports(css, packageName) {
2812
+ if (!css.includes("tailwindcss")) return css;
2813
+ let root;
2814
+ try {
2815
+ root = require_watch_dependencies.postcss_default.parse(css);
2816
+ } catch {
2817
+ return css;
2853
2818
  }
2854
- return restored;
2819
+ const importSpecifiers = createTailwindV4CssImportSpecifierSet(packageName);
2820
+ let changed = false;
2821
+ root.walkAtRules("import", (rule) => {
2822
+ const parsed = parseCssImportSpecifier$1(rule.params);
2823
+ if (!parsed || !importSpecifiers.has(parsed.specifier)) return;
2824
+ const cssEntryPoint = resolvePackageCssEntryPoint(`${parsed.specifier}/index.css`);
2825
+ if (!cssEntryPoint) return;
2826
+ rule.params = rule.params.replace(parsed.raw, quoteCssImportSpecifier(cssEntryPoint, parsed.quote));
2827
+ changed = true;
2828
+ });
2829
+ return changed ? root.toString() : css;
2855
2830
  }
2856
- function restoreBareArbitraryValueClassSet(classSet, originalCandidates, bareArbitraryValues) {
2857
- if (!(0, tailwindcss_patch.isBareArbitraryValuesEnabled)(bareArbitraryValues)) return new Set(classSet);
2858
- const restored = new Set(classSet);
2859
- for (const originalCandidate of originalCandidates) {
2860
- const canonical = (0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(originalCandidate, bareArbitraryValues)?.canonicalCandidate;
2861
- if (canonical && restored.has(canonical)) {
2862
- restored.delete(canonical);
2863
- restored.add(originalCandidate);
2831
+ function normalizeTailwindV4CssSources(cssSources, packageName) {
2832
+ if (!cssSources?.length) return cssSources;
2833
+ let changed = false;
2834
+ const normalizedCssSources = cssSources.map((cssSource) => {
2835
+ if (typeof cssSource.css !== "string") return cssSource;
2836
+ const css = normalizeTailwindV4CssPackageImports(cssSource.css, packageName);
2837
+ if (css === cssSource.css) return cssSource;
2838
+ changed = true;
2839
+ return {
2840
+ ...cssSource,
2841
+ css
2842
+ };
2843
+ });
2844
+ return changed ? normalizedCssSources : cssSources;
2845
+ }
2846
+ function normalizeTailwindV4CssEntrySources(cssEntries, packageName) {
2847
+ if (!cssEntries?.length) return;
2848
+ const remainingCssEntries = [];
2849
+ const cssSources = [];
2850
+ for (const cssEntry of cssEntries) {
2851
+ const file = node_path.default.resolve(cssEntry);
2852
+ if (!(0, node_fs.existsSync)(file)) {
2853
+ remainingCssEntries.push(cssEntry);
2854
+ continue;
2864
2855
  }
2856
+ const base = node_path.default.dirname(file);
2857
+ const rawCss = (0, node_fs.readFileSync)(file, "utf8");
2858
+ const css = normalizeTailwindV4CssPackageImports(normalizeConfigDirective(rawCss, resolveCssEntrySource(rawCss, base, { removeConfig: false })?.config), packageName);
2859
+ cssSources.push({
2860
+ file,
2861
+ base,
2862
+ css,
2863
+ dependencies: [file]
2864
+ });
2865
2865
  }
2866
- return restored;
2866
+ return {
2867
+ cssEntries: remainingCssEntries,
2868
+ cssSources
2869
+ };
2867
2870
  }
2868
- function collectGeneratedCandidates(context, candidates, restoreCandidates) {
2869
- const classSet = /* @__PURE__ */ new Set();
2870
- for (const candidate of candidates) if (context.classCache.has(candidate)) classSet.add(restoreCandidates.get(candidate) ?? candidate);
2871
- return classSet;
2871
+ function normalizeTailwindV4SourceOptions(options) {
2872
+ if (!options) return options;
2873
+ const css = options.css === void 0 ? void 0 : normalizeTailwindV4CssPackageImports(options.css, options.packageName);
2874
+ const entrySources = normalizeTailwindV4CssEntrySources(options.cssEntries, options.packageName);
2875
+ const cssSources = normalizeTailwindV4CssSources(options.cssSources || entrySources?.cssSources ? [...options.cssSources ?? [], ...entrySources?.cssSources ?? []] : void 0, options.packageName);
2876
+ const cssEntries = entrySources?.cssEntries ?? options.cssEntries;
2877
+ if (css === options.css && cssSources === options.cssSources && cssEntries === options.cssEntries) return options;
2878
+ return {
2879
+ ...options,
2880
+ ...css === void 0 ? {} : { css },
2881
+ ...cssEntries === void 0 ? {} : { cssEntries },
2882
+ ...cssSources === void 0 ? {} : { cssSources }
2883
+ };
2872
2884
  }
2873
- function hasRemovedCandidates(previousCandidates, nextCandidates) {
2874
- for (const candidate of previousCandidates) if (!nextCandidates.has(candidate)) return true;
2875
- return false;
2885
+ function resolveTailwindCssImportTarget(patcher) {
2886
+ const configuredPackageName = resolveTailwindcssOptions(patcher.options)?.packageName;
2887
+ if (typeof configuredPackageName === "string" && configuredPackageName.length > 0 && !isPostcssPluginImportTarget(configuredPackageName)) return configuredPackageName;
2888
+ const packageName = patcher.packageInfo?.name;
2889
+ if (typeof packageName === "string" && packageName.length > 0 && !isPostcssPluginImportTarget(packageName)) return packageName;
2890
+ return "tailwindcss";
2876
2891
  }
2877
- function collectApplyCandidatesFromCss(css) {
2878
- if (!css.includes("@apply")) return [];
2879
- const candidates = /* @__PURE__ */ new Set();
2880
- try {
2881
- require_runtime_registry.postcss_default.parse(css).walkAtRules("apply", (rule) => {
2882
- for (const candidate of rule.params.split(/\s+/)) {
2883
- const normalized = candidate.replace(/!important$/, "").trim();
2884
- if (normalized) candidates.add(normalized);
2885
- }
2886
- });
2887
- } catch {}
2888
- return [...candidates];
2892
+ function readTailwindV4Options(patcher) {
2893
+ return resolveTailwindcssOptions(patcher.options)?.v4 ?? patcher.options?.tailwind?.v4;
2889
2894
  }
2890
- function isTailwindCandidateLayer(params) {
2891
- return params.split(/[,\s]+/).some((layer) => layer === "components" || layer === "utilities");
2895
+ function isRawTailwindcssPatchOptions(options) {
2896
+ return Boolean(options && "tailwindcss" in options);
2892
2897
  }
2893
- function extractClassCandidatesFromSelector(selector, candidates) {
2894
- for (let index = 0; index < selector.length; index++) {
2895
- if (selector[index] !== ".") continue;
2896
- let candidate = "";
2897
- let escaped = false;
2898
- for (let tokenIndex = index + 1; tokenIndex < selector.length; tokenIndex++) {
2899
- const char = selector[tokenIndex];
2900
- if (escaped) {
2901
- candidate += char;
2902
- escaped = false;
2903
- continue;
2904
- }
2905
- if (char === "\\") {
2906
- escaped = true;
2907
- continue;
2908
- }
2909
- if (char && /[\w-]/.test(char)) {
2910
- candidate += char;
2911
- continue;
2912
- }
2913
- break;
2914
- }
2915
- if (candidate) candidates.add(candidate);
2898
+ function resolvePatchTailwindV4SourceOptions(patcher) {
2899
+ if (patcher.options) {
2900
+ const projectRoot = getProjectRoot$1(patcher);
2901
+ const tailwindOptions = resolveTailwindcssOptions(patcher.options);
2902
+ const tailwindV4Options = readTailwindV4Options(patcher);
2903
+ const cwd = resolveBase(tailwindOptions?.cwd, projectRoot);
2904
+ const configuredBase = tailwindV4Options?.configuredBase ?? (isRawTailwindcssPatchOptions(patcher.options) ? tailwindV4Options?.base : void 0);
2905
+ const baseFallbacks = uniqueDefined([
2906
+ configuredBase,
2907
+ cwd,
2908
+ projectRoot,
2909
+ resolveConfigDir(tailwindOptions?.config, projectRoot)
2910
+ ]);
2911
+ return {
2912
+ projectRoot,
2913
+ cwd,
2914
+ ...configuredBase === void 0 ? {} : { base: configuredBase },
2915
+ baseFallbacks,
2916
+ ...tailwindV4Options?.css === void 0 ? {} : { css: tailwindV4Options.css },
2917
+ ...tailwindV4Options?.cssSources === void 0 ? {} : { cssSources: tailwindV4Options.cssSources },
2918
+ ...tailwindV4Options?.cssEntries === void 0 ? {} : { cssEntries: tailwindV4Options.cssEntries },
2919
+ packageName: resolveTailwindCssImportTarget(patcher)
2920
+ };
2916
2921
  }
2917
- }
2918
- function collectLayerCandidatesFromCss(css) {
2919
- if (!css.includes("@layer")) return [];
2920
- const candidates = /* @__PURE__ */ new Set();
2921
- try {
2922
- require_runtime_registry.postcss_default.parse(css).walkAtRules("layer", (layer) => {
2923
- if (!isTailwindCandidateLayer(layer.params)) return;
2924
- layer.walkRules((rule) => {
2925
- extractClassCandidatesFromSelector(rule.selector, candidates);
2926
- });
2927
- });
2928
- } catch {}
2929
- return [...candidates];
2930
- }
2931
- function mergeGenerateCandidates(source, options) {
2932
- return collectCandidates([
2933
- ...collectLayerCandidatesFromCss(source.css),
2934
- ...collectApplyCandidatesFromCss(source.css),
2935
- ...collectCandidates(options.candidates)
2936
- ]);
2937
- }
2938
- function mergeContent(content, rawEntries) {
2939
- if (isLegacyContentObject(content)) return {
2940
- ...content,
2941
- relative: content.relative ?? true,
2942
- files: [...[].concat(content.files ?? []), ...rawEntries]
2943
- };
2944
- return {
2945
- relative: true,
2946
- files: [...[].concat(content ?? []), ...rawEntries]
2947
- };
2948
- }
2949
- function normalizeConfigObject(config) {
2950
- if (!config || typeof config !== "object") return config;
2951
- const maybeDefault = config.default;
2952
- if (maybeDefault && typeof maybeDefault === "object") return maybeDefault;
2953
- return config;
2954
- }
2955
- function hasExplicitContentInput(options) {
2956
- return options.candidates !== void 0 || options.sources !== void 0;
2957
- }
2958
- function createExplicitContentConfig(rawEntries) {
2959
2922
  return {
2960
- relative: true,
2961
- files: rawEntries
2923
+ projectRoot: getProjectRoot$1(patcher),
2924
+ packageName: resolveTailwindCssImportTarget(patcher)
2962
2925
  };
2963
2926
  }
2964
- function createTailwindConfig(source, options) {
2965
- const config = { ...normalizeConfigObject(source.configObject) ?? {} };
2966
- const rawEntries = createRawContentEntries(mergeGenerateCandidates(source, options), options.sources ?? []);
2967
- config.content = hasExplicitContentInput(options) ? createExplicitContentConfig(rawEntries) : mergeContent(config.content, rawEntries);
2968
- return config;
2927
+ function resolveTailwindV4SourceOptionsFromPatcher(patcher) {
2928
+ const tailwindV4Options = readTailwindV4Options(patcher);
2929
+ return omitUndefined({
2930
+ ...resolvePatchTailwindV4SourceOptions(patcher),
2931
+ sources: tailwindV4Options?.sources
2932
+ });
2969
2933
  }
2970
- function shouldAutoEnableCssMacro(source) {
2971
- return hasCssMacroTailwindPlugin(normalizeConfigObject(source.configObject)?.plugins);
2934
+ function resolveTailwindV4Source(options) {
2935
+ return (0, tailwindcss_patch.resolveTailwindV4Source)(normalizeTailwindV4SourceOptions(options));
2972
2936
  }
2973
- function resolveStyleOptions(source, options) {
2974
- return shouldAutoEnableCssMacro(source) ? withCssMacroStyleOptions(options) : options;
2937
+ async function resolveTailwindV4SourceFromPatcher(patcher) {
2938
+ return resolveTailwindV4Source(resolveTailwindV4SourceOptionsFromPatcher(patcher));
2975
2939
  }
2976
- function loadTailwindV3Internals(source) {
2977
- const requireFromProject = (0, node_module.createRequire)(`${source.cwd}/package.json`);
2978
- const requireFromRuntime = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
2979
- const requireTailwind = (id) => {
2980
- try {
2981
- return requireFromProject(id);
2982
- } catch {
2983
- return requireFromRuntime(id);
2940
+ //#endregion
2941
+ //#region src/bundlers/vite/static-config-content.ts
2942
+ function skipWhitespaceAndComments(source, start) {
2943
+ let index = start;
2944
+ while (index < source.length) {
2945
+ const char = source[index];
2946
+ if (/\s/.test(char ?? "")) {
2947
+ index += 1;
2948
+ continue;
2984
2949
  }
2985
- };
2986
- const collapseAdjacentRulesModule = requireTailwind(`${source.packageName}/lib/lib/collapseAdjacentRules`);
2987
- const collapseDuplicateDeclarationsModule = requireTailwind(`${source.packageName}/lib/lib/collapseDuplicateDeclarations`);
2988
- const escapeClassNameModule = requireTailwind(`${source.packageName}/lib/util/escapeClassName`);
2989
- const generateRulesModule = requireTailwind(`${source.packageName}/lib/lib/generateRules`);
2990
- const sharedStateModule = requireTailwind(`${source.packageName}/lib/lib/sharedState`);
2991
- const setupContextUtils = requireTailwind(`${source.packageName}/lib/lib/setupContextUtils`);
2992
- const processTailwindFeaturesModule = requireTailwind(`${source.packageName}/lib/processTailwindFeatures`);
2993
- const resolveDefaultsAtRulesModule = requireTailwind(`${source.packageName}/lib/lib/resolveDefaultsAtRules`);
2994
- const resolveConfigModule = requireTailwind(`${source.packageName}/lib/public/resolve-config`);
2995
- const validateConfigModule = requireTailwind(`${source.packageName}/lib/util/validateConfig.js`);
2996
- return {
2997
- collapseAdjacentRules: collapseAdjacentRulesModule["default"] ?? collapseAdjacentRulesModule,
2998
- collapseDuplicateDeclarations: collapseDuplicateDeclarationsModule["default"] ?? collapseDuplicateDeclarationsModule,
2999
- createContext: setupContextUtils["createContext"],
3000
- escapeClassName: escapeClassNameModule["default"] ?? escapeClassNameModule,
3001
- generateRules: generateRulesModule["generateRules"],
3002
- notOnDemandCandidate: String(sharedStateModule["NOT_ON_DEMAND"] ?? "*"),
3003
- processTailwindFeatures: processTailwindFeaturesModule["default"] ?? processTailwindFeaturesModule,
3004
- resolveDefaultsAtRules: resolveDefaultsAtRulesModule["default"] ?? resolveDefaultsAtRulesModule,
3005
- resolveConfig: resolveConfigModule["default"] ?? resolveConfigModule,
3006
- validateConfig: validateConfigModule["validateConfig"]
3007
- };
3008
- }
3009
- function createStableJson$1(value) {
3010
- if (value === void 0) return "undefined";
3011
- if (value === null || typeof value !== "object") return JSON.stringify(value);
3012
- if (Array.isArray(value)) return `[${value.map((item) => createStableJson$1(item)).join(",")}]`;
3013
- return `{${Object.keys(value).sort().map((key) => {
3014
- const record = value;
3015
- return `${JSON.stringify(key)}:${createStableJson$1(record[key])}`;
3016
- }).join(",")}}`;
3017
- }
3018
- function createDependencyFingerprint(files) {
3019
- return files.map((file) => {
3020
- try {
3021
- const stat = node_fs.default.statSync(file);
3022
- return `${file}:${stat.size}:${stat.mtimeMs}`;
3023
- } catch {
3024
- return `${file}:missing`;
2950
+ if (char === "/" && source[index + 1] === "/") {
2951
+ index += 2;
2952
+ while (index < source.length && source[index] !== "\n") index += 1;
2953
+ continue;
3025
2954
  }
3026
- }).join("|");
3027
- }
3028
- function createIncrementalGenerateCacheKey(source, target, styleOptions, bareArbitraryValues) {
3029
- return [
3030
- source.packageName,
3031
- source.postcssPlugin,
3032
- source.cwd,
3033
- source.config ?? "config:missing",
3034
- createDependencyFingerprint(source.dependencies),
3035
- source.css,
3036
- createStableJson$1(normalizeConfigObject(source.configObject)?.content),
3037
- target,
3038
- createStableJson$1(styleOptions),
3039
- createStableJson$1(bareArbitraryValues)
3040
- ].join("\0");
3041
- }
3042
- function createRuntimeReadyCacheKey(source, rootPath) {
3043
- return [
3044
- source.packageName,
3045
- source.postcssPlugin,
3046
- rootPath ?? "missing",
3047
- source.config ?? "config:missing",
3048
- source.cwd
3049
- ].join("\0");
3050
- }
3051
- function isDirectUtilitiesOnlyCss(css) {
3052
- return css.replace(/\s+/g, "") === "@tailwindutilities;";
3053
- }
3054
- function collectClassSet(context) {
3055
- const classSet = /* @__PURE__ */ new Set();
3056
- for (const candidate of context.classCache.keys()) if (String(candidate) !== "*") classSet.add(candidate);
3057
- return classSet;
3058
- }
3059
- function collectDependencyMessages(result) {
3060
- const dependencies = /* @__PURE__ */ new Set();
3061
- for (const message of result.messages) {
3062
- const file = message["file"];
3063
- if (message["type"] === "dependency" && typeof file === "string") dependencies.add(file);
2955
+ if (char === "/" && source[index + 1] === "*") {
2956
+ index += 2;
2957
+ while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) index += 1;
2958
+ index = Math.min(index + 2, source.length);
2959
+ continue;
2960
+ }
2961
+ break;
3064
2962
  }
3065
- return dependencies;
3066
- }
3067
- function sortCandidates(candidates) {
3068
- return [...candidates].sort((a, z) => {
3069
- if (a === z) return 0;
3070
- return a < z ? -1 : 1;
3071
- });
2963
+ return index;
3072
2964
  }
3073
- function appendUtilityRules(root, context, rules) {
3074
- const sortedRules = context.offsets.sort(rules);
3075
- for (const [sort, rule] of sortedRules) {
3076
- const tailwindRaw = rule.raws.tailwind;
3077
- if (sort.layer === "utilities" || sort.layer === "variants" && tailwindRaw?.parentLayer === "utilities") root.append(rule.clone());
2965
+ function readQuotedString(source, start) {
2966
+ const quote = source[start];
2967
+ if (quote !== "\"" && quote !== "'") return;
2968
+ let value = "";
2969
+ for (let index = start + 1; index < source.length; index++) {
2970
+ const char = source[index];
2971
+ if (char === "\\") {
2972
+ const next = source[index + 1];
2973
+ if (next === void 0) return;
2974
+ value += next;
2975
+ index += 1;
2976
+ continue;
2977
+ }
2978
+ if (char === quote) return {
2979
+ end: index + 1,
2980
+ value
2981
+ };
2982
+ value += char;
3078
2983
  }
3079
2984
  }
3080
- function appendDirectUtilityRules(root, context) {
3081
- appendUtilityRules(root, context, [...context.ruleCache]);
2985
+ function readIdentifier(source, start) {
2986
+ return /^[A-Z_$][\w$]*/i.exec(source.slice(start))?.[0];
3082
2987
  }
3083
- function createRuntimeReadyPromise(source) {
3084
- const patcher = createTailwindcssPatcher({
3085
- basedir: source.cwd,
3086
- supportCustomLengthUnitsPatch: true,
3087
- tailwindcss: {
3088
- ...source.config === void 0 ? {} : { config: source.config },
3089
- cwd: source.cwd,
3090
- packageName: source.packageName,
3091
- postcssPlugin: source.postcssPlugin,
3092
- version: 3
2988
+ function findMatchingBracket(source, start, open, close) {
2989
+ let depth = 0;
2990
+ let quote;
2991
+ for (let index = start; index < source.length; index++) {
2992
+ const char = source[index];
2993
+ if (char === "\\") {
2994
+ index += 1;
2995
+ continue;
3093
2996
  }
3094
- });
3095
- const cacheKey = createRuntimeReadyCacheKey(source, patcher.packageInfo?.rootPath);
3096
- const cached = runtimeReadyPromiseCache.get(cacheKey);
3097
- if (cached) return cached;
3098
- const task = ensureTailwindcssRuntimePatch(patcher, { clearRequireCache: true }).catch((error) => {
3099
- runtimeReadyPromiseCache.delete(cacheKey);
3100
- throw error;
3101
- });
3102
- runtimeReadyPromiseCache.set(cacheKey, task);
3103
- return task;
2997
+ if (quote) {
2998
+ if (char === quote) quote = void 0;
2999
+ continue;
3000
+ }
3001
+ if (char === "\"" || char === "'") {
3002
+ quote = char;
3003
+ continue;
3004
+ }
3005
+ if (char === "`") return;
3006
+ if (char === open) {
3007
+ depth += 1;
3008
+ continue;
3009
+ }
3010
+ if (char === close) {
3011
+ depth -= 1;
3012
+ if (depth === 0) return index;
3013
+ }
3014
+ }
3104
3015
  }
3105
- function createTailwindV3Engine(source) {
3106
- const runtimeReadyPromise = createRuntimeReadyPromise(source);
3107
- let tailwindInternals;
3108
- async function generateOnce(generateSource, options = {}) {
3109
- await runtimeReadyPromise;
3110
- tailwindInternals ??= loadTailwindV3Internals(source);
3111
- const internals = tailwindInternals;
3112
- const { styleOptions, target = "weapp" } = options;
3113
- const resolvedStyleOptions = resolveStyleOptions(generateSource, styleOptions);
3114
- const requestedCandidates = mergeGenerateCandidates(generateSource, options);
3115
- for (const candidate of await collectSourceBareArbitraryValueCandidates(options.sources, options.bareArbitraryValues)) requestedCandidates.add(candidate);
3116
- const normalizedCandidates = normalizeBareArbitraryValueCandidates(requestedCandidates, options.bareArbitraryValues);
3117
- const tailwindOptions = {
3118
- ...options,
3119
- candidates: normalizedCandidates.candidates
3120
- };
3121
- const tailwindConfig = internals.validateConfig(internals.resolveConfig(createTailwindConfig(generateSource, tailwindOptions)));
3122
- const candidates = normalizedCandidates.candidates;
3123
- const changedContent = createChangedContentEntries(candidates, options.sources ?? []);
3124
- const root = require_runtime_registry.postcss_default.parse(generateSource.css, { from: void 0 });
3125
- const result = {
3126
- css: "",
3127
- messages: []
3016
+ function findContentPropertyValue(source) {
3017
+ let index = 0;
3018
+ while (index < source.length) {
3019
+ const nextIndex = source.indexOf("content", index);
3020
+ if (nextIndex === -1) return;
3021
+ const previous = source[nextIndex - 1];
3022
+ const next = source[nextIndex + 7];
3023
+ if (previous && /[\w$]/.test(previous) || next && /[\w$]/.test(next)) {
3024
+ index = nextIndex + 7;
3025
+ continue;
3026
+ }
3027
+ let colonIndex = skipWhitespaceAndComments(source, nextIndex + 7);
3028
+ if (source[colonIndex] !== ":") {
3029
+ index = nextIndex + 7;
3030
+ continue;
3031
+ }
3032
+ colonIndex = skipWhitespaceAndComments(source, colonIndex + 1);
3033
+ return { start: colonIndex };
3034
+ }
3035
+ }
3036
+ function parseStaticContentArray(source, start) {
3037
+ if (source[start] !== "[") return;
3038
+ const value = [];
3039
+ let index = skipWhitespaceAndComments(source, start + 1);
3040
+ while (index < source.length) {
3041
+ if (source[index] === "]") return {
3042
+ end: index + 1,
3043
+ value
3128
3044
  };
3129
- let context;
3130
- if (isDirectUtilitiesOnlyCss(generateSource.css)) {
3131
- context = internals.createContext(tailwindConfig, changedContent, root);
3132
- internals.generateRules(new Set(sortCandidates([internals.notOnDemandCandidate, ...candidates])), context);
3133
- root.removeAll();
3134
- appendDirectUtilityRules(root, context);
3135
- internals.resolveDefaultsAtRules(context)(root, result);
3136
- internals.collapseAdjacentRules(context)(root, result);
3137
- internals.collapseDuplicateDeclarations(context)(root, result);
3045
+ const parsed = parseStaticContentValue(source, index);
3046
+ if (!parsed) return;
3047
+ value.push(parsed.value);
3048
+ index = skipWhitespaceAndComments(source, parsed.end);
3049
+ if (source[index] === ",") {
3050
+ index = skipWhitespaceAndComments(source, index + 1);
3051
+ continue;
3052
+ }
3053
+ if (source[index] === "]") continue;
3054
+ return;
3055
+ }
3056
+ }
3057
+ function parseStaticContentObject(source, start) {
3058
+ if (source[start] !== "{") return;
3059
+ const end = findMatchingBracket(source, start, "{", "}");
3060
+ if (end === void 0) return;
3061
+ let index = skipWhitespaceAndComments(source, start + 1);
3062
+ let files;
3063
+ while (index < end) {
3064
+ let key;
3065
+ const quotedKey = readQuotedString(source, index);
3066
+ if (quotedKey) {
3067
+ key = quotedKey.value;
3068
+ index = quotedKey.end;
3138
3069
  } else {
3139
- const setupContext = () => {
3140
- return (currentRoot) => internals.createContext(tailwindConfig, changedContent, currentRoot);
3141
- };
3142
- context = await internals.processTailwindFeatures(setupContext)(root, result);
3070
+ key = readIdentifier(source, index);
3071
+ if (!key) return;
3072
+ index += key.length;
3143
3073
  }
3144
- const rawCss = restoreBareArbitraryValueCssSelectors(root.toString(), requestedCandidates, options.bareArbitraryValues, internals.escapeClassName);
3145
- const css = await transformTailwindV3CssByTarget(rawCss, target, resolvedStyleOptions);
3146
- const dependencies = collectDependencyMessages(result);
3147
- for (const dependency of generateSource.dependencies) dependencies.add(dependency);
3148
- const classSet = restoreBareArbitraryValueClassSet(collectClassSet(context), requestedCandidates, options.bareArbitraryValues);
3149
- return {
3150
- css,
3151
- rawCss,
3152
- context,
3153
- classSet,
3154
- rawCandidates: requestedCandidates,
3155
- dependencies: [...dependencies],
3156
- sources: [],
3157
- root: null,
3158
- target,
3159
- version: 3
3160
- };
3074
+ index = skipWhitespaceAndComments(source, index);
3075
+ if (source[index] !== ":") return;
3076
+ index = skipWhitespaceAndComments(source, index + 1);
3077
+ const parsedValue = parseStaticContentValue(source, index);
3078
+ if (!parsedValue) return;
3079
+ if (key === "files") files = parsedValue.value;
3080
+ index = skipWhitespaceAndComments(source, parsedValue.end);
3081
+ if (source[index] === ",") {
3082
+ index = skipWhitespaceAndComments(source, index + 1);
3083
+ continue;
3084
+ }
3085
+ if (index < end) return;
3161
3086
  }
3162
- async function generateIncrementalMissingUtilities(context, candidates, target, styleOptions, bareArbitraryValues) {
3163
- tailwindInternals ??= loadTailwindV3Internals(source);
3164
- const internals = tailwindInternals;
3165
- const root = require_runtime_registry.postcss_default.root();
3166
- const result = {
3167
- css: "",
3168
- messages: []
3169
- };
3170
- const normalizedCandidates = normalizeBareArbitraryValueCandidates(candidates, bareArbitraryValues);
3171
- const sortedCandidates = sortCandidates(normalizedCandidates.candidates);
3172
- appendUtilityRules(root, context, internals.generateRules(new Set(sortedCandidates), context));
3173
- internals.resolveDefaultsAtRules(context)(root, result);
3174
- internals.collapseAdjacentRules(context)(root, result);
3175
- internals.collapseDuplicateDeclarations(context)(root, result);
3176
- const rawCss = restoreBareArbitraryValueCssSelectors(root.toString(), candidates, bareArbitraryValues, internals.escapeClassName);
3177
- return {
3178
- css: await transformTailwindV3CssByTarget(rawCss, target, resolveStyleOptions(source, styleOptions)),
3179
- rawCss,
3180
- classSet: collectGeneratedCandidates(context, sortedCandidates, normalizedCandidates.restoreCandidates),
3181
- dependencies: collectDependencyMessages(result)
3182
- };
3087
+ return files === void 0 ? void 0 : {
3088
+ end: end + 1,
3089
+ value: { files }
3090
+ };
3091
+ }
3092
+ function parseStaticContentValue(source, start) {
3093
+ const index = skipWhitespaceAndComments(source, start);
3094
+ const quoted = readQuotedString(source, index);
3095
+ if (quoted) return quoted;
3096
+ if (source[index] === "[") return parseStaticContentArray(source, index);
3097
+ if (source[index] === "{") return parseStaticContentObject(source, index);
3098
+ }
3099
+ function readStaticConfigContent(configPath) {
3100
+ let source;
3101
+ try {
3102
+ source = (0, node_fs.readFileSync)(configPath, "utf8");
3103
+ } catch {
3104
+ return;
3183
3105
  }
3184
- async function generateWithIncrementalCache(options = {}) {
3185
- if ((options.sources?.length ?? 0) > 0) return generateOnce(source, options);
3186
- const target = options.target ?? "weapp";
3187
- const requestedCandidates = mergeGenerateCandidates(source, options);
3188
- if (requestedCandidates.size === 0) return generateOnce(source, options);
3189
- const styleOptions = resolveStyleOptions(source, options.styleOptions);
3190
- const cacheKey = createIncrementalGenerateCacheKey(source, target, styleOptions, options.bareArbitraryValues);
3191
- const cached = incrementalGenerateCache.get(cacheKey);
3192
- if (cached) {
3193
- if (hasRemovedCandidates(cached.seenCandidates, requestedCandidates)) {
3194
- const generated = await generateOnce(source, options);
3195
- incrementalGenerateCache.set(cacheKey, {
3196
- context: generated.context,
3197
- seenCandidates: new Set(requestedCandidates),
3198
- classSet: new Set(generated.classSet),
3199
- css: generated.css,
3200
- rawCss: generated.rawCss,
3201
- dependencies: generated.dependencies,
3202
- target: generated.target
3203
- });
3204
- return generated;
3205
- }
3206
- const missingCandidates = [...requestedCandidates].filter((candidate) => !cached.seenCandidates.has(candidate));
3207
- if (missingCandidates.length === 0) return {
3208
- css: cached.css,
3209
- rawCss: cached.rawCss,
3210
- incrementalCss: "",
3211
- incrementalRawCss: "",
3212
- classSet: new Set(cached.classSet),
3213
- rawCandidates: new Set(cached.seenCandidates),
3214
- dependencies: cached.dependencies,
3215
- sources: [],
3216
- root: null,
3217
- target: cached.target,
3218
- version: 3
3219
- };
3220
- const generated = await generateIncrementalMissingUtilities(cached.context, missingCandidates, target, styleOptions, options.bareArbitraryValues);
3221
- for (const candidate of missingCandidates) cached.seenCandidates.add(candidate);
3222
- for (const className of generated.classSet) cached.classSet.add(className);
3223
- cached.css = [cached.css, generated.css].filter(Boolean).join("\n");
3224
- cached.rawCss = [cached.rawCss, generated.rawCss].filter(Boolean).join("\n");
3225
- cached.dependencies = [...new Set([...cached.dependencies, ...generated.dependencies])];
3226
- return {
3227
- css: cached.css,
3228
- rawCss: cached.rawCss,
3229
- incrementalCss: generated.css,
3230
- incrementalRawCss: generated.rawCss,
3231
- classSet: new Set(cached.classSet),
3232
- rawCandidates: new Set(cached.seenCandidates),
3233
- dependencies: cached.dependencies,
3234
- sources: [],
3235
- root: null,
3236
- target: cached.target,
3237
- version: 3
3238
- };
3106
+ const contentProperty = findContentPropertyValue(source);
3107
+ if (!contentProperty) return;
3108
+ return parseStaticContentValue(source, contentProperty.start)?.value;
3109
+ }
3110
+ //#endregion
3111
+ //#region src/bundlers/vite/source-scan.ts
3112
+ const VITE_SOURCE_CANDIDATE_PATTERN = FULL_SOURCE_SCAN_PATTERN;
3113
+ function parseImportSourceParam(params) {
3114
+ const match = /\bsource\(\s*(none|(['"])(.*?)\2)\s*\)/.exec(params);
3115
+ if (!match) return;
3116
+ return {
3117
+ none: match[1] === "none",
3118
+ sourcePath: match[3]
3119
+ };
3120
+ }
3121
+ function parseCssImportSpecifier(params) {
3122
+ const value = params.trim();
3123
+ const quoted = /^(['"])(.*?)\1/.exec(value);
3124
+ if (quoted) return quoted[2];
3125
+ const url = /^url\(\s*(?:(['"])(.*?)\1|([^'")\s]+))\s*\)/.exec(value);
3126
+ return url?.[2] ?? url?.[3];
3127
+ }
3128
+ function isTailwindCssImport(params) {
3129
+ const specifier = parseCssImportSpecifier(params);
3130
+ return specifier === "tailwindcss" || specifier?.startsWith("tailwindcss/") || specifier?.replaceAll("\\", "/").endsWith("/tailwindcss/index.css");
3131
+ }
3132
+ function resolveSourceBase(base, sourcePath) {
3133
+ return node_path.default.isAbsolute(sourcePath) ? sourcePath : node_path.default.resolve(base, sourcePath);
3134
+ }
3135
+ function resolveConfigPath(base, configPath) {
3136
+ if (node_path.default.isAbsolute(configPath)) return node_path.default.resolve(configPath);
3137
+ return node_path.default.resolve(base, configPath);
3138
+ }
3139
+ async function resolveConfigContentEntries(root, base) {
3140
+ const configPaths = /* @__PURE__ */ new Set();
3141
+ root.walkAtRules("config", (rule) => {
3142
+ const configPath = parseConfigParam$1(rule.params);
3143
+ if (configPath) configPaths.add(resolveConfigPath(base, configPath));
3144
+ });
3145
+ const entries = [];
3146
+ for (const configPath of configPaths) {
3147
+ const staticContent = readStaticConfigContent(configPath);
3148
+ if (staticContent !== void 0) {
3149
+ entries.push(...normalizeLegacyContentEntries(staticContent, node_path.default.dirname(configPath), { relativeBase: node_path.default.dirname(configPath) }));
3150
+ continue;
3239
3151
  }
3240
- const generated = await generateOnce(source, options);
3241
- incrementalGenerateCache.set(cacheKey, {
3242
- context: generated.context,
3243
- seenCandidates: new Set(requestedCandidates),
3244
- classSet: new Set(generated.classSet),
3245
- css: generated.css,
3246
- rawCss: generated.rawCss,
3247
- dependencies: generated.dependencies,
3248
- target: generated.target
3249
- });
3250
- return generated;
3152
+ try {
3153
+ const loaded = await (0, tailwindcss_config.loadConfig)({
3154
+ config: configPath,
3155
+ cwd: node_path.default.dirname(configPath)
3156
+ });
3157
+ entries.push(...normalizeLegacyContentEntries(loaded?.config.content, node_path.default.dirname(configPath), { relativeBase: node_path.default.dirname(configPath) }));
3158
+ } catch {}
3159
+ }
3160
+ return {
3161
+ dependencies: [...configPaths],
3162
+ entries
3163
+ };
3164
+ }
3165
+ async function resolveTailwindV4EntriesFromCss(css, base) {
3166
+ let root;
3167
+ try {
3168
+ root = require_watch_dependencies.postcss_default.parse(css);
3169
+ } catch {
3170
+ return;
3171
+ }
3172
+ let importSourceBase;
3173
+ let hasSourceNone = false;
3174
+ let hasTailwindCssImport = false;
3175
+ const [sourceEntries, configEntries] = await Promise.all([resolveCssSourceEntries(root, base, VITE_SOURCE_CANDIDATE_PATTERN), resolveConfigContentEntries(root, base)]);
3176
+ const entries = [...configEntries.entries, ...sourceEntries];
3177
+ const hasPositiveEntries = entries.some((entry) => !entry.negated);
3178
+ const inlineCandidates = collectCssInlineSourceCandidates(root);
3179
+ root.walkAtRules("import", (rule) => {
3180
+ if (!isTailwindCssImport(rule.params)) return;
3181
+ hasTailwindCssImport = true;
3182
+ const sourceParam = parseImportSourceParam(rule.params);
3183
+ if (sourceParam?.none) hasSourceNone = true;
3184
+ if (sourceParam?.sourcePath) importSourceBase = resolveSourceBase(base, sourceParam.sourcePath);
3185
+ });
3186
+ if (importSourceBase) return {
3187
+ entries: [{
3188
+ base: importSourceBase,
3189
+ negated: false,
3190
+ pattern: VITE_SOURCE_CANDIDATE_PATTERN
3191
+ }, ...entries],
3192
+ explicit: true,
3193
+ inlineCandidates,
3194
+ dependencies: configEntries.dependencies
3195
+ };
3196
+ if (hasSourceNone) return {
3197
+ entries,
3198
+ explicit: true,
3199
+ inlineCandidates,
3200
+ dependencies: configEntries.dependencies
3201
+ };
3202
+ if (hasPositiveEntries) return {
3203
+ entries,
3204
+ explicit: true,
3205
+ inlineCandidates,
3206
+ dependencies: configEntries.dependencies
3207
+ };
3208
+ if (inlineCandidates.included.size > 0 || inlineCandidates.excluded.size > 0) return {
3209
+ entries: [],
3210
+ explicit: true,
3211
+ inlineCandidates,
3212
+ dependencies: configEntries.dependencies
3213
+ };
3214
+ return hasTailwindCssImport ? {
3215
+ entries,
3216
+ explicit: false,
3217
+ inlineCandidates,
3218
+ dependencies: configEntries.dependencies
3219
+ } : void 0;
3220
+ }
3221
+ //#endregion
3222
+ //#region src/tailwindcss/runtime/cache.ts
3223
+ const runtimeSignaturePatchersSymbol = Symbol.for("weapp-tailwindcss.runtimeSignaturePatchers");
3224
+ //#endregion
3225
+ //#region src/tailwindcss/runtime-patch.ts
3226
+ const debug$2 = createDebug("[tailwindcss:runtime-patch] ");
3227
+ const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
3228
+ const runtimePatchPromiseCache = /* @__PURE__ */ new WeakMap();
3229
+ function getNestedPatchers(twPatcher) {
3230
+ const nested = twPatcher[runtimeSignaturePatchersSymbol];
3231
+ return Array.isArray(nested) && nested.length > 0 ? nested : void 0;
3232
+ }
3233
+ function shouldApplyRuntimePatch(twPatcher) {
3234
+ return twPatcher.majorVersion === 3 && typeof twPatcher.patch === "function";
3235
+ }
3236
+ function clearTailwindcssRequireCache(twPatcher) {
3237
+ const rootPath = twPatcher.packageInfo?.rootPath;
3238
+ if (!rootPath) return;
3239
+ const normalizedRoot = node_path.default.resolve(rootPath);
3240
+ let count = 0;
3241
+ for (const id of Object.keys(require$1.cache)) {
3242
+ const normalizedId = node_path.default.resolve(id);
3243
+ if (normalizedId === normalizedRoot || normalizedId.startsWith(`${normalizedRoot}${node_path.default.sep}`)) {
3244
+ delete require$1.cache[id];
3245
+ count += 1;
3246
+ }
3247
+ }
3248
+ if (count > 0) debug$2("clear tailwindcss require cache after runtime patch, count=%d root=%s", count, normalizedRoot);
3249
+ }
3250
+ async function ensureTailwindcssRuntimePatch(twPatcher, options = {}) {
3251
+ const nestedPatchers = getNestedPatchers(twPatcher);
3252
+ if (nestedPatchers) {
3253
+ await Promise.all(nestedPatchers.map((patcher) => ensureTailwindcssRuntimePatch(patcher)));
3254
+ return;
3251
3255
  }
3252
- async function generate(options = {}) {
3253
- return options.incrementalCache ? generateWithIncrementalCache(options) : generateOnce(source, options);
3256
+ if (!shouldApplyRuntimePatch(twPatcher)) return;
3257
+ const cached = runtimePatchPromiseCache.get(twPatcher);
3258
+ if (cached) {
3259
+ await cached;
3260
+ if (options.clearRequireCache) clearTailwindcssRequireCache(twPatcher);
3261
+ return;
3254
3262
  }
3255
- return {
3256
- source,
3257
- async validateCandidates(candidates) {
3258
- return (await generate({
3259
- candidates,
3260
- incrementalCache: true,
3261
- target: "tailwind"
3262
- })).classSet;
3263
- },
3264
- generate
3265
- };
3263
+ const task = Promise.resolve().then(async () => {
3264
+ debug$2("apply tailwindcss runtime patch, package=%s version=%s root=%s", twPatcher.packageInfo?.name ?? "tailwindcss", twPatcher.packageInfo?.version ?? "unknown", twPatcher.packageInfo?.rootPath ?? "unknown");
3265
+ await twPatcher.patch?.();
3266
+ if (options.clearRequireCache) clearTailwindcssRequireCache(twPatcher);
3267
+ }).catch((error) => {
3268
+ runtimePatchPromiseCache.delete(twPatcher);
3269
+ throw error;
3270
+ });
3271
+ runtimePatchPromiseCache.set(twPatcher, task);
3272
+ return task;
3266
3273
  }
3267
3274
  //#endregion
3268
- //#region src/tailwindcss/v3-engine/source.ts
3269
- const DEFAULT_TAILWIND_V3_CSS = [
3270
- "@tailwind base;",
3271
- "@tailwind components;",
3272
- "@tailwind utilities;"
3273
- ].join("\n");
3274
- function parseConfigParam(params) {
3275
- const value = params.trim();
3276
- return /^(['"])(.+)\1$/.exec(value)?.[2];
3275
+ //#region src/tailwindcss/v3-engine/miniprogram.ts
3276
+ const defaultStyleHandler = (0, _weapp_tailwindcss_postcss.createStyleHandler)({
3277
+ cssChildCombinatorReplaceValue: ["view", "text"],
3278
+ cssRemoveHoverPseudoClass: true,
3279
+ isMainChunk: true,
3280
+ majorVersion: 3
3281
+ });
3282
+ const MINI_PROGRAM_V3_PREFLIGHT_SELECTORS = new Set([
3283
+ "view,text,:before,:after",
3284
+ "view,text,:after,:before",
3285
+ "view,text,::before,::after",
3286
+ "view,text,::after,::before"
3287
+ ]);
3288
+ const V3_PREFLIGHT_RESET_PROPS = new Set([
3289
+ "box-sizing",
3290
+ "border",
3291
+ "border-width",
3292
+ "border-style",
3293
+ "border-color",
3294
+ "margin",
3295
+ "padding"
3296
+ ]);
3297
+ function normalizeSelector(selector) {
3298
+ return selector.trim().replace(/\s+/g, "");
3277
3299
  }
3278
- function resolveOptionalPath(value, base) {
3279
- if (!value) return;
3280
- return node_path.default.isAbsolute(value) ? value : node_path.default.resolve(base, value);
3300
+ function isMiniProgramV3PreflightRule(rule) {
3301
+ return MINI_PROGRAM_V3_PREFLIGHT_SELECTORS.has(normalizeSelector(rule.selector));
3281
3302
  }
3282
- function resolveCssConfig(css, base) {
3283
- if (!css) return {
3284
- css,
3285
- config: void 0
3286
- };
3287
- const root = require_runtime_registry.postcss_default.parse(css);
3288
- let config;
3289
- root.walkAtRules("config", (rule) => {
3290
- const configPath = parseConfigParam(rule.params);
3291
- if (!configPath) return;
3292
- if (!config) config = resolveOptionalPath(configPath, base);
3293
- rule.remove();
3303
+ function hasResetDeclaration(rule) {
3304
+ let found = false;
3305
+ rule.walkDecls((decl) => {
3306
+ if (V3_PREFLIGHT_RESET_PROPS.has(decl.prop)) found = true;
3294
3307
  });
3295
- return {
3296
- config,
3297
- css: root.toString()
3308
+ return found;
3309
+ }
3310
+ function createPreflightDeclarations(cssPreflight) {
3311
+ if (!cssPreflight || typeof cssPreflight !== "object") return [];
3312
+ return Object.entries(cssPreflight).filter((entry) => entry[1] !== false).map(([prop, value]) => require_watch_dependencies.postcss_default.decl({
3313
+ prop,
3314
+ value: value.toString()
3315
+ }));
3316
+ }
3317
+ function ensureMiniProgramV3PreflightReset(css, cssPreflight) {
3318
+ const declarations = createPreflightDeclarations(cssPreflight);
3319
+ if (declarations.length === 0) return css;
3320
+ try {
3321
+ const root = require_watch_dependencies.postcss_default.parse(css);
3322
+ let targetRule;
3323
+ let hasReset = false;
3324
+ root.walkRules((rule) => {
3325
+ if (!isMiniProgramV3PreflightRule(rule)) return;
3326
+ targetRule ??= rule;
3327
+ if (hasResetDeclaration(rule)) hasReset = true;
3328
+ });
3329
+ if (!targetRule || hasReset) return css;
3330
+ targetRule.append(...declarations.map((decl) => decl.clone()));
3331
+ return root.toString();
3332
+ } catch {
3333
+ return css;
3334
+ }
3335
+ }
3336
+ async function transformTailwindV3CssToWeapp(css, options) {
3337
+ const result = await defaultStyleHandler(hasCssMacroStyleOptions(options) ? await transformCssMacroCss(css, options) : css, {
3338
+ cssChildCombinatorReplaceValue: ["view", "text"],
3339
+ cssRemoveHoverPseudoClass: true,
3340
+ isMainChunk: true,
3341
+ majorVersion: 3,
3342
+ ...options
3343
+ });
3344
+ const pruneOptions = {
3345
+ preservePreflight: true,
3346
+ preserveConditionalComments: hasCssMacroStyleOptions(options)
3298
3347
  };
3348
+ return ensureMiniProgramV3PreflightReset((0, _weapp_tailwindcss_postcss.pruneMiniProgramGeneratedCss)(result.css, pruneOptions), options?.cssPreflight);
3299
3349
  }
3300
- function getProjectRoot(patcher) {
3301
- return patcher.options?.projectRoot ?? node_process.default.cwd();
3350
+ async function transformTailwindV3CssByTarget(css, target, options) {
3351
+ if (target === "weapp") return transformTailwindV3CssToWeapp(css, options);
3352
+ return hasCssMacroStyleOptions(options) ? transformCssMacroCss(css, options) : css;
3302
3353
  }
3303
- function normalizeLoadedConfig(config) {
3304
- if (!config || typeof config !== "object") return config;
3305
- const maybeDefault = config.default;
3306
- if (maybeDefault && typeof maybeDefault === "object") return maybeDefault;
3307
- return config;
3354
+ //#endregion
3355
+ //#region src/tailwindcss/v3-engine/generator.ts
3356
+ const runtimeReadyPromiseCache = /* @__PURE__ */ new Map();
3357
+ const incrementalGenerateCache = /* @__PURE__ */ new Map();
3358
+ function isLegacyContentObject(value) {
3359
+ return typeof value === "object" && value !== null && "files" in value;
3308
3360
  }
3309
- function resolveTailwindCssPackageName(patcher) {
3310
- return resolveTailwindcssOptions(patcher.options)?.packageName ?? patcher.packageInfo?.name ?? "tailwindcss";
3361
+ function createRawContentEntries(candidates, sources) {
3362
+ const entries = [];
3363
+ const candidateContent = [...candidates].join(" ");
3364
+ if (candidateContent.length > 0) entries.push({
3365
+ raw: candidateContent,
3366
+ extension: "html"
3367
+ });
3368
+ for (const source of sources) entries.push({
3369
+ raw: source.content,
3370
+ extension: source.extension ?? "html"
3371
+ });
3372
+ return entries;
3311
3373
  }
3312
- async function resolveTailwindV3Source(options = {}) {
3313
- const projectRoot = options.projectRoot ?? node_process.default.cwd();
3314
- const base = options.base ?? options.cwd ?? projectRoot;
3315
- const cssConfig = resolveCssConfig(options.css, base);
3316
- const config = resolveOptionalPath(options.config, base) ?? cssConfig.config;
3317
- const cwd = options.cwd ?? (config ? node_path.default.dirname(config) : projectRoot);
3318
- const loaded = await (0, tailwindcss_config.loadConfig)(omitUndefined({
3319
- config,
3320
- cwd
3374
+ function createChangedContentEntries(candidates, sources) {
3375
+ return createRawContentEntries(candidates, sources).map((entry) => ({
3376
+ content: entry.raw,
3377
+ extension: entry.extension
3321
3378
  }));
3322
- return {
3323
- version: 3,
3324
- projectRoot,
3325
- cwd,
3326
- base,
3327
- css: cssConfig.css ?? options.css ?? DEFAULT_TAILWIND_V3_CSS,
3328
- config: loaded?.filepath ?? config,
3329
- configObject: normalizeLoadedConfig(loaded?.config),
3330
- dependencies: loaded?.filepath ? [loaded.filepath] : [],
3331
- packageName: options.packageName ?? "tailwindcss",
3332
- postcssPlugin: options.postcssPlugin ?? options.packageName ?? "tailwindcss"
3333
- };
3334
3379
  }
3335
- function resolveTailwindV3SourceOptionsFromPatcher(patcher) {
3336
- const projectRoot = getProjectRoot(patcher);
3337
- const tailwindOptions = resolveTailwindcssOptions(patcher.options);
3380
+ function collectCandidates(candidates) {
3381
+ return new Set(candidates ?? []);
3382
+ }
3383
+ function normalizeBareArbitraryValueCandidate(candidate, bareArbitraryValues) {
3384
+ return (0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(candidate, bareArbitraryValues)?.canonicalCandidate ?? candidate;
3385
+ }
3386
+ function normalizeBareArbitraryValueCandidates(candidates, bareArbitraryValues) {
3387
+ const normalized = /* @__PURE__ */ new Set();
3388
+ const restoreCandidates = /* @__PURE__ */ new Map();
3389
+ for (const candidate of candidates) {
3390
+ const normalizedCandidate = normalizeBareArbitraryValueCandidate(candidate, bareArbitraryValues);
3391
+ normalized.add(normalizedCandidate);
3392
+ if (normalizedCandidate !== candidate) restoreCandidates.set(normalizedCandidate, candidate);
3393
+ }
3338
3394
  return {
3339
- projectRoot,
3340
- cwd: tailwindOptions?.v3?.cwd ?? tailwindOptions?.cwd ?? projectRoot,
3341
- config: tailwindOptions?.v3?.config ?? tailwindOptions?.config,
3342
- packageName: resolveTailwindCssPackageName(patcher),
3343
- postcssPlugin: tailwindOptions?.v3?.postcssPlugin ?? tailwindOptions?.postcssPlugin
3395
+ candidates: normalized,
3396
+ restoreCandidates
3344
3397
  };
3345
3398
  }
3346
- function resolveTailwindV3SourceFromPatcher(patcher) {
3347
- return resolveTailwindV3Source(resolveTailwindV3SourceOptionsFromPatcher(patcher));
3348
- }
3349
- //#endregion
3350
- //#region src/generator/options.ts
3351
- const explicitGeneratorTargetEnvKeys = ["WEAPP_TW_TARGET", "WEAPP_TAILWINDCSS_TARGET"];
3352
- const uniWebPlatformEnvKeys = ["UNI_PLATFORM", "UNI_UTS_PLATFORM"];
3353
- const mpxWebPlatformEnvKeys = ["MPX_CLI_MODE", "MPX_CURRENT_TARGET_MODE"];
3354
- function getEnvValue(key) {
3355
- return typeof node_process.default === "undefined" ? void 0 : node_process.default.env[key];
3399
+ async function collectSourceBareArbitraryValueCandidates(sources, bareArbitraryValues) {
3400
+ if (!(0, tailwindcss_patch.isBareArbitraryValuesEnabled)(bareArbitraryValues)) return [];
3401
+ const candidates = /* @__PURE__ */ new Set();
3402
+ for (const source of sources ?? []) for (const candidate of await (0, tailwindcss_patch.extractSourceCandidates)(source.content, source.extension ?? "html", { bareArbitraryValues })) if ((0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(candidate, bareArbitraryValues)) candidates.add(candidate);
3403
+ return [...candidates];
3356
3404
  }
3357
- function normalizeGeneratorTargetValue(value) {
3358
- return value === "weapp" || value === "web" || value === "tailwind" ? value : void 0;
3405
+ function escapeCssClassSelector(className) {
3406
+ return className.replace(/[^\w-]/g, (char) => `\\${char}`);
3359
3407
  }
3360
- function isUniWebPlatform(value) {
3361
- const normalized = value?.trim().toLowerCase();
3362
- return normalized === "h5" || normalized?.startsWith("web") === true;
3408
+ function restoreBareArbitraryValueCssSelectors(css, originalCandidates, bareArbitraryValues, escapeClassName) {
3409
+ if (!(0, tailwindcss_patch.isBareArbitraryValuesEnabled)(bareArbitraryValues)) return css;
3410
+ let restored = css;
3411
+ for (const originalCandidate of originalCandidates) {
3412
+ const canonical = (0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(originalCandidate, bareArbitraryValues)?.canonicalCandidate;
3413
+ if (canonical) restored = restored.split(`.${escapeClassName(canonical)}`).join(`.${escapeCssClassSelector(originalCandidate)}`);
3414
+ }
3415
+ return restored;
3363
3416
  }
3364
- function isUniAppWebViewPlatform(value) {
3365
- const normalized = value?.trim().toLowerCase();
3366
- return normalized === "app" || normalized === "app-plus";
3417
+ function restoreBareArbitraryValueClassSet(classSet, originalCandidates, bareArbitraryValues) {
3418
+ if (!(0, tailwindcss_patch.isBareArbitraryValuesEnabled)(bareArbitraryValues)) return new Set(classSet);
3419
+ const restored = new Set(classSet);
3420
+ for (const originalCandidate of originalCandidates) {
3421
+ const canonical = (0, tailwindcss_patch.resolveBareArbitraryValueCandidate)(originalCandidate, bareArbitraryValues)?.canonicalCandidate;
3422
+ if (canonical && restored.has(canonical)) {
3423
+ restored.delete(canonical);
3424
+ restored.add(originalCandidate);
3425
+ }
3426
+ }
3427
+ return restored;
3367
3428
  }
3368
- function isUniNativeAppPlatform(value) {
3369
- return (value?.trim().toLowerCase())?.startsWith("app-") === true;
3429
+ function collectGeneratedCandidates(context, candidates, restoreCandidates) {
3430
+ const classSet = /* @__PURE__ */ new Set();
3431
+ for (const candidate of candidates) if (context.classCache.has(candidate)) classSet.add(restoreCandidates.get(candidate) ?? candidate);
3432
+ return classSet;
3370
3433
  }
3371
- function isMpxWebPlatform(value) {
3372
- return value?.trim().toLowerCase() === "web";
3434
+ function hasRemovedCandidates(previousCandidates, nextCandidates) {
3435
+ for (const candidate of previousCandidates) if (!nextCandidates.has(candidate)) return true;
3436
+ return false;
3373
3437
  }
3374
- function inferGeneratorTargetFromEnv() {
3375
- for (const key of explicitGeneratorTargetEnvKeys) {
3376
- const target = normalizeGeneratorTargetValue(getEnvValue(key));
3377
- if (target !== void 0) return target;
3378
- }
3379
- if (uniWebPlatformEnvKeys.some((key) => isUniWebPlatform(getEnvValue(key))) || isUniAppWebViewPlatform(getEnvValue("UNI_PLATFORM")) && !isUniNativeAppPlatform(getEnvValue("UNI_UTS_PLATFORM")) || mpxWebPlatformEnvKeys.some((key) => isMpxWebPlatform(getEnvValue(key))) || getEnvValue("TARO_ENV") === "h5") return "web";
3380
- return "weapp";
3438
+ function collectApplyCandidatesFromCss(css) {
3439
+ if (!css.includes("@apply")) return [];
3440
+ const candidates = /* @__PURE__ */ new Set();
3441
+ try {
3442
+ require_watch_dependencies.postcss_default.parse(css).walkAtRules("apply", (rule) => {
3443
+ for (const candidate of rule.params.split(/\s+/)) {
3444
+ const normalized = candidate.replace(/!important$/, "").trim();
3445
+ if (normalized) candidates.add(normalized);
3446
+ }
3447
+ });
3448
+ } catch {}
3449
+ return [...candidates];
3381
3450
  }
3382
- function normalizeWeappTailwindcssGeneratorOptions(options) {
3383
- const target = options?.target ?? inferGeneratorTargetFromEnv();
3384
- if (options == null) return {
3385
- target,
3386
- importFallback: true,
3387
- tailwindcssV3Compatibility: target === "weapp",
3388
- bareArbitraryValues: void 0
3389
- };
3390
- return {
3391
- target,
3392
- config: options.config,
3393
- styleOptions: options.styleOptions,
3394
- importFallback: options.importFallback ?? true,
3395
- tailwindcssV3Compatibility: options.tailwindcssV3Compatibility ?? target === "weapp",
3396
- bareArbitraryValues: options.bareArbitraryValues
3397
- };
3451
+ function isTailwindCandidateLayer(params) {
3452
+ return params.split(/[,\s]+/).some((layer) => layer === "components" || layer === "utilities");
3398
3453
  }
3399
- //#endregion
3400
- //#region src/generator/index.ts
3401
- function isTailwindV3Source(source) {
3402
- return "version" in source && source.version === 3;
3454
+ function extractClassCandidatesFromSelector(selector, candidates) {
3455
+ for (let index = 0; index < selector.length; index++) {
3456
+ if (selector[index] !== ".") continue;
3457
+ let candidate = "";
3458
+ let escaped = false;
3459
+ for (let tokenIndex = index + 1; tokenIndex < selector.length; tokenIndex++) {
3460
+ const char = selector[tokenIndex];
3461
+ if (escaped) {
3462
+ candidate += char;
3463
+ escaped = false;
3464
+ continue;
3465
+ }
3466
+ if (char === "\\") {
3467
+ escaped = true;
3468
+ continue;
3469
+ }
3470
+ if (char && /[\w-]/.test(char)) {
3471
+ candidate += char;
3472
+ continue;
3473
+ }
3474
+ break;
3475
+ }
3476
+ if (candidate) candidates.add(candidate);
3477
+ }
3403
3478
  }
3404
- function createWeappTailwindcssGenerator(source) {
3405
- return isTailwindV3Source(source) ? createTailwindV3Engine(source) : createTailwindV4Engine(source);
3479
+ function collectLayerCandidatesFromCss(css) {
3480
+ if (!css.includes("@layer")) return [];
3481
+ const candidates = /* @__PURE__ */ new Set();
3482
+ try {
3483
+ require_watch_dependencies.postcss_default.parse(css).walkAtRules("layer", (layer) => {
3484
+ if (!isTailwindCandidateLayer(layer.params)) return;
3485
+ layer.walkRules((rule) => {
3486
+ extractClassCandidatesFromSelector(rule.selector, candidates);
3487
+ });
3488
+ });
3489
+ } catch {}
3490
+ return [...candidates];
3406
3491
  }
3407
- //#endregion
3408
- //#region src/bundlers/shared/generator-css/markers.ts
3409
- const TAILWIND_V4_BANNER_RE = /\/\*!\s*tailwindcss v4\./;
3410
- const TAILWIND_GENERATED_CSS_MARKER_RE = /\/\*!\s*tailwindcss v|@property\s+--tw-|--tw-|:not\(#\\#\)|\.[^,{]*(?:\\:|\\\[|\\#)|(?::host|page|\.tw-root|wx-root-portal-content)[^{]*\{[^}]*--(?:color|spacing|text|font-weight|radius)-/;
3411
- const GENERATOR_PLACEHOLDER_MARKER_RE = /\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\//i;
3412
- const GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE = /\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\/\s*/gi;
3413
- const TAILWIND_BANNER_PREFIX_RE = /^\/\*!\s*tailwindcss v[^*]*\*\/\s*/i;
3414
- const TAILWIND_BANNER_RE = /\/\*!\s*tailwindcss v[^*]*\*\//i;
3415
- const TAILWIND_BANNER_GLOBAL_RE = /\/\*!\s*tailwindcss v[^*]*\*\/\s*/gi;
3416
- const VITE_MARKER_RE = /\/\*\$vite\$:[^*]*\*\//g;
3417
- function createCssAppend(base, extra) {
3418
- if (!base) return extra;
3419
- if (!extra) return base;
3420
- return `${base}\n${extra}`;
3492
+ function mergeGenerateCandidates(source, options) {
3493
+ return collectCandidates([
3494
+ ...collectLayerCandidatesFromCss(source.css),
3495
+ ...collectApplyCandidatesFromCss(source.css),
3496
+ ...collectCandidates(options.candidates)
3497
+ ]);
3421
3498
  }
3422
- function splitTailwindV4GeneratedCssBySourceOrder(rawSource, rawTailwindCss) {
3423
- const trimmedRaw = rawSource.trim();
3424
- const trimmedTailwind = rawTailwindCss.trim();
3425
- if (trimmedRaw === trimmedTailwind) return {
3426
- before: "",
3427
- after: ""
3428
- };
3429
- if (trimmedTailwind.startsWith(trimmedRaw)) return {
3430
- before: "",
3431
- after: ""
3499
+ function mergeContent(content, rawEntries) {
3500
+ if (isLegacyContentObject(content)) return {
3501
+ ...content,
3502
+ relative: content.relative ?? true,
3503
+ files: [...[].concat(content.files ?? []), ...rawEntries]
3432
3504
  };
3433
- const start = rawSource.indexOf(rawTailwindCss);
3434
- if (start === -1) return;
3435
3505
  return {
3436
- before: rawSource.slice(0, start),
3437
- after: rawSource.slice(start + rawTailwindCss.length)
3506
+ relative: true,
3507
+ files: [...[].concat(content ?? []), ...rawEntries]
3438
3508
  };
3439
3509
  }
3440
- function splitGeneratorPlaceholderCssBySourceOrder(rawSource, rawTailwindCss) {
3441
- const match = GENERATOR_PLACEHOLDER_MARKER_RE.exec(rawSource);
3442
- if (!match || match.index === void 0) return;
3443
- let afterStart = match.index + match[0].length;
3444
- while (/\s/.test(rawSource[afterStart] ?? "")) afterStart++;
3445
- if (rawTailwindCss && rawSource.slice(afterStart).startsWith(rawTailwindCss)) {
3446
- afterStart += rawTailwindCss.length;
3447
- while (/\s/.test(rawSource[afterStart] ?? "")) afterStart++;
3448
- }
3449
- return {
3450
- before: rawSource.slice(0, match.index),
3451
- after: rawSource.slice(afterStart)
3452
- };
3510
+ function normalizeConfigObject(config) {
3511
+ if (!config || typeof config !== "object") return config;
3512
+ const maybeDefault = config.default;
3513
+ if (maybeDefault && typeof maybeDefault === "object") return maybeDefault;
3514
+ return config;
3453
3515
  }
3454
- function splitTailwindGeneratedCssByBanner(rawSource, start) {
3455
- const match = start === void 0 ? TAILWIND_BANNER_RE.exec(rawSource) : { index: start };
3456
- if (!match || match.index === void 0) return;
3516
+ function hasExplicitContentInput(options) {
3517
+ return options.candidates !== void 0 || options.sources !== void 0;
3518
+ }
3519
+ function createExplicitContentConfig(rawEntries) {
3457
3520
  return {
3458
- before: rawSource.slice(0, match.index),
3459
- after: [...rawSource.slice(match.index).matchAll(VITE_MARKER_RE)].map((item) => item[0]).join("\n")
3521
+ relative: true,
3522
+ files: rawEntries
3460
3523
  };
3461
3524
  }
3462
- function stripTailwindBanner(css) {
3463
- return css.replace(TAILWIND_BANNER_PREFIX_RE, "");
3525
+ function createTailwindConfig(source, options) {
3526
+ const config = { ...normalizeConfigObject(source.configObject) ?? {} };
3527
+ const rawEntries = createRawContentEntries(mergeGenerateCandidates(source, options), options.sources ?? []);
3528
+ config.content = hasExplicitContentInput(options) ? createExplicitContentConfig(rawEntries) : mergeContent(config.content, rawEntries);
3529
+ return config;
3464
3530
  }
3465
- function stripTailwindBanners(css) {
3466
- return css.replace(TAILWIND_BANNER_GLOBAL_RE, "");
3531
+ function shouldAutoEnableCssMacro(source) {
3532
+ return hasCssMacroTailwindPlugin(normalizeConfigObject(source.configObject)?.plugins);
3467
3533
  }
3468
- function stripGeneratorPlaceholderMarkers(css) {
3469
- return css.replace(GENERATOR_PLACEHOLDER_MARKER_GLOBAL_RE, "");
3534
+ function resolveStyleOptions(source, options) {
3535
+ return shouldAutoEnableCssMacro(source) ? withCssMacroStyleOptions(options) : options;
3470
3536
  }
3471
- function hasTailwindGeneratedCss(rawSource) {
3472
- return TAILWIND_V4_BANNER_RE.test(rawSource);
3537
+ function loadTailwindV3Internals(source) {
3538
+ const requireFromProject = (0, node_module.createRequire)(`${source.cwd}/package.json`);
3539
+ const requireFromRuntime = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
3540
+ const requireTailwind = (id) => {
3541
+ try {
3542
+ return requireFromProject(id);
3543
+ } catch {
3544
+ return requireFromRuntime(id);
3545
+ }
3546
+ };
3547
+ const collapseAdjacentRulesModule = requireTailwind(`${source.packageName}/lib/lib/collapseAdjacentRules`);
3548
+ const collapseDuplicateDeclarationsModule = requireTailwind(`${source.packageName}/lib/lib/collapseDuplicateDeclarations`);
3549
+ const escapeClassNameModule = requireTailwind(`${source.packageName}/lib/util/escapeClassName`);
3550
+ const generateRulesModule = requireTailwind(`${source.packageName}/lib/lib/generateRules`);
3551
+ const sharedStateModule = requireTailwind(`${source.packageName}/lib/lib/sharedState`);
3552
+ const setupContextUtils = requireTailwind(`${source.packageName}/lib/lib/setupContextUtils`);
3553
+ const processTailwindFeaturesModule = requireTailwind(`${source.packageName}/lib/processTailwindFeatures`);
3554
+ const resolveDefaultsAtRulesModule = requireTailwind(`${source.packageName}/lib/lib/resolveDefaultsAtRules`);
3555
+ const resolveConfigModule = requireTailwind(`${source.packageName}/lib/public/resolve-config`);
3556
+ const validateConfigModule = requireTailwind(`${source.packageName}/lib/util/validateConfig.js`);
3557
+ return {
3558
+ collapseAdjacentRules: collapseAdjacentRulesModule["default"] ?? collapseAdjacentRulesModule,
3559
+ collapseDuplicateDeclarations: collapseDuplicateDeclarationsModule["default"] ?? collapseDuplicateDeclarationsModule,
3560
+ createContext: setupContextUtils["createContext"],
3561
+ escapeClassName: escapeClassNameModule["default"] ?? escapeClassNameModule,
3562
+ generateRules: generateRulesModule["generateRules"],
3563
+ notOnDemandCandidate: String(sharedStateModule["NOT_ON_DEMAND"] ?? "*"),
3564
+ processTailwindFeatures: processTailwindFeaturesModule["default"] ?? processTailwindFeaturesModule,
3565
+ resolveDefaultsAtRules: resolveDefaultsAtRulesModule["default"] ?? resolveDefaultsAtRulesModule,
3566
+ resolveConfig: resolveConfigModule["default"] ?? resolveConfigModule,
3567
+ validateConfig: validateConfigModule["validateConfig"]
3568
+ };
3473
3569
  }
3474
- function hasTailwindGeneratedCssMarkers(rawSource) {
3475
- return TAILWIND_GENERATED_CSS_MARKER_RE.test(rawSource) || GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource);
3570
+ function createStableJson$1(value) {
3571
+ if (value === void 0) return "undefined";
3572
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
3573
+ if (Array.isArray(value)) return `[${value.map((item) => createStableJson$1(item)).join(",")}]`;
3574
+ return `{${Object.keys(value).sort().map((key) => {
3575
+ const record = value;
3576
+ return `${JSON.stringify(key)}:${createStableJson$1(record[key])}`;
3577
+ }).join(",")}}`;
3476
3578
  }
3477
- //#endregion
3478
- //#region src/bundlers/shared/generator-css/directives.ts
3479
- const TAILWIND_REMOVABLE_SOURCE_DIRECTIVE_NAMES = new Set([
3480
- "config",
3481
- "custom-variant",
3482
- "layer",
3483
- "plugin",
3484
- "reference",
3485
- "source",
3486
- "tailwind",
3487
- "theme",
3488
- "utility",
3489
- "variant"
3490
- ]);
3491
- const TAILWIND_ROOT_DIRECTIVE_NAMES = new Set([
3492
- "config",
3493
- "custom-variant",
3494
- "plugin",
3495
- "source",
3496
- "tailwind",
3497
- "theme",
3498
- "utility",
3499
- "variant"
3500
- ]);
3501
- const TAILWIND_ROOT_DIRECTIVE_RE = /@(?:import\s+(?:url\(\s*)?["']?tailwindcss4?(?:\/[^"')\s]*)?|(?:use|forward)\s+(?:url\(\s*)?["']?tailwindcss4?(?:\/[^"')\s]*)?|tailwind|config|custom-variant|plugin|source|theme|utility|variant)\b/;
3502
- const TAILWIND_EXTRACTABLE_DIRECTIVE_RE = /^\s*@(?:import|use|forward|tailwind|config|source|reference|plugin)\b[\s\S]*?(?:;|$)/;
3503
- const TAILWIND_EXTRACTABLE_LAYER_STATEMENT_RE = /^\s*@layer\s[^;{]+;\s*$/;
3504
- const TAILWIND_EXTRACTABLE_BLOCK_START_RE = /^\s*@(?:layer|theme|utility|variant|custom-variant)\b[\s\S]*\{/;
3505
- const TAILWIND_V3_SUBPATH_IMPORT_LAYERS = new Map([
3506
- ["tailwindcss/base", "base"],
3507
- ["tailwindcss/components", "components"],
3508
- ["tailwindcss/utilities", "utilities"]
3509
- ]);
3510
- function parseImportRequest(params) {
3511
- return /^(?:url\(\s*)?(["']?)([^"')\s]+)\1\s*\)?/.exec(params.trim())?.[2];
3579
+ function createDependencyFingerprint(files) {
3580
+ return files.map((file) => {
3581
+ try {
3582
+ const stat = node_fs.default.statSync(file);
3583
+ return `${file}:${stat.size}:${stat.mtimeMs}`;
3584
+ } catch {
3585
+ return `${file}:missing`;
3586
+ }
3587
+ }).join("|");
3512
3588
  }
3513
- function parseConfigRequest(params) {
3514
- return /^(["'])(.+)\1\s*;?$/.exec(params.trim())?.[2];
3589
+ function createIncrementalGenerateCacheKey(source, target, styleOptions, bareArbitraryValues) {
3590
+ return [
3591
+ source.packageName,
3592
+ source.postcssPlugin,
3593
+ source.cwd,
3594
+ source.config ?? "config:missing",
3595
+ createDependencyFingerprint(source.dependencies),
3596
+ source.css,
3597
+ createStableJson$1(normalizeConfigObject(source.configObject)?.content),
3598
+ target,
3599
+ createStableJson$1(styleOptions),
3600
+ createStableJson$1(bareArbitraryValues)
3601
+ ].join("\0");
3515
3602
  }
3516
- function isPackageJsonImportRequest$1(request) {
3517
- return typeof request === "string" && request.startsWith("#");
3603
+ function createRuntimeReadyCacheKey(source, rootPath) {
3604
+ return [
3605
+ source.packageName,
3606
+ source.postcssPlugin,
3607
+ rootPath ?? "missing",
3608
+ source.config ?? "config:missing",
3609
+ source.cwd
3610
+ ].join("\0");
3518
3611
  }
3519
- function isWeappTailwindcssImportRequest(request) {
3520
- return request === "weapp-tailwindcss" || request?.startsWith("weapp-tailwindcss/");
3612
+ function isDirectUtilitiesOnlyCss(css) {
3613
+ return css.replace(/\s+/g, "") === "@tailwindutilities;";
3521
3614
  }
3522
- function normalizeTailwindImportRequest(request, options = {}) {
3523
- if (options.importFallback && isWeappTailwindcssImportRequest(request)) return request.replace(/^weapp-tailwindcss/, "tailwindcss");
3524
- return request;
3615
+ function collectClassSet(context) {
3616
+ const classSet = /* @__PURE__ */ new Set();
3617
+ for (const candidate of context.classCache.keys()) if (String(candidate) !== "*") classSet.add(candidate);
3618
+ return classSet;
3525
3619
  }
3526
- function replaceImportRequest(params, request, replacement) {
3527
- const index = params.indexOf(request);
3528
- if (index === -1) return params;
3529
- return `${params.slice(0, index)}${replacement}${params.slice(index + request.length)}`;
3620
+ function collectDependencyMessages(result) {
3621
+ const dependencies = /* @__PURE__ */ new Set();
3622
+ for (const message of result.messages) {
3623
+ const file = message["file"];
3624
+ if (message["type"] === "dependency" && typeof file === "string") dependencies.add(file);
3625
+ }
3626
+ return dependencies;
3530
3627
  }
3531
- function normalizeTailwindImportAtRules(root, options = {}) {
3532
- if (!options.importFallback) return false;
3533
- let changed = false;
3534
- const seenCanonicalImports = /* @__PURE__ */ new Set();
3535
- root.walkAtRules("import", (node) => {
3536
- const request = parseImportRequest(node.params);
3537
- const normalizedRequest = normalizeTailwindImportRequest(request, options);
3538
- if (!normalizedRequest || !isTailwindImportRequest(normalizedRequest)) return;
3539
- const normalizedParams = request && normalizedRequest !== request ? replaceImportRequest(node.params, request, normalizedRequest) : node.params;
3540
- const normalizedKey = normalizedParams.trim();
3541
- if (seenCanonicalImports.has(normalizedKey)) {
3542
- node.remove();
3543
- changed = true;
3544
- return;
3545
- }
3546
- seenCanonicalImports.add(normalizedKey);
3547
- if (normalizedParams !== node.params) {
3548
- node.params = normalizedParams;
3549
- changed = true;
3628
+ function sortCandidates(candidates) {
3629
+ return [...candidates].sort((a, z) => {
3630
+ if (a === z) return 0;
3631
+ return a < z ? -1 : 1;
3632
+ });
3633
+ }
3634
+ function appendUtilityRules(root, context, rules) {
3635
+ const sortedRules = context.offsets.sort(rules);
3636
+ for (const [sort, rule] of sortedRules) {
3637
+ const tailwindRaw = rule.raws.tailwind;
3638
+ if (sort.layer === "utilities" || sort.layer === "variants" && tailwindRaw?.parentLayer === "utilities") root.append(rule.clone());
3639
+ }
3640
+ }
3641
+ function appendDirectUtilityRules(root, context) {
3642
+ appendUtilityRules(root, context, [...context.ruleCache]);
3643
+ }
3644
+ function createRuntimeReadyPromise(source) {
3645
+ const patcher = createTailwindcssPatcher({
3646
+ basedir: source.cwd,
3647
+ supportCustomLengthUnitsPatch: true,
3648
+ tailwindcss: {
3649
+ ...source.config === void 0 ? {} : { config: source.config },
3650
+ cwd: source.cwd,
3651
+ packageName: source.packageName,
3652
+ postcssPlugin: source.postcssPlugin,
3653
+ version: 3
3550
3654
  }
3551
3655
  });
3552
- return changed;
3656
+ const cacheKey = createRuntimeReadyCacheKey(source, patcher.packageInfo?.rootPath);
3657
+ const cached = runtimeReadyPromiseCache.get(cacheKey);
3658
+ if (cached) return cached;
3659
+ const task = ensureTailwindcssRuntimePatch(patcher, { clearRequireCache: true }).catch((error) => {
3660
+ runtimeReadyPromiseCache.delete(cacheKey);
3661
+ throw error;
3662
+ });
3663
+ runtimeReadyPromiseCache.set(cacheKey, task);
3664
+ return task;
3553
3665
  }
3554
- function normalizeTailwindDirectiveLine(line, options = {}) {
3555
- const trimmed = line.trimStart();
3556
- if (/^@(?:use|forward)\b/.test(trimmed)) {
3557
- const request = parseImportRequest(trimmed.replace(/^@(?:use|forward)\b/, ""));
3558
- if (isTailwindImportRequest(request) || options.importFallback && isWeappTailwindcssImportRequest(request)) {
3559
- const normalizedRequest = normalizeTailwindImportRequest(request, options);
3560
- return replaceImportRequest(line.replace(/^(\s*)@(?:use|forward)\b/, "$1@import"), request, normalizedRequest);
3666
+ function createTailwindV3Engine(source) {
3667
+ const runtimeReadyPromise = createRuntimeReadyPromise(source);
3668
+ let tailwindInternals;
3669
+ async function generateOnce(generateSource, options = {}) {
3670
+ await runtimeReadyPromise;
3671
+ tailwindInternals ??= loadTailwindV3Internals(source);
3672
+ const internals = tailwindInternals;
3673
+ const { styleOptions, target = "weapp" } = options;
3674
+ const resolvedStyleOptions = resolveStyleOptions(generateSource, styleOptions);
3675
+ const requestedCandidates = mergeGenerateCandidates(generateSource, options);
3676
+ for (const candidate of await collectSourceBareArbitraryValueCandidates(options.sources, options.bareArbitraryValues)) requestedCandidates.add(candidate);
3677
+ const normalizedCandidates = normalizeBareArbitraryValueCandidates(requestedCandidates, options.bareArbitraryValues);
3678
+ const tailwindOptions = {
3679
+ ...options,
3680
+ candidates: normalizedCandidates.candidates
3681
+ };
3682
+ const tailwindConfig = internals.validateConfig(internals.resolveConfig(createTailwindConfig(generateSource, tailwindOptions)));
3683
+ const candidates = normalizedCandidates.candidates;
3684
+ const changedContent = createChangedContentEntries(candidates, options.sources ?? []);
3685
+ const root = require_watch_dependencies.postcss_default.parse(generateSource.css, { from: void 0 });
3686
+ const result = {
3687
+ css: "",
3688
+ messages: []
3689
+ };
3690
+ let context;
3691
+ if (isDirectUtilitiesOnlyCss(generateSource.css)) {
3692
+ context = internals.createContext(tailwindConfig, changedContent, root);
3693
+ internals.generateRules(new Set(sortCandidates([internals.notOnDemandCandidate, ...candidates])), context);
3694
+ root.removeAll();
3695
+ appendDirectUtilityRules(root, context);
3696
+ internals.resolveDefaultsAtRules(context)(root, result);
3697
+ internals.collapseAdjacentRules(context)(root, result);
3698
+ internals.collapseDuplicateDeclarations(context)(root, result);
3699
+ } else {
3700
+ const setupContext = () => {
3701
+ return (currentRoot) => internals.createContext(tailwindConfig, changedContent, currentRoot);
3702
+ };
3703
+ context = await internals.processTailwindFeatures(setupContext)(root, result);
3561
3704
  }
3562
- return line;
3705
+ const rawCss = restoreBareArbitraryValueCssSelectors(root.toString(), requestedCandidates, options.bareArbitraryValues, internals.escapeClassName);
3706
+ const css = await transformTailwindV3CssByTarget(rawCss, target, resolvedStyleOptions);
3707
+ const dependencies = collectDependencyMessages(result);
3708
+ for (const dependency of generateSource.dependencies) dependencies.add(dependency);
3709
+ const classSet = restoreBareArbitraryValueClassSet(collectClassSet(context), requestedCandidates, options.bareArbitraryValues);
3710
+ return {
3711
+ css,
3712
+ rawCss,
3713
+ context,
3714
+ classSet,
3715
+ rawCandidates: requestedCandidates,
3716
+ dependencies: [...dependencies],
3717
+ sources: [],
3718
+ root: null,
3719
+ target,
3720
+ version: 3
3721
+ };
3563
3722
  }
3564
- if (!options.importFallback || !trimmed.startsWith("@import")) return line;
3565
- const request = parseImportRequest(trimmed.replace(/^@import\b/, ""));
3566
- if (!request || !isWeappTailwindcssImportRequest(request)) return line;
3567
- return replaceImportRequest(line, request, request.replace(/^weapp-tailwindcss/, "tailwindcss"));
3568
- }
3569
- function extractTailwindDirectiveLines(rawSource, options = {}) {
3570
- const directives = [];
3571
- const seenImports = /* @__PURE__ */ new Set();
3572
- for (const line of stripGeneratorPlaceholderMarkers(rawSource).split(/\r?\n/)) {
3573
- const trimmed = line.trim();
3574
- if (!trimmed || trimmed.startsWith("//")) continue;
3575
- const directive = TAILWIND_EXTRACTABLE_DIRECTIVE_RE.exec(line)?.[0] ?? TAILWIND_EXTRACTABLE_LAYER_STATEMENT_RE.exec(line)?.[0];
3576
- if (!directive) continue;
3577
- const normalized = normalizeTailwindDirectiveLine(directive.trimEnd(), options);
3578
- const normalizedTrimmed = normalized.trim();
3579
- if (options.removeConfig && normalizedTrimmed.startsWith("@config")) continue;
3580
- const request = /^@(?:import|use|forward)\b/.test(normalizedTrimmed) ? parseImportRequest(normalizedTrimmed.replace(/^@(?:import|use|forward)\b/, "")) : void 0;
3581
- if (request && !isTailwindImportRequest(request) && !isPackageJsonImportRequest$1(request)) continue;
3582
- if (/^@(?:import|use|forward)\b/.test(normalizedTrimmed) && !request) continue;
3583
- if (request && isTailwindImportRequest(request)) {
3584
- const key = normalizedTrimmed;
3585
- if (seenImports.has(key)) continue;
3586
- seenImports.add(key);
3723
+ async function generateIncrementalMissingUtilities(context, candidates, target, styleOptions, bareArbitraryValues) {
3724
+ tailwindInternals ??= loadTailwindV3Internals(source);
3725
+ const internals = tailwindInternals;
3726
+ const root = require_watch_dependencies.postcss_default.root();
3727
+ const result = {
3728
+ css: "",
3729
+ messages: []
3730
+ };
3731
+ const normalizedCandidates = normalizeBareArbitraryValueCandidates(candidates, bareArbitraryValues);
3732
+ const sortedCandidates = sortCandidates(normalizedCandidates.candidates);
3733
+ appendUtilityRules(root, context, internals.generateRules(new Set(sortedCandidates), context));
3734
+ internals.resolveDefaultsAtRules(context)(root, result);
3735
+ internals.collapseAdjacentRules(context)(root, result);
3736
+ internals.collapseDuplicateDeclarations(context)(root, result);
3737
+ const rawCss = restoreBareArbitraryValueCssSelectors(root.toString(), candidates, bareArbitraryValues, internals.escapeClassName);
3738
+ return {
3739
+ css: await transformTailwindV3CssByTarget(rawCss, target, resolveStyleOptions(source, styleOptions)),
3740
+ rawCss,
3741
+ classSet: collectGeneratedCandidates(context, sortedCandidates, normalizedCandidates.restoreCandidates),
3742
+ dependencies: collectDependencyMessages(result)
3743
+ };
3744
+ }
3745
+ async function generateWithIncrementalCache(options = {}) {
3746
+ if ((options.sources?.length ?? 0) > 0) return generateOnce(source, options);
3747
+ const target = options.target ?? "weapp";
3748
+ const requestedCandidates = mergeGenerateCandidates(source, options);
3749
+ if (requestedCandidates.size === 0) return generateOnce(source, options);
3750
+ const styleOptions = resolveStyleOptions(source, options.styleOptions);
3751
+ const cacheKey = createIncrementalGenerateCacheKey(source, target, styleOptions, options.bareArbitraryValues);
3752
+ const cached = incrementalGenerateCache.get(cacheKey);
3753
+ if (cached) {
3754
+ if (hasRemovedCandidates(cached.seenCandidates, requestedCandidates)) {
3755
+ const generated = await generateOnce(source, options);
3756
+ incrementalGenerateCache.set(cacheKey, {
3757
+ context: generated.context,
3758
+ seenCandidates: new Set(requestedCandidates),
3759
+ classSet: new Set(generated.classSet),
3760
+ css: generated.css,
3761
+ rawCss: generated.rawCss,
3762
+ dependencies: generated.dependencies,
3763
+ target: generated.target
3764
+ });
3765
+ return generated;
3766
+ }
3767
+ const missingCandidates = [...requestedCandidates].filter((candidate) => !cached.seenCandidates.has(candidate));
3768
+ if (missingCandidates.length === 0) return {
3769
+ css: cached.css,
3770
+ rawCss: cached.rawCss,
3771
+ incrementalCss: "",
3772
+ incrementalRawCss: "",
3773
+ classSet: new Set(cached.classSet),
3774
+ rawCandidates: new Set(cached.seenCandidates),
3775
+ dependencies: cached.dependencies,
3776
+ sources: [],
3777
+ root: null,
3778
+ target: cached.target,
3779
+ version: 3
3780
+ };
3781
+ const generated = await generateIncrementalMissingUtilities(cached.context, missingCandidates, target, styleOptions, options.bareArbitraryValues);
3782
+ for (const candidate of missingCandidates) cached.seenCandidates.add(candidate);
3783
+ for (const className of generated.classSet) cached.classSet.add(className);
3784
+ cached.css = [cached.css, generated.css].filter(Boolean).join("\n");
3785
+ cached.rawCss = [cached.rawCss, generated.rawCss].filter(Boolean).join("\n");
3786
+ cached.dependencies = [...new Set([...cached.dependencies, ...generated.dependencies])];
3787
+ return {
3788
+ css: cached.css,
3789
+ rawCss: cached.rawCss,
3790
+ incrementalCss: generated.css,
3791
+ incrementalRawCss: generated.rawCss,
3792
+ classSet: new Set(cached.classSet),
3793
+ rawCandidates: new Set(cached.seenCandidates),
3794
+ dependencies: cached.dependencies,
3795
+ sources: [],
3796
+ root: null,
3797
+ target: cached.target,
3798
+ version: 3
3799
+ };
3587
3800
  }
3588
- directives.push(normalized);
3801
+ const generated = await generateOnce(source, options);
3802
+ incrementalGenerateCache.set(cacheKey, {
3803
+ context: generated.context,
3804
+ seenCandidates: new Set(requestedCandidates),
3805
+ classSet: new Set(generated.classSet),
3806
+ css: generated.css,
3807
+ rawCss: generated.rawCss,
3808
+ dependencies: generated.dependencies,
3809
+ target: generated.target
3810
+ });
3811
+ return generated;
3589
3812
  }
3590
- return directives;
3591
- }
3592
- function stripPreprocessorLineComment(line) {
3593
- let quote;
3594
- let escaped = false;
3595
- for (let index = 0; index < line.length; index++) {
3596
- const char = line[index];
3597
- if (escaped) {
3598
- escaped = false;
3599
- continue;
3600
- }
3601
- if (char === "\\") {
3602
- escaped = true;
3603
- continue;
3604
- }
3605
- if (quote) {
3606
- if (char === quote) quote = void 0;
3607
- continue;
3608
- }
3609
- if (char === "\"" || char === "'") {
3610
- quote = char;
3611
- continue;
3612
- }
3613
- if (char === "/" && line[index + 1] === "/" && (index === 0 || /\s/.test(line[index - 1]))) return line.slice(0, index).trimEnd();
3813
+ async function generate(options = {}) {
3814
+ return options.incrementalCache ? generateWithIncrementalCache(options) : generateOnce(source, options);
3614
3815
  }
3615
- return line;
3816
+ return {
3817
+ source,
3818
+ async validateCandidates(candidates) {
3819
+ return (await generate({
3820
+ candidates,
3821
+ incrementalCache: true,
3822
+ target: "tailwind"
3823
+ })).classSet;
3824
+ },
3825
+ generate
3826
+ };
3616
3827
  }
3617
- function countBlockBraceDelta(line) {
3618
- let quote;
3619
- let escaped = false;
3620
- let delta = 0;
3621
- for (let index = 0; index < line.length; index++) {
3622
- const char = line[index];
3623
- if (escaped) {
3624
- escaped = false;
3625
- continue;
3626
- }
3627
- if (char === "\\") {
3628
- escaped = true;
3629
- continue;
3630
- }
3631
- if (quote) {
3632
- if (char === quote) quote = void 0;
3633
- continue;
3634
- }
3635
- if (char === "\"" || char === "'") {
3636
- quote = char;
3637
- continue;
3638
- }
3639
- if (char === "{") delta++;
3640
- else if (char === "}") delta--;
3641
- }
3642
- return delta;
3828
+ //#endregion
3829
+ //#region src/tailwindcss/v3-engine/source.ts
3830
+ const DEFAULT_TAILWIND_V3_CSS = [
3831
+ "@tailwind base;",
3832
+ "@tailwind components;",
3833
+ "@tailwind utilities;"
3834
+ ].join("\n");
3835
+ function parseConfigParam(params) {
3836
+ const value = params.trim();
3837
+ return /^(['"])(.+)\1$/.exec(value)?.[2];
3643
3838
  }
3644
- function extractTailwindFallbackBlocks(rawSource) {
3645
- const blocks = [];
3646
- let current;
3647
- let depth = 0;
3648
- for (const rawLine of stripGeneratorPlaceholderMarkers(rawSource).split(/\r?\n/)) {
3649
- const line = stripPreprocessorLineComment(rawLine);
3650
- if (!line.trim()) continue;
3651
- if (!current) {
3652
- if (!TAILWIND_EXTRACTABLE_BLOCK_START_RE.test(line)) continue;
3653
- current = [line];
3654
- depth = countBlockBraceDelta(line);
3655
- if (depth <= 0) {
3656
- blocks.push(current.join("\n"));
3657
- current = void 0;
3658
- depth = 0;
3659
- }
3660
- continue;
3661
- }
3662
- current.push(line);
3663
- depth += countBlockBraceDelta(line);
3664
- if (depth <= 0) {
3665
- blocks.push(current.join("\n"));
3666
- current = void 0;
3667
- depth = 0;
3668
- }
3669
- }
3670
- return blocks;
3839
+ function resolveOptionalPath(value, base) {
3840
+ if (!value) return;
3841
+ return node_path.default.isAbsolute(value) ? value : node_path.default.resolve(base, value);
3671
3842
  }
3672
- function extractTailwindSourceForPostcssFallback(rawSource, options = {}) {
3673
- const directives = [...extractTailwindDirectiveLines(rawSource, options), ...extractTailwindFallbackBlocks(rawSource)];
3674
- return directives.length > 0 ? directives.join("\n") : void 0;
3843
+ function resolveCssConfig(css, base) {
3844
+ if (!css) return {
3845
+ css,
3846
+ config: void 0
3847
+ };
3848
+ const root = require_watch_dependencies.postcss_default.parse(css);
3849
+ let config;
3850
+ root.walkAtRules("config", (rule) => {
3851
+ const configPath = parseConfigParam(rule.params);
3852
+ if (!configPath) return;
3853
+ if (!config) config = resolveOptionalPath(configPath, base);
3854
+ rule.remove();
3855
+ });
3856
+ return {
3857
+ config,
3858
+ css: root.toString()
3859
+ };
3675
3860
  }
3676
- function extractConfigRequestFromSource(rawSource) {
3677
- for (const line of rawSource.split(/\r?\n/)) {
3678
- const match = /^\s*@config\b([\s\S]*?)(?:;|$)/.exec(line);
3679
- const request = match ? parseConfigRequest(match[1] ?? "") : void 0;
3680
- if (request) return request;
3681
- }
3861
+ function getProjectRoot(patcher) {
3862
+ return patcher.options?.projectRoot ?? node_process.default.cwd();
3682
3863
  }
3683
- function hasPreprocessorOnlySyntax(rawSource) {
3684
- return /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@[\w-]+\s*:|@(?:mixin|include|function|use|forward)\b)/.test(rawSource);
3864
+ function normalizeLoadedConfig(config) {
3865
+ if (!config || typeof config !== "object") return config;
3866
+ const maybeDefault = config.default;
3867
+ if (maybeDefault && typeof maybeDefault === "object") return maybeDefault;
3868
+ return config;
3685
3869
  }
3686
- function normalizeTailwindSourceForGenerator(rawSource, options = {}) {
3687
- return hasPreprocessorOnlySyntax(rawSource) ? extractTailwindSourceForPostcssFallback(rawSource, options) ?? rawSource : rawSource;
3870
+ function resolveTailwindCssPackageName(patcher) {
3871
+ return resolveTailwindcssOptions(patcher.options)?.packageName ?? patcher.packageInfo?.name ?? "tailwindcss";
3688
3872
  }
3689
- function normalizeTailwindV3CssEntrySource(rawSource) {
3690
- try {
3691
- const root = require_runtime_registry.postcss_default.parse(rawSource);
3692
- let changed = false;
3693
- root.walkAtRules("import", (node) => {
3694
- const layer = TAILWIND_V3_SUBPATH_IMPORT_LAYERS.get(parseImportRequest(node.params) ?? "");
3695
- if (!layer) return;
3696
- node.replaceWith(require_runtime_registry.postcss_default.atRule({
3697
- name: "tailwind",
3698
- params: layer
3699
- }));
3700
- changed = true;
3701
- });
3702
- return changed ? root.toString() : rawSource;
3703
- } catch {
3704
- return rawSource;
3705
- }
3873
+ async function resolveTailwindV3Source(options = {}) {
3874
+ const projectRoot = options.projectRoot ?? node_process.default.cwd();
3875
+ const base = options.base ?? options.cwd ?? projectRoot;
3876
+ const cssConfig = resolveCssConfig(options.css, base);
3877
+ const config = resolveOptionalPath(options.config, base) ?? cssConfig.config;
3878
+ const cwd = options.cwd ?? (config ? node_path.default.dirname(config) : projectRoot);
3879
+ const loaded = await (0, tailwindcss_config.loadConfig)(omitUndefined({
3880
+ config,
3881
+ cwd
3882
+ }));
3883
+ return {
3884
+ version: 3,
3885
+ projectRoot,
3886
+ cwd,
3887
+ base,
3888
+ css: cssConfig.css ?? options.css ?? DEFAULT_TAILWIND_V3_CSS,
3889
+ config: loaded?.filepath ?? config,
3890
+ configObject: normalizeLoadedConfig(loaded?.config),
3891
+ dependencies: loaded?.filepath ? [loaded.filepath] : [],
3892
+ packageName: options.packageName ?? "tailwindcss",
3893
+ postcssPlugin: options.postcssPlugin ?? options.packageName ?? "tailwindcss"
3894
+ };
3706
3895
  }
3707
- function normalizeTailwindSourceDirectives(rawSource, options = {}) {
3708
- if (!options.importFallback) return rawSource;
3709
- try {
3710
- const root = require_runtime_registry.postcss_default.parse(rawSource);
3711
- return normalizeTailwindImportAtRules(root, options) ? root.toString() : rawSource;
3712
- } catch {
3713
- return extractTailwindSourceForPostcssFallback(rawSource, options) ?? rawSource;
3714
- }
3896
+ function resolveTailwindV3SourceOptionsFromPatcher(patcher) {
3897
+ const projectRoot = getProjectRoot(patcher);
3898
+ const tailwindOptions = resolveTailwindcssOptions(patcher.options);
3899
+ return {
3900
+ projectRoot,
3901
+ cwd: tailwindOptions?.v3?.cwd ?? tailwindOptions?.cwd ?? projectRoot,
3902
+ config: tailwindOptions?.v3?.config ?? tailwindOptions?.config,
3903
+ packageName: resolveTailwindCssPackageName(patcher),
3904
+ postcssPlugin: tailwindOptions?.v3?.postcssPlugin ?? tailwindOptions?.postcssPlugin
3905
+ };
3715
3906
  }
3716
- function isTailwindImportRequest(request) {
3717
- return request === "tailwindcss" || request === "tailwindcss4" || request?.startsWith("tailwindcss/") || request?.startsWith("tailwindcss4/");
3907
+ function resolveTailwindV3SourceFromPatcher(patcher) {
3908
+ return resolveTailwindV3Source(resolveTailwindV3SourceOptionsFromPatcher(patcher));
3718
3909
  }
3719
- function isTailwindImportAtRule(node, options = {}) {
3720
- if (node.name === "tailwind") return true;
3721
- if (node.name !== "import" && node.name !== "use" && node.name !== "forward") return false;
3722
- return isTailwindImportRequest(normalizeTailwindImportRequest(parseImportRequest(node.params), options));
3910
+ //#endregion
3911
+ //#region src/generator/options.ts
3912
+ const explicitGeneratorTargetEnvKeys = ["WEAPP_TW_TARGET", "WEAPP_TAILWINDCSS_TARGET"];
3913
+ const uniWebPlatformEnvKeys = ["UNI_PLATFORM", "UNI_UTS_PLATFORM"];
3914
+ const mpxWebPlatformEnvKeys = ["MPX_CLI_MODE", "MPX_CURRENT_TARGET_MODE"];
3915
+ function getEnvValue(key) {
3916
+ return typeof node_process.default === "undefined" ? void 0 : node_process.default.env[key];
3723
3917
  }
3724
- function isTailwindSourceDirective(node, options = {}) {
3725
- if (node.type !== "atrule") return false;
3726
- const atRule = node;
3727
- if (isTailwindImportAtRule(atRule, options)) return true;
3728
- if (atRule.name === "import" && isPackageJsonImportRequest$1(parseImportRequest(atRule.params))) return true;
3729
- if (atRule.name === "layer") return !atRule.nodes || atRule.nodes.length === 0;
3730
- return TAILWIND_REMOVABLE_SOURCE_DIRECTIVE_NAMES.has(atRule.name);
3918
+ function normalizeGeneratorTargetValue(value) {
3919
+ return value === "weapp" || value === "web" || value === "tailwind" ? value : void 0;
3731
3920
  }
3732
- function hasGeneratedCssArtifacts(rawSource) {
3733
- return hasTailwindGeneratedCssMarkers(rawSource) && !GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource);
3921
+ function isUniWebPlatform(value) {
3922
+ const normalized = value?.trim().toLowerCase();
3923
+ return normalized === "h5" || normalized?.startsWith("web") === true;
3734
3924
  }
3735
- function isTailwindGenerationDirective(node, options = {}) {
3736
- if (node.type !== "atrule") return false;
3737
- const atRule = node;
3738
- const request = atRule.name === "import" ? parseImportRequest(atRule.params) : atRule.name === "config" || atRule.name === "plugin" || atRule.name === "reference" ? parseConfigRequest(atRule.params) : void 0;
3739
- return isTailwindImportAtRule(atRule, options) || isPackageJsonImportRequest$1(request) || atRule.name === "apply" || !options.ignoreLayer && atRule.name === "layer" || atRule.name === "config" || atRule.name === "source";
3925
+ function isUniAppWebViewPlatform(value) {
3926
+ const normalized = value?.trim().toLowerCase();
3927
+ return normalized === "app" || normalized === "app-plus";
3928
+ }
3929
+ function isUniNativeAppPlatform(value) {
3930
+ return (value?.trim().toLowerCase())?.startsWith("app-") === true;
3740
3931
  }
3741
- function removeTailwindSourceDirectives(rawSource, options = {}) {
3742
- try {
3743
- const source = hasPreprocessorOnlySyntax(rawSource) ? extractTailwindSourceForPostcssFallback(rawSource, options) : stripGeneratorPlaceholderMarkers(rawSource);
3744
- if (!source) return "";
3745
- const root = require_runtime_registry.postcss_default.parse(source);
3746
- let removed = false;
3747
- root.walk((node) => {
3748
- if (isTailwindSourceDirective(node, options)) {
3749
- node.remove();
3750
- removed = true;
3751
- }
3752
- });
3753
- return removed ? root.toString() : source;
3754
- } catch {
3755
- return stripGeneratorPlaceholderMarkers(rawSource);
3756
- }
3932
+ function isMpxWebPlatform(value) {
3933
+ return value?.trim().toLowerCase() === "web";
3757
3934
  }
3758
- function hasTailwindSourceDirectives(rawSource, options = {}) {
3759
- try {
3760
- if (GENERATOR_PLACEHOLDER_MARKER_RE.test(rawSource)) return true;
3761
- const root = require_runtime_registry.postcss_default.parse(rawSource);
3762
- let found = false;
3763
- const ignoreLayer = hasGeneratedCssArtifacts(rawSource);
3764
- root.walk((node) => {
3765
- if (isTailwindGenerationDirective(node, {
3766
- ...options,
3767
- ignoreLayer
3768
- })) {
3769
- found = true;
3770
- return false;
3771
- }
3772
- });
3773
- return found;
3774
- } catch {
3775
- return extractTailwindDirectiveLines(rawSource, options).length > 0;
3935
+ function inferGeneratorTargetFromEnv() {
3936
+ for (const key of explicitGeneratorTargetEnvKeys) {
3937
+ const target = normalizeGeneratorTargetValue(getEnvValue(key));
3938
+ if (target !== void 0) return target;
3776
3939
  }
3940
+ if (uniWebPlatformEnvKeys.some((key) => isUniWebPlatform(getEnvValue(key))) || isUniAppWebViewPlatform(getEnvValue("UNI_PLATFORM")) && !isUniNativeAppPlatform(getEnvValue("UNI_UTS_PLATFORM")) || mpxWebPlatformEnvKeys.some((key) => isMpxWebPlatform(getEnvValue(key))) || getEnvValue("TARO_ENV") === "h5") return "web";
3941
+ return "weapp";
3777
3942
  }
3778
- function hasTailwindRootDirectives(rawSource, options = {}) {
3779
- if (!TAILWIND_ROOT_DIRECTIVE_RE.test(rawSource) && !(options.importFallback && rawSource.includes("weapp-tailwindcss"))) return false;
3780
- try {
3781
- const root = require_runtime_registry.postcss_default.parse(rawSource);
3782
- let found = false;
3783
- root.walkAtRules((node) => {
3784
- const request = node.name === "import" ? parseImportRequest(node.params) : node.name === "config" || node.name === "plugin" ? parseConfigRequest(node.params) : void 0;
3785
- if (isTailwindImportAtRule(node, options) || isPackageJsonImportRequest$1(request) || TAILWIND_ROOT_DIRECTIVE_NAMES.has(node.name)) {
3786
- found = true;
3787
- return false;
3788
- }
3789
- });
3790
- return found;
3791
- } catch {
3792
- return extractTailwindDirectiveLines(rawSource, options).length > 0;
3793
- }
3943
+ function normalizeWeappTailwindcssGeneratorOptions(options) {
3944
+ const target = options?.target ?? inferGeneratorTargetFromEnv();
3945
+ if (options == null) return {
3946
+ target,
3947
+ importFallback: true,
3948
+ tailwindcssV3Compatibility: target === "weapp",
3949
+ bareArbitraryValues: void 0
3950
+ };
3951
+ return {
3952
+ target,
3953
+ config: options.config,
3954
+ styleOptions: options.styleOptions,
3955
+ importFallback: options.importFallback ?? true,
3956
+ tailwindcssV3Compatibility: options.tailwindcssV3Compatibility ?? target === "weapp",
3957
+ bareArbitraryValues: options.bareArbitraryValues
3958
+ };
3794
3959
  }
3795
- function hasTailwindApplyDirective(rawSource) {
3796
- if (!rawSource.includes("@apply")) return false;
3797
- try {
3798
- const root = require_runtime_registry.postcss_default.parse(rawSource);
3799
- let found = false;
3800
- root.walkAtRules("apply", () => {
3801
- found = true;
3802
- return false;
3803
- });
3804
- return found;
3805
- } catch {
3806
- return false;
3807
- }
3960
+ //#endregion
3961
+ //#region src/generator/index.ts
3962
+ function isTailwindV3Source(source) {
3963
+ return "version" in source && source.version === 3;
3808
3964
  }
3809
- function resolveCssEntrySource(rawSource, base, options = {}) {
3810
- try {
3811
- const root = require_runtime_registry.postcss_default.parse(rawSource);
3812
- const normalizedImports = normalizeTailwindImportAtRules(root, options);
3813
- let found = false;
3814
- let config;
3815
- let configRequest;
3816
- let removedConfig = false;
3817
- const removeConfig = options.removeConfig ?? true;
3818
- const ignoreLayer = hasGeneratedCssArtifacts(rawSource);
3819
- root.walk((node) => {
3820
- if (isTailwindGenerationDirective(node, {
3821
- ...options,
3822
- ignoreLayer
3823
- })) found = true;
3824
- if (node.type === "atrule" && node.name === "config") {
3825
- const configPath = parseConfigRequest(node.params);
3826
- if (configPath && !config) {
3827
- configRequest = configPath;
3828
- config = isPackageJsonImportRequest$1(configPath) ? void 0 : node_path.default.isAbsolute(configPath) ? configPath : node_path.default.resolve(base, configPath);
3829
- }
3830
- if (removeConfig) {
3831
- node.remove();
3832
- removedConfig = true;
3833
- }
3834
- }
3835
- });
3836
- if (!found) return;
3837
- if (hasPreprocessorOnlySyntax(rawSource)) {
3838
- const css = extractTailwindSourceForPostcssFallback(rawSource, {
3839
- ...options,
3840
- removeConfig
3841
- });
3842
- if (css) return {
3843
- css,
3844
- config,
3845
- configRequest,
3846
- base
3847
- };
3848
- }
3849
- return {
3850
- css: removedConfig || normalizedImports ? root.toString() : rawSource,
3851
- config,
3852
- configRequest,
3853
- base
3854
- };
3855
- } catch {
3856
- const css = extractTailwindSourceForPostcssFallback(rawSource, options);
3857
- const configRequest = extractConfigRequestFromSource(rawSource);
3858
- const config = configRequest && !isPackageJsonImportRequest$1(configRequest) ? node_path.default.isAbsolute(configRequest) ? configRequest : node_path.default.resolve(base, configRequest) : void 0;
3859
- return css ? {
3860
- css,
3861
- config,
3862
- configRequest,
3863
- base
3864
- } : void 0;
3865
- }
3965
+ function createWeappTailwindcssGenerator(source) {
3966
+ return isTailwindV3Source(source) ? createTailwindV3Engine(source) : createTailwindV4Engine(source);
3866
3967
  }
3867
3968
  //#endregion
3868
3969
  //#region src/wxml/shared.ts
@@ -4147,7 +4248,7 @@ function collectGeneratedSelectors(css) {
4147
4248
  if (cached) return cached;
4148
4249
  const selectors = /* @__PURE__ */ new Set();
4149
4250
  try {
4150
- require_runtime_registry.postcss_default.parse(css).walkRules((rule) => {
4251
+ require_watch_dependencies.postcss_default.parse(css).walkRules((rule) => {
4151
4252
  if (isCustomPropertyOnlyRule(rule) && !isPseudoContentInitRule(rule) && !hasUtilityClassSelector(rule.selector)) return;
4152
4253
  for (const selector of getRuleCompatSelectorKeys(rule)) selectors.add(selector);
4153
4254
  });
@@ -4160,7 +4261,7 @@ function collectGeneratedSelectors(css) {
4160
4261
  function collectGeneratedDeclarationPropsBySelector(generatedCss, selectors) {
4161
4262
  const propsBySelector = /* @__PURE__ */ new Map();
4162
4263
  try {
4163
- require_runtime_registry.postcss_default.parse(generatedCss).walkRules((rule) => {
4264
+ require_watch_dependencies.postcss_default.parse(generatedCss).walkRules((rule) => {
4164
4265
  const matchedSelectors = getRuleCompatSelectorKeys(rule).filter((selector) => selectors.has(selector));
4165
4266
  if (matchedSelectors.length === 0) return;
4166
4267
  const props = /* @__PURE__ */ new Set();
@@ -4182,7 +4283,7 @@ function removeGeneratedSelectorCompatCss(css, generatedCss) {
4182
4283
  const generatedSelectors = collectGeneratedSelectors(generatedCss);
4183
4284
  if (generatedSelectors.size === 0) return css;
4184
4285
  try {
4185
- const root = require_runtime_registry.postcss_default.parse(css);
4286
+ const root = require_watch_dependencies.postcss_default.parse(css);
4186
4287
  let removed = false;
4187
4288
  root.walkRules((rule) => {
4188
4289
  if (isPseudoContentInitRule(rule)) {
@@ -4210,7 +4311,7 @@ function collectDedupedPostTransformCompatCss(css, generatedCss) {
4210
4311
  const generatedDeclarationPropsBySelector = collectGeneratedDeclarationPropsBySelector(generatedCss, generatedSelectors);
4211
4312
  const preservedNodes = [];
4212
4313
  try {
4213
- const root = require_runtime_registry.postcss_default.parse(css);
4314
+ const root = require_watch_dependencies.postcss_default.parse(css);
4214
4315
  root.each((node) => {
4215
4316
  if (node.type === "rule") {
4216
4317
  const nodeSelectors = getRuleCompatSelectorKeys(node);
@@ -4239,7 +4340,7 @@ function collectDedupedPostTransformCompatCss(css, generatedCss) {
4239
4340
  preservedNodes.push(node.clone());
4240
4341
  });
4241
4342
  if (preservedNodes.length === root.nodes.length) return css;
4242
- const nextRoot = require_runtime_registry.postcss_default.root();
4343
+ const nextRoot = require_watch_dependencies.postcss_default.root();
4243
4344
  nextRoot.append(preservedNodes);
4244
4345
  return nextRoot.toString();
4245
4346
  } catch {
@@ -4252,75 +4353,112 @@ function removeDuplicatedViteMarkers(css, baseCss) {
4252
4353
  return css.replace(VITE_MARKER_RE, "");
4253
4354
  }
4254
4355
  //#endregion
4255
- //#region src/bundlers/shared/generator-css/config-directive.ts
4256
- function quoteCssString(value) {
4257
- return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
4258
- }
4259
- function toCssPath(value) {
4260
- return value.replaceAll("\\", "/");
4261
- }
4262
- function prependConfigDirective(css, config) {
4263
- if (!config || /@config\s+/.test(css)) return css;
4264
- return `@config "${quoteCssString(toCssPath(config))}";\n${css}`;
4265
- }
4266
- function normalizeConfigDirective(css, config) {
4267
- if (!config || !/@config\s+/.test(css)) return css;
4268
- return css.replace(/@config\s+(["'])(.+?)\1\s*;?/, `@config "${quoteCssString(toCssPath(config))}";`);
4269
- }
4270
- //#endregion
4271
4356
  //#region src/bundlers/shared/generator-css/source-files.ts
4272
- const SOURCE_STYLE_EXTENSIONS = [
4273
- ".vue",
4274
- ".uvue",
4275
- ".nvue",
4276
- ".css",
4277
- ".scss",
4278
- ".sass",
4279
- ".less",
4280
- ".styl",
4281
- ".stylus",
4282
- ".wxss",
4283
- ".acss",
4284
- ".jxss",
4285
- ".ttss",
4286
- ".qss"
4287
- ];
4288
4357
  const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
4289
4358
  function stripStyleExtension(file) {
4290
- return file.replace(/[?#].*$/, "").replace(/\.(?:wx|ac|jx|tt|q|c|ty)?ss$/i, "");
4359
+ const normalized = file.replace(/[?#].*$/, "");
4360
+ const ext = node_path.default.extname(normalized);
4361
+ return ext ? normalized.slice(0, -ext.length) : normalized;
4291
4362
  }
4292
- function createSourceStylePathCandidates(file, sourceOptions) {
4293
- const bases = [
4363
+ function normalizeMatchPath$1(file) {
4364
+ return file.split(node_path.default.sep).join("/");
4365
+ }
4366
+ function isPathWithinRoot$1(file, root) {
4367
+ const relative = node_path.default.relative(root, file);
4368
+ return Boolean(relative) && !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
4369
+ }
4370
+ function countCommonSuffixSegments(a, b) {
4371
+ const aSegments = a.split("/").filter(Boolean);
4372
+ const bSegments = b.split("/").filter(Boolean);
4373
+ let count = 0;
4374
+ while (count < aSegments.length && count < bSegments.length && aSegments[aSegments.length - 1 - count] === bSegments[bSegments.length - 1 - count]) count++;
4375
+ return count;
4376
+ }
4377
+ function collectOutputMatchBases(file, sourceOptions) {
4378
+ const normalizedFile = file.replace(/[?#].*$/, "");
4379
+ const roots = [
4380
+ sourceOptions.outputRoot,
4294
4381
  sourceOptions.projectRoot,
4295
- sourceOptions.cwd,
4296
- node_process.default.cwd()
4382
+ sourceOptions.cwd
4297
4383
  ].filter((item) => typeof item === "string" && item.length > 0);
4298
- const outputRoots = [sourceOptions.outputRoot].filter((item) => typeof item === "string" && item.length > 0);
4299
- const strippedFile = stripStyleExtension(file);
4300
- const relativeFiles = /* @__PURE__ */ new Set();
4301
- const addOutputRelativePath = (absoluteFile) => {
4302
- for (const outputRoot of outputRoots) {
4303
- const relative = node_path.default.relative(outputRoot, absoluteFile);
4304
- if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) continue;
4305
- relativeFiles.add(relative);
4306
- }
4384
+ const bases = /* @__PURE__ */ new Set();
4385
+ const addBase = (candidate) => {
4386
+ const stripped = normalizeMatchPath$1(stripStyleExtension(candidate));
4387
+ if (stripped.length > 0) bases.add(stripped);
4307
4388
  };
4308
- if (node_path.default.isAbsolute(strippedFile)) {
4309
- addOutputRelativePath(strippedFile);
4310
- for (const base of bases) {
4311
- const relative = node_path.default.relative(base, strippedFile);
4312
- if (!relative || relative.startsWith("..") || node_path.default.isAbsolute(relative)) continue;
4313
- relativeFiles.add(relative);
4314
- }
4315
- } else relativeFiles.add(strippedFile);
4389
+ addBase(normalizedFile);
4390
+ if (node_path.default.isAbsolute(normalizedFile)) for (const root of roots) {
4391
+ const normalizedRoot = node_path.default.resolve(root);
4392
+ if (isPathWithinRoot$1(normalizedFile, normalizedRoot)) addBase(node_path.default.relative(normalizedRoot, normalizedFile));
4393
+ }
4394
+ else for (const root of roots) addBase(node_path.default.resolve(root, normalizedFile));
4395
+ return bases;
4396
+ }
4397
+ function isMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
4398
+ const outputBases = collectOutputMatchBases(file, sourceOptions);
4399
+ const normalizedSourceFile = sourceFile.replace(/[?#].*$/, "");
4400
+ const sourceBases = /* @__PURE__ */ new Set();
4401
+ const addSourceBase = (candidate) => {
4402
+ const stripped = normalizeMatchPath$1(stripStyleExtension(candidate));
4403
+ if (stripped.length > 0) sourceBases.add(stripped);
4404
+ };
4405
+ addSourceBase(normalizedSourceFile);
4406
+ if (node_path.default.isAbsolute(normalizedSourceFile)) for (const root of [sourceOptions.projectRoot, sourceOptions.cwd]) {
4407
+ if (!root) continue;
4408
+ const normalizedRoot = node_path.default.resolve(root);
4409
+ if (isPathWithinRoot$1(normalizedSourceFile, normalizedRoot)) addSourceBase(node_path.default.relative(normalizedRoot, normalizedSourceFile));
4410
+ }
4411
+ 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;
4412
+ return false;
4413
+ }
4414
+ function scoreMatchingSourceStyleFile(file, sourceFile, sourceOptions) {
4415
+ const outputBases = collectOutputMatchBases(file, sourceOptions);
4416
+ const normalizedSourceFile = sourceFile.replace(/[?#].*$/, "");
4417
+ const sourceBases = /* @__PURE__ */ new Set();
4418
+ const addSourceBase = (candidate) => {
4419
+ const stripped = normalizeMatchPath$1(stripStyleExtension(candidate));
4420
+ if (stripped.length > 0) sourceBases.add(stripped);
4421
+ };
4422
+ addSourceBase(normalizedSourceFile);
4423
+ if (node_path.default.isAbsolute(normalizedSourceFile)) for (const root of [sourceOptions.projectRoot, sourceOptions.cwd]) {
4424
+ if (!root) continue;
4425
+ const normalizedRoot = node_path.default.resolve(root);
4426
+ if (isPathWithinRoot$1(normalizedSourceFile, normalizedRoot)) addSourceBase(node_path.default.relative(normalizedRoot, normalizedSourceFile));
4427
+ }
4428
+ let bestScore = 0;
4429
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) {
4430
+ const commonSuffixSegments = countCommonSuffixSegments(outputBase, sourceBase);
4431
+ if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
4432
+ else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
4433
+ else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
4434
+ else if (commonSuffixSegments >= 2) bestScore = Math.max(bestScore, 100 + commonSuffixSegments);
4435
+ }
4436
+ return bestScore;
4437
+ }
4438
+ function collectMatchedConfiguredSourceFiles(file, sourceOptions) {
4439
+ const matches = [...(sourceOptions.cssSources ?? []).map((cssSource) => cssSource.file), ...sourceOptions.cssEntries ?? []].filter((sourceFile) => typeof sourceFile === "string" && node_path.default.isAbsolute(sourceFile)).map((sourceFile) => node_path.default.resolve(sourceFile.replace(/[?#].*$/, ""))).filter((sourceFile, index, files) => files.indexOf(sourceFile) === index).map((sourceFile) => ({
4440
+ sourceFile,
4441
+ score: scoreMatchingSourceStyleFile(file, sourceFile, sourceOptions)
4442
+ })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score);
4443
+ const bestScore = matches[0]?.score ?? 0;
4444
+ return matches.filter((match) => match.score === bestScore).map((match) => match.sourceFile);
4445
+ }
4446
+ function hasConfiguredSourceFiles(sourceOptions) {
4447
+ return Boolean(sourceOptions.cssEntries?.length) || Boolean(sourceOptions.cssSources?.some((cssSource) => typeof cssSource.file === "string" && cssSource.file.length > 0));
4448
+ }
4449
+ function createSourceStylePathCandidates(file, sourceOptions) {
4316
4450
  const candidates = /* @__PURE__ */ new Set();
4317
- for (const relativeFile of relativeFiles) {
4318
- if (!relativeFile || node_path.default.isAbsolute(relativeFile)) continue;
4319
- for (const base of bases) for (const sourceRoot of ["", "src"]) {
4320
- const prefix = sourceRoot ? node_path.default.resolve(base, sourceRoot, relativeFile) : node_path.default.resolve(base, relativeFile);
4321
- for (const extension of SOURCE_STYLE_EXTENSIONS) candidates.add(`${prefix}${extension}`);
4322
- }
4451
+ const addCandidate = (candidate) => {
4452
+ if (candidate && node_path.default.isAbsolute(candidate)) candidates.add(candidate.replace(/[?#].*$/, ""));
4453
+ };
4454
+ const matchedConfiguredSourceFiles = collectMatchedConfiguredSourceFiles(file, sourceOptions);
4455
+ if (matchedConfiguredSourceFiles.length === 1) addCandidate(matchedConfiguredSourceFiles[0]);
4456
+ else if (matchedConfiguredSourceFiles.length === 0) for (const cssSource of sourceOptions.cssSources ?? []) {
4457
+ const sourceFile = cssSource.file;
4458
+ if (typeof sourceFile === "string" && node_path.default.isAbsolute(sourceFile) && isMatchingSourceStyleFile(file, sourceFile, sourceOptions)) addCandidate(sourceFile);
4323
4459
  }
4460
+ if (hasConfiguredSourceFiles(sourceOptions)) return [...candidates];
4461
+ if (!hasConfiguredSourceFiles(sourceOptions)) addCandidate(sourceOptions.sourceFile);
4324
4462
  return [...candidates];
4325
4463
  }
4326
4464
  function extractStyleDirectiveSources(source) {
@@ -4366,6 +4504,24 @@ function resolvePostcssSourceFile(cssHandlerOptions) {
4366
4504
  function resolveCssHandlerSourceOptions(cssHandlerOptions) {
4367
4505
  return cssHandlerOptions.sourceOptions;
4368
4506
  }
4507
+ function createCssEntrySources(cssEntries) {
4508
+ return cssEntries?.filter((entry) => typeof entry === "string" && entry.length > 0 && node_path.default.isAbsolute(entry)).map((entry) => ({ file: node_path.default.resolve(entry) }));
4509
+ }
4510
+ function mergeCssSources(cssSources, cssEntrySources) {
4511
+ const merged = [];
4512
+ const seenFiles = /* @__PURE__ */ new Set();
4513
+ const addSource = (cssSource) => {
4514
+ const file = typeof cssSource.file === "string" && cssSource.file.length > 0 ? node_path.default.resolve(cssSource.file) : void 0;
4515
+ if (file) {
4516
+ if (seenFiles.has(file)) return;
4517
+ seenFiles.add(file);
4518
+ }
4519
+ merged.push(cssSource);
4520
+ };
4521
+ for (const cssSource of cssSources ?? []) addSource(cssSource);
4522
+ for (const cssSource of cssEntrySources ?? []) addSource(cssSource);
4523
+ return merged.length > 0 ? merged : void 0;
4524
+ }
4369
4525
  function createSingleTailwindV4SourceOptions(sourceOptions, options) {
4370
4526
  return omitUndefined({
4371
4527
  projectRoot: sourceOptions.projectRoot,
@@ -4375,6 +4531,27 @@ function createSingleTailwindV4SourceOptions(sourceOptions, options) {
4375
4531
  css: options.css
4376
4532
  });
4377
4533
  }
4534
+ async function resolveTailwindV4CssEntrySource(cssEntry, sourceOptions) {
4535
+ const { cssEntries: _cssEntries, cssSources: _cssSources, ...singleEntrySourceOptions } = sourceOptions;
4536
+ if (!(0, node_fs.existsSync)(cssEntry)) return resolveTailwindV4Source({
4537
+ ...omitUndefined(singleEntrySourceOptions),
4538
+ cssEntries: [cssEntry]
4539
+ });
4540
+ const css = (0, node_fs.readFileSync)(cssEntry, "utf8");
4541
+ const base = node_path.default.dirname(node_path.default.resolve(cssEntry));
4542
+ const entrySource = resolveCssEntrySource(css, base, { removeConfig: false });
4543
+ const config = resolveExistingConfigPath(entrySource?.config, entrySource?.configRequest, cssEntry, sourceOptions);
4544
+ return withGeneratorSourceMetadata(await resolveTailwindV4Source({
4545
+ ...omitUndefined(singleEntrySourceOptions),
4546
+ base,
4547
+ css: normalizeConfigDirective(css, config),
4548
+ cssEntries: [cssEntry]
4549
+ }), {
4550
+ matchedCssSourceFile: cssEntry,
4551
+ sourceBase: base,
4552
+ sourceCss: css
4553
+ });
4554
+ }
4378
4555
  function resolveCssSourceBase(file, cssHandlerOptions) {
4379
4556
  const normalized = (resolvePostcssFromOption(cssHandlerOptions) ?? file).replace(/[?#].*$/, "");
4380
4557
  return node_path.default.dirname(node_path.default.resolve(normalized));
@@ -4384,24 +4561,30 @@ function resolveExistingConfigPath(config, configRequest, file, sourceOptions) {
4384
4561
  if (!configRequest || node_path.default.isAbsolute(configRequest)) return sourceOptions.config;
4385
4562
  const outputDir = node_path.default.dirname(file.replace(/[?#].*$/, ""));
4386
4563
  const baseCandidates = [
4564
+ sourceOptions.sourceFile ? node_path.default.dirname(sourceOptions.sourceFile.replace(/[?#].*$/, "")) : void 0,
4565
+ node_path.default.isAbsolute(outputDir) ? outputDir : void 0,
4387
4566
  sourceOptions.projectRoot,
4388
- sourceOptions.cwd,
4389
- node_process.default.cwd()
4567
+ sourceOptions.cwd
4390
4568
  ].filter((item) => typeof item === "string" && item.length > 0);
4569
+ const seenCandidates = /* @__PURE__ */ new Set();
4570
+ const configCandidates = [];
4571
+ const addConfigCandidate = (candidate) => {
4572
+ if (!candidate) return;
4573
+ const normalized = node_path.default.resolve(candidate);
4574
+ if (seenCandidates.has(normalized)) return;
4575
+ seenCandidates.add(normalized);
4576
+ configCandidates.push(normalized);
4577
+ };
4391
4578
  for (const base of baseCandidates) {
4392
- const candidates = [
4393
- node_path.default.resolve(base, configRequest),
4394
- node_path.default.resolve(base, "src", configRequest),
4395
- node_path.default.resolve(base, outputDir, configRequest),
4396
- node_path.default.resolve(base, "src", outputDir, configRequest)
4397
- ];
4398
- for (const candidate of candidates) if ((0, node_fs.existsSync)(candidate)) return candidate;
4579
+ addConfigCandidate(node_path.default.resolve(base, configRequest));
4580
+ if (!node_path.default.isAbsolute(outputDir)) addConfigCandidate(node_path.default.resolve(base, outputDir, configRequest));
4399
4581
  }
4582
+ for (const candidate of configCandidates) if ((0, node_fs.existsSync)(candidate)) return candidate;
4400
4583
  return sourceOptions.config;
4401
4584
  }
4402
- function canResolveSourceSideCssEntry(file, cssHandlerOptions) {
4585
+ function canResolveSourceSideCssEntry(file, cssHandlerOptions, sourceOptions) {
4403
4586
  const from = resolvePostcssFromOption(cssHandlerOptions);
4404
- if (!from || !node_path.default.isAbsolute(from)) return node_path.default.isAbsolute(file);
4587
+ if (!from || !node_path.default.isAbsolute(from)) return node_path.default.isAbsolute(file) || Boolean(sourceOptions?.sourceFile) || Boolean(sourceOptions?.cssSources?.length);
4405
4588
  return true;
4406
4589
  }
4407
4590
  function shouldResolveSourceSideCssEntry(rawSource) {
@@ -4410,6 +4593,9 @@ function shouldResolveSourceSideCssEntry(rawSource) {
4410
4593
  function shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) {
4411
4594
  return Boolean(sourceSideEntrySource) && !hasTailwindSourceDirectives(rawSource, { importFallback: true });
4412
4595
  }
4596
+ function shouldPreferResolvedSourceSideEntry(cssEntrySource, sourceSideEntrySource) {
4597
+ return Boolean(sourceSideEntrySource?.config) && Boolean(cssEntrySource?.configRequest) && (!cssEntrySource?.config || !(0, node_fs.existsSync)(cssEntrySource.config));
4598
+ }
4413
4599
  function normalizeCssSourceForCompare(css) {
4414
4600
  return stripGeneratorPlaceholderMarkers(stripTailwindBanners(css)).trim();
4415
4601
  }
@@ -4425,38 +4611,119 @@ function getOutputFileWithoutExtension(file) {
4425
4611
  function normalizeMatchPath(file) {
4426
4612
  return file.split(node_path.default.sep).join("/");
4427
4613
  }
4428
- function stripKnownBuildRootPrefix(file) {
4429
- const segments = normalizeMatchPath(file).split("/");
4430
- const knownRoots = new Set(["dist", "src"]);
4431
- for (let index = segments.length - 1; index >= 0; index--) if (knownRoots.has(segments[index])) return segments.slice(index + 1).join("/");
4432
- return segments.join("/");
4614
+ function isPathWithinRoot(file, root) {
4615
+ const relative = node_path.default.relative(root, file);
4616
+ return Boolean(relative) && !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
4617
+ }
4618
+ function collectCssSourceMatchBases(file, roots) {
4619
+ const normalizedFile = file.replace(/[?#].*$/, "");
4620
+ const bases = /* @__PURE__ */ new Set();
4621
+ const addBase = (candidate) => {
4622
+ const base = normalizeMatchPath(getOutputFileWithoutExtension(candidate));
4623
+ if (base.length > 0) {
4624
+ bases.add(base);
4625
+ const withoutWorkspaceSegment = base.replace(/^(?:src|dist)\//, "");
4626
+ if (withoutWorkspaceSegment !== base && withoutWorkspaceSegment.length > 0) bases.add(withoutWorkspaceSegment);
4627
+ }
4628
+ };
4629
+ addBase(normalizedFile);
4630
+ const resolvedRoots = roots.filter((root) => typeof root === "string" && root.length > 0).map((root) => node_path.default.resolve(root));
4631
+ if (node_path.default.isAbsolute(normalizedFile)) {
4632
+ for (const root of resolvedRoots) if (isPathWithinRoot(normalizedFile, root)) addBase(node_path.default.relative(root, normalizedFile));
4633
+ } else for (const root of resolvedRoots) addBase(node_path.default.resolve(root, normalizedFile));
4634
+ return bases;
4635
+ }
4636
+ function hasMatchingCssSourceBase(outputBases, sourceBases) {
4637
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`)) return true;
4638
+ return false;
4639
+ }
4640
+ function isMatchingTailwindV4CssSourceFile(file, cssSourceFile, sourceOptions) {
4641
+ return hasMatchingCssSourceBase(collectCssSourceMatchBases(file, [
4642
+ sourceOptions.outputRoot,
4643
+ sourceOptions.projectRoot,
4644
+ sourceOptions.cwd
4645
+ ]), collectCssSourceMatchBases(cssSourceFile, [sourceOptions.projectRoot, sourceOptions.cwd]));
4433
4646
  }
4434
- function isMatchingTailwindV4CssSourceFile(file, cssSourceFile) {
4435
- const outputBase = normalizeMatchPath(getOutputFileWithoutExtension(node_path.default.resolve(file)));
4436
- const sourceBase = normalizeMatchPath(getOutputFileWithoutExtension(node_path.default.resolve(cssSourceFile)));
4437
- const outputRelativeBase = stripKnownBuildRootPrefix(outputBase);
4438
- const sourceRelativeBase = stripKnownBuildRootPrefix(sourceBase);
4439
- return outputBase === sourceBase || outputBase.endsWith(`/${sourceBase}`) || sourceBase.endsWith(`/${outputBase}`) || outputRelativeBase.length > 0 && outputRelativeBase === sourceRelativeBase;
4647
+ function scoreTailwindV4CssSourceFileMatch(file, cssSourceFile, sourceOptions) {
4648
+ const outputBases = collectCssSourceMatchBases(file, [
4649
+ sourceOptions.outputRoot,
4650
+ sourceOptions.projectRoot,
4651
+ sourceOptions.cwd
4652
+ ]);
4653
+ const sourceBases = collectCssSourceMatchBases(cssSourceFile, [sourceOptions.projectRoot, sourceOptions.cwd]);
4654
+ let bestScore = 0;
4655
+ for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
4656
+ else if (outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
4657
+ else if (sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
4658
+ return bestScore;
4440
4659
  }
4441
4660
  function resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) {
4442
4661
  const cssEntries = sourceOptions.cssEntries;
4443
4662
  if (!cssEntries?.length) return;
4444
4663
  const normalizedRawSource = normalizeCssSourceForCompare(rawSource);
4445
4664
  const outputStem = getOutputFileStem(file);
4446
- const matchingEntry = cssEntries.find((cssEntry) => {
4447
- if (!(0, node_fs.existsSync)(cssEntry)) return false;
4665
+ const matches = cssEntries.map((cssEntry) => {
4666
+ if (!(0, node_fs.existsSync)(cssEntry)) return;
4448
4667
  try {
4449
- if (normalizeCssSourceForCompare((0, node_fs.readFileSync)(cssEntry, "utf8")) === normalizedRawSource) return true;
4450
- return outputStem.length > 0 && getOutputFileStem(cssEntry) === outputStem;
4668
+ const entrySource = (0, node_fs.readFileSync)(cssEntry, "utf8");
4669
+ const pathScore = scoreTailwindV4CssSourceFileMatch(file, cssEntry, sourceOptions);
4670
+ if (normalizeCssSourceForCompare(entrySource) === normalizedRawSource) return {
4671
+ cssEntry,
4672
+ score: 1e6 + pathScore
4673
+ };
4674
+ if (pathScore > 0) return {
4675
+ cssEntry,
4676
+ score: pathScore
4677
+ };
4678
+ if (cssEntries.length === 1 && outputStem.length > 0 && getOutputFileStem(cssEntry) === outputStem) return {
4679
+ cssEntry,
4680
+ score: 1
4681
+ };
4682
+ return;
4451
4683
  } catch {
4452
- return false;
4684
+ return;
4453
4685
  }
4454
- });
4686
+ }).filter((match) => Boolean(match)).sort((a, b) => b.score - a.score);
4687
+ const bestScore = matches[0]?.score;
4688
+ const matchingEntry = bestScore && matches.filter((match) => match.score === bestScore).length === 1 ? matches[0]?.cssEntry : void 0;
4455
4689
  if (!matchingEntry) return;
4456
- return resolveTailwindV4Source({
4457
- ...omitUndefined(sourceOptions),
4458
- cssEntries: [matchingEntry]
4690
+ return resolveTailwindV4CssEntrySource(matchingEntry, sourceOptions);
4691
+ }
4692
+ function normalizeTailwindV4CssSourceConfig(cssSource, sourceBase) {
4693
+ if (typeof cssSource.css !== "string" || cssSource.css.length === 0 || !cssSource.css.includes("@config")) return cssSource;
4694
+ const entrySource = resolveCssEntrySource(cssSource.css, sourceBase, { removeConfig: false });
4695
+ if (!entrySource?.config) return cssSource;
4696
+ return {
4697
+ ...cssSource,
4698
+ css: normalizeConfigDirective(cssSource.css, entrySource.config)
4699
+ };
4700
+ }
4701
+ function hydrateTailwindV4CssSource(cssSource) {
4702
+ if (typeof cssSource.css === "string" && cssSource.css.length > 0) return cssSource;
4703
+ if (typeof cssSource.file !== "string" || !(0, node_fs.existsSync)(cssSource.file)) return cssSource;
4704
+ const file = node_path.default.resolve(cssSource.file);
4705
+ return {
4706
+ ...cssSource,
4707
+ file,
4708
+ base: cssSource.base ?? node_path.default.dirname(file),
4709
+ css: (0, node_fs.readFileSync)(file, "utf8"),
4710
+ dependencies: [...new Set([...cssSource.dependencies ?? [], file])]
4711
+ };
4712
+ }
4713
+ function normalizeTailwindV4CssSourceConfigs(sourceOptions) {
4714
+ if (!sourceOptions.cssSources?.length) return sourceOptions;
4715
+ const sourceBaseFallback = sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd();
4716
+ let changed = false;
4717
+ const cssSources = sourceOptions.cssSources.map((cssSource) => {
4718
+ const hydratedCssSource = hydrateTailwindV4CssSource(cssSource);
4719
+ const normalizedCssSource = normalizeTailwindV4CssSourceConfig(hydratedCssSource, resolveTailwindV4CssSourceBase(hydratedCssSource, sourceBaseFallback));
4720
+ changed ||= normalizedCssSource !== cssSource;
4721
+ return normalizedCssSource;
4459
4722
  });
4723
+ return changed ? {
4724
+ ...sourceOptions,
4725
+ cssSources
4726
+ } : sourceOptions;
4460
4727
  }
4461
4728
  async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions) {
4462
4729
  const cssSources = sourceOptions.cssSources;
@@ -4466,11 +4733,11 @@ async function resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOpt
4466
4733
  const matchingSource = cssSources.find((cssSource) => {
4467
4734
  if (typeof cssSource.css !== "string" || cssSource.css.length === 0) return false;
4468
4735
  if (sourceFile && typeof cssSource.file === "string" && node_path.default.resolve(sourceFile) === node_path.default.resolve(cssSource.file)) return true;
4469
- if (typeof cssSource.file === "string" && isMatchingTailwindV4CssSourceFile(file, cssSource.file)) return true;
4736
+ if (typeof cssSource.file === "string" && isMatchingTailwindV4CssSourceFile(file, cssSource.file, sourceOptions)) return true;
4470
4737
  return normalizeCssSourceForCompare(cssSource.css) === normalizedRawSource;
4471
4738
  });
4472
4739
  if (!matchingSource) return;
4473
- return resolveSingleTailwindV4CssSource(matchingSource, sourceOptions);
4740
+ return resolveSingleTailwindV4CssSource(matchingSource, sourceOptions, { matched: true });
4474
4741
  }
4475
4742
  function tryResolveTailwindV4SourceOptions(runtimeState) {
4476
4743
  try {
@@ -4482,16 +4749,16 @@ function tryResolveTailwindV4SourceOptions(runtimeState) {
4482
4749
  function hasConfiguredTailwindV4CssSource(sourceOptions) {
4483
4750
  return Boolean(sourceOptions?.css) || Boolean(sourceOptions?.cssSources?.length);
4484
4751
  }
4485
- async function resolveSingleTailwindV4CssSource(cssSource, sourceOptions) {
4486
- const source = await resolveTailwindV4Source({
4752
+ async function resolveSingleTailwindV4CssSource(cssSource, sourceOptions, options = {}) {
4753
+ const sourceBase = resolveTailwindV4CssSourceBase(cssSource, sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd());
4754
+ const normalizedCssSource = normalizeTailwindV4CssSourceConfig(cssSource, sourceBase);
4755
+ return withGeneratorSourceMetadata(await resolveTailwindV4Source({
4487
4756
  ...omitUndefined(sourceOptions),
4488
- cssSources: [cssSource]
4489
- });
4490
- const sourceBaseFallback = sourceOptions.base ?? sourceOptions.projectRoot ?? node_process.default.cwd();
4491
- return withGeneratorSourceMetadata(source, {
4492
- matchedCssSourceFile: typeof cssSource.file === "string" ? cssSource.file : void 0,
4493
- sourceBase: resolveTailwindV4CssSourceBase(cssSource, sourceBaseFallback),
4494
- sourceCss: cssSource.css
4757
+ cssSources: [normalizedCssSource]
4758
+ }), {
4759
+ matchedCssSourceFile: options.matched && typeof normalizedCssSource.file === "string" ? normalizedCssSource.file : void 0,
4760
+ sourceBase,
4761
+ sourceCss: normalizedCssSource.css
4495
4762
  });
4496
4763
  }
4497
4764
  async function resolveTailwindV4CssSourceEntries(cssSource, sourceOptions) {
@@ -4505,10 +4772,10 @@ function countRuntimeCandidateHits(candidates, runtime) {
4505
4772
  for (const candidate of candidates) if (runtime.has(candidate)) hits += 1;
4506
4773
  return hits;
4507
4774
  }
4508
- async function resolveCandidateMatchedTailwindV4CssSource(_rawSource, cssHandlerOptions, sourceOptions, selectionOptions) {
4775
+ async function resolveCandidateMatchedTailwindV4CssSource(_rawSource, _cssHandlerOptions, sourceOptions, selectionOptions) {
4509
4776
  const cssSources = sourceOptions.cssSources;
4510
4777
  const getSourceCandidatesForEntries = selectionOptions?.getSourceCandidatesForEntries;
4511
- if (!cssHandlerOptions.isMainChunk || !cssSources?.length || !getSourceCandidatesForEntries) return;
4778
+ if (!cssSources?.length || !getSourceCandidatesForEntries) return;
4512
4779
  const matches = [];
4513
4780
  await Promise.all(cssSources.map(async (cssSource, index) => {
4514
4781
  const resolved = await resolveTailwindV4CssSourceEntries(cssSource, sourceOptions);
@@ -4529,13 +4796,10 @@ async function resolveCandidateMatchedTailwindV4CssSource(_rawSource, cssHandler
4529
4796
  const second = matches[1];
4530
4797
  if (!best) return;
4531
4798
  if (second && second.runtimeHits === best.runtimeHits && second.totalCandidates === best.totalCandidates) return;
4532
- return resolveSingleTailwindV4CssSource(best.cssSource, sourceOptions);
4799
+ return resolveSingleTailwindV4CssSource(best.cssSource, sourceOptions, { matched: true });
4533
4800
  }
4534
4801
  function createTailwindV4CssSourceResolver(sourceOptions, generatorOptions) {
4535
- return (cssSource) => resolveTailwindV4Source({
4536
- ...omitUndefined(sourceOptions),
4537
- cssSources: [cssSource]
4538
- }).then((source) => generatorOptions?.config ? {
4802
+ return (cssSource) => resolveSingleTailwindV4CssSource(cssSource, sourceOptions).then((source) => generatorOptions?.config ? {
4539
4803
  ...source,
4540
4804
  css: prependConfigDirective(source.css, generatorOptions.config)
4541
4805
  } : source);
@@ -4556,6 +4820,15 @@ function withGeneratorSourceMetadata(source, metadata) {
4556
4820
  __weappTailwindcssMeta: metadata
4557
4821
  };
4558
4822
  }
4823
+ function resolveTailwindV3SourceEntries(source) {
4824
+ if (!("version" in source) || source.version !== 3) return;
4825
+ const entries = normalizeLegacyContentEntries(source.configObject?.content, source.cwd, { relativeBase: source.config ? node_path.default.dirname(source.config) : source.cwd });
4826
+ return entries.length > 0 ? entries : void 0;
4827
+ }
4828
+ function withTailwindV3SourceMetadata(source) {
4829
+ const sourceEntries = resolveTailwindV3SourceEntries(source);
4830
+ return sourceEntries ? withGeneratorSourceMetadata(source, { sourceEntries }) : source;
4831
+ }
4559
4832
  function withMatchedSourceSideMetadata(source, resolvedEntrySource) {
4560
4833
  return resolvedEntrySource.file ? withGeneratorSourceMetadata(source, {
4561
4834
  matchedCssSourceFile: resolvedEntrySource.file,
@@ -4578,43 +4851,52 @@ async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, fil
4578
4851
  const mergedSourceOptions = omitUndefined({
4579
4852
  ...sourceOptions,
4580
4853
  config: generatorOptions?.config ?? sourceOptions.config,
4581
- ...resolveCssHandlerSourceOptions(cssHandlerOptions)
4854
+ sourceFile: resolvePostcssSourceFile(cssHandlerOptions),
4855
+ ...resolveCssHandlerSourceOptions(cssHandlerOptions),
4856
+ cssEntries: selectionOptions?.cssEntries,
4857
+ cssSources: createCssEntrySources(selectionOptions?.cssEntries)
4582
4858
  });
4583
4859
  const applyEntrySource = hasTailwindApplyDirective(rawSource) ? {
4584
4860
  base,
4585
4861
  css: rawSource
4586
4862
  } : void 0;
4587
- const sourceSideEntrySource = canResolveSourceSideCssEntry(file, cssHandlerOptions) ? resolveSourceSideCssEntrySource(file, mergedSourceOptions, { removeConfig: true }) : void 0;
4588
- const resolvedEntrySource = shouldResolveSourceSideCssEntry(rawSource) ? cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource : shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) ? sourceSideEntrySource ?? cssEntrySource : cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource;
4589
- if (!resolvedEntrySource) return generatorOptions?.config ? resolveTailwindV3Source(mergedSourceOptions) : resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher);
4590
- if (cssEntrySource && !sourceSideEntrySource && !applyEntrySource && !hasTailwindRootDirectives(rawSource, { importFallback: true })) return generatorOptions?.config ? resolveTailwindV3Source(mergedSourceOptions) : resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher);
4863
+ const sourceSideEntrySource = canResolveSourceSideCssEntry(file, cssHandlerOptions, mergedSourceOptions) ? resolveSourceSideCssEntrySource(file, mergedSourceOptions, { removeConfig: true }) : void 0;
4864
+ const shouldPreferSourceSideEntry = shouldPreferResolvedSourceSideEntry(cssEntrySource, sourceSideEntrySource);
4865
+ const resolvedEntrySource = shouldResolveSourceSideCssEntry(rawSource) ? shouldPreferSourceSideEntry ? sourceSideEntrySource ?? cssEntrySource ?? applyEntrySource : cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource : shouldPreferTailwindV3SourceSideEntry(rawSource, sourceSideEntrySource) || shouldPreferSourceSideEntry ? sourceSideEntrySource ?? cssEntrySource ?? applyEntrySource : cssEntrySource ?? applyEntrySource ?? sourceSideEntrySource;
4866
+ if (!resolvedEntrySource) return withTailwindV3SourceMetadata(await (generatorOptions?.config ? resolveTailwindV3Source(mergedSourceOptions) : resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher)));
4867
+ if (cssEntrySource && !sourceSideEntrySource && !applyEntrySource && !hasTailwindRootDirectives(rawSource, { importFallback: true })) return withTailwindV3SourceMetadata(await (generatorOptions?.config ? resolveTailwindV3Source(mergedSourceOptions) : resolveTailwindV3SourceFromPatcher(runtimeState.twPatcher)));
4591
4868
  const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, omitUndefined(mergedSourceOptions));
4592
- return resolveTailwindV3Source({
4869
+ const sourceWithMetadata = withTailwindV3SourceMetadata(await resolveTailwindV3Source({
4593
4870
  ...mergedSourceOptions,
4594
4871
  base: resolvedEntrySource.base,
4595
4872
  css: normalizeTailwindV3CssEntrySource(resolvedEntrySource.css),
4596
4873
  ...config ? { config } : {}
4874
+ }));
4875
+ return withGeneratorSourceMetadata(sourceWithMetadata, {
4876
+ ...sourceWithMetadata.__weappTailwindcssMeta,
4877
+ matchedCssSourceFile: resolvedEntrySource.file
4597
4878
  });
4598
4879
  }
4599
4880
  const sourceOptions = tryResolveTailwindV4SourceOptions(runtimeState);
4600
4881
  const resolvedSourceOptions = sourceOptions ? omitUndefined({
4601
4882
  ...sourceOptions,
4602
- ...resolveCssHandlerSourceOptions(cssHandlerOptions)
4883
+ sourceFile: resolvePostcssSourceFile(cssHandlerOptions),
4884
+ ...resolveCssHandlerSourceOptions(cssHandlerOptions),
4885
+ cssEntries: selectionOptions?.cssEntries ?? sourceOptions.cssEntries,
4886
+ cssSources: mergeCssSources(sourceOptions.cssSources, sourceOptions.cssSources?.length ? void 0 : createCssEntrySources(selectionOptions?.cssEntries ?? sourceOptions.cssEntries))
4603
4887
  }) : void 0;
4604
- const shouldPreferSourceSideEntry = shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder"));
4605
- const sourceSideEntrySource = resolvedSourceOptions && shouldPreferSourceSideEntry ? resolveSourceSideCssEntrySource(file, resolvedSourceOptions, { removeConfig: false }) : void 0;
4606
- const matchedCssSource = sourceOptions ? await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions) : void 0;
4607
- const candidateMatchedCssSource = sourceOptions ? await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions) : void 0;
4608
- const configuredCssSource = sourceOptions && hasConfiguredTailwindV4CssSource(sourceOptions) && hasTailwindGeneratedCssMarkers(rawSource) ? matchedCssSource ?? candidateMatchedCssSource ?? await resolveTailwindV4Source(sourceOptions) : void 0;
4888
+ const normalizedSourceOptions = resolvedSourceOptions ? normalizeTailwindV4CssSourceConfigs(resolvedSourceOptions) : void 0;
4889
+ const shouldPreferSourceSideEntry = shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) && (sourceOptions?.cssEntries?.length ?? 0) <= 1;
4890
+ const sourceSideEntrySource = normalizedSourceOptions && shouldPreferSourceSideEntry && canResolveSourceSideCssEntry(file, cssHandlerOptions, normalizedSourceOptions) ? resolveSourceSideCssEntrySource(file, normalizedSourceOptions, { removeConfig: false }) : void 0;
4891
+ const matchedCssEntrySource = normalizedSourceOptions ? await resolveMatchingTailwindV4CssEntry(rawSource, file, normalizedSourceOptions) : void 0;
4892
+ const matchedCssSource = normalizedSourceOptions && !matchedCssEntrySource ? await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, normalizedSourceOptions) : void 0;
4893
+ const candidateMatchedCssSource = normalizedSourceOptions && !matchedCssEntrySource ? await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, normalizedSourceOptions, selectionOptions) : void 0;
4894
+ const configuredCssSource = normalizedSourceOptions && hasConfiguredTailwindV4CssSource(normalizedSourceOptions) && hasTailwindGeneratedCssMarkers(rawSource) ? matchedCssSource ?? candidateMatchedCssSource ?? await resolveTailwindV4Source(normalizedSourceOptions) : void 0;
4609
4895
  if (configuredCssSource) return generatorOptions?.config ? {
4610
4896
  ...configuredCssSource,
4611
4897
  css: prependConfigDirective(configuredCssSource.css, generatorOptions.config)
4612
4898
  } : configuredCssSource;
4613
- const matchedCssEntrySource = sourceOptions && cssEntrySource ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
4614
- const mainCssEntrySource = sourceOptions && cssHandlerOptions.isMainChunk && sourceOptions.cssEntries?.length === 1 ? await resolveTailwindV4Source({
4615
- ...omitUndefined(sourceOptions),
4616
- cssEntries: [sourceOptions.cssEntries[0]]
4617
- }) : void 0;
4899
+ const mainCssEntrySource = normalizedSourceOptions && cssHandlerOptions.isMainChunk && normalizedSourceOptions.cssEntries?.length === 1 ? await resolveTailwindV4CssEntrySource(normalizedSourceOptions.cssEntries[0], normalizedSourceOptions) : void 0;
4618
4900
  const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource ?? mainCssEntrySource;
4619
4901
  if (preferredCssEntrySource) return generatorOptions?.config ? {
4620
4902
  ...preferredCssEntrySource,
@@ -4628,11 +4910,12 @@ async function resolveGeneratorSource(majorVersion, runtimeState, rawSource, fil
4628
4910
  css: prependConfigDirective(source.css, generatorOptions.config)
4629
4911
  } : source;
4630
4912
  }
4631
- if (sourceSideEntrySource && resolvedSourceOptions) return resolveTailwindV4SourceSideEntrySource(sourceSideEntrySource, resolvedSourceOptions, generatorOptions, file);
4913
+ if (sourceSideEntrySource && normalizedSourceOptions) return resolveTailwindV4SourceSideEntrySource(sourceSideEntrySource, normalizedSourceOptions, generatorOptions, file);
4632
4914
  const config = resolveExistingConfigPath(resolvedEntrySource.config, resolvedEntrySource.configRequest, file, resolvedSourceOptions ?? {});
4633
- const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), resolvedSourceOptions ?? {});
4634
- return resolveTailwindV4Source(createSingleTailwindV4SourceOptions(resolvedSourceOptions ?? {}, {
4635
- base: resolvedEntrySource.base,
4915
+ const sourceBase = resolvedEntrySource === cssEntrySource && config ? node_path.default.dirname(config) : resolvedEntrySource.base;
4916
+ const css = createTailwindV4ApplyReferenceSource(normalizeConfigDirective(prependConfigDirective(resolvedEntrySource.css, generatorOptions?.config), config), normalizedSourceOptions ?? {});
4917
+ return resolveTailwindV4Source(createSingleTailwindV4SourceOptions(normalizedSourceOptions ?? {}, {
4918
+ base: sourceBase,
4636
4919
  css
4637
4920
  }));
4638
4921
  }
@@ -4647,18 +4930,23 @@ async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, fi
4647
4930
  }
4648
4931
  let sourceOptions;
4649
4932
  try {
4933
+ const sourceOptionsFromPatcher = resolveTailwindV4SourceOptionsFromPatcher(runtimeState.twPatcher);
4934
+ const cssEntries = selectionOptions?.cssEntries ?? sourceOptionsFromPatcher.cssEntries;
4650
4935
  sourceOptions = omitUndefined({
4651
- ...resolveTailwindV4SourceOptionsFromPatcher(runtimeState.twPatcher),
4652
- ...resolveCssHandlerSourceOptions(cssHandlerOptions)
4936
+ ...sourceOptionsFromPatcher,
4937
+ sourceFile: resolvePostcssSourceFile(cssHandlerOptions),
4938
+ ...resolveCssHandlerSourceOptions(cssHandlerOptions),
4939
+ cssEntries,
4940
+ cssSources: mergeCssSources(sourceOptionsFromPatcher.cssSources, sourceOptionsFromPatcher.cssSources?.length ? void 0 : createCssEntrySources(cssEntries))
4653
4941
  });
4654
4942
  } catch {
4655
4943
  const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
4656
4944
  return resolved ? [resolved] : [];
4657
4945
  }
4658
- const matchedCssEntrySource = cssEntrySource ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
4946
+ const matchedCssEntrySource = sourceOptions ? await resolveMatchingTailwindV4CssEntry(rawSource, file, sourceOptions) : void 0;
4659
4947
  const matchedCssSource = await resolveMatchingTailwindV4CssSource(rawSource, file, cssHandlerOptions, sourceOptions);
4660
4948
  const candidateMatchedCssSource = await resolveCandidateMatchedTailwindV4CssSource(rawSource, cssHandlerOptions, sourceOptions, selectionOptions);
4661
- const sourceSideCssSource = await resolveTailwindV4SourceSideEntrySource(shouldResolveSourceSideCssEntry(rawSource) || Boolean(cssEntrySource?.css.includes("weapp-tailwindcss generator-placeholder")) ? resolveSourceSideCssEntrySource(file, sourceOptions, { removeConfig: false }) : void 0, sourceOptions, generatorOptions, file);
4949
+ 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);
4662
4950
  const preferredCssEntrySource = matchedCssEntrySource ?? matchedCssSource ?? candidateMatchedCssSource;
4663
4951
  if (sourceSideCssSource) return [sourceSideCssSource];
4664
4952
  if (preferredCssEntrySource) return [generatorOptions?.config ? {
@@ -4666,14 +4954,20 @@ async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, fi
4666
4954
  css: prependConfigDirective(preferredCssEntrySource.css, generatorOptions.config)
4667
4955
  } : preferredCssEntrySource];
4668
4956
  if (!sourceOptions.cssEntries || sourceOptions.cssEntries.length <= 1) {
4957
+ if (cssHandlerOptions.isMainChunk && sourceOptions.cssEntries?.length === 1) return [await resolveTailwindV4CssEntrySource(sourceOptions.cssEntries[0], normalizeTailwindV4CssSourceConfigs(sourceOptions)).then((source) => generatorOptions?.config ? {
4958
+ ...source,
4959
+ css: prependConfigDirective(source.css, generatorOptions.config)
4960
+ } : source)];
4669
4961
  if (sourceOptions.cssSources?.length === 1) return [await createTailwindV4CssSourceResolver(sourceOptions, generatorOptions)(sourceOptions.cssSources[0])];
4670
4962
  const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
4671
4963
  return resolved ? [resolved] : [];
4672
4964
  }
4673
- const cssEntrySources = await Promise.all(sourceOptions.cssEntries.map((cssEntry) => resolveTailwindV4Source({
4674
- ...omitUndefined(sourceOptions),
4675
- cssEntries: [cssEntry]
4676
- }).then((source) => generatorOptions?.config ? {
4965
+ if (cssHandlerOptions.isMainChunk && !cssEntrySource && !hasTailwindGeneratedCss(rawSource) && !hasTailwindGeneratedCssMarkers(rawSource) && !hasTailwindSourceDirectives(rawSource, { importFallback: generatorOptions?.importFallback ?? false }) && !rawSource.includes("weapp-tailwindcss generator-placeholder") && !hasConfiguredTailwindV4CssSource(sourceOptions)) {
4966
+ const resolved = await resolveGeneratorSource(majorVersion, runtimeState, rawSource, file, cssHandlerOptions, generatorOptions, selectionOptions);
4967
+ return resolved ? [resolved] : [];
4968
+ }
4969
+ const normalizedCssSourceOptions = normalizeTailwindV4CssSourceConfigs(sourceOptions);
4970
+ const cssEntrySources = await Promise.all(sourceOptions.cssEntries.map((cssEntry) => resolveTailwindV4CssEntrySource(cssEntry, normalizedCssSourceOptions).then((source) => generatorOptions?.config ? {
4677
4971
  ...source,
4678
4972
  css: prependConfigDirective(source.css, generatorOptions.config)
4679
4973
  } : source)));
@@ -4681,8 +4975,9 @@ async function resolveGeneratorSources(majorVersion, runtimeState, rawSource, fi
4681
4975
  return [...cssEntrySources, ...cssSources];
4682
4976
  }
4683
4977
  async function resolveGeneratorSourceEntries(source, runtimeState) {
4684
- if (!("css" in source) || !("base" in source) || !("baseFallbacks" in source)) return;
4685
4978
  const sourceMetadata = source.__weappTailwindcssMeta;
4979
+ if (sourceMetadata?.sourceEntries) return sourceMetadata.sourceEntries;
4980
+ if (!("css" in source) || !("base" in source) || !("baseFallbacks" in source)) return;
4686
4981
  const resolved = await resolveTailwindV4EntriesFromCss(sourceMetadata?.sourceCss ?? source.css, sourceMetadata?.sourceBase ?? source.base);
4687
4982
  if (resolved?.entries.length || !resolved?.explicit && !sourceMetadata?.matchedCssSourceFile || !runtimeState) return resolved?.entries;
4688
4983
  const matchingCssSource = tryResolveTailwindV4SourceOptions(runtimeState)?.cssSources?.find((cssSource) => {
@@ -4798,7 +5093,7 @@ function countUnclosedBlocks(source) {
4798
5093
  }
4799
5094
  function closeTrailingUnclosedBlocks(source) {
4800
5095
  try {
4801
- require_runtime_registry.postcss_default.parse(source);
5096
+ require_watch_dependencies.postcss_default.parse(source);
4802
5097
  return source;
4803
5098
  } catch (error) {
4804
5099
  if (error.reason !== "Unclosed block") return source;
@@ -4808,7 +5103,7 @@ function closeTrailingUnclosedBlocks(source) {
4808
5103
  }
4809
5104
  function removeTailwindApplyRules(rawSource) {
4810
5105
  try {
4811
- const root = require_runtime_registry.postcss_default.parse(rawSource);
5106
+ const root = require_watch_dependencies.postcss_default.parse(rawSource);
4812
5107
  let removed = false;
4813
5108
  root.walkAtRules("apply", (rule) => {
4814
5109
  const parent = rule.parent;
@@ -4900,7 +5195,7 @@ const CSS_LENGTH_UNIT_RE = /(?:^|[\s(,])[-+]?(?:\d+|\d*\.\d+)(?:px|rem)\b/i;
4900
5195
  const RPX_UNIT_RE = /(?:^|[\s(,])[-+]?(?:\d+|\d*\.\d+)rpx\b/i;
4901
5196
  function createLegacyDeclarationValueMap(css) {
4902
5197
  const values = /* @__PURE__ */ new Map();
4903
- require_runtime_registry.postcss_default.parse(css).walkRules((rule) => {
5198
+ require_watch_dependencies.postcss_default.parse(css).walkRules((rule) => {
4904
5199
  if (!rule.selectors || rule.selectors.length === 0) return;
4905
5200
  for (const selector of rule.selectors) {
4906
5201
  const normalizedSelectors = normalizeCompatSelectors(selector);
@@ -4915,7 +5210,7 @@ function inheritLegacyUnitConvertedDeclarations(css, legacyCss) {
4915
5210
  try {
4916
5211
  const legacyValues = createLegacyDeclarationValueMap(legacyCss);
4917
5212
  if (legacyValues.size === 0) return css;
4918
- const root = require_runtime_registry.postcss_default.parse(css);
5213
+ const root = require_watch_dependencies.postcss_default.parse(css);
4919
5214
  let changed = false;
4920
5215
  root.walkRules((rule) => {
4921
5216
  if (!rule.selectors || rule.selectors.length === 0) return;
@@ -5015,11 +5310,12 @@ function finalizeMiniProgramGeneratorCss(css, target, majorVersion, cssPreflight
5015
5310
  });
5016
5311
  }
5017
5312
  function mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtime, options) {
5018
- if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.isolateCssSource) return scopedRuntime;
5313
+ if (options.isolateCssSource && options.currentCssCandidates?.length) return new Set([...scopedRuntime, ...options.currentCssCandidates]);
5314
+ if (runtime.size === 0 || !options.cssHandlerOptions.isMainChunk || options.matchedCssSourceFile || options.isolateCssSource && scopedRuntime.size === 0) return scopedRuntime;
5019
5315
  return new Set([...scopedRuntime, ...runtime]);
5020
5316
  }
5021
- function shouldIsolateMatchedCssSource(source, sourceEntries) {
5022
- return Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile && sourceEntries !== void 0);
5317
+ function shouldIsolateScopedCssSource(source, sourceEntries) {
5318
+ return sourceEntries !== void 0 && Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile || sourceEntries.length > 0);
5023
5319
  }
5024
5320
  function shouldScanTailwindV4Sources(majorVersion, target, generatorRuntime, isolateCssSource) {
5025
5321
  if (majorVersion !== 4 || isolateCssSource) return false;
@@ -5051,7 +5347,7 @@ function isLocalImportRequest(request) {
5051
5347
  }
5052
5348
  function isCommentOnlyCss(source) {
5053
5349
  try {
5054
- const root = require_runtime_registry.postcss_default.parse(source);
5350
+ const root = require_watch_dependencies.postcss_default.parse(source);
5055
5351
  return root.nodes.length > 0 && root.nodes.every((node) => node.type === "comment");
5056
5352
  } catch {
5057
5353
  return false;
@@ -5065,7 +5361,7 @@ function stripLeadingTailwindSourceMediaCloseFragment(source) {
5065
5361
  }
5066
5362
  function stripUnmatchedTailwindSourceMediaCloseFragments(source) {
5067
5363
  try {
5068
- require_runtime_registry.postcss_default.parse(source);
5364
+ require_watch_dependencies.postcss_default.parse(source);
5069
5365
  return source;
5070
5366
  } catch {
5071
5367
  return stripLeadingTailwindSourceMediaCloseFragment(source).replace(/\s*\}\s*$/, "");
@@ -5093,9 +5389,9 @@ function splitUserCssLayerBlocks(source) {
5093
5389
  rest: source
5094
5390
  };
5095
5391
  try {
5096
- const root = require_runtime_registry.postcss_default.parse(source);
5097
- const layerRoot = require_runtime_registry.postcss_default.root();
5098
- const restRoot = require_runtime_registry.postcss_default.root();
5392
+ const root = require_watch_dependencies.postcss_default.parse(source);
5393
+ const layerRoot = require_watch_dependencies.postcss_default.root();
5394
+ const restRoot = require_watch_dependencies.postcss_default.root();
5099
5395
  for (const node of root.nodes) (node.type === "atrule" && node.name === "layer" && node.nodes?.length ? layerRoot : restRoot).append(node.clone());
5100
5396
  return {
5101
5397
  layer: layerRoot.toString(),
@@ -5112,7 +5408,7 @@ function hasUserCssLayerBlocks(source) {
5112
5408
  if (!source.includes("@layer")) return false;
5113
5409
  try {
5114
5410
  let hasLayerBlock = false;
5115
- require_runtime_registry.postcss_default.parse(source).walkAtRules("layer", (node) => {
5411
+ require_watch_dependencies.postcss_default.parse(source).walkAtRules("layer", (node) => {
5116
5412
  if (node.nodes?.length) hasLayerBlock = true;
5117
5413
  });
5118
5414
  return hasLayerBlock;
@@ -5123,7 +5419,7 @@ function hasUserCssLayerBlocks(source) {
5123
5419
  function collectUserLayerSelectors(source) {
5124
5420
  const selectors = /* @__PURE__ */ new Set();
5125
5421
  try {
5126
- require_runtime_registry.postcss_default.parse(source).walkRules((rule) => {
5422
+ require_watch_dependencies.postcss_default.parse(source).walkRules((rule) => {
5127
5423
  for (const selector of rule.selectors ?? [rule.selector]) {
5128
5424
  const normalized = selector.trim();
5129
5425
  if (normalized) selectors.add(normalized);
@@ -5145,8 +5441,8 @@ function extractGeneratedCssForUserLayerSelectors(css, userLayerSource) {
5145
5441
  rest: css
5146
5442
  };
5147
5443
  try {
5148
- const root = require_runtime_registry.postcss_default.parse(css);
5149
- const layerRoot = require_runtime_registry.postcss_default.root();
5444
+ const root = require_watch_dependencies.postcss_default.parse(css);
5445
+ const layerRoot = require_watch_dependencies.postcss_default.root();
5150
5446
  const selectorList = [...selectors];
5151
5447
  root.walkRules((rule) => {
5152
5448
  if ((rule.selectors ?? [rule.selector]).some((selector) => selectorList.some((userSelector) => matchesUserLayerSelector(selector.trim(), userSelector)))) {
@@ -5182,7 +5478,7 @@ async function transformGeneratorUserCss(source, options) {
5182
5478
  function isPureLocalCssImportWrapper(css) {
5183
5479
  let hasImport = false;
5184
5480
  try {
5185
- const root = require_runtime_registry.postcss_default.parse(css);
5481
+ const root = require_watch_dependencies.postcss_default.parse(css);
5186
5482
  for (const node of root.nodes) {
5187
5483
  if (node.type === "comment") continue;
5188
5484
  if (node.type !== "atrule" || node.name !== "import") return false;
@@ -5199,7 +5495,7 @@ function cleanLocalCssImportWrapperTailwindDirectives(css) {
5199
5495
  let hasLocalImport = false;
5200
5496
  let hasTailwindDirective = false;
5201
5497
  try {
5202
- const root = require_runtime_registry.postcss_default.parse(css);
5498
+ const root = require_watch_dependencies.postcss_default.parse(css);
5203
5499
  for (const node of root.nodes) {
5204
5500
  if (node.type === "comment") continue;
5205
5501
  if (node.type === "atrule" && node.name === "import") {
@@ -5221,7 +5517,7 @@ function cleanLocalCssImportWrapperTailwindDirectives(css) {
5221
5517
  }
5222
5518
  function prefixLocalCssImportsWithWebpackIgnore(css) {
5223
5519
  try {
5224
- const root = require_runtime_registry.postcss_default.parse(css);
5520
+ const root = require_watch_dependencies.postcss_default.parse(css);
5225
5521
  root.walkAtRules("import", (atRule) => {
5226
5522
  const request = parseImportRequest(atRule.params);
5227
5523
  if (request && isLocalImportRequest(request)) atRule.raws.before = `${atRule.raws.before ?? ""}/* webpackIgnore: true */\n`;
@@ -5254,22 +5550,30 @@ async function generateCssByGenerator(options) {
5254
5550
  if (!SUPPORTED_GENERATOR_MAJOR_VERSIONS.has(majorVersion ?? 0) || !shouldGenerateCurrentCss || majorVersion === 3 && !hasSourceDirectives && !hasGeneratedCss && !hasGeneratedMarkers) return;
5255
5551
  try {
5256
5552
  await runtimeState.readyPromise;
5257
- const currentCssCandidates = majorVersion === 4 ? await (0, tailwindcss_patch.extractSourceCandidates)(effectiveRawSource, "css", { bareArbitraryValues: generatorOptions.bareArbitraryValues }) : [];
5553
+ const currentCssCandidates = majorVersion === 4 ? await (0, tailwindcss_patch.extractSourceCandidates)(effectiveRawSource, "css", { ...generatorOptions.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: generatorOptions.bareArbitraryValues } }) : [];
5258
5554
  const runtimeWithCurrentCss = currentCssCandidates.length > 0 ? new Set([...runtime, ...currentCssCandidates]) : runtime;
5259
5555
  const sources = await resolveGeneratorSources(majorVersion, runtimeState, effectiveRawSource, file, cssHandlerOptions, generatorOptions, {
5556
+ cssEntries: opts.cssEntries,
5260
5557
  getSourceCandidatesForEntries,
5261
5558
  runtime: runtimeWithCurrentCss
5262
5559
  });
5263
5560
  const generatorStyleOptions = resolveGeneratorStyleOptions(opts, cssHandlerOptions, generatorOptions.styleOptions);
5264
5561
  const configuredContainerCompat = hasConfiguredContainerCompatSources(sources);
5265
- const generatedResults = await Promise.all(sources.map(async (source) => {
5562
+ const generatedResults = (await Promise.all(sources.map(async (source) => {
5266
5563
  const generator = createWeappTailwindcssGenerator(source);
5267
- const sourceEntries = getSourceCandidatesForEntries && majorVersion === 4 ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
5564
+ const sourceEntries = getSourceCandidatesForEntries && (majorVersion === 3 || majorVersion === 4) ? await resolveGeneratorSourceEntries(source, runtimeState) : void 0;
5268
5565
  const scopedRuntime = sourceEntries ? getSourceCandidatesForEntries?.(sourceEntries) : void 0;
5269
- const isolateCssSource = shouldIsolateMatchedCssSource(source, sourceEntries);
5566
+ const isolateCssSource = shouldIsolateScopedCssSource(source, sourceEntries);
5567
+ const matchedCssSourceFile = Boolean(source.__weappTailwindcssMeta?.matchedCssSourceFile);
5568
+ if (options.deferEmptyScopedCssSource && isolateCssSource && scopedRuntime?.size === 0 && currentCssCandidates.length === 0 && !cssHandlerOptions.isMainChunk) {
5569
+ debug("defer empty scoped css source generation: %s", file);
5570
+ return;
5571
+ }
5270
5572
  const sourceRuntime = scopedRuntime && (scopedRuntime.size > 0 || isolateCssSource) ? mergeScopedRuntimeWithCurrentRuntime(scopedRuntime, runtimeWithCurrentCss, {
5573
+ currentCssCandidates,
5271
5574
  cssHandlerOptions,
5272
- isolateCssSource
5575
+ isolateCssSource,
5576
+ matchedCssSourceFile
5273
5577
  }) : runtimeWithCurrentCss;
5274
5578
  const generatorRuntime = majorVersion === 4 && generatorOptions.target === "weapp" ? filterUnsupportedMiniProgramTailwindV4Candidates(sourceRuntime) : sourceRuntime;
5275
5579
  return generator.generate({
@@ -5281,7 +5585,7 @@ async function generateCssByGenerator(options) {
5281
5585
  tailwindcssV3Compatibility: generatorOptions.tailwindcssV3Compatibility,
5282
5586
  target: generatorOptions.target
5283
5587
  });
5284
- }));
5588
+ }))).filter((item) => Boolean(item));
5285
5589
  const firstGenerated = generatedResults[0];
5286
5590
  if (!firstGenerated) return;
5287
5591
  const incrementalCssResults = generatedResults.map((item) => item.incrementalCss).filter((css) => typeof css === "string");
@@ -5309,6 +5613,7 @@ async function generateCssByGenerator(options) {
5309
5613
  }
5310
5614
  const hasMatchedCssSourceFile = sources.some((source) => source.__weappTailwindcssMeta?.matchedCssSourceFile);
5311
5615
  const orderedExtraCss = hasMatchedCssSourceFile ? splitTailwindV4GeneratedCssBySourceOrder(effectiveRawSource, generated.rawCss) : splitRawSourceByGeneratedCssOrder(effectiveRawSource, generated.rawCss);
5616
+ const shouldAppendMatchedCssSourceCompat = !hasMatchedCssSourceFile || orderedExtraCss !== void 0;
5312
5617
  if (orderedExtraCss) {
5313
5618
  let css = stripTailwindBanner(generated.css);
5314
5619
  if (generated.target === "weapp") css = inheritLegacyUnitConvertedDeclarations(css, effectiveRawSource);
@@ -5334,11 +5639,11 @@ async function generateCssByGenerator(options) {
5334
5639
  const userCss = await transformGeneratorUserCss(effectiveRawSource, userCssOptions);
5335
5640
  css = createCssSourceOrderAppend(css, userCss);
5336
5641
  }
5337
- if (generated.target === "weapp") {
5642
+ if (generated.target === "weapp" && shouldAppendMatchedCssSourceCompat) {
5338
5643
  if (shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
5339
5644
  css = await appendLegacyCompatCss(css, effectiveRawSource, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
5340
5645
  css = await appendLegacyContainerCompatCss(css, effectiveRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
5341
- }
5646
+ } else if (generated.target === "weapp" && shouldFinalizeMarkedUserLayerComponentsCss(file)) css = reorderMarkedUserLayerComponentsCss(css);
5342
5647
  return {
5343
5648
  css: finalizeMiniProgramGeneratorCss(css, generated.target, majorVersion, opts.cssPreflight),
5344
5649
  target: generated.target,
@@ -5370,6 +5675,17 @@ async function generateCssByGenerator(options) {
5370
5675
  }
5371
5676
  }
5372
5677
  if (hasMatchedCssSourceFile || generated.target === "web") {
5678
+ if (hasMatchedCssSourceFile && generated.target === "weapp" && !hasGeneratedCss && !hasGeneratedMarkers) {
5679
+ const userCss = await transformGeneratorUserCss(effectiveRawSource, {
5680
+ generatorTarget: generated.target,
5681
+ generatorStyleOptions,
5682
+ cssUserHandlerOptions,
5683
+ styleHandler,
5684
+ importFallback: generatorOptions.importFallback
5685
+ });
5686
+ css = createCssSourceOrderAppend(css, userCss);
5687
+ }
5688
+ if (hasMatchedCssSourceFile && generated.target === "weapp") css = await appendLegacyContainerCompatCss(css, effectiveRawSource, file, runtime, configuredContainerCompat, generated.target, styleHandler, cssHandlerOptions, generatorStyleOptions);
5373
5689
  if (shouldAppendWebBundleCssFallback(generated.target, {
5374
5690
  hasSourceDirectives,
5375
5691
  hasMatchedCssSourceFile
@@ -5406,7 +5722,7 @@ async function generateCssByGenerator(options) {
5406
5722
  //#endregion
5407
5723
  //#region src/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.ts
5408
5724
  function resolveLoaderOptions(options) {
5409
- const runtime = require_runtime_registry.getWebpackLoaderRuntime(options?.tailwindcssImportRewriteRuntimeKey)?.cssImportRewrite;
5725
+ const runtime = require_watch_dependencies.getWebpackLoaderRuntime(options?.tailwindcssImportRewriteRuntimeKey)?.cssImportRewrite;
5410
5726
  return runtime ? {
5411
5727
  ...options,
5412
5728
  tailwindcssImportRewrite: runtime
@@ -5428,17 +5744,12 @@ function applyCssImportRewrite(source, options) {
5428
5744
  function isPackageJsonImportRequest(request) {
5429
5745
  return request.startsWith("#");
5430
5746
  }
5431
- function toRootRelativeConfigPath(configPath, rootContext) {
5432
- if (!rootContext) return (0, _weapp_tailwindcss_shared.ensurePosix)(configPath);
5433
- const relative = (0, _weapp_tailwindcss_shared.ensurePosix)(node_path.default.relative(rootContext, configPath));
5434
- return relative.startsWith(".") ? relative : `./${relative}`;
5435
- }
5436
- function normalizeCssConfigDirectives(source, resourcePath, rootContext) {
5747
+ function normalizeCssConfigDirectives(source, resourcePath) {
5437
5748
  if (!resourcePath) return source;
5438
5749
  const base = node_path.default.dirname(resourcePath);
5439
5750
  return source.replace(/@config\s+(["'])(.+?)\1\s*;?/g, (full, quote, request) => {
5440
5751
  if (node_path.default.isAbsolute(request) || isPackageJsonImportRequest(request)) return full;
5441
- return `@config ${quote}${toRootRelativeConfigPath(node_path.default.resolve(base, request), rootContext)}${quote};`;
5752
+ return `@config ${quote}${(0, _weapp_tailwindcss_shared.ensurePosix)(node_path.default.resolve(base, request))}${quote};`;
5442
5753
  });
5443
5754
  }
5444
5755
  function createCssHandlerOptions(options, majorVersion, file, appType) {
@@ -5457,7 +5768,7 @@ async function generateCssForWebpackPipeline(source, loaderContext, options) {
5457
5768
  await runtimeState.readyPromise;
5458
5769
  const runtime = await getRuntimeSet();
5459
5770
  const file = loaderContext.resourcePath;
5460
- const normalizedSource = normalizeCssConfigDirectives(source, file, loaderContext.rootContext);
5771
+ const normalizedSource = normalizeCssConfigDirectives(source, file);
5461
5772
  const cssHandlerOptions = createCssHandlerOptions(compilerOptions, runtimeState.twPatcher.majorVersion, file, rewriteOptions.appType);
5462
5773
  const generated = await generateCssByGenerator({
5463
5774
  opts: compilerOptions,
@@ -5475,7 +5786,7 @@ async function generateCssForWebpackPipeline(source, loaderContext, options) {
5475
5786
  });
5476
5787
  if (!generated) return;
5477
5788
  rewriteOptions.markGeneratedCssSource?.(file);
5478
- for (const dependency of generated.dependencies) loaderContext.addDependency?.(dependency);
5789
+ for (const dependency of generated.dependencies) require_watch_dependencies.registerWebpackWatchFile(loaderContext, dependency);
5479
5790
  return `${createBundlerGeneratedCssMarker("webpack", file)}\n${generated.css}`;
5480
5791
  }
5481
5792
  function transformCssImportRewriteSource(source, options) {
@@ -5495,11 +5806,11 @@ const WeappTwCssImportRewriteLoader = function(source) {
5495
5806
  const hasTailwindRoot = typeof input === "string" && hasTailwindRootDirectives(input, { importFallback: true });
5496
5807
  const registerTask = hasTailwindRoot ? opt?.tailwindcssImportRewrite?.registerCssSource?.({
5497
5808
  file: this.resourcePath,
5498
- css: normalizeCssConfigDirectives(normalizeTailwindSourceForGenerator(input, { importFallback: true }), this.resourcePath, this.rootContext)
5809
+ css: normalizeCssConfigDirectives(normalizeTailwindSourceForGenerator(input, { importFallback: true }), this.resourcePath)
5499
5810
  }) : void 0;
5500
5811
  const transform = () => {
5501
5812
  const transformed = transformCssImportRewriteSource(source, opt);
5502
- if (typeof transformed === "string") return normalizeCssConfigDirectives(transformed, this.resourcePath, this.rootContext);
5813
+ if (typeof transformed === "string") return normalizeCssConfigDirectives(transformed, this.resourcePath);
5503
5814
  return transformed;
5504
5815
  };
5505
5816
  const generate = hasTailwindRoot && opt?.tailwindcssImportRewrite?.compilerOptions && opt.tailwindcssImportRewrite.runtimeState && opt.tailwindcssImportRewrite.getRuntimeSet ? async () => {