weapp-tailwindcss 5.1.0 → 5.1.1

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 (83) hide show
  1. package/dist/bundlers/shared/generator-css/class-selectors.d.ts +2 -0
  2. package/dist/bundlers/shared/generator-css/generation-helpers.d.ts +6 -14
  3. package/dist/bundlers/shared/generator-css/source-resolver/metadata.d.ts +1 -1
  4. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +2 -2
  5. package/dist/bundlers/shared/generator-css/validate.d.ts +1 -0
  6. package/dist/bundlers/vite/css-memory.d.ts +6 -0
  7. package/dist/bundlers/vite/generate-bundle/css-assets.d.ts +1 -1
  8. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +1 -1
  9. package/dist/bundlers/vite/generate-bundle/css-output-helpers.d.ts +39 -0
  10. package/dist/bundlers/vite/generate-bundle/env-flags.d.ts +1 -0
  11. package/dist/bundlers/vite/generate-bundle/final-css-assets.d.ts +2 -1
  12. package/dist/bundlers/vite/generate-bundle/finalize.d.ts +2 -0
  13. package/dist/bundlers/vite/generate-bundle/html-processing.d.ts +26 -0
  14. package/dist/bundlers/vite/generate-bundle/js-processing.d.ts +4 -0
  15. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +1 -1
  16. package/dist/bundlers/vite/generate-bundle/remembered-css.d.ts +1 -1
  17. package/dist/bundlers/vite/generate-bundle/root-style-output.d.ts +6 -0
  18. package/dist/bundlers/vite/generate-bundle/runtime-linked-source-memory.d.ts +25 -0
  19. package/dist/bundlers/vite/generate-bundle/source-candidate-source.d.ts +9 -0
  20. package/dist/bundlers/vite/generate-bundle/tailwind-v4-css-source.d.ts +9 -0
  21. package/dist/bundlers/vite/generate-bundle/transform-filter.d.ts +15 -0
  22. package/dist/bundlers/vite/generate-bundle/types.d.ts +1 -0
  23. package/dist/bundlers/vite/generate-bundle.d.ts +1 -2
  24. package/dist/bundlers/vite/plugin-cache.d.ts +15 -0
  25. package/dist/bundlers/vite/runtime-class-set.d.ts +2 -1
  26. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +3 -3
  27. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/css-source-resolvers.d.ts +34 -0
  28. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/js-module-graph.d.ts +37 -0
  29. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/pipeline-helpers.d.ts +199 -0
  30. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets/source-candidate-refresh.d.ts +11 -0
  31. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +1 -0
  32. package/dist/cli.js +15 -8
  33. package/dist/cli.mjs +15 -8
  34. package/dist/context/style-options.d.ts +1 -0
  35. package/dist/{context-BHxLe743.js → context-B6hVF7dr.js} +20 -9
  36. package/dist/{context-Mbzkek1q.mjs → context-DlpKD7aN.mjs} +15 -10
  37. package/dist/core.js +1 -1
  38. package/dist/core.mjs +1 -1
  39. package/dist/css-macro/index.d.ts +3 -7
  40. package/dist/{defaults-ZElj1zKc.mjs → defaults-BhE26nSw.mjs} +7 -3
  41. package/dist/{defaults-CVcKbXBG.js → defaults-CmFBmxsr.js} +7 -3
  42. package/dist/defaults.d.ts +1 -1
  43. package/dist/defaults.js +1 -1
  44. package/dist/defaults.mjs +1 -1
  45. package/dist/generator/types.d.ts +1 -1
  46. package/dist/{generator-9rUz4Hcb.js → generator-6oMJtTDO.js} +1 -1
  47. package/dist/{generator-Dc4qaPmT.mjs → generator-CjzBK7h-.mjs} +1 -1
  48. package/dist/generator.js +2 -2
  49. package/dist/generator.mjs +2 -2
  50. package/dist/{gulp-B_sdP6dx.js → gulp-BtGq6LP9.js} +11 -9
  51. package/dist/{gulp-uM36oIJs.mjs → gulp-DNU10Vtc.mjs} +11 -9
  52. package/dist/gulp.js +1 -1
  53. package/dist/gulp.mjs +1 -1
  54. package/dist/{hmr-timing-BXMLsF4b.mjs → hmr-timing-B0KuWDjV.mjs} +121 -85
  55. package/dist/{hmr-timing-CogqkFaF.js → hmr-timing-CegXR9O4.js} +132 -84
  56. package/dist/index.js +4 -4
  57. package/dist/index.mjs +4 -4
  58. package/dist/postcss.js +2 -2
  59. package/dist/postcss.mjs +2 -2
  60. package/dist/presets.js +2 -2
  61. package/dist/presets.mjs +2 -2
  62. package/dist/{source-candidate-scan-signature-Cvb5z1ha.mjs → source-candidate-scan-signature-B5af2Ahe.mjs} +3 -3
  63. package/dist/{source-candidate-scan-signature-2ybpptAK.js → source-candidate-scan-signature-BKYb9jxa.js} +3 -3
  64. package/dist/tailwindcss/runtime-types.d.ts +1 -0
  65. package/dist/tailwindcss/v4-engine/source.d.ts +5 -14
  66. package/dist/tailwindcss/v4-engine/types.d.ts +10 -2
  67. package/dist/{tailwindcss-wyUHrfil.mjs → tailwindcss-B5mRo0-M.mjs} +12 -7
  68. package/dist/{tailwindcss-DHIYcqXT.js → tailwindcss-dbrbY4cd.js} +11 -6
  69. package/dist/{transform-tExdt40m.mjs → transform-fRBeuuK-.mjs} +1 -1
  70. package/dist/{transform-CQVOgmzM.js → transform-vLwZpiTE.js} +1 -1
  71. package/dist/types/user-defined-options/matcher.d.ts +7 -0
  72. package/dist/{v4-engine-CF9zt4Cw.mjs → v4-engine-C3qSwQ-e.mjs} +7 -27
  73. package/dist/{v4-engine-D4ubP7N5.js → v4-engine-ON_oSLfO.js} +5 -31
  74. package/dist/{vite-CPO83EhA.mjs → vite-CWRooooa.mjs} +730 -393
  75. package/dist/{vite-CP0ylSxZ.js → vite-w-RkgaTY.js} +730 -392
  76. package/dist/vite.js +1 -1
  77. package/dist/vite.mjs +1 -1
  78. package/dist/weapp-tw-css-import-rewrite-loader.js +122 -85
  79. package/dist/{webpack-BzqhJ8yK.mjs → webpack-8PaV1gG3.mjs} +923 -671
  80. package/dist/{webpack-Bsek8VhR.js → webpack-CGgBOx9l.js} +923 -671
  81. package/dist/webpack.js +1 -1
  82. package/dist/webpack.mjs +1 -1
  83. package/package.json +5 -5
@@ -1,10 +1,10 @@
1
- import { A as removeTailwindSourceDirectives, C as hasTailwindRootDirectives, E as normalizeTailwindConfigDirectives, F as hasTailwindGeneratedCss, I as hasTailwindGeneratedCssMarkers, K as getTailwindV4IncrementalGenerateCacheStats, T as hasTailwindSourceDirectives, _ as resolveTailwindcssOptions, k as parseImportRequest, lt as inferGeneratorTargetFromEnv, o as hasConfiguredTailwindV4CssRoots, rt as resolveSourceScanPath, s as upsertTailwindV4CssSource, x as hasTailwindApplyDirective } from "./v4-engine-CF9zt4Cw.mjs";
2
- import { o as resolveRuntimeBranch } from "./generator-Dc4qaPmT.mjs";
1
+ import { C as hasTailwindRootDirectives, F as hasTailwindGeneratedCssMarkers, G as getTailwindV4IncrementalGenerateCacheStats, O as parseImportRequest, P as hasTailwindGeneratedCss, T as normalizeTailwindConfigDirectives, _ as resolveTailwindcssOptions, ct as inferGeneratorTargetFromEnv, k as removeTailwindSourceDirectives, nt as resolveSourceScanPath, o as hasConfiguredTailwindV4CssRoots, s as upsertTailwindV4CssSource, w as hasTailwindSourceDirectives, x as hasTailwindApplyDirective } from "./v4-engine-C3qSwQ-e.mjs";
2
+ import { o as resolveRuntimeBranch } from "./generator-CjzBK7h-.mjs";
3
3
  import { r as getGroupedEntries } from "./utils-DodxWHGz.mjs";
4
- import { S as md5Hash, b as refreshTailwindRuntimeState, c as shouldSkipJsTransform, d as _defineProperty, n as resolveStyleOptionsFromContext, r as pluginName, t as getCompilerContext, v as createTailwindRuntimeReadyPromise, x as createDebug, y as ensureRuntimeClassSet } from "./context-Mbzkek1q.mjs";
5
- import { l as getRuntimeClassSetSignature, p as resolveViteSourceScanEntries } from "./tailwindcss-wyUHrfil.mjs";
6
- import { A as stripMiniProgramCssSpecificityPlaceholders, C as stripUnmatchedTailwindSourceMediaCloseFragments, D as finalizeMiniProgramCss, E as hasMiniProgramTailwindV4PreflightReset, F as processCachedTask, M as createCssSourceTraceCacheSignature, N as createCssTokenSourceMap, P as isCssSourceTraceEnabled, S as stripTailwindSourceMediaFragments, T as createCssSourceOrderAppend, _ as isPureLocalCssImportWrapper, a as isSourceCandidateRequest, b as removeMiniProgramHoverSelectors, c as collectStrictEscapedRuntimeCandidates, f as pushConcurrentTaskFactories, i as createSourceCandidateStore, j as annotateCssSourceTrace, k as pruneMiniProgramGeneratedCss, l as createEscapeFragments, n as emitHmrTiming, o as resolveSourceCandidateScanFiles, p as resolveTaskConcurrency, s as createBundleRuntimeClassSetManager, w as scoreTailwindV4CssSourceFileMatch, x as removeTailwindV4GeneratorAtRules } from "./hmr-timing-BXMLsF4b.mjs";
7
- import { A as isSourceStyleRequest, C as resolvePluginDisabledState, N as resolveOutputSpecifier, P as toAbsoluteOutputPath, S as resolvePackageDir, _ as generateTailwindV4Css, d as classifyBundleEntry, f as createBundleBuildState, i as createCandidateSignature, j as stripRequestQuery, m as createRuntimeAffectingSourceSignature, p as updateBundleBuildState, r as createScopedGeneratorRuntime, t as createSourceCandidateScanSignature, x as stripBundlerGeneratedCssMarkers, y as hasBundlerGeneratedCssMarker } from "./source-candidate-scan-signature-Cvb5z1ha.mjs";
4
+ import { C as md5Hash, S as createDebug, b as ensureRuntimeClassSet, f as _defineProperty, i as pluginName, l as shouldSkipJsTransform, n as normalizeStyleHandlerMajorVersion, r as resolveStyleOptionsFromContext, t as getCompilerContext, x as refreshTailwindRuntimeState, y as createTailwindRuntimeReadyPromise } from "./context-DlpKD7aN.mjs";
5
+ import { l as getRuntimeClassSetSignature, p as resolveViteSourceScanEntries } from "./tailwindcss-B5mRo0-M.mjs";
6
+ import { C as stripTailwindSourceMediaFragments, D as createCssSourceOrderAppend, E as removeGeneratedSelectorCompatCss, F as createCssTokenSourceMap, I as isCssSourceTraceEnabled, L as processCachedTask, M as stripMiniProgramCssSpecificityPlaceholders, N as annotateCssSourceTrace, O as hasMiniProgramTailwindV4PreflightReset, P as createCssSourceTraceCacheSignature, S as removeTailwindV4GeneratorAtRules, T as scoreTailwindV4CssSourceFileMatch, _ as isPureLocalCssImportWrapper, a as isSourceCandidateRequest, b as removeMiniProgramHoverSelectors, c as collectStrictEscapedRuntimeCandidates, f as pushConcurrentTaskFactories, i as createSourceCandidateStore, j as pruneMiniProgramGeneratedCss, k as finalizeMiniProgramCss, l as createEscapeFragments, n as emitHmrTiming, o as resolveSourceCandidateScanFiles, p as resolveTaskConcurrency, s as createBundleRuntimeClassSetManager, w as stripUnmatchedTailwindSourceMediaCloseFragments, x as removeTailwindV4GeneratedUserCssArtifacts } from "./hmr-timing-B0KuWDjV.mjs";
7
+ import { A as isSourceStyleRequest, C as resolvePluginDisabledState, N as resolveOutputSpecifier, P as toAbsoluteOutputPath, S as resolvePackageDir, _ as generateTailwindV4Css, d as classifyBundleEntry, f as createBundleBuildState, i as createCandidateSignature, j as stripRequestQuery, m as createRuntimeAffectingSourceSignature, p as updateBundleBuildState, r as createScopedGeneratorRuntime, t as createSourceCandidateScanSignature, x as stripBundlerGeneratedCssMarkers, y as hasBundlerGeneratedCssMarker } from "./source-candidate-scan-signature-B5af2Ahe.mjs";
8
8
  import Module, { createRequire } from "node:module";
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
@@ -323,6 +323,609 @@ function isWebpackCssLoaderRuntimeSource(source) {
323
323
  return source.includes("___CSS_LOADER_EXPORT___") && source.includes("___CSS_LOADER_API_IMPORT___") && source.includes("module.exports = ___CSS_LOADER_EXPORT___");
324
324
  }
325
325
  //#endregion
326
+ //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets/pipeline-helpers.ts
327
+ const WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX = 128;
328
+ function removeTailwindV4StandaloneHostPreflightRule(source) {
329
+ if (!source.includes("--theme(")) return source;
330
+ try {
331
+ const root = postcss.parse(source);
332
+ let changed = false;
333
+ root.walkRules((rule) => {
334
+ if (rule.selector.trim() !== ":host") return;
335
+ if (!rule.nodes?.some((node) => node.type === "decl" && node.value?.includes("--theme("))) return;
336
+ rule.remove();
337
+ changed = true;
338
+ });
339
+ return changed ? root.toString() : source;
340
+ } catch {
341
+ return source;
342
+ }
343
+ }
344
+ function isRuntimeTransformCandidate(candidate) {
345
+ return candidate.length > 0 && !candidate.includes("=") && !candidate.includes("<") && !candidate.includes(">") && !candidate.includes("${");
346
+ }
347
+ function collectRuntimeTokenSignatureParts(source) {
348
+ return source.match(/[\w-]+_[A-Z][\w-]*/gi) ?? [];
349
+ }
350
+ function hasMissingRuntimeCandidates(classSet, candidates) {
351
+ if (!classSet || !candidates?.size) return false;
352
+ for (const candidate of candidates) if (isRuntimeTransformCandidate(candidate) && !classSet.has(candidate)) return true;
353
+ return false;
354
+ }
355
+ function resolveGeneratedCssRuntimeCandidates(source, fallbackClassSet) {
356
+ const classSet = collectGeneratedCssRuntimeCandidates(source);
357
+ if (classSet.size > 0 || fallbackClassSet === void 0) return classSet;
358
+ return fallbackClassSet;
359
+ }
360
+ function getRuntimeClassSetSync(tailwindRuntime) {
361
+ if (typeof tailwindRuntime.getClassSetSync !== "function") return /* @__PURE__ */ new Set();
362
+ try {
363
+ return new Set(tailwindRuntime.getClassSetSync() ?? []);
364
+ } catch {
365
+ return /* @__PURE__ */ new Set();
366
+ }
367
+ }
368
+ function toMb(bytes) {
369
+ return Math.round(bytes / 1024 / 1024);
370
+ }
371
+ function pruneMapToMaxSize(map, maxSize) {
372
+ while (map.size > maxSize) {
373
+ const oldestKey = map.keys().next().value;
374
+ if (oldestKey === void 0) break;
375
+ map.delete(oldestKey);
376
+ }
377
+ }
378
+ function stripTrailingLineWhitespace(source) {
379
+ return source.replace(/[ \t]+$/gm, "");
380
+ }
381
+ function pruneWebpackCssHandlerOptionCaches(cssHandlerOptionsCache, cssUserHandlerOptionsCache, activeCssFiles) {
382
+ const activeSuffixes = [...activeCssFiles].map((file) => `:${file}`);
383
+ for (const key of cssHandlerOptionsCache.keys()) if (!activeSuffixes.some((suffix) => key.endsWith(suffix))) cssHandlerOptionsCache.delete(key);
384
+ for (const key of cssUserHandlerOptionsCache.keys()) if (!activeSuffixes.some((suffix) => key.endsWith(suffix))) cssUserHandlerOptionsCache.delete(key);
385
+ pruneMapToMaxSize(cssHandlerOptionsCache, WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX);
386
+ pruneMapToMaxSize(cssUserHandlerOptionsCache, WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX);
387
+ }
388
+ function resolveWebpackGeneratorRawSource(rawSource, cssHandlerOptions) {
389
+ const sourceCss = cssHandlerOptions.sourceOptions?.sourceCss;
390
+ if (sourceCss && (hasTailwindRootDirectives(sourceCss, { importFallback: true }) || hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || hasTailwindApplyDirective(sourceCss) || hasTailwindGeneratedCss(sourceCss) || hasTailwindGeneratedCssMarkers(sourceCss))) return sourceCss;
391
+ return rawSource;
392
+ }
393
+ function hasUsableWebpackGeneratorCssSources(cssSources) {
394
+ return Array.isArray(cssSources) && cssSources.some((source) => typeof source?.css === "string" && source.css.length > 0);
395
+ }
396
+ function normalizeWebpackGeneratorCssSources(cssSources) {
397
+ if (!Array.isArray(cssSources)) return;
398
+ const normalized = cssSources.filter((source) => typeof source?.css === "string" && source.css.length > 0);
399
+ return normalized.length > 0 ? normalized : void 0;
400
+ }
401
+ function hasProcessedCssAssetUrl(css) {
402
+ return /url\(\s*["']?data:/i.test(css);
403
+ }
404
+ function shouldUseWebpackAssetAsGeneratorUserCss(rawSource, generatorRawSource, options = {}) {
405
+ return rawSource !== generatorRawSource && (options.processed === true || !rawSource.includes("data:")) && !hasTailwindRootDirectives(rawSource, { importFallback: true }) && !hasTailwindSourceDirectives(rawSource, { importFallback: true }) && !hasTailwindApplyDirective(rawSource) && /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i.test(rawSource) && (!hasTailwindGeneratedCssMarkers(rawSource) || hasAdditionalWebpackAssetUserCssMarkers(rawSource, generatorRawSource));
406
+ }
407
+ function collectWebpackAssetUserCssMarkers(source) {
408
+ const markers = /* @__PURE__ */ new Set();
409
+ for (const match of source.matchAll(/\.((?:\\.|[_a-z\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/gi)) markers.add(`class:${match[1]}`);
410
+ for (const match of source.matchAll(/@(?:-[\w-]+-)?keyframes\s+((?:\\.|[-\w\u00A0-\uFFFF])+)/gi)) markers.add(`keyframes:${match[1]}`);
411
+ try {
412
+ const root = postcss.parse(source);
413
+ root.walkRules((rule) => {
414
+ for (const selector of rule.selectors) if (!/(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i.test(selector)) markers.add(`selector:${selector.trim().replace(/\s+/g, " ")}`);
415
+ rule.walkDecls((decl) => {
416
+ if (decl.prop.startsWith("--")) markers.add(`custom-property:${decl.prop}`);
417
+ });
418
+ });
419
+ root.walkAtRules("font-face", (rule) => {
420
+ rule.walkDecls("font-family", (decl) => {
421
+ markers.add(`font-face:${decl.value.trim()}`);
422
+ });
423
+ });
424
+ } catch {}
425
+ return markers;
426
+ }
427
+ const WEBPACK_TAILWIND_GENERATED_LAYER_NAMES = new Set([
428
+ "theme",
429
+ "base",
430
+ "utilities"
431
+ ]);
432
+ const WEBPACK_TAILWIND_UTILITY_RULE_MARKER_RE = /(?:^|[^\w-])\.[^,{]{0,512}(?:\\:|\\\[|\\#)/;
433
+ const WEBPACK_TAILWIND_UTILITY_PREFIX_RE = /^\.(?:-?(?:bg|text|border|ring|shadow|drop-shadow|[pmwhz]|px|py|pt|pr|pb|pl|mx|my|mt|mr|mb|ml|min-w|min-h|max-w|max-h|flex|grid|inline|block|hidden|rounded|opacity|translate|scale|rotate|skew|top|right|bottom|left|inset|gap|font|leading|tracking|underline|container)(?:[\-\\{]|$)|\\\[)/;
434
+ function parseWebpackCssLayerNames(params) {
435
+ return params.split(",").map((name) => name.trim()).filter(Boolean);
436
+ }
437
+ function removeWebpackTailwindGeneratedAssetCss(source) {
438
+ const cleaned = removeTailwindV4GeneratedUserCssArtifacts(source);
439
+ try {
440
+ const root = postcss.parse(cleaned);
441
+ let changed = false;
442
+ root.walkAtRules("layer", (rule) => {
443
+ const names = parseWebpackCssLayerNames(rule.params);
444
+ const hasGeneratedLayerName = names.some((name) => WEBPACK_TAILWIND_GENERATED_LAYER_NAMES.has(name));
445
+ const isLayerDeclaration = rule.nodes === void 0;
446
+ const shouldRemoveLayer = isLayerDeclaration ? hasGeneratedLayerName : names.length > 0 && names.every((name) => WEBPACK_TAILWIND_GENERATED_LAYER_NAMES.has(name));
447
+ if (shouldRemoveLayer && isLayerDeclaration) {
448
+ rule.remove();
449
+ changed = true;
450
+ return;
451
+ }
452
+ if (shouldRemoveLayer && !names.includes("utilities")) {
453
+ rule.remove();
454
+ changed = true;
455
+ return;
456
+ }
457
+ if (shouldRemoveLayer) {
458
+ rule.walkRules((nestedRule) => {
459
+ const selector = nestedRule.selector.trim();
460
+ if (WEBPACK_TAILWIND_UTILITY_RULE_MARKER_RE.test(selector) || WEBPACK_TAILWIND_UTILITY_PREFIX_RE.test(selector)) {
461
+ nestedRule.remove();
462
+ changed = true;
463
+ }
464
+ });
465
+ if (rule.nodes?.length === 0) {
466
+ rule.remove();
467
+ changed = true;
468
+ }
469
+ }
470
+ });
471
+ root.walkAtRules((rule) => {
472
+ if (rule.nodes !== void 0 && rule.nodes.length === 0) {
473
+ rule.remove();
474
+ changed = true;
475
+ }
476
+ });
477
+ return changed ? root.toString() : cleaned;
478
+ } catch {
479
+ return cleaned;
480
+ }
481
+ }
482
+ function collectWebpackCssRuleIdentityMarkers(source) {
483
+ const markers = /* @__PURE__ */ new Set();
484
+ try {
485
+ const root = postcss.parse(source);
486
+ root.walkRules((rule) => {
487
+ for (const selector of rule.selectors) for (const match of selector.matchAll(/\.((?:\\.|[_a-z\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/gi)) markers.add(`class:${match[1]}`);
488
+ });
489
+ root.walkAtRules("keyframes", (rule) => {
490
+ if (rule.params) markers.add(`keyframes:${rule.params}`);
491
+ });
492
+ } catch {}
493
+ return markers;
494
+ }
495
+ function unescapeCssIdentifier(value) {
496
+ return value.replace(/\\([0-9a-f]{1,6}\s?|.)/gi, (_match, escaped) => {
497
+ const hex = escaped.trim();
498
+ if (/^[0-9a-f]+$/i.test(hex)) return String.fromCodePoint(Number.parseInt(hex, 16));
499
+ return escaped;
500
+ });
501
+ }
502
+ function collectGeneratedCssRuntimeCandidates(source) {
503
+ const candidates = /* @__PURE__ */ new Set();
504
+ if (hasBundlerGeneratedCssMarker(source) || !hasTailwindGeneratedCss(source) && !hasTailwindGeneratedCssMarkers(source)) return candidates;
505
+ try {
506
+ postcss.parse(source).walkRules((rule) => {
507
+ for (const selector of rule.selectors) for (const match of selector.matchAll(/\.((?:\\.|[\w\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/g)) {
508
+ const candidate = unescapeCssIdentifier(match[1]);
509
+ if (isRuntimeTransformCandidate(candidate)) candidates.add(candidate);
510
+ }
511
+ });
512
+ } catch {}
513
+ return candidates;
514
+ }
515
+ function hasAdditionalWebpackAssetUserCssMarkers(rawSource, generatorRawSource) {
516
+ const rawMarkers = collectWebpackAssetUserCssMarkers(rawSource);
517
+ if (rawMarkers.size === 0) return false;
518
+ const generatorMarkers = collectWebpackAssetUserCssMarkers(generatorRawSource);
519
+ for (const marker of rawMarkers) if (!generatorMarkers.has(marker)) return true;
520
+ return false;
521
+ }
522
+ function hasWebpackTailwindSourceDirectives(source) {
523
+ return Boolean(source) && (hasTailwindRootDirectives(source, { importFallback: true }) || hasTailwindSourceDirectives(source, { importFallback: true }) || hasTailwindApplyDirective(source) || hasTailwindGeneratedCss(source) || hasTailwindGeneratedCssMarkers(source));
524
+ }
525
+ function isWebpackTailwindImportRequest(request) {
526
+ return request === "tailwindcss" || request === "tailwindcss4" || request?.startsWith("tailwindcss/") || request?.startsWith("tailwindcss4/") || request === "weapp-tailwindcss" || request?.startsWith("weapp-tailwindcss/");
527
+ }
528
+ function removeWebpackGeneratorNonTailwindImports(source) {
529
+ if (!source?.includes("@import")) return source;
530
+ try {
531
+ const root = postcss.parse(source);
532
+ let changed = false;
533
+ root.walkAtRules("import", (rule) => {
534
+ if (isWebpackTailwindImportRequest(parseImportRequest(rule.params))) return;
535
+ rule.remove();
536
+ changed = true;
537
+ });
538
+ return changed ? root.toString() : source;
539
+ } catch {
540
+ return source;
541
+ }
542
+ }
543
+ function isWebpackCssSourceRepresentedInAsset(rawSource, sourceCss) {
544
+ if (!sourceCss || !hasWebpackTailwindSourceDirectives(sourceCss)) return false;
545
+ const sourceMarkers = collectWebpackCssRuleIdentityMarkers(sourceCss);
546
+ if (sourceMarkers.size === 0) return false;
547
+ const rawMarkers = collectWebpackCssRuleIdentityMarkers(rawSource);
548
+ for (const marker of sourceMarkers) if (!rawMarkers.has(marker)) return false;
549
+ return true;
550
+ }
551
+ function createWebpackGeneratorCssSource(file, css) {
552
+ if (!file || !css || !hasWebpackTailwindSourceDirectives(css)) return;
553
+ return {
554
+ file,
555
+ base: path.dirname(file),
556
+ css,
557
+ dependencies: [file]
558
+ };
559
+ }
560
+ function createWebpackUserCssSourceAppend(sources, generatorRawSource, currentSourceFile, shouldIncludeSource) {
561
+ const matchedSources = [];
562
+ const seen = /* @__PURE__ */ new Set();
563
+ for (const source of sources) {
564
+ const css = source.css;
565
+ if (!css || seen.has(css)) continue;
566
+ if (shouldIncludeSource && !shouldIncludeSource(source.file)) continue;
567
+ seen.add(css);
568
+ if ((source.processed === true || !css.includes("data:")) && hasAdditionalWebpackAssetUserCssMarkers(css, generatorRawSource)) matchedSources.push({
569
+ css,
570
+ file: source.file,
571
+ processed: source.processed === true
572
+ });
573
+ }
574
+ const currentFile = currentSourceFile ? path.resolve(currentSourceFile) : void 0;
575
+ const parts = matchedSources.sort((a, b) => {
576
+ const aCurrent = currentFile !== void 0 && path.resolve(a.file) === currentFile;
577
+ if (aCurrent !== (currentFile !== void 0 && path.resolve(b.file) === currentFile)) return aCurrent ? -1 : 1;
578
+ return a.file.localeCompare(b.file);
579
+ }).map((source) => source.css);
580
+ return parts.length > 0 ? {
581
+ css: parts.join("\n"),
582
+ processed: matchedSources.every((source) => source.processed)
583
+ } : void 0;
584
+ }
585
+ function createWebpackGeneratorUserCssSourceAppend(...sources) {
586
+ const parts = sources.filter((source) => source !== void 0 && source.css.trim().length > 0);
587
+ if (parts.length === 0) return;
588
+ let css = "";
589
+ const usedParts = [];
590
+ for (const source of parts) {
591
+ const nextCss = css.trim().length > 0 ? filterExistingCssRules(css, source.css) : source.css;
592
+ if (!(nextCss.trim().length > 0)) continue;
593
+ css = createCssSourceOrderAppend(css, nextCss);
594
+ usedParts.push(source);
595
+ }
596
+ return {
597
+ css,
598
+ processed: usedParts.every((source) => source.processed)
599
+ };
600
+ }
601
+ function resolveWebpackMemoryDebugStats(context) {
602
+ if (process.env["WEAPP_TW_HMR_MEMORY_DEBUG"] !== "1") return;
603
+ const memory = process.memoryUsage();
604
+ const processCacheInstanceSize = context.cache.instance.size;
605
+ const processCacheHashMapSize = context.cache.hashMap.size;
606
+ return {
607
+ phase: context.phase,
608
+ process: {
609
+ rssMb: toMb(memory.rss),
610
+ heapTotalMb: toMb(memory.heapTotal),
611
+ heapUsedMb: toMb(memory.heapUsed),
612
+ externalMb: toMb(memory.external),
613
+ arrayBuffersMb: toMb(memory.arrayBuffers)
614
+ },
615
+ assets: {
616
+ active: context.activeAssetFiles,
617
+ activeCss: context.activeCssFiles
618
+ },
619
+ processCache: {
620
+ instance: processCacheInstanceSize,
621
+ hashMap: processCacheHashMapSize,
622
+ activeCacheKeys: context.activeProcessCacheKeys.size,
623
+ activeHashKeys: context.activeProcessHashKeys.size,
624
+ staleCacheKeys: Math.max(0, processCacheInstanceSize - context.activeProcessCacheKeys.size),
625
+ staleHashKeys: Math.max(0, processCacheHashMapSize - context.activeProcessHashKeys.size),
626
+ pruned: true,
627
+ pruneSkipped: false
628
+ },
629
+ webpackCss: {
630
+ handlerOptions: context.cssHandlerOptionsCache.size,
631
+ userHandlerOptions: context.cssUserHandlerOptionsCache.size,
632
+ maxHandlerOptions: WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX
633
+ },
634
+ sourceCandidateScan: context.sourceCandidateScan,
635
+ tailwind: { v4: getTailwindV4IncrementalGenerateCacheStats() }
636
+ };
637
+ }
638
+ function shouldInjectWebpackCssTracePreflight(appType, cssHandlerOptions) {
639
+ return appType !== "mpx" || cssHandlerOptions.isMainChunk !== false;
640
+ }
641
+ function finalizeMiniProgramUserCssAssetSource(source, compilerOptions, isWebGeneratorTarget, options = {}) {
642
+ const styleOptions = resolveStyleOptionsFromContext(compilerOptions);
643
+ if (isWebGeneratorTarget) return source;
644
+ return stripMiniProgramCssSpecificityPlaceholders(removeTailwindV4StandaloneHostPreflightRule(finalizeMiniProgramCss(removeMiniProgramHoverSelectors(source, styleOptions.cssRemoveHoverPseudoClass), {
645
+ cssPreflight: options.cssPreflight !== false && !hasMiniProgramTailwindV4PreflightReset(source) ? compilerOptions.cssPreflight : void 0,
646
+ isTailwindcssV4: true,
647
+ tailwindcssV4GradientFallback: styleOptions.tailwindcssV4GradientFallback
648
+ })));
649
+ }
650
+ function shouldFallbackToWebpackUserCssOnGeneratorError(options) {
651
+ return !hasTailwindRootDirectives(options.generatorRawSource, { importFallback: true }) && !hasTailwindSourceDirectives(options.generatorRawSource, { importFallback: true }) && !hasTailwindApplyDirective(options.generatorRawSource) && !options.hasExplicitTailwindV4SourceCss && options.configuredMainCssEntryFilesLength === 0;
652
+ }
653
+ function isWindowsAbsoluteResourcePath(file) {
654
+ return /^[a-z]:[\\/]/i.test(file) || /^[/\\]{2}[^/\\]/.test(file);
655
+ }
656
+ function isPosixAbsoluteResourcePath(file) {
657
+ return file.startsWith("/");
658
+ }
659
+ function resolveWebpackResourcePath(file, base) {
660
+ if (isWindowsAbsoluteResourcePath(file)) return path.win32.resolve(file);
661
+ if (isPosixAbsoluteResourcePath(file)) return path.posix.resolve(file);
662
+ if (base) {
663
+ if (isWindowsAbsoluteResourcePath(base)) return path.win32.resolve(base, file);
664
+ if (isPosixAbsoluteResourcePath(base)) return path.posix.resolve(base, file);
665
+ return path.resolve(base, file);
666
+ }
667
+ }
668
+ function dirnameWebpackResourcePath(file) {
669
+ if (isWindowsAbsoluteResourcePath(file)) return path.win32.dirname(file);
670
+ if (isPosixAbsoluteResourcePath(file)) return path.posix.dirname(file);
671
+ return path.dirname(file);
672
+ }
673
+ function resolveWebpackCssAssetModuleResource(resource, issuer, options) {
674
+ if (!isCssLikeModuleResource(resource, options.cssMatcher, options.appType)) return;
675
+ const normalized = stripResourceQuery(resource);
676
+ if (!normalized) return;
677
+ const absoluteResource = resolveWebpackResourcePath(normalized);
678
+ if (absoluteResource) return absoluteResource;
679
+ const issuerResource = issuer?.resource ? stripResourceQuery(issuer.resource) : void 0;
680
+ const issuerResourcePath = issuerResource ? resolveWebpackResourcePath(issuerResource) : void 0;
681
+ return resolveWebpackResourcePath(normalized, issuerResourcePath ? dirnameWebpackResourcePath(issuerResourcePath) : issuer?.context);
682
+ }
683
+ function isSameWebpackCssSourceScope(options) {
684
+ if (!options.currentSourceFile) return false;
685
+ const candidateKey = resolveWebpackResourcePath(options.candidateSourceFile) ?? path.resolve(options.candidateSourceFile);
686
+ if (candidateKey === (resolveWebpackResourcePath(options.currentSourceFile) ?? path.resolve(options.currentSourceFile))) return true;
687
+ const outputResources = options.resourcesByAsset.get(options.outputFile);
688
+ if (!outputResources) return false;
689
+ return [...outputResources].some((resource) => {
690
+ return (resolveWebpackResourcePath(resource) ?? path.resolve(resource)) === candidateKey;
691
+ });
692
+ }
693
+ function shouldAppendCurrentWebpackAssetUserCss(options) {
694
+ const hasGeneratedAssetUserCss = options.currentAssetLooksGenerated && options.currentAssetHasUserCss;
695
+ return !options.currentAssetHasBundlerGeneratedMarker && !options.shouldPreserveGeneratedWebAssetUserCss && (hasGeneratedAssetUserCss || !options.sourceCssProcessed || options.registeredUserRawSource === void 0 || options.currentAssetHasUserCss) && !(options.sourceCssProcessed && options.currentAssetLooksGenerated && !options.currentAssetHasUserCss);
696
+ }
697
+ function createWebpackCurrentAssetUserRawSource(options) {
698
+ if (!options.shouldAppendCurrentAssetUserCss) return;
699
+ if (options.sourceCssProcessed) return {
700
+ css: options.currentAssetUserCssSource,
701
+ processed: true
702
+ };
703
+ if (!options.currentAssetHasUserCss) return;
704
+ return {
705
+ css: options.currentAssetUserCssSource,
706
+ processed: options.currentAssetLooksGenerated
707
+ };
708
+ }
709
+ function finalizeTracedWebpackCssAsset(css, cssHandlerOptions, options) {
710
+ const traced = options.annotateCss(css);
711
+ if (options.isWebGeneratorTarget || !isCssSourceTraceEnabled(options.compilerOptions)) return traced;
712
+ return finalizeMiniProgramUserCssAssetSource(traced, options.compilerOptions, options.isWebGeneratorTarget, { cssPreflight: shouldInjectWebpackCssTracePreflight(options.compilerOptions.appType, cssHandlerOptions) });
713
+ }
714
+ function finalizeWebpackCssAssetSource(source, compilerOptions, isWebGeneratorTarget, options = {}) {
715
+ const styleOptions = resolveStyleOptionsFromContext(compilerOptions);
716
+ if (isWebGeneratorTarget) {
717
+ if (options.generatedCss === true) return stripTrailingLineWhitespace(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(stripBundlerGeneratedCssMarkers(source))));
718
+ return stripTrailingLineWhitespace(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(removeTailwindV4GeneratorAtRules(removeTailwindSourceDirectives(stripBundlerGeneratedCssMarkers(source), { importFallback: true })))));
719
+ }
720
+ let finalized = removeTailwindSourceDirectives(stripBundlerGeneratedCssMarkers(source), { importFallback: true });
721
+ if (options.generatedCss !== true) return stripMiniProgramCssSpecificityPlaceholders(removeMiniProgramHoverSelectors(finalized, styleOptions.cssRemoveHoverPseudoClass));
722
+ try {
723
+ finalized = pruneMiniProgramGeneratedCss(finalized, { preservePreflight: true });
724
+ } catch {
725
+ finalized = finalizeMiniProgramCss(finalized, {
726
+ cssPreflight: !hasMiniProgramTailwindV4PreflightReset(finalized) ? compilerOptions.cssPreflight : void 0,
727
+ isTailwindcssV4: true,
728
+ tailwindcssV4GradientFallback: styleOptions.tailwindcssV4GradientFallback
729
+ });
730
+ }
731
+ return stripMiniProgramCssSpecificityPlaceholders(removeMiniProgramHoverSelectors(finalized, styleOptions.cssRemoveHoverPseudoClass));
732
+ }
733
+ function collectWebpackJsRuntimeCandidatesFromAssets(options) {
734
+ if (options.isWebGeneratorTarget) return;
735
+ const candidates = /* @__PURE__ */ new Set();
736
+ for (const file of options.jsAssets) {
737
+ const sourceLike = options.getAssetSource(file);
738
+ if (sourceLike === void 0) continue;
739
+ const source = stringifyWebpackSourceLike(sourceLike);
740
+ for (const candidate of collectStrictEscapedRuntimeCandidates(source, MappingChars2String, options.escapeFragments)) if (isRuntimeTransformCandidate(candidate)) candidates.add(candidate);
741
+ }
742
+ return candidates;
743
+ }
744
+ function collectWebpackJsRuntimeTokenSignature(options) {
745
+ if (options.isWebGeneratorTarget) return "";
746
+ const tokens = [];
747
+ for (const file of options.jsAssets) {
748
+ const sourceLike = options.getAssetSource(file);
749
+ if (sourceLike === void 0) continue;
750
+ tokens.push(...collectRuntimeTokenSignatureParts(stringifyWebpackSourceLike(sourceLike)));
751
+ }
752
+ return tokens.sort().join("\n");
753
+ }
754
+ function addRuntimeTransformCandidates(target, candidates) {
755
+ if (!candidates?.size) return;
756
+ for (const candidate of candidates) if (isRuntimeTransformCandidate(candidate)) target.add(candidate);
757
+ }
758
+ function createWebpackCssSourceTraceTokenSources(compilerOptions, webpackSourceCandidates) {
759
+ if (!isCssSourceTraceEnabled(compilerOptions) || !webpackSourceCandidates) return;
760
+ return createCssTokenSourceMap(webpackSourceCandidates.tokenSources, compilerOptions);
761
+ }
762
+ function stringifyOptionalWebpackSourceValue(value) {
763
+ return typeof value === "string" ? value : value?.toString() ?? "";
764
+ }
765
+ function stringifyWebpackSourceLike(source) {
766
+ if (typeof source === "string") return source;
767
+ const value = source.source();
768
+ return typeof value === "string" ? value : value.toString();
769
+ }
770
+ //#endregion
771
+ //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets/css-source-resolvers.ts
772
+ function createWebpackCssSourceResolvers(options) {
773
+ const { activeWebpackAssetResourceFiles, appType, compilerOptions, compilation, cssAssetResources, cssHandlerOptionsCache, cssSources, cssUserHandlerOptionsCache, groupedCssEntriesLength, singleCssAssetFile, isWebGeneratorTarget, outputDir, runtimeState } = options;
774
+ const hasConfiguredTailwindV4SourceRoots = () => {
775
+ const tailwindOptions = resolveTailwindcssOptions(runtimeState.tailwindRuntime.options);
776
+ return (tailwindOptions?.v4?.cssEntries?.length ?? 0) > 0 || (tailwindOptions?.v4?.cssSources?.length ?? 0) > 0;
777
+ };
778
+ const configuredMainCssEntryFiles = (() => {
779
+ return [...resolveTailwindcssOptions(runtimeState.tailwindRuntime.options)?.v4?.cssEntries ?? []].filter((file) => typeof file === "string" && file.length > 0).map((file) => path.resolve(file));
780
+ })();
781
+ const inferredMainCssFiles = inferWebpackMainCssFiles(compilation.chunks, compilerOptions.cssMatcher, {
782
+ mainSourceFiles: new Set(configuredMainCssEntryFiles),
783
+ resourcesByAsset: cssAssetResources
784
+ });
785
+ const singleConfiguredCssAsset = isWebGeneratorTarget && configuredMainCssEntryFiles.length > 0 && groupedCssEntriesLength === 1 ? singleCssAssetFile : void 0;
786
+ const isMainCssChunk = (file) => compilerOptions.mainCssChunkMatcher(file, appType) || inferredMainCssFiles.has(file) || file === singleConfiguredCssAsset;
787
+ const activeWebpackCssSourceFiles = /* @__PURE__ */ new Set();
788
+ const resolveConfiguredMainCssSourceFile = (file) => {
789
+ if (!isMainCssChunk(file)) return;
790
+ for (const sourceFile of configuredMainCssEntryFiles) if (cssSources.has(sourceFile)) {
791
+ activeWebpackCssSourceFiles.add(sourceFile);
792
+ return sourceFile;
793
+ }
794
+ };
795
+ const resolveWebpackCssSourceFile = (file, rawSource) => {
796
+ const assetResources = cssAssetResources.get(file);
797
+ const activeAssetResource = resolveSingleActiveWebpackCssResource(assetResources, activeWebpackAssetResourceFiles);
798
+ if (cssSources.size === 0) {
799
+ if (activeAssetResource) {
800
+ activeWebpackCssSourceFiles.add(activeAssetResource);
801
+ return activeAssetResource;
802
+ }
803
+ if (assetResources && assetResources.size > 0) return;
804
+ return resolveConfiguredMainCssSourceFile(file);
805
+ }
806
+ const resourceMatches = [...assetResources ?? []].filter((sourceFile) => cssSources.has(sourceFile)).sort();
807
+ if (resourceMatches.length === 1) {
808
+ const sourceFile = resourceMatches[0];
809
+ activeWebpackCssSourceFiles.add(sourceFile);
810
+ return sourceFile;
811
+ }
812
+ const tailwindSourceMatches = resourceMatches.filter((sourceFile) => {
813
+ const sourceCss = cssSources.get(sourceFile)?.css;
814
+ return sourceCss && (hasTailwindRootDirectives(sourceCss, { importFallback: true }) || hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || hasTailwindApplyDirective(sourceCss) || hasTailwindGeneratedCss(sourceCss) || hasTailwindGeneratedCssMarkers(sourceCss));
815
+ });
816
+ if (tailwindSourceMatches.length === 1) {
817
+ const sourceFile = tailwindSourceMatches[0];
818
+ activeWebpackCssSourceFiles.add(sourceFile);
819
+ return sourceFile;
820
+ }
821
+ if (activeAssetResource) {
822
+ activeWebpackCssSourceFiles.add(activeAssetResource);
823
+ return activeAssetResource;
824
+ }
825
+ if (rawSource) {
826
+ const representedTailwindSourceMatches = [...cssSources.entries()].filter(([, source]) => isWebpackCssSourceRepresentedInAsset(rawSource, source.css)).map(([sourceFile]) => ({
827
+ sourceFile,
828
+ score: scoreTailwindV4CssSourceFileMatch(file, sourceFile, {
829
+ outputRoot: outputDir,
830
+ projectRoot: compilerOptions.tailwindcssBasedir,
831
+ cwd: compilerOptions.tailwindcssBasedir
832
+ })
833
+ })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score || a.sourceFile.localeCompare(b.sourceFile));
834
+ const bestScore = representedTailwindSourceMatches[0]?.score ?? 0;
835
+ const bestMatches = representedTailwindSourceMatches.filter((match) => match.score === bestScore);
836
+ if (bestMatches.length === 1) {
837
+ const sourceFile = bestMatches[0].sourceFile;
838
+ activeWebpackCssSourceFiles.add(sourceFile);
839
+ return sourceFile;
840
+ }
841
+ }
842
+ const pathMatches = [...cssSources.keys()].map((sourceFile) => ({
843
+ sourceFile,
844
+ score: scoreTailwindV4CssSourceFileMatch(file, sourceFile, {
845
+ outputRoot: outputDir,
846
+ projectRoot: compilerOptions.tailwindcssBasedir,
847
+ cwd: compilerOptions.tailwindcssBasedir
848
+ })
849
+ })).filter((match) => match.score >= 1e3).sort((a, b) => b.score - a.score || a.sourceFile.localeCompare(b.sourceFile));
850
+ const bestPathScore = pathMatches[0]?.score ?? 0;
851
+ const bestPathMatches = pathMatches.filter((match) => match.score === bestPathScore);
852
+ if (bestPathMatches.length === 1) {
853
+ const sourceFile = bestPathMatches[0].sourceFile;
854
+ activeWebpackCssSourceFiles.add(sourceFile);
855
+ return sourceFile;
856
+ }
857
+ if (assetResources && assetResources.size > 0) return;
858
+ return resolveConfiguredMainCssSourceFile(file);
859
+ };
860
+ const isSameWebpackSourceScope = (outputFile, candidateSourceFile, currentSourceFile) => isSameWebpackCssSourceScope({
861
+ candidateSourceFile,
862
+ currentSourceFile,
863
+ outputFile,
864
+ resourcesByAsset: cssAssetResources
865
+ });
866
+ const getCssHandlerOptions = (file, rawSource) => {
867
+ const majorVersion = runtimeState.tailwindRuntime.majorVersion;
868
+ const isMainChunk = isMainCssChunk(file);
869
+ const sourceFile = resolveWebpackCssSourceFile(file, rawSource);
870
+ const sourceCss = sourceFile ? cssSources.get(sourceFile)?.css : void 0;
871
+ const generatorSourceCss = removeWebpackGeneratorNonTailwindImports(sourceCss);
872
+ const generatorCssSource = createWebpackGeneratorCssSource(sourceFile, generatorSourceCss);
873
+ const cacheKey = [
874
+ majorVersion ?? "unknown",
875
+ isMainChunk ? "1" : "0",
876
+ sourceFile ?? "asset",
877
+ sourceCss === void 0 ? "source:0" : compilerOptions.cache.computeHash(sourceCss),
878
+ generatorSourceCss === sourceCss || generatorSourceCss === void 0 ? "generator-source:0" : compilerOptions.cache.computeHash(generatorSourceCss),
879
+ file
880
+ ].join(":");
881
+ const cached = cssHandlerOptionsCache.get(cacheKey);
882
+ if (cached) return cached;
883
+ const created = {
884
+ isMainChunk,
885
+ postcssOptions: { options: { from: sourceFile ?? file } },
886
+ sourceOptions: {
887
+ outputRoot: outputDir,
888
+ ...generatorCssSource === void 0 ? {} : { cssSources: [generatorCssSource] },
889
+ ...generatorSourceCss === void 0 ? {} : { sourceCss: generatorSourceCss },
890
+ ...sourceFile === void 0 ? {} : { sourceFile }
891
+ },
892
+ ...normalizeStyleHandlerMajorVersion(majorVersion) === void 0 ? {} : { majorVersion: 4 }
893
+ };
894
+ cssHandlerOptionsCache.set(cacheKey, created);
895
+ return created;
896
+ };
897
+ const getCssUserHandlerOptions = (file) => {
898
+ const majorVersion = runtimeState.tailwindRuntime.majorVersion;
899
+ const sourceFile = resolveWebpackCssSourceFile(file);
900
+ const sourceCss = sourceFile ? cssSources.get(sourceFile)?.css : void 0;
901
+ const generatorSourceCss = removeWebpackGeneratorNonTailwindImports(sourceCss);
902
+ const cacheKey = [
903
+ majorVersion ?? "unknown",
904
+ sourceFile ?? "asset",
905
+ sourceCss === void 0 ? "source:0" : compilerOptions.cache.computeHash(sourceCss),
906
+ generatorSourceCss === sourceCss || generatorSourceCss === void 0 ? "generator-source:0" : compilerOptions.cache.computeHash(generatorSourceCss),
907
+ file
908
+ ].join(":");
909
+ const cached = cssUserHandlerOptionsCache.get(cacheKey);
910
+ if (cached) return cached;
911
+ const created = {
912
+ ...getCssHandlerOptions(file),
913
+ isMainChunk: false
914
+ };
915
+ cssUserHandlerOptionsCache.set(cacheKey, created);
916
+ return created;
917
+ };
918
+ return {
919
+ activeWebpackCssSourceFiles,
920
+ configuredMainCssEntryFiles,
921
+ getCssHandlerOptions,
922
+ getCssUserHandlerOptions,
923
+ hasConfiguredTailwindV4SourceRoots,
924
+ isSameWebpackSourceScope,
925
+ resolveWebpackCssSourceFile
926
+ };
927
+ }
928
+ //#endregion
326
929
  //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets/helpers.ts
327
930
  function createChangedByType() {
328
931
  return {
@@ -375,6 +978,11 @@ function buildWebpackBundleSnapshot(assets, opts, state, compilation) {
375
978
  file,
376
979
  output: {
377
980
  fileName: file,
981
+ name: void 0,
982
+ names: [],
983
+ needsCodeReference: false,
984
+ originalFileName: null,
985
+ originalFileNames: [],
378
986
  source,
379
987
  type: "asset"
380
988
  },
@@ -398,7 +1006,8 @@ function buildWebpackBundleSnapshot(assets, opts, state, compilation) {
398
1006
  function releaseWebpackBundleSnapshotSources(snapshot) {
399
1007
  for (const entry of snapshot.entries) {
400
1008
  entry.source = "";
401
- entry.output.source = "";
1009
+ if (entry.output.type === "asset") entry.output.source = "";
1010
+ else entry.output.code = "";
402
1011
  }
403
1012
  }
404
1013
  function stringifyWebpackSource(source) {
@@ -432,6 +1041,50 @@ function createWebpackAssetUpdater(options) {
432
1041
  };
433
1042
  }
434
1043
  //#endregion
1044
+ //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets/js-module-graph.ts
1045
+ function createWebpackJsAssetModuleGraph(options) {
1046
+ const jsAssets = /* @__PURE__ */ new Map();
1047
+ for (const [file] of options.entries) if (options.compilerOptions.jsMatcher(file) || options.compilerOptions.wxsMatcher(file)) {
1048
+ const absolute = toAbsoluteOutputPath(file, options.outputDir);
1049
+ jsAssets.set(absolute, file);
1050
+ }
1051
+ return {
1052
+ jsAssets,
1053
+ moduleGraphOptions: {
1054
+ resolve(specifier, importer) {
1055
+ return resolveOutputSpecifier(specifier, importer, options.outputDir, (candidate) => jsAssets.has(candidate));
1056
+ },
1057
+ load: (id) => {
1058
+ const assetName = jsAssets.get(id);
1059
+ if (!assetName) return;
1060
+ const asset = options.compilation.getAsset(assetName);
1061
+ if (!asset) return;
1062
+ const source = asset.source.source();
1063
+ return source == null ? "" : String(source);
1064
+ },
1065
+ filter(id) {
1066
+ return jsAssets.has(id);
1067
+ }
1068
+ }
1069
+ };
1070
+ }
1071
+ function applyWebpackLinkedJsResults(options) {
1072
+ if (!options.linked) return;
1073
+ for (const [id, { code }] of Object.entries(options.linked)) {
1074
+ const assetName = options.jsAssets.get(id);
1075
+ if (!assetName) continue;
1076
+ const asset = options.compilation.getAsset(assetName);
1077
+ if (!asset) continue;
1078
+ const previousSource = asset.source.source();
1079
+ const previous = previousSource == null ? "" : String(previousSource);
1080
+ if (previous === code) continue;
1081
+ const source = new options.ConcatSource(code);
1082
+ options.compilation.updateAsset(assetName, source);
1083
+ options.compilerOptions.onUpdate(assetName, previous, code);
1084
+ options.debug("js linked handle: %s", assetName);
1085
+ }
1086
+ }
1087
+ //#endregion
435
1088
  //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets/source-candidate-cache.ts
436
1089
  const WEBPACK_SOURCE_CANDIDATE_SCAN_CACHE_MAX = 2;
437
1090
  function trimScanCache(cache) {
@@ -495,359 +1148,140 @@ async function resolveScanFileSnapshot(file) {
495
1148
  try {
496
1149
  const stats = await stat(file);
497
1150
  const source = await readFile(file, "utf8");
498
- return {
499
- meta: {
500
- contentHash: md5Hash(source),
501
- mtimeMs: stats.mtimeMs,
502
- size: stats.size
503
- },
504
- source
505
- };
506
- } catch (error) {
507
- if ((typeof error === "object" && error !== null && "code" in error ? error.code : void 0) === "ENOENT") return;
508
- throw error;
509
- }
510
- }
511
- function isSameFileMeta(left, right) {
512
- return left?.contentHash === right?.contentHash && left?.mtimeMs === right?.mtimeMs && left?.size === right?.size;
513
- }
514
- async function resolveScanFiles(roots, outDir) {
515
- const files = /* @__PURE__ */ new Set();
516
- await Promise.all(roots.map(async (root) => {
517
- const rootFiles = await resolveSourceCandidateScanFiles({
518
- entries: root.entries,
519
- explicit: root.explicit,
520
- filter: isSourceCandidateRequest,
521
- outDir,
522
- root: root.root
523
- });
524
- for (const file of rootFiles) files.add(resolveSourceScanPath(file));
525
- }));
526
- return files;
527
- }
528
- async function syncChangedScanFiles(collector, cachedScan, scanFiles, changedFiles) {
529
- for (const file of cachedScan.files.keys()) {
530
- if (scanFiles.has(file)) continue;
531
- collector.remove(file);
532
- cachedScan.files.delete(file);
533
- }
534
- await Promise.all([...scanFiles].map(async (file) => {
535
- const nextSnapshot = await resolveScanFileSnapshot(file);
536
- if (!nextSnapshot) {
537
- collector.remove(file);
538
- cachedScan.files.delete(file);
539
- return;
540
- }
541
- const previousMeta = cachedScan.files.get(file);
542
- if (previousMeta && isSameFileMeta(previousMeta, nextSnapshot.meta) && !changedFiles.has(file)) return;
543
- await collector.sync(file, nextSnapshot.source);
544
- cachedScan.files.set(file, nextSnapshot.meta);
545
- }));
546
- }
547
- function createWebpackSourceCandidateScanCache() {
548
- const scans = /* @__PURE__ */ new Map();
549
- let lastHit = false;
550
- let lastSignatureHash;
551
- async function resolve({ changedFiles, collector, outDir, root, sourceScan, watchMode }) {
552
- const explicit = sourceScan?.explicit ?? false;
553
- const roots = collectWebpackSourceCandidateScanRoots(root, sourceScan?.entries, explicit);
554
- const nextSignatureHash = md5Hash(createSourceCandidateScanSignature({
555
- inlineCandidates: sourceScan?.inlineCandidates,
556
- outDir,
557
- roots,
558
- scanAllSources: !explicit
559
- }));
560
- const scanFiles = await resolveScanFiles(roots, outDir);
561
- const cachedScan = watchMode ? scans.get(nextSignatureHash) : void 0;
562
- if (cachedScan) {
563
- collector.restore(cachedScan.snapshot);
564
- collector.syncInline(sourceScan?.inlineCandidates);
565
- await syncChangedScanFiles(collector, cachedScan, scanFiles, normalizeChangedFiles(changedFiles));
566
- cachedScan.snapshot = compactSnapshot(collector.snapshot());
567
- lastHit = true;
568
- lastSignatureHash = nextSignatureHash;
569
- return createWebpackSourceCandidateCacheRecord(collector, sourceScan, nextSignatureHash);
570
- }
571
- collector.clearScan();
572
- collector.syncInline(sourceScan?.inlineCandidates);
573
- const files = /* @__PURE__ */ new Map();
574
- await Promise.all([...scanFiles].map(async (file) => {
575
- const nextSnapshot = await resolveScanFileSnapshot(file);
576
- if (!nextSnapshot) return;
577
- await collector.sync(file, nextSnapshot.source);
578
- files.set(file, nextSnapshot.meta);
579
- }));
580
- if (watchMode) {
581
- scans.set(nextSignatureHash, {
582
- files,
583
- snapshot: compactSnapshot(collector.snapshot())
584
- });
585
- trimScanCache(scans);
586
- } else scans.clear();
587
- lastHit = false;
588
- lastSignatureHash = nextSignatureHash;
589
- return createWebpackSourceCandidateCacheRecord(collector, sourceScan, nextSignatureHash);
590
- }
591
- function getMemoryStats() {
592
- const cachedScans = [...scans.values()];
593
- return {
594
- entries: cachedScans.reduce((count, scan) => count + (scan.snapshot.scanCandidatesById?.length ?? scan.snapshot.candidatesById.length), 0),
595
- files: cachedScans.reduce((count, scan) => count + scan.files.size, 0),
596
- lastHit,
597
- signatureHash: lastSignatureHash,
598
- snapshots: scans.size
599
- };
600
- }
601
- return {
602
- getMemoryStats,
603
- resolve
604
- };
605
- }
606
- //#endregion
607
- //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets.ts
608
- const WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX = 128;
609
- function removeTailwindV4StandaloneHostPreflightRule(source) {
610
- if (!source.includes("--theme(")) return source;
611
- try {
612
- const root = postcss.parse(source);
613
- let changed = false;
614
- root.walkRules((rule) => {
615
- if (rule.selector.trim() !== ":host") return;
616
- if (!rule.nodes?.some((node) => node.type === "decl" && node.value?.includes("--theme("))) return;
617
- rule.remove();
618
- changed = true;
619
- });
620
- return changed ? root.toString() : source;
621
- } catch {
622
- return source;
623
- }
624
- }
625
- function isRuntimeTransformCandidate(candidate) {
626
- return candidate.length > 0 && !candidate.includes("=") && !candidate.includes("<") && !candidate.includes(">") && !candidate.includes("${");
627
- }
628
- function collectRuntimeTokenSignatureParts(source) {
629
- return source.match(/[\w-]+_[A-Z][\w-]*/gi) ?? [];
630
- }
631
- function hasMissingRuntimeCandidates(classSet, candidates) {
632
- if (!classSet || !candidates?.size) return false;
633
- for (const candidate of candidates) if (isRuntimeTransformCandidate(candidate) && !classSet.has(candidate)) return true;
634
- return false;
635
- }
636
- function resolveGeneratedCssRuntimeCandidates(source, fallbackClassSet) {
637
- const classSet = collectGeneratedCssRuntimeCandidates(source);
638
- if (classSet.size > 0 || fallbackClassSet === void 0) return classSet;
639
- return fallbackClassSet;
640
- }
641
- function getRuntimeClassSetSync(tailwindRuntime) {
642
- if (typeof tailwindRuntime.getClassSetSync !== "function") return /* @__PURE__ */ new Set();
643
- try {
644
- return new Set(tailwindRuntime.getClassSetSync() ?? []);
645
- } catch {
646
- return /* @__PURE__ */ new Set();
647
- }
648
- }
649
- function toMb(bytes) {
650
- return Math.round(bytes / 1024 / 1024);
651
- }
652
- function pruneMapToMaxSize(map, maxSize) {
653
- while (map.size > maxSize) {
654
- const oldestKey = map.keys().next().value;
655
- if (oldestKey === void 0) break;
656
- map.delete(oldestKey);
657
- }
658
- }
659
- function stripTrailingLineWhitespace(source) {
660
- return source.replace(/[ \t]+$/gm, "");
661
- }
662
- function pruneWebpackCssHandlerOptionCaches(cssHandlerOptionsCache, cssUserHandlerOptionsCache, activeCssFiles) {
663
- const activeSuffixes = [...activeCssFiles].map((file) => `:${file}`);
664
- for (const key of cssHandlerOptionsCache.keys()) if (!activeSuffixes.some((suffix) => key.endsWith(suffix))) cssHandlerOptionsCache.delete(key);
665
- for (const key of cssUserHandlerOptionsCache.keys()) if (!activeSuffixes.some((suffix) => key.endsWith(suffix))) cssUserHandlerOptionsCache.delete(key);
666
- pruneMapToMaxSize(cssHandlerOptionsCache, WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX);
667
- pruneMapToMaxSize(cssUserHandlerOptionsCache, WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX);
668
- }
669
- function resolveWebpackGeneratorRawSource(rawSource, cssHandlerOptions) {
670
- const sourceCss = cssHandlerOptions.sourceOptions?.sourceCss;
671
- if (sourceCss && (hasTailwindRootDirectives(sourceCss, { importFallback: true }) || hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || hasTailwindApplyDirective(sourceCss) || hasTailwindGeneratedCss(sourceCss) || hasTailwindGeneratedCssMarkers(sourceCss))) return sourceCss;
672
- return rawSource;
673
- }
674
- function hasUsableWebpackGeneratorCssSources(cssSources) {
675
- return Array.isArray(cssSources) && cssSources.some((source) => typeof source?.css === "string" && source.css.length > 0);
676
- }
677
- function normalizeWebpackGeneratorCssSources(cssSources) {
678
- if (!Array.isArray(cssSources)) return;
679
- const normalized = cssSources.filter((source) => typeof source?.css === "string" && source.css.length > 0);
680
- return normalized.length > 0 ? normalized : void 0;
681
- }
682
- function shouldUseWebpackAssetAsGeneratorUserCss(rawSource, generatorRawSource, options = {}) {
683
- return rawSource !== generatorRawSource && (options.processed === true || !rawSource.includes("data:")) && !hasTailwindRootDirectives(rawSource, { importFallback: true }) && !hasTailwindSourceDirectives(rawSource, { importFallback: true }) && !hasTailwindApplyDirective(rawSource) && /(?:^|[^\w-])\.[_a-z\u00A0-\uFFFF\\-]/i.test(rawSource) && (!hasTailwindGeneratedCssMarkers(rawSource) || hasAdditionalWebpackAssetUserCssMarkers(rawSource, generatorRawSource));
684
- }
685
- function collectWebpackAssetUserCssMarkers(source) {
686
- const markers = /* @__PURE__ */ new Set();
687
- for (const match of source.matchAll(/\.((?:\\.|[_a-z\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/gi)) markers.add(`class:${match[1]}`);
688
- for (const match of source.matchAll(/@(?:-[\w-]+-)?keyframes\s+((?:\\.|[-\w\u00A0-\uFFFF])+)/gi)) markers.add(`keyframes:${match[1]}`);
689
- return markers;
690
- }
691
- function collectWebpackCssRuleIdentityMarkers(source) {
692
- const markers = /* @__PURE__ */ new Set();
693
- try {
694
- const root = postcss.parse(source);
695
- root.walkRules((rule) => {
696
- for (const selector of rule.selectors ?? [rule.selector]) for (const match of selector.matchAll(/\.((?:\\.|[_a-z\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/gi)) markers.add(`class:${match[1]}`);
697
- });
698
- root.walkAtRules("keyframes", (rule) => {
699
- if (rule.params) markers.add(`keyframes:${rule.params}`);
700
- });
701
- } catch {}
702
- return markers;
703
- }
704
- function unescapeCssIdentifier(value) {
705
- return value.replace(/\\([0-9a-f]{1,6}\s?|.)/gi, (_match, escaped) => {
706
- const hex = escaped.trim();
707
- if (/^[0-9a-f]+$/i.test(hex)) {
708
- const codePoint = Number.parseInt(hex, 16);
709
- if (Number.isFinite(codePoint)) return String.fromCodePoint(codePoint);
710
- }
711
- return escaped;
712
- });
713
- }
714
- function collectGeneratedCssRuntimeCandidates(source) {
715
- const candidates = /* @__PURE__ */ new Set();
716
- if (hasBundlerGeneratedCssMarker(source) || !hasTailwindGeneratedCss(source) && !hasTailwindGeneratedCssMarkers(source)) return candidates;
717
- try {
718
- postcss.parse(source).walkRules((rule) => {
719
- for (const selector of rule.selectors ?? [rule.selector]) for (const match of selector.matchAll(/\.((?:\\.|[\w\u00A0-\uFFFF-])(?:\\.|[\w\u00A0-\uFFFF-])*)/g)) {
720
- const candidate = unescapeCssIdentifier(match[1] ?? "");
721
- if (isRuntimeTransformCandidate(candidate)) candidates.add(candidate);
722
- }
723
- });
724
- } catch {}
725
- return candidates;
726
- }
727
- function hasAdditionalWebpackAssetUserCssMarkers(rawSource, generatorRawSource) {
728
- const rawMarkers = collectWebpackAssetUserCssMarkers(rawSource);
729
- if (rawMarkers.size === 0) return false;
730
- const generatorMarkers = collectWebpackAssetUserCssMarkers(generatorRawSource);
731
- for (const marker of rawMarkers) if (!generatorMarkers.has(marker)) return true;
732
- return false;
733
- }
734
- function hasWebpackTailwindSourceDirectives(source) {
735
- return Boolean(source) && (hasTailwindRootDirectives(source, { importFallback: true }) || hasTailwindSourceDirectives(source, { importFallback: true }) || hasTailwindApplyDirective(source) || hasTailwindGeneratedCss(source) || hasTailwindGeneratedCssMarkers(source));
736
- }
737
- function isWebpackTailwindImportRequest(request) {
738
- return request === "tailwindcss" || request === "tailwindcss4" || request?.startsWith("tailwindcss/") || request?.startsWith("tailwindcss4/") || request === "weapp-tailwindcss" || request?.startsWith("weapp-tailwindcss/");
739
- }
740
- function removeWebpackGeneratorNonTailwindImports(source) {
741
- if (!source?.includes("@import")) return source;
742
- try {
743
- const root = postcss.parse(source);
744
- let changed = false;
745
- root.walkAtRules("import", (rule) => {
746
- if (isWebpackTailwindImportRequest(parseImportRequest(rule.params))) return;
747
- rule.remove();
748
- changed = true;
749
- });
750
- return changed ? root.toString() : source;
751
- } catch {
752
- return source;
1151
+ return {
1152
+ meta: {
1153
+ contentHash: md5Hash(source),
1154
+ mtimeMs: stats.mtimeMs,
1155
+ size: stats.size
1156
+ },
1157
+ source
1158
+ };
1159
+ } catch (error) {
1160
+ if ((typeof error === "object" && error !== null && "code" in error ? error.code : void 0) === "ENOENT") return;
1161
+ throw error;
753
1162
  }
754
1163
  }
755
- function isWebpackCssSourceRepresentedInAsset(rawSource, sourceCss) {
756
- if (!sourceCss || !hasWebpackTailwindSourceDirectives(sourceCss)) return false;
757
- const sourceMarkers = collectWebpackCssRuleIdentityMarkers(sourceCss);
758
- if (sourceMarkers.size === 0) return false;
759
- const rawMarkers = collectWebpackCssRuleIdentityMarkers(rawSource);
760
- for (const marker of sourceMarkers) if (!rawMarkers.has(marker)) return false;
761
- return true;
762
- }
763
- function createWebpackGeneratorCssSource(file, css) {
764
- if (!file || !css || !hasWebpackTailwindSourceDirectives(css)) return;
765
- return {
766
- file,
767
- base: path.dirname(file),
768
- css,
769
- dependencies: [file]
770
- };
1164
+ function isSameFileMeta(left, right) {
1165
+ return left?.contentHash === right?.contentHash && left?.mtimeMs === right?.mtimeMs && left?.size === right?.size;
771
1166
  }
772
- function createWebpackUserCssSourceAppend(sources, generatorRawSource, currentSourceFile, shouldIncludeSource) {
773
- const matchedSources = [];
774
- const seen = /* @__PURE__ */ new Set();
775
- for (const source of sources) {
776
- const css = source.css;
777
- if (!css || seen.has(css)) continue;
778
- if (shouldIncludeSource && !shouldIncludeSource(source.file)) continue;
779
- seen.add(css);
780
- if ((source.processed === true || !css.includes("data:")) && hasAdditionalWebpackAssetUserCssMarkers(css, generatorRawSource)) matchedSources.push({
781
- css,
782
- file: source.file,
783
- processed: source.processed === true
1167
+ async function resolveScanFiles(roots, outDir) {
1168
+ const files = /* @__PURE__ */ new Set();
1169
+ await Promise.all(roots.map(async (root) => {
1170
+ const rootFiles = await resolveSourceCandidateScanFiles({
1171
+ entries: root.entries,
1172
+ explicit: root.explicit,
1173
+ filter: isSourceCandidateRequest,
1174
+ outDir,
1175
+ root: root.root
784
1176
  });
1177
+ for (const file of rootFiles) files.add(resolveSourceScanPath(file));
1178
+ }));
1179
+ return files;
1180
+ }
1181
+ async function syncChangedScanFiles(collector, cachedScan, scanFiles, changedFiles) {
1182
+ for (const file of cachedScan.files.keys()) {
1183
+ if (scanFiles.has(file)) continue;
1184
+ collector.remove(file);
1185
+ cachedScan.files.delete(file);
785
1186
  }
786
- const currentFile = currentSourceFile ? path.resolve(currentSourceFile) : void 0;
787
- const parts = matchedSources.sort((a, b) => {
788
- const aCurrent = currentFile !== void 0 && path.resolve(a.file) === currentFile;
789
- if (aCurrent !== (currentFile !== void 0 && path.resolve(b.file) === currentFile)) return aCurrent ? -1 : 1;
790
- return a.file.localeCompare(b.file);
791
- }).map((source) => source.css);
792
- return parts.length > 0 ? {
793
- css: parts.join("\n"),
794
- processed: matchedSources.every((source) => source.processed)
795
- } : void 0;
1187
+ await Promise.all([...scanFiles].map(async (file) => {
1188
+ const nextSnapshot = await resolveScanFileSnapshot(file);
1189
+ if (!nextSnapshot) {
1190
+ collector.remove(file);
1191
+ cachedScan.files.delete(file);
1192
+ return;
1193
+ }
1194
+ const previousMeta = cachedScan.files.get(file);
1195
+ if (previousMeta && isSameFileMeta(previousMeta, nextSnapshot.meta) && !changedFiles.has(file)) return;
1196
+ await collector.sync(file, nextSnapshot.source);
1197
+ cachedScan.files.set(file, nextSnapshot.meta);
1198
+ }));
796
1199
  }
797
- function createWebpackGeneratorUserCssSourceAppend(...sources) {
798
- const parts = sources.filter((source) => source !== void 0 && source.css.trim().length > 0);
799
- if (parts.length === 0) return;
800
- let css = "";
801
- const usedParts = [];
802
- for (const source of parts) {
803
- const nextCss = css.trim().length > 0 ? filterExistingCssRules(css, source.css) : source.css;
804
- if (nextCss.trim().length === 0) continue;
805
- css = createCssSourceOrderAppend(css, nextCss);
806
- usedParts.push(source);
1200
+ function createWebpackSourceCandidateScanCache() {
1201
+ const scans = /* @__PURE__ */ new Map();
1202
+ let lastHit = false;
1203
+ let lastSignatureHash;
1204
+ async function resolve({ changedFiles, collector, outDir, root, sourceScan, watchMode }) {
1205
+ const explicit = sourceScan?.explicit ?? false;
1206
+ const roots = collectWebpackSourceCandidateScanRoots(root, sourceScan?.entries, explicit);
1207
+ const nextSignatureHash = md5Hash(createSourceCandidateScanSignature({
1208
+ inlineCandidates: sourceScan?.inlineCandidates,
1209
+ outDir,
1210
+ roots,
1211
+ scanAllSources: !explicit
1212
+ }));
1213
+ const scanFiles = await resolveScanFiles(roots, outDir);
1214
+ const cachedScan = watchMode ? scans.get(nextSignatureHash) : void 0;
1215
+ if (cachedScan) {
1216
+ collector.restore(cachedScan.snapshot);
1217
+ collector.syncInline(sourceScan?.inlineCandidates);
1218
+ await syncChangedScanFiles(collector, cachedScan, scanFiles, normalizeChangedFiles(changedFiles));
1219
+ cachedScan.snapshot = compactSnapshot(collector.snapshot());
1220
+ lastHit = true;
1221
+ lastSignatureHash = nextSignatureHash;
1222
+ return createWebpackSourceCandidateCacheRecord(collector, sourceScan, nextSignatureHash);
1223
+ }
1224
+ collector.clearScan();
1225
+ collector.syncInline(sourceScan?.inlineCandidates);
1226
+ const files = /* @__PURE__ */ new Map();
1227
+ await Promise.all([...scanFiles].map(async (file) => {
1228
+ const nextSnapshot = await resolveScanFileSnapshot(file);
1229
+ if (!nextSnapshot) return;
1230
+ await collector.sync(file, nextSnapshot.source);
1231
+ files.set(file, nextSnapshot.meta);
1232
+ }));
1233
+ if (watchMode) {
1234
+ scans.set(nextSignatureHash, {
1235
+ files,
1236
+ snapshot: compactSnapshot(collector.snapshot())
1237
+ });
1238
+ trimScanCache(scans);
1239
+ } else scans.clear();
1240
+ lastHit = false;
1241
+ lastSignatureHash = nextSignatureHash;
1242
+ return createWebpackSourceCandidateCacheRecord(collector, sourceScan, nextSignatureHash);
1243
+ }
1244
+ function getMemoryStats() {
1245
+ const cachedScans = [...scans.values()];
1246
+ return {
1247
+ entries: cachedScans.reduce((count, scan) => count + (scan.snapshot.scanCandidatesById?.length ?? scan.snapshot.candidatesById.length), 0),
1248
+ files: cachedScans.reduce((count, scan) => count + scan.files.size, 0),
1249
+ lastHit,
1250
+ signatureHash: lastSignatureHash,
1251
+ snapshots: scans.size
1252
+ };
807
1253
  }
808
- if (css.trim().length === 0) return;
809
1254
  return {
810
- css,
811
- processed: usedParts.every((source) => source.processed)
1255
+ getMemoryStats,
1256
+ resolve
812
1257
  };
813
1258
  }
814
- function resolveWebpackMemoryDebugStats(context) {
815
- if (process.env["WEAPP_TW_HMR_MEMORY_DEBUG"] !== "1") return;
816
- const memory = process.memoryUsage();
817
- const processCacheInstanceSize = context.cache.instance.size;
818
- const processCacheHashMapSize = context.cache.hashMap.size;
819
- return {
820
- phase: context.phase,
821
- process: {
822
- rssMb: toMb(memory.rss),
823
- heapTotalMb: toMb(memory.heapTotal),
824
- heapUsedMb: toMb(memory.heapUsed),
825
- externalMb: toMb(memory.external),
826
- arrayBuffersMb: toMb(memory.arrayBuffers)
827
- },
828
- assets: {
829
- active: context.activeAssetFiles,
830
- activeCss: context.activeCssFiles
831
- },
832
- processCache: {
833
- instance: processCacheInstanceSize,
834
- hashMap: processCacheHashMapSize,
835
- activeCacheKeys: context.activeProcessCacheKeys.size,
836
- activeHashKeys: context.activeProcessHashKeys.size,
837
- staleCacheKeys: Math.max(0, processCacheInstanceSize - context.activeProcessCacheKeys.size),
838
- staleHashKeys: Math.max(0, processCacheHashMapSize - context.activeProcessHashKeys.size),
839
- pruned: true,
840
- pruneSkipped: false
841
- },
842
- webpackCss: {
843
- handlerOptions: context.cssHandlerOptionsCache.size,
844
- userHandlerOptions: context.cssUserHandlerOptionsCache.size,
845
- maxHandlerOptions: WEBPACK_CSS_HANDLER_OPTIONS_CACHE_MAX
846
- },
847
- sourceCandidateScan: context.sourceCandidateScan,
848
- tailwind: { v4: getTailwindV4IncrementalGenerateCacheStats() }
849
- };
1259
+ //#endregion
1260
+ //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets/source-candidate-refresh.ts
1261
+ async function refreshWebpackSourceCandidates(options) {
1262
+ const root = options.compilerOptions.tailwindcssBasedir ?? process.cwd();
1263
+ let sourceScan;
1264
+ try {
1265
+ sourceScan = await resolveViteSourceScanEntries(options.compilerOptions, options.runtimeState.tailwindRuntime, {
1266
+ root,
1267
+ outDir: options.outputDir
1268
+ });
1269
+ } catch (error) {
1270
+ options.debug("webpack source candidate scan skipped: %O", error);
1271
+ return;
1272
+ }
1273
+ if (!sourceScan || !sourceScan.explicit && !sourceScan.entries?.length && !sourceScan.inlineCandidates) return;
1274
+ return options.scanCache.resolve({
1275
+ changedFiles: options.watchChangedFiles,
1276
+ collector: createSourceCandidateStore({ bareArbitraryValues: options.compilerOptions.arbitraryValues?.bareArbitraryValues }),
1277
+ outDir: options.outputDir,
1278
+ root,
1279
+ sourceScan,
1280
+ watchMode: options.watchMode
1281
+ });
850
1282
  }
1283
+ //#endregion
1284
+ //#region src/bundlers/webpack/BaseUnifiedPlugin/v5-assets.ts
851
1285
  function setupWebpackV5ProcessAssetsHook(options) {
852
1286
  const { compiler, options: compilerOptions, appType, runtimeState, getRuntimeRefreshRequirement, refreshRuntimeMetadata, isKnownWebpackProcessedCssAsset, isWebpackProcessedCssAsset, consumeRuntimeRefreshRequirement, isWatchMode, getWatchChangedFiles, runtimeClassSetManager, getWebpackCssSources, getWebpackGeneratedCssSources, pruneWebpackCssSources, prepareWebpackCssSources, debug } = options;
853
1287
  const { Compilation, sources } = compiler.webpack;
@@ -869,7 +1303,7 @@ function setupWebpackV5ProcessAssetsHook(options) {
869
1303
  const entries = Object.entries(assets);
870
1304
  if (entries.length === 0) return;
871
1305
  const groupedEntries = getGroupedEntries(entries, compilerOptions);
872
- if (isWebGeneratorTarget && !groupedEntries.css?.length) return;
1306
+ if (isWebGeneratorTarget && groupedEntries.css.length === 0) return;
873
1307
  compilerOptions.onStart();
874
1308
  debug("start");
875
1309
  await runtimeState.readyPromise;
@@ -884,49 +1318,17 @@ function setupWebpackV5ProcessAssetsHook(options) {
884
1318
  });
885
1319
  const compilerOutputPath = compilation.compiler?.outputPath ?? compiler.outputPath;
886
1320
  const outputDir = compilerOutputPath ? path.resolve(compilerOutputPath) : compilation.outputOptions?.path ?? process.cwd();
887
- const jsAssets = /* @__PURE__ */ new Map();
888
- for (const [file] of entries) if (compilerOptions.jsMatcher(file) || compilerOptions.wxsMatcher(file)) {
889
- const absolute = toAbsoluteOutputPath(file, outputDir);
890
- jsAssets.set(absolute, file);
891
- }
892
- const moduleGraphOptions = {
893
- resolve(specifier, importer) {
894
- return resolveOutputSpecifier(specifier, importer, outputDir, (candidate) => jsAssets.has(candidate));
895
- },
896
- load: (id) => {
897
- const assetName = jsAssets.get(id);
898
- if (!assetName) return;
899
- const asset = compilation.getAsset(assetName);
900
- if (!asset) return;
901
- const source = asset.source.source();
902
- return typeof source === "string" ? source : source.toString();
903
- },
904
- filter(id) {
905
- return jsAssets.has(id);
906
- }
907
- };
908
- const applyLinkedResults = (linked) => {
909
- if (!linked) return;
910
- for (const [id, { code }] of Object.entries(linked)) {
911
- const assetName = jsAssets.get(id);
912
- if (!assetName) continue;
913
- const asset = compilation.getAsset(assetName);
914
- if (!asset) continue;
915
- const previousSource = asset.source.source();
916
- if ((typeof previousSource === "string" ? previousSource : previousSource.toString()) === code) continue;
917
- if (updateAssetIfChanged(assetName, new ConcatSource(code))) debug("js linked handle: %s", assetName);
918
- }
919
- };
920
- const watchMode = isWatchMode?.() === true;
921
- const cssAssetResources = createWebpackCssAssetResourceMap(compilation.chunks, compilation.chunkGraph, compilerOptions.cssMatcher, (resource, issuer) => {
922
- if (!isCssLikeModuleResource(resource, compilerOptions.cssMatcher, appType)) return;
923
- const normalized = stripResourceQuery(resource);
924
- if (!normalized) return;
925
- if (path.isAbsolute(normalized)) return path.resolve(normalized);
926
- const issuerResource = issuer?.resource ? stripResourceQuery(issuer.resource) : void 0;
927
- const issuerContext = issuerResource && path.isAbsolute(issuerResource) ? path.dirname(issuerResource) : issuer?.context;
928
- return issuerContext ? path.resolve(issuerContext, normalized) : void 0;
1321
+ const { jsAssets, moduleGraphOptions } = createWebpackJsAssetModuleGraph({
1322
+ compilation,
1323
+ compilerOptions,
1324
+ entries,
1325
+ outputDir
929
1326
  });
1327
+ const watchMode = isWatchMode?.() === true;
1328
+ const cssAssetResources = createWebpackCssAssetResourceMap(compilation.chunks, compilation.chunkGraph, compilerOptions.cssMatcher, (resource, issuer) => resolveWebpackCssAssetModuleResource(resource, issuer, {
1329
+ appType,
1330
+ cssMatcher: compilerOptions.cssMatcher
1331
+ }));
930
1332
  const watchChangedFiles = new Set([...getWatchChangedFiles?.() ?? []].map((file) => path.resolve(file)));
931
1333
  const taskConcurrency = watchMode ? resolveTaskConcurrency(1) : void 0;
932
1334
  const activeProcessCacheKeys = /* @__PURE__ */ new Set();
@@ -940,215 +1342,43 @@ function setupWebpackV5ProcessAssetsHook(options) {
940
1342
  for (const chunk of compilation.chunks) if (chunk.id) activeProcessHashKeys.add(chunk.id);
941
1343
  const cssSources = new Map([...getWebpackCssSources?.() ?? []].map(([file, source]) => [path.resolve(file), source]));
942
1344
  const generatedCssSources = new Map([...getWebpackGeneratedCssSources?.() ?? []].map(([file, source]) => [path.resolve(file), source]));
943
- const hasConfiguredTailwindV4SourceRoots = () => {
944
- const tailwindOptions = resolveTailwindcssOptions(runtimeState.tailwindRuntime.options);
945
- return (tailwindOptions?.v4?.cssEntries?.length ?? 0) > 0 || (tailwindOptions?.v4?.cssSources?.length ?? 0) > 0;
946
- };
947
- const configuredMainCssEntryFiles = (() => {
948
- return [...resolveTailwindcssOptions(runtimeState.tailwindRuntime.options)?.v4?.cssEntries ?? []].filter((file) => typeof file === "string" && file.length > 0).map((file) => path.resolve(file));
949
- })();
950
- const inferredMainCssFiles = inferWebpackMainCssFiles(compilation.chunks, compilerOptions.cssMatcher, {
951
- mainSourceFiles: new Set(configuredMainCssEntryFiles),
952
- resourcesByAsset: cssAssetResources
1345
+ const { activeWebpackCssSourceFiles, configuredMainCssEntryFiles, getCssHandlerOptions, getCssUserHandlerOptions, hasConfiguredTailwindV4SourceRoots, isSameWebpackSourceScope, resolveWebpackCssSourceFile } = createWebpackCssSourceResolvers({
1346
+ activeWebpackAssetResourceFiles,
1347
+ appType,
1348
+ compilerOptions,
1349
+ compilation,
1350
+ cssAssetResources,
1351
+ cssHandlerOptionsCache,
1352
+ cssSources,
1353
+ cssUserHandlerOptionsCache,
1354
+ groupedCssEntriesLength: groupedEntries.css.length,
1355
+ singleCssAssetFile: groupedEntries.css[0]?.[0],
1356
+ isWebGeneratorTarget,
1357
+ outputDir,
1358
+ runtimeState
953
1359
  });
954
- const singleConfiguredCssAsset = isWebGeneratorTarget && configuredMainCssEntryFiles.length > 0 && (groupedEntries.css?.length ?? 0) === 1 ? groupedEntries.css?.[0]?.[0] : void 0;
955
- const isMainCssChunk = (file) => compilerOptions.mainCssChunkMatcher(file, appType) || inferredMainCssFiles.has(file) || file === singleConfiguredCssAsset;
956
- const activeWebpackCssSourceFiles = /* @__PURE__ */ new Set();
957
- const resolveConfiguredMainCssSourceFile = (file) => {
958
- if (!isMainCssChunk(file)) return;
959
- for (const sourceFile of configuredMainCssEntryFiles) if (cssSources.has(sourceFile)) {
960
- activeWebpackCssSourceFiles.add(sourceFile);
961
- return sourceFile;
962
- }
963
- };
964
- const resolveWebpackCssSourceFile = (file, rawSource) => {
965
- const assetResources = cssAssetResources.get(file);
966
- const activeAssetResource = resolveSingleActiveWebpackCssResource(assetResources, activeWebpackAssetResourceFiles);
967
- if (cssSources.size === 0) {
968
- if (activeAssetResource) {
969
- activeWebpackCssSourceFiles.add(activeAssetResource);
970
- return activeAssetResource;
971
- }
972
- if (assetResources && assetResources.size > 0) return;
973
- return resolveConfiguredMainCssSourceFile(file);
974
- }
975
- const resourceMatches = [...assetResources ?? []].filter((sourceFile) => cssSources.has(sourceFile)).sort();
976
- if (resourceMatches.length === 1) {
977
- const sourceFile = resourceMatches[0];
978
- activeWebpackCssSourceFiles.add(sourceFile);
979
- return sourceFile;
980
- }
981
- const tailwindSourceMatches = resourceMatches.filter((sourceFile) => {
982
- const sourceCss = cssSources.get(sourceFile)?.css;
983
- return sourceCss && (hasTailwindRootDirectives(sourceCss, { importFallback: true }) || hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || hasTailwindApplyDirective(sourceCss) || hasTailwindGeneratedCss(sourceCss) || hasTailwindGeneratedCssMarkers(sourceCss));
984
- });
985
- if (tailwindSourceMatches.length === 1) {
986
- const sourceFile = tailwindSourceMatches[0];
987
- activeWebpackCssSourceFiles.add(sourceFile);
988
- return sourceFile;
989
- }
990
- if (activeAssetResource) {
991
- activeWebpackCssSourceFiles.add(activeAssetResource);
992
- return activeAssetResource;
993
- }
994
- if (rawSource) {
995
- const representedTailwindSourceMatches = [...cssSources.entries()].filter(([, source]) => isWebpackCssSourceRepresentedInAsset(rawSource, source.css)).map(([sourceFile]) => ({
996
- sourceFile,
997
- score: scoreTailwindV4CssSourceFileMatch(file, sourceFile, {
998
- outputRoot: outputDir,
999
- projectRoot: compilerOptions.tailwindcssBasedir,
1000
- cwd: compilerOptions.tailwindcssBasedir
1001
- })
1002
- })).filter((match) => match.score > 0).sort((a, b) => b.score - a.score || a.sourceFile.localeCompare(b.sourceFile));
1003
- const bestScore = representedTailwindSourceMatches[0]?.score ?? 0;
1004
- const bestMatches = representedTailwindSourceMatches.filter((match) => match.score === bestScore);
1005
- if (bestMatches.length === 1) {
1006
- const sourceFile = bestMatches[0]?.sourceFile;
1007
- activeWebpackCssSourceFiles.add(sourceFile);
1008
- return sourceFile;
1009
- }
1010
- }
1011
- const pathMatches = [...cssSources.keys()].map((sourceFile) => ({
1012
- sourceFile,
1013
- score: scoreTailwindV4CssSourceFileMatch(file, sourceFile, {
1014
- outputRoot: outputDir,
1015
- projectRoot: compilerOptions.tailwindcssBasedir,
1016
- cwd: compilerOptions.tailwindcssBasedir
1017
- })
1018
- })).filter((match) => match.score >= 1e3).sort((a, b) => b.score - a.score || a.sourceFile.localeCompare(b.sourceFile));
1019
- const bestPathScore = pathMatches[0]?.score ?? 0;
1020
- const bestPathMatches = pathMatches.filter((match) => match.score === bestPathScore);
1021
- if (bestPathMatches.length === 1) {
1022
- const sourceFile = bestPathMatches[0]?.sourceFile;
1023
- activeWebpackCssSourceFiles.add(sourceFile);
1024
- return sourceFile;
1025
- }
1026
- if (assetResources && assetResources.size > 0) return;
1027
- return resolveConfiguredMainCssSourceFile(file);
1028
- };
1029
- const isSameWebpackSourceScope = (outputFile, candidateSourceFile, currentSourceFile) => {
1030
- if (!currentSourceFile) return false;
1031
- if (path.resolve(candidateSourceFile) === path.resolve(currentSourceFile)) return true;
1032
- const candidateKey = path.resolve(candidateSourceFile);
1033
- return cssAssetResources.get(outputFile)?.has(candidateKey) === true;
1034
- };
1035
- const getCssHandlerOptions = (file, rawSource) => {
1036
- const majorVersion = runtimeState.tailwindRuntime.majorVersion;
1037
- const isMainChunk = isMainCssChunk(file);
1038
- const sourceFile = resolveWebpackCssSourceFile(file, rawSource);
1039
- const sourceCss = sourceFile ? cssSources.get(sourceFile)?.css : void 0;
1040
- const generatorSourceCss = removeWebpackGeneratorNonTailwindImports(sourceCss);
1041
- const generatorCssSource = createWebpackGeneratorCssSource(sourceFile, generatorSourceCss);
1042
- const cacheKey = [
1043
- majorVersion ?? "unknown",
1044
- isMainChunk ? "1" : "0",
1045
- sourceFile ?? "asset",
1046
- sourceCss === void 0 ? "source:0" : compilerOptions.cache.computeHash(sourceCss),
1047
- generatorSourceCss === sourceCss || generatorSourceCss === void 0 ? "generator-source:0" : compilerOptions.cache.computeHash(generatorSourceCss),
1048
- file
1049
- ].join(":");
1050
- const cached = cssHandlerOptionsCache.get(cacheKey);
1051
- if (cached) return cached;
1052
- const created = {
1053
- isMainChunk,
1054
- postcssOptions: { options: { from: sourceFile ?? file } },
1055
- sourceOptions: {
1056
- outputRoot: outputDir,
1057
- ...generatorCssSource === void 0 ? {} : { cssSources: [generatorCssSource] },
1058
- ...generatorSourceCss === void 0 ? {} : { sourceCss: generatorSourceCss },
1059
- ...sourceFile === void 0 ? {} : { sourceFile }
1060
- },
1061
- ...majorVersion === void 0 ? {} : { majorVersion }
1062
- };
1063
- cssHandlerOptionsCache.set(cacheKey, created);
1064
- return created;
1065
- };
1066
- const getCssUserHandlerOptions = (file) => {
1067
- const majorVersion = runtimeState.tailwindRuntime.majorVersion;
1068
- const sourceFile = resolveWebpackCssSourceFile(file);
1069
- const sourceCss = sourceFile ? cssSources.get(sourceFile)?.css : void 0;
1070
- const generatorSourceCss = removeWebpackGeneratorNonTailwindImports(sourceCss);
1071
- const cacheKey = [
1072
- majorVersion ?? "unknown",
1073
- sourceFile ?? "asset",
1074
- sourceCss === void 0 ? "source:0" : compilerOptions.cache.computeHash(sourceCss),
1075
- generatorSourceCss === sourceCss || generatorSourceCss === void 0 ? "generator-source:0" : compilerOptions.cache.computeHash(generatorSourceCss),
1076
- file
1077
- ].join(":");
1078
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
1079
- if (cached) return cached;
1080
- const created = {
1081
- ...getCssHandlerOptions(file),
1082
- isMainChunk: false
1083
- };
1084
- cssUserHandlerOptionsCache.set(cacheKey, created);
1085
- return created;
1086
- };
1087
- const refreshWebpackSourceCandidates = async () => {
1088
- const root = compilerOptions.tailwindcssBasedir ?? process.cwd();
1089
- let sourceScan;
1090
- try {
1091
- sourceScan = await resolveViteSourceScanEntries(compilerOptions, runtimeState.tailwindRuntime, {
1092
- root,
1093
- outDir: outputDir
1094
- });
1095
- } catch (error) {
1096
- debug("webpack source candidate scan skipped: %O", error);
1097
- return;
1098
- }
1099
- return webpackSourceCandidateScanCache.resolve({
1100
- changedFiles: watchChangedFiles,
1101
- collector: createSourceCandidateStore({ bareArbitraryValues: compilerOptions.arbitraryValues?.bareArbitraryValues }),
1102
- outDir: outputDir,
1103
- root,
1104
- sourceScan,
1105
- watchMode
1106
- });
1107
- };
1108
- const finalizeCssAssetSource = (source, options = {}) => {
1109
- const styleOptions = resolveStyleOptionsFromContext(compilerOptions);
1110
- if (isWebGeneratorTarget) {
1111
- if (options.generatedCss === true) return stripTrailingLineWhitespace(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(stripBundlerGeneratedCssMarkers(source))));
1112
- return stripTrailingLineWhitespace(stripUnmatchedTailwindSourceMediaCloseFragments(stripTailwindSourceMediaFragments(removeTailwindV4GeneratorAtRules(removeTailwindSourceDirectives(stripBundlerGeneratedCssMarkers(source), { importFallback: true })))));
1113
- }
1114
- let finalized = removeTailwindSourceDirectives(stripBundlerGeneratedCssMarkers(source), { importFallback: true });
1115
- if (isWebGeneratorTarget || options.generatedCss !== true) return isWebGeneratorTarget ? finalized : stripMiniProgramCssSpecificityPlaceholders(removeMiniProgramHoverSelectors(finalized, styleOptions.cssRemoveHoverPseudoClass));
1116
- try {
1117
- finalized = pruneMiniProgramGeneratedCss(finalized, { preservePreflight: true });
1118
- } catch {
1119
- finalized = finalizeMiniProgramCss(finalized, {
1120
- cssPreflight: !hasMiniProgramTailwindV4PreflightReset(finalized) ? compilerOptions.cssPreflight : void 0,
1121
- isTailwindcssV4: true,
1122
- tailwindcssV4GradientFallback: styleOptions.tailwindcssV4GradientFallback
1123
- });
1124
- }
1125
- return stripMiniProgramCssSpecificityPlaceholders(removeMiniProgramHoverSelectors(finalized, styleOptions.cssRemoveHoverPseudoClass));
1126
- };
1127
- const finalizeMiniProgramUserCssAssetSource = (source, options = {}) => {
1128
- const styleOptions = resolveStyleOptionsFromContext(compilerOptions);
1129
- if (isWebGeneratorTarget) return source;
1130
- return stripMiniProgramCssSpecificityPlaceholders(removeTailwindV4StandaloneHostPreflightRule(finalizeMiniProgramCss(removeMiniProgramHoverSelectors(source, styleOptions.cssRemoveHoverPseudoClass), {
1131
- cssPreflight: options.cssPreflight !== false && !hasMiniProgramTailwindV4PreflightReset(source) ? compilerOptions.cssPreflight : void 0,
1132
- isTailwindcssV4: true,
1133
- tailwindcssV4GradientFallback: styleOptions.tailwindcssV4GradientFallback
1134
- })));
1135
- };
1136
- const webpackSourceCandidates = !isWebGeneratorTarget && (groupedEntries.css?.length ?? 0) > 0 || cssSources.size > 0 || generatedCssSources.size > 0 || isCssSourceTraceEnabled(compilerOptions) ? await refreshWebpackSourceCandidates() : void 0;
1360
+ const finalizeCssAssetSource = (source, options = {}) => finalizeWebpackCssAssetSource(source, compilerOptions, isWebGeneratorTarget, options);
1361
+ const webpackSourceCandidates = !isWebGeneratorTarget && groupedEntries.css.length > 0 || cssSources.size > 0 || generatedCssSources.size > 0 || isCssSourceTraceEnabled(compilerOptions) ? await refreshWebpackSourceCandidates({
1362
+ compilerOptions,
1363
+ debug,
1364
+ outputDir,
1365
+ runtimeState,
1366
+ scanCache: webpackSourceCandidateScanCache,
1367
+ watchChangedFiles,
1368
+ watchMode
1369
+ }) : void 0;
1137
1370
  const webpackSourceCandidateValueSignature = webpackSourceCandidates ? createCandidateSignature(webpackSourceCandidates.getSourceCandidatesForEntries(void 0)) : "source-candidates:0";
1138
- const cssSourceTraceTokenSources = isCssSourceTraceEnabled(compilerOptions) && webpackSourceCandidates ? createCssTokenSourceMap(webpackSourceCandidates.tokenSources, compilerOptions) : void 0;
1371
+ const cssSourceTraceTokenSources = createWebpackCssSourceTraceTokenSources(compilerOptions, webpackSourceCandidates);
1139
1372
  const cssSourceTraceSignature = createCssSourceTraceCacheSignature(cssSourceTraceTokenSources, compilerOptions);
1140
1373
  const annotateCss = (css) => annotateCssSourceTrace(css, {
1141
1374
  opts: compilerOptions,
1142
1375
  tokenSources: cssSourceTraceTokenSources
1143
1376
  });
1144
- const shouldInjectCssTracePreflight = (cssHandlerOptions) => {
1145
- return compilerOptions.appType !== "mpx" || cssHandlerOptions.isMainChunk !== false;
1146
- };
1147
- const finalizeTracedCss = (css, cssHandlerOptions) => {
1148
- const traced = annotateCss(css);
1149
- if (isWebGeneratorTarget || !isCssSourceTraceEnabled(compilerOptions)) return traced;
1150
- return finalizeMiniProgramUserCssAssetSource(traced, { cssPreflight: shouldInjectCssTracePreflight(cssHandlerOptions) });
1151
- };
1377
+ const finalizeTracedCss = (css, cssHandlerOptions) => finalizeTracedWebpackCssAsset(css, cssHandlerOptions, {
1378
+ annotateCss,
1379
+ compilerOptions,
1380
+ isWebGeneratorTarget
1381
+ });
1152
1382
  const hasRuntimeTransformAssets = Boolean(!isWebGeneratorTarget && ((groupedEntries.html?.length ?? 0) > 0 || (groupedEntries.js?.length ?? 0) > 0));
1153
1383
  const forceRuntimeRefresh = getRuntimeRefreshRequirement();
1154
1384
  debug("processAssets ensure runtime set forceRefresh=%s major=%s", forceRuntimeRefresh, runtimeState.tailwindRuntime.majorVersion ?? "unknown");
@@ -1156,15 +1386,11 @@ function setupWebpackV5ProcessAssetsHook(options) {
1156
1386
  let runtimeAffectingSourceHash = "runtime-affecting:0";
1157
1387
  if (isWebGeneratorTarget && !hasRuntimeTransformAssets && !forceRuntimeRefresh) runtimeSet = getRuntimeClassSetSync(runtimeState.tailwindRuntime);
1158
1388
  else if (watchMode && !forceRuntimeRefresh) {
1159
- const shouldSkipInitialRuntimeBundleScan = isWebGeneratorTarget && !webpackWatchRuntimeScanInitialized;
1160
1389
  const baseRuntimeSet = getRuntimeClassSetSync(runtimeState.tailwindRuntime);
1161
1390
  const snapshot = buildWebpackBundleSnapshot(assets, compilerOptions, bundleBuildState, compilation);
1162
- if (!webpackWatchRuntimeScanInitialized && !shouldSkipInitialRuntimeBundleScan) {
1163
- for (const entry of snapshot.entries) if (entry.type === "html" || entry.type === "js") snapshot.runtimeAffectingChangedByType[entry.type].add(entry.file);
1164
- }
1165
- runtimeAffectingSourceHash = compilerOptions.cache.computeHash([...(groupedEntries.html ?? []).map(([file, source]) => `${file}:${compilerOptions.cache.computeHash(source.source().toString())}`), ...(groupedEntries.js ?? []).map(([file, source]) => `${file}:${compilerOptions.cache.computeHash(source.source().toString())}`)].sort().join("\n\n"));
1166
- if (shouldSkipInitialRuntimeBundleScan) runtimeSet = baseRuntimeSet;
1167
- else try {
1391
+ if (!webpackWatchRuntimeScanInitialized) for (const entry of snapshot.entries) snapshot.runtimeAffectingChangedByType[entry.type].add(entry.file);
1392
+ runtimeAffectingSourceHash = compilerOptions.cache.computeHash([...groupedEntries.html.map(([file, source]) => `${file}:${compilerOptions.cache.computeHash(source.source().toString())}`), ...groupedEntries.js.map(([file, source]) => `${file}:${compilerOptions.cache.computeHash(source.source().toString())}`)].sort().join("\n\n"));
1393
+ try {
1168
1394
  runtimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.tailwindRuntime, snapshot, {
1169
1395
  baseClassSet: baseRuntimeSet,
1170
1396
  skipInitialFullScanWithBase: false
@@ -1193,49 +1419,38 @@ function setupWebpackV5ProcessAssetsHook(options) {
1193
1419
  consumeRuntimeRefreshRequirement();
1194
1420
  const webpackSourceCandidateSet = webpackSourceCandidates?.getSourceCandidatesForEntries(void 0);
1195
1421
  const generatorRuntimeSet = new Set(runtimeSet);
1196
- if (webpackSourceCandidateSet?.size) {
1197
- for (const candidate of webpackSourceCandidateSet) if (isRuntimeTransformCandidate(candidate)) generatorRuntimeSet.add(candidate);
1198
- }
1422
+ addRuntimeTransformCandidates(generatorRuntimeSet, webpackSourceCandidateSet);
1199
1423
  const transformRuntimeSet = new Set(runtimeSet);
1200
- if (hasRuntimeTransformAssets && Array.isArray(groupedEntries.css)) for (const [, originalSource] of groupedEntries.css) for (const candidate of collectGeneratedCssRuntimeCandidates(originalSource.source().toString())) transformRuntimeSet.add(candidate);
1424
+ if (hasRuntimeTransformAssets) for (const [, originalSource] of groupedEntries.css) for (const candidate of collectGeneratedCssRuntimeCandidates(originalSource.source().toString())) transformRuntimeSet.add(candidate);
1201
1425
  const transformedJsRuntimeCandidates = /* @__PURE__ */ new Set();
1202
1426
  let currentJsRuntimeCandidates;
1203
1427
  let currentJsRuntimeTokenSignature;
1428
+ const getWebpackAssetSource = (file) => {
1429
+ return compilation.getAsset(file)?.source;
1430
+ };
1204
1431
  const getCurrentJsRuntimeCandidates = () => {
1205
- if (isWebGeneratorTarget) return;
1206
1432
  if (currentJsRuntimeCandidates) return currentJsRuntimeCandidates;
1207
- currentJsRuntimeCandidates = /* @__PURE__ */ new Set();
1208
- for (const file of jsAssets.values()) {
1209
- const asset = compilation.getAsset(file);
1210
- if (!asset) continue;
1211
- const value = asset.source.source();
1212
- const source = typeof value === "string" ? value : value.toString();
1213
- for (const candidate of collectStrictEscapedRuntimeCandidates(source, MappingChars2String, escapeFragments)) if (isRuntimeTransformCandidate(candidate)) currentJsRuntimeCandidates.add(candidate);
1214
- }
1433
+ currentJsRuntimeCandidates = collectWebpackJsRuntimeCandidatesFromAssets({
1434
+ escapeFragments,
1435
+ getAssetSource: getWebpackAssetSource,
1436
+ isWebGeneratorTarget,
1437
+ jsAssets: jsAssets.values()
1438
+ });
1215
1439
  return currentJsRuntimeCandidates;
1216
1440
  };
1217
1441
  const getCurrentJsRuntimeTokenSignature = () => {
1218
1442
  if (currentJsRuntimeTokenSignature !== void 0) return currentJsRuntimeTokenSignature;
1219
- if (isWebGeneratorTarget) {
1220
- currentJsRuntimeTokenSignature = "";
1221
- return currentJsRuntimeTokenSignature;
1222
- }
1223
- const tokens = [];
1224
- for (const file of jsAssets.values()) {
1225
- const asset = compilation.getAsset(file);
1226
- if (!asset) continue;
1227
- const value = asset.source.source();
1228
- const source = typeof value === "string" ? value : value.toString();
1229
- tokens.push(...collectRuntimeTokenSignatureParts(source));
1230
- }
1231
- currentJsRuntimeTokenSignature = tokens.sort().join("\n");
1443
+ currentJsRuntimeTokenSignature = collectWebpackJsRuntimeTokenSignature({
1444
+ getAssetSource: getWebpackAssetSource,
1445
+ isWebGeneratorTarget,
1446
+ jsAssets: jsAssets.values()
1447
+ });
1232
1448
  return currentJsRuntimeTokenSignature;
1233
1449
  };
1234
1450
  const rememberTransformedRuntimeCandidates = (source) => {
1235
1451
  currentJsRuntimeCandidates = void 0;
1236
1452
  currentJsRuntimeTokenSignature = void 0;
1237
- const value = typeof source === "string" ? source : source.source();
1238
- const code = typeof value === "string" ? value : value.toString();
1453
+ const code = stringifyWebpackSourceLike(source);
1239
1454
  for (const candidate of collectStrictEscapedRuntimeCandidates(code, MappingChars2String, escapeFragments)) if (isRuntimeTransformCandidate(candidate)) transformedJsRuntimeCandidates.add(candidate);
1240
1455
  };
1241
1456
  const createRuntimeSetHash = (generatorRuntimeSet) => compilerOptions.cache.computeHash([
@@ -1248,11 +1463,10 @@ function setupWebpackV5ProcessAssetsHook(options) {
1248
1463
  const getGeneratorRuntimeSet = () => {
1249
1464
  const currentJsCandidates = getCurrentJsRuntimeCandidates();
1250
1465
  if (transformedJsRuntimeCandidates.size === 0 && (!currentJsCandidates || currentJsCandidates.size === 0)) return generatorRuntimeSet;
1251
- return new Set([
1252
- ...generatorRuntimeSet,
1253
- ...currentJsCandidates ?? [],
1254
- ...transformedJsRuntimeCandidates
1255
- ]);
1466
+ const nextRuntimeSet = new Set(generatorRuntimeSet);
1467
+ for (const candidate of currentJsCandidates) nextRuntimeSet.add(candidate);
1468
+ for (const candidate of transformedJsRuntimeCandidates) nextRuntimeSet.add(candidate);
1469
+ return nextRuntimeSet;
1256
1470
  };
1257
1471
  const defaultTemplateHandlerOptions = { runtimeSet: transformRuntimeSet };
1258
1472
  debug("get runtimeSet, class count: %d, transform class count: %d", runtimeSet.size, transformRuntimeSet.size);
@@ -1312,21 +1526,15 @@ function setupWebpackV5ProcessAssetsHook(options) {
1312
1526
  const hashKey = `${file}:asset`;
1313
1527
  rememberProcessCacheKey(cacheKey, hashKey);
1314
1528
  const absoluteFile = toAbsoluteOutputPath(file, outputDir);
1315
- let initialRawSource;
1316
- const readInitialRawSource = () => {
1317
- if (initialRawSource === void 0) {
1318
- const initialSource = asset.source.source();
1319
- initialRawSource = typeof initialSource === "string" ? initialSource : initialSource.toString();
1320
- }
1321
- return initialRawSource;
1322
- };
1529
+ const initialSource = asset.source.source();
1530
+ const initialRawSource = typeof initialSource === "string" ? initialSource : initialSource.toString();
1323
1531
  const chunkHash = assetHashByChunk.get(file);
1324
1532
  await enqueueJsTask(async () => {
1325
1533
  await processCachedTask({
1326
1534
  cache: compilerOptions.cache,
1327
1535
  cacheKey,
1328
1536
  hashKey,
1329
- rawSource: chunkHash === void 0 ? readInitialRawSource() : void 0,
1537
+ rawSource: chunkHash === void 0 ? initialRawSource : void 0,
1330
1538
  hash: chunkHash,
1331
1539
  applyResult(source, { cacheHit }) {
1332
1540
  if (updateAssetIfChanged(file, source, {
@@ -1339,7 +1547,7 @@ function setupWebpackV5ProcessAssetsHook(options) {
1339
1547
  },
1340
1548
  transform: async () => {
1341
1549
  const currentSourceValue = compilation.getAsset(file)?.source.source();
1342
- const currentSource = typeof currentSourceValue === "string" ? currentSourceValue : currentSourceValue?.toString() ?? "";
1550
+ const currentSource = stringifyOptionalWebpackSourceValue(currentSourceValue);
1343
1551
  const handlerOptions = {
1344
1552
  tailwindcssMajorVersion: runtimeState.tailwindRuntime.majorVersion,
1345
1553
  generateMap: false,
@@ -1354,13 +1562,20 @@ function setupWebpackV5ProcessAssetsHook(options) {
1354
1562
  const { code, linked } = await compilerOptions.jsHandler(currentSource, transformRuntimeSet, handlerOptions);
1355
1563
  const source = new ConcatSource(code);
1356
1564
  debug("js handle: %s", file);
1357
- applyLinkedResults(linked);
1565
+ applyWebpackLinkedJsResults({
1566
+ ConcatSource,
1567
+ compilation,
1568
+ compilerOptions,
1569
+ debug,
1570
+ jsAssets,
1571
+ linked
1572
+ });
1358
1573
  return { result: source };
1359
1574
  }
1360
1575
  });
1361
1576
  });
1362
1577
  }
1363
- if (Array.isArray(groupedEntries.css)) for (const element of groupedEntries.css) {
1578
+ for (const element of groupedEntries.css) {
1364
1579
  const [file, originalSource] = element;
1365
1580
  let rawSource;
1366
1581
  const readRawSource = () => {
@@ -1375,7 +1590,8 @@ function setupWebpackV5ProcessAssetsHook(options) {
1375
1590
  const shouldRegenerateProcessedTailwindV4SourceCss = processedSourceCss !== void 0 && (hasTailwindSourceDirectives(processedSourceCss, { importFallback: true }) || processedSourceCss.includes("@config"));
1376
1591
  const processedCssAssetKnown = isKnownWebpackProcessedCssAsset?.(file, processedCssAssetMetadata) === true;
1377
1592
  const processedLoaderGeneratedCss = processedSourceFile ? generatedCssSources.get(path.resolve(processedSourceFile)) : void 0;
1378
- const processedCssDecisionCacheKey = `${file}:${createRuntimeAwareCssHash(chunkHash, chunkHash === void 0 ? void 0 : "webpack-css-asset:chunk", `${createRuntimeSetHash(getGeneratorRuntimeSet())}:${runtimeAffectingSourceHash}:${webpackSourceCandidates?.signatureHash ?? "source-candidates:0"}:${webpackSourceCandidateValueSignature}:${cssSourceTraceSignature}`) ?? "hash:0"}`;
1593
+ const processedAssetSourceHash = watchMode && isWebGeneratorTarget && cssHandlerOptionsForProcessedAsset.isMainChunk ? compilerOptions.cache.computeHash(readRawSource()) : chunkHash === void 0 ? processedCssAssetKnown ? "webpack-css-asset:known" : compilerOptions.cache.computeHash(readRawSource()) : "webpack-css-asset:chunk";
1594
+ const processedCssDecisionCacheKey = `${file}:${createRuntimeAwareCssHash(chunkHash, processedAssetSourceHash, `${createRuntimeSetHash(getGeneratorRuntimeSet())}:${runtimeAffectingSourceHash}:${webpackSourceCandidates?.signatureHash ?? "source-candidates:0"}:${webpackSourceCandidateValueSignature}:${cssSourceTraceSignature}`)}`;
1379
1595
  let currentProcessedRawSource;
1380
1596
  let hasGeneratedCssMarker = false;
1381
1597
  let hasTailwindGeneratedAssetCss = false;
@@ -1383,8 +1599,8 @@ function setupWebpackV5ProcessAssetsHook(options) {
1383
1599
  currentProcessedRawSource ?? (currentProcessedRawSource = readRawSource());
1384
1600
  return currentProcessedRawSource;
1385
1601
  };
1386
- const shouldRegenerateStaleProcessedWebCssAsset = isWebGeneratorTarget && cssHandlerOptionsForProcessedAsset.isMainChunk && webpackSourceCandidateSet !== void 0 && (hasMissingRuntimeCandidates(processedLoaderGeneratedCss?.classSet, webpackSourceCandidateSet) || hasMissingRuntimeCandidates(resolveGeneratedCssRuntimeCandidates(readCurrentProcessedRawSource(), processedLoaderGeneratedCss?.classSet), webpackSourceCandidateSet));
1387
1602
  const cachedSkipProcessedCssAsset = processedCssAssetKnown ? processedCssAssetSkipDecisionCache.get(processedCssDecisionCacheKey) : void 0;
1603
+ const shouldRegenerateStaleProcessedWebCssAsset = isWebGeneratorTarget && !processedCssAssetKnown && cachedSkipProcessedCssAsset === void 0 && cssHandlerOptionsForProcessedAsset.isMainChunk && webpackSourceCandidateSet !== void 0 && (hasMissingRuntimeCandidates(processedLoaderGeneratedCss?.classSet, webpackSourceCandidateSet) || hasMissingRuntimeCandidates(resolveGeneratedCssRuntimeCandidates(readCurrentProcessedRawSource(), processedLoaderGeneratedCss?.classSet), webpackSourceCandidateSet));
1388
1604
  if (cachedSkipProcessedCssAsset !== void 0) {
1389
1605
  hasGeneratedCssMarker = cachedSkipProcessedCssAsset && cssHandlerOptionsForProcessedAsset.isMainChunk;
1390
1606
  hasTailwindGeneratedAssetCss = hasGeneratedCssMarker;
@@ -1393,7 +1609,11 @@ function setupWebpackV5ProcessAssetsHook(options) {
1393
1609
  hasGeneratedCssMarker = hasBundlerGeneratedCssMarker(source);
1394
1610
  hasTailwindGeneratedAssetCss = hasTailwindGeneratedCss(source) || hasTailwindGeneratedCssMarkers(source);
1395
1611
  }
1396
- const shouldForceConfiguredMainCssGeneration = cssHandlerOptionsForProcessedAsset.isMainChunk && hasConfiguredTailwindV4SourceRoots() && !hasGeneratedCssMarker;
1612
+ const hasProcessedAssetTailwindDirectives = () => {
1613
+ const source = readCurrentProcessedRawSource();
1614
+ return hasTailwindRootDirectives(source, { importFallback: true }) || hasTailwindSourceDirectives(source, { importFallback: true }) || hasTailwindApplyDirective(source);
1615
+ };
1616
+ const shouldForceConfiguredMainCssGeneration = cssHandlerOptionsForProcessedAsset.isMainChunk && hasConfiguredTailwindV4SourceRoots() && !hasGeneratedCssMarker && (configuredMainCssEntryFiles.length > 0 || shouldRegenerateProcessedTailwindV4SourceCss || hasProcessedAssetTailwindDirectives());
1397
1617
  const hasProcessedMainAssetUserCss = cachedSkipProcessedCssAsset === void 0 && cssHandlerOptionsForProcessedAsset.isMainChunk && (hasGeneratedCssMarker || hasTailwindGeneratedAssetCss) && createWebpackUserCssSourceAppend([...cssSources.entries()].map(([sourceFile, source]) => ({
1398
1618
  ...source,
1399
1619
  file: sourceFile
@@ -1402,17 +1622,17 @@ function setupWebpackV5ProcessAssetsHook(options) {
1402
1622
  const shouldPreserveFinalWebCssAsset = isWebGeneratorTarget && processedSourceFile === void 0 && !shouldForceConfiguredMainCssGeneration && (hasGeneratedCssMarker || hasTailwindGeneratedAssetCss);
1403
1623
  const shouldSkipKnownProcessedCssAsset = !shouldForceConfiguredMainCssGeneration && !shouldRegenerateProcessedTailwindV4SourceCss && !shouldRegenerateStaleProcessedWebCssAsset && (processedCssAssetKnown || isWebpackProcessedCssAsset?.(file, readCurrentProcessedRawSource(), processedCssAssetMetadata)) && !hasProcessedMainAssetUserCss && (!cssHandlerOptionsForProcessedAsset.isMainChunk || hasGeneratedCssMarker || hasTailwindGeneratedAssetCss);
1404
1624
  const shouldSkipProcessedCssAsset = cachedSkipProcessedCssAsset ?? (shouldFinalizeProcessedWebCssAsset || shouldPreserveFinalWebCssAsset || shouldSkipKnownProcessedCssAsset);
1405
- if (processedCssAssetKnown && cachedSkipProcessedCssAsset === void 0 && !shouldFinalizeProcessedWebCssAsset && !shouldPreserveFinalWebCssAsset) processedCssAssetSkipDecisionCache.set(processedCssDecisionCacheKey, shouldSkipProcessedCssAsset);
1625
+ if (processedCssAssetKnown && cachedSkipProcessedCssAsset === void 0 && !shouldFinalizeProcessedWebCssAsset && !shouldPreserveFinalWebCssAsset) processedCssAssetSkipDecisionCache.set(processedCssDecisionCacheKey, shouldSkipProcessedCssAsset === true);
1406
1626
  if (shouldSkipProcessedCssAsset) {
1407
1627
  const hashKey = `${file}:asset`;
1408
- const sourceHash = chunkHash === void 0 ? compilerOptions.cache.computeHash(readCurrentProcessedRawSource()) : "webpack-css-asset:chunk";
1628
+ const sourceHash = processedAssetSourceHash;
1409
1629
  rememberProcessCacheKey(file, hashKey);
1410
1630
  await enqueueTask(async () => {
1411
1631
  await processCachedTask({
1412
1632
  cache: compilerOptions.cache,
1413
1633
  cacheKey: file,
1414
1634
  hashKey,
1415
- rawSource: chunkHash === void 0 ? readCurrentProcessedRawSource() : void 0,
1635
+ rawSource: chunkHash === void 0 && !processedCssAssetKnown ? readCurrentProcessedRawSource() : void 0,
1416
1636
  hash: createRuntimeAwareCssHash(chunkHash, sourceHash, `${createRuntimeSetHash(getGeneratorRuntimeSet())}:${runtimeAffectingSourceHash}:${webpackSourceCandidates?.signatureHash ?? "source-candidates:0"}:${webpackSourceCandidateValueSignature}:${cssSourceTraceSignature}`),
1417
1637
  applyResult(source, { cacheHit }) {
1418
1638
  updateAssetIfChanged(file, source, {
@@ -1496,13 +1716,22 @@ function setupWebpackV5ProcessAssetsHook(options) {
1496
1716
  const loaderGeneratedCss = sourceFile && !isWebGeneratorTarget ? generatedCssSources.get(path.resolve(sourceFile)) : void 0;
1497
1717
  const sourceCss = sourceFile ? cssSources.get(path.resolve(sourceFile))?.css : void 0;
1498
1718
  const shouldRegenerateExplicitTailwindV4CssSource = sourceCss !== void 0 && (hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || sourceCss.includes("@config"));
1499
- if (loaderGeneratedCss && !shouldRegenerateExplicitTailwindV4CssSource) {
1719
+ if (loaderGeneratedCss && (!shouldRegenerateExplicitTailwindV4CssSource || hasBundlerGeneratedCssMarker(currentRawSource))) {
1500
1720
  for (const className of loaderGeneratedCss.classSet) {
1501
1721
  generatorRuntimeSet.add(className);
1502
1722
  transformRuntimeSet.add(className);
1503
1723
  }
1504
1724
  for (const dependency of loaderGeneratedCss.dependencies) compilation.fileDependencies?.add?.(dependency);
1505
- const css = finalizeTracedCss(finalizeCssAssetSource(loaderGeneratedCss.css, { generatedCss: true }), cssHandlerOptions);
1725
+ const currentRawSourceWithoutBundlerMarkers = stripBundlerGeneratedCssMarkers(currentRawSource);
1726
+ const currentAssetHasProcessedUrl = hasProcessedCssAssetUrl(currentRawSourceWithoutBundlerMarkers) && currentRawSourceWithoutBundlerMarkers !== loaderGeneratedCss.css;
1727
+ const currentAssetUserCss = currentAssetHasProcessedUrl ? currentRawSourceWithoutBundlerMarkers : shouldUseWebpackAssetAsGeneratorUserCss(currentRawSourceWithoutBundlerMarkers, loaderGeneratedCss.css, { processed: true }) ? removeGeneratedSelectorCompatCss(currentRawSourceWithoutBundlerMarkers, loaderGeneratedCss.css) : void 0;
1728
+ const css = finalizeTracedCss(finalizeCssAssetSource(currentAssetUserCss === void 0 ? loaderGeneratedCss.css : createWebpackGeneratorUserCssSourceAppend({
1729
+ css: currentAssetHasProcessedUrl ? removeGeneratedSelectorCompatCss(loaderGeneratedCss.css, currentAssetUserCss) : filterExistingCssRules(currentAssetUserCss, loaderGeneratedCss.css),
1730
+ processed: true
1731
+ }, {
1732
+ css: currentAssetUserCss,
1733
+ processed: true
1734
+ }).css, { generatedCss: true }), cssHandlerOptions);
1506
1735
  debug("css consume webpack loader generation: %s <- %s", file, sourceFile);
1507
1736
  return { result: new ConcatSource(css) };
1508
1737
  }
@@ -1513,18 +1742,25 @@ function setupWebpackV5ProcessAssetsHook(options) {
1513
1742
  })), generatorRawSource, sourceFile, (registeredSourceFile) => isSameWebpackSourceScope(file, registeredSourceFile, sourceFile));
1514
1743
  const currentAssetLooksGenerated = hasTailwindGeneratedCss(currentRawSource) || hasTailwindGeneratedCssMarkers(currentRawSource);
1515
1744
  const currentAssetHasBundlerGeneratedMarker = hasBundlerGeneratedCssMarker(currentRawSource);
1516
- const shouldPreserveGeneratedWebAssetUserCss = isWebGeneratorTarget && currentAssetLooksGenerated && !currentAssetHasBundlerGeneratedMarker;
1745
+ const currentAssetUserCssSource = currentAssetLooksGenerated ? removeWebpackTailwindGeneratedAssetCss(currentRawSource) : currentRawSource;
1746
+ const currentAssetHasAdditionalUserCss = currentAssetLooksGenerated && (hasAdditionalWebpackAssetUserCssMarkers(currentAssetUserCssSource, generatorRawSource) || currentAssetUserCssSource.trim().length > 0);
1747
+ const shouldPreserveGeneratedWebAssetUserCss = isWebGeneratorTarget && currentAssetLooksGenerated && !currentAssetHasBundlerGeneratedMarker && !currentAssetHasAdditionalUserCss;
1517
1748
  const hasExplicitSourceCssForCurrentAsset = sourceCss !== void 0 && (hasTailwindRootDirectives(sourceCss, { importFallback: true }) || hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || hasTailwindApplyDirective(sourceCss));
1518
- const currentAssetHasAdditionalUserCss = currentAssetLooksGenerated && hasAdditionalWebpackAssetUserCssMarkers(currentRawSource, generatorRawSource);
1519
- const currentAssetHasUserCss = (sourceCssProcessed || hasExplicitSourceCssForCurrentAsset) && currentAssetLooksGenerated && !shouldPreserveGeneratedWebAssetUserCss ? currentAssetHasAdditionalUserCss : shouldUseWebpackAssetAsGeneratorUserCss(currentRawSource, generatorRawSource, { processed: sourceCssProcessed || shouldPreserveGeneratedWebAssetUserCss });
1520
- const shouldAppendCurrentAssetUserCss = !currentAssetHasBundlerGeneratedMarker && !shouldPreserveGeneratedWebAssetUserCss && (!sourceCssProcessed || registeredUserRawSource === void 0 || currentAssetHasUserCss) && !(sourceCssProcessed && currentAssetLooksGenerated && !currentAssetHasUserCss);
1521
- const userRawSource = createWebpackGeneratorUserCssSourceAppend(sourceCssProcessed && shouldAppendCurrentAssetUserCss ? {
1522
- css: currentRawSource,
1523
- processed: true
1524
- } : shouldAppendCurrentAssetUserCss && currentAssetHasUserCss ? {
1525
- css: currentRawSource,
1526
- processed: currentAssetLooksGenerated
1527
- } : void 0, registeredUserRawSource);
1749
+ const currentAssetHasUserCss = (sourceCssProcessed || hasExplicitSourceCssForCurrentAsset) && currentAssetLooksGenerated && !shouldPreserveGeneratedWebAssetUserCss ? currentAssetHasAdditionalUserCss : shouldUseWebpackAssetAsGeneratorUserCss(currentAssetUserCssSource, generatorRawSource, { processed: sourceCssProcessed || shouldPreserveGeneratedWebAssetUserCss });
1750
+ const userRawSource = createWebpackGeneratorUserCssSourceAppend(createWebpackCurrentAssetUserRawSource({
1751
+ currentAssetHasUserCss,
1752
+ currentAssetLooksGenerated,
1753
+ currentAssetUserCssSource,
1754
+ shouldAppendCurrentAssetUserCss: shouldAppendCurrentWebpackAssetUserCss({
1755
+ currentAssetHasBundlerGeneratedMarker,
1756
+ currentAssetHasUserCss,
1757
+ currentAssetLooksGenerated,
1758
+ registeredUserRawSource,
1759
+ shouldPreserveGeneratedWebAssetUserCss,
1760
+ sourceCssProcessed
1761
+ }),
1762
+ sourceCssProcessed
1763
+ }), registeredUserRawSource);
1528
1764
  if (isPureLocalCssImportWrapper(currentRawSource)) return { result: new ConcatSource(removeTailwindSourceDirectives(stripBundlerGeneratedCssMarkers(currentRawSource), { importFallback: true })) };
1529
1765
  const fallbackGeneratorRuntimeSet = getGeneratorRuntimeSet();
1530
1766
  const hasExplicitTailwindV4SourceCss = sourceCss !== void 0 && (hasTailwindSourceDirectives(sourceCss, { importFallback: true }) || sourceCss.includes("@config"));
@@ -1545,7 +1781,7 @@ function setupWebpackV5ProcessAssetsHook(options) {
1545
1781
  const generatorCssHandlerOptions = generatorCssSources === void 0 ? cssHandlerOptions : {
1546
1782
  ...cssHandlerOptions,
1547
1783
  sourceOptions: {
1548
- ...cssHandlerOptions.sourceOptions ?? {},
1784
+ ...cssHandlerOptions.sourceOptions,
1549
1785
  cssSources: generatorCssSources
1550
1786
  }
1551
1787
  };
@@ -1574,11 +1810,21 @@ function setupWebpackV5ProcessAssetsHook(options) {
1574
1810
  outputFile: file
1575
1811
  });
1576
1812
  } catch (error) {
1577
- if (!(!hasTailwindRootDirectives(generatorRawSource, { importFallback: true }) && !hasTailwindSourceDirectives(generatorRawSource, { importFallback: true }) && !hasTailwindApplyDirective(generatorRawSource) && !hasExplicitTailwindV4SourceCss && configuredMainCssEntryFiles.length === 0)) throw error;
1813
+ if (!shouldFallbackToWebpackUserCssOnGeneratorError({
1814
+ configuredMainCssEntryFilesLength: configuredMainCssEntryFiles.length,
1815
+ generatorRawSource,
1816
+ hasExplicitTailwindV4SourceCss
1817
+ })) throw error;
1578
1818
  debug("css generator skipped for plain webpack css asset: %s %O", file, error);
1579
1819
  generated = void 0;
1580
1820
  }
1581
- const source = new ConcatSource(finalizeTracedCss(generated ? finalizeCssAssetSource(generated.css, { generatedCss: true }) : isWebGeneratorTarget ? finalizeCssAssetSource(generatorRawSource, { generatedCss: false }) : finalizeCssAssetSource((await compilerOptions.styleHandler(generatorRawSource, cssHandlerOptions)).css, { generatedCss: false }), cssHandlerOptions));
1821
+ const source = new ConcatSource(finalizeTracedCss(generated ? finalizeCssAssetSource(isWebGeneratorTarget && currentRawSource.includes("tailwindcss v4.") ? createWebpackGeneratorUserCssSourceAppend({
1822
+ css: generated.css,
1823
+ processed: true
1824
+ }, {
1825
+ css: removeWebpackTailwindGeneratedAssetCss(currentRawSource),
1826
+ processed: true
1827
+ })?.css ?? generated.css : generated.css, { generatedCss: true }) : isWebGeneratorTarget ? finalizeCssAssetSource(generatorRawSource, { generatedCss: false }) : finalizeCssAssetSource((await compilerOptions.styleHandler(generatorRawSource, cssHandlerOptions)).css, { generatedCss: false }), cssHandlerOptions));
1582
1828
  if (generated) {
1583
1829
  for (const className of generated.classSet) generatorRuntimeSet.add(className);
1584
1830
  debug("css handle via tailwind v%s engine(%s): %s", runtimeState.tailwindRuntime.majorVersion, generated.target, file);
@@ -1602,7 +1848,7 @@ function setupWebpackV5ProcessAssetsHook(options) {
1602
1848
  cacheKeys: activeProcessCacheKeys,
1603
1849
  hashKeys: activeProcessHashKeys
1604
1850
  });
1605
- const activeCssFiles = new Set(groupedEntries.css?.map(([file]) => file) ?? []);
1851
+ const activeCssFiles = new Set(groupedEntries.css.map(([file]) => file));
1606
1852
  pruneWebpackCssHandlerOptionCaches(cssHandlerOptionsCache, cssUserHandlerOptionsCache, activeCssFiles);
1607
1853
  if (activeCssFiles.size > 0) pruneWebpackCssSources?.(new Set([
1608
1854
  ...registeredWebpackCssSourceFiles,
@@ -1899,8 +2145,14 @@ var WeappTailwindcss = class {
1899
2145
  if (typeof runtimeState.tailwindRuntime.collectContentTokens !== "function") return;
1900
2146
  try {
1901
2147
  const report = await runtimeState.tailwindRuntime.collectContentTokens();
1902
- for (const entry of report.entries ?? []) if (entry.file) runtimeWatchDependencyFiles.add(entry.file);
1903
- for (const source of report.sources ?? []) if (source?.base) runtimeWatchDependencyContexts.add(source.base);
2148
+ for (const entry of report.entries ?? []) {
2149
+ const file = typeof entry === "object" && entry !== null && "file" in entry ? entry.file : void 0;
2150
+ if (typeof file === "string") runtimeWatchDependencyFiles.add(file);
2151
+ }
2152
+ for (const source of report.sources ?? []) {
2153
+ const base = typeof source === "object" && source !== null && "base" in source ? source.base : void 0;
2154
+ if (typeof base === "string") runtimeWatchDependencyContexts.add(base);
2155
+ }
1904
2156
  } catch (error) {
1905
2157
  debug("collect runtime watch dependencies failed: %O", error);
1906
2158
  }