weapp-tailwindcss 5.0.0-next.9 → 5.0.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 (167) hide show
  1. package/README.md +2 -2
  2. package/dist/auto-DEHRmEAx.mjs +200 -0
  3. package/dist/auto-dPpsm6FB.js +238 -0
  4. package/dist/bundle-state-CBF5YX1m.js +529 -0
  5. package/dist/bundle-state-CQmxxx0R.mjs +413 -0
  6. package/dist/bundlers/shared/cache.d.ts +9 -7
  7. package/dist/bundlers/shared/css-cleanup/at-rules.d.ts +1 -2
  8. package/dist/bundlers/shared/css-cleanup.d.ts +1 -3
  9. package/dist/bundlers/shared/css-imports.d.ts +3 -3
  10. package/dist/bundlers/shared/generated-css-marker.d.ts +3 -0
  11. package/dist/bundlers/shared/generator-css/directives.d.ts +11 -3
  12. package/dist/bundlers/shared/generator-css/markers.d.ts +12 -0
  13. package/dist/bundlers/shared/generator-css/source-files.d.ts +9 -6
  14. package/dist/bundlers/shared/generator-css/source-resolver.d.ts +16 -2
  15. package/dist/bundlers/shared/generator-css/user-layer-order.d.ts +10 -0
  16. package/dist/bundlers/shared/generator-css.d.ts +6 -2
  17. package/dist/bundlers/shared/hmr-timing.d.ts +22 -0
  18. package/dist/bundlers/shared/style-requests.d.ts +2 -0
  19. package/dist/bundlers/vite/bundle-state.d.ts +1 -0
  20. package/dist/bundlers/vite/css-finalizer.d.ts +6 -0
  21. package/dist/bundlers/vite/generate-bundle/candidates.d.ts +1 -1
  22. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +5 -1
  23. package/dist/bundlers/vite/generate-bundle/css-share-scope.d.ts +1 -0
  24. package/dist/bundlers/vite/generate-bundle.d.ts +13 -1
  25. package/dist/bundlers/vite/incremental-runtime-class-set.d.ts +10 -2
  26. package/dist/bundlers/vite/index.d.ts +5 -2
  27. package/dist/bundlers/vite/processed-css-assets.d.ts +32 -0
  28. package/dist/bundlers/vite/rewrite-css-imports.d.ts +8 -5
  29. package/dist/bundlers/vite/runtime-class-set.d.ts +5 -1
  30. package/dist/bundlers/vite/serve-css-generation.d.ts +11 -0
  31. package/dist/bundlers/vite/source-candidates.d.ts +24 -2
  32. package/dist/bundlers/vite/source-scan.d.ts +26 -0
  33. package/dist/bundlers/vite/static-config-content.d.ts +5 -0
  34. package/dist/bundlers/webpack/BaseUnifiedPlugin/shared.d.ts +5 -0
  35. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-assets.d.ts +5 -1
  36. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5-loaders.d.ts +8 -3
  37. package/dist/bundlers/webpack/BaseUnifiedPlugin/v5.d.ts +1 -1
  38. package/dist/bundlers/webpack/loaders/runtime-registry.d.ts +31 -0
  39. package/dist/bundlers/webpack/loaders/weapp-tw-css-import-rewrite-loader.d.ts +2 -8
  40. package/dist/bundlers/webpack/loaders/weapp-tw-runtime-classset-loader.d.ts +3 -7
  41. package/dist/cache/index.d.ts +6 -6
  42. package/dist/{chunk-8l464Juk.js → chunk-C5U5_Hdc.js} +14 -0
  43. package/dist/cli/context.d.ts +1 -11
  44. package/dist/cli/doctor/types.d.ts +11 -11
  45. package/dist/cli/vscode-entry.d.ts +3 -3
  46. package/dist/cli.js +684 -41
  47. package/dist/cli.mjs +682 -40
  48. package/dist/context/runtime-package-replacements.d.ts +2 -0
  49. package/dist/context/style-options.d.ts +3 -0
  50. package/dist/context/tailwindcss.d.ts +1 -1
  51. package/dist/core.js +1 -2
  52. package/dist/core.mjs +1 -1
  53. package/dist/css-macro/auto.d.ts +11 -0
  54. package/dist/css-macro/constants.d.ts +5 -2
  55. package/dist/css-macro/postcss.d.ts +1 -0
  56. package/dist/css-macro/postcss.js +7 -46
  57. package/dist/css-macro/postcss.mjs +2 -46
  58. package/dist/css-macro.js +16 -7
  59. package/dist/css-macro.mjs +15 -6
  60. package/dist/defaults-8xrgzxFY.mjs +151 -0
  61. package/dist/defaults-zKUH2mDe.js +193 -0
  62. package/dist/defaults.js +6 -150
  63. package/dist/defaults.mjs +1 -143
  64. package/dist/escape.js +10 -2
  65. package/dist/escape.mjs +10 -2
  66. package/dist/generator/options.d.ts +11 -6
  67. package/dist/generator/types.d.ts +3 -3
  68. package/dist/generator-CvmsIQFI.js +92 -0
  69. package/dist/generator-DDtsUvkH.mjs +67 -0
  70. package/dist/generator.js +12 -12
  71. package/dist/generator.mjs +2 -1
  72. package/dist/gulp.js +163 -40
  73. package/dist/gulp.mjs +155 -32
  74. package/dist/incremental-runtime-class-set-BffodqHh.js +2366 -0
  75. package/dist/incremental-runtime-class-set-DArodvWs.mjs +2291 -0
  76. package/dist/index.d.ts +2 -1
  77. package/dist/index.js +17 -5
  78. package/dist/index.mjs +6 -5
  79. package/dist/js/babel/cache-options.d.ts +3 -0
  80. package/dist/js/babel/parse.d.ts +7 -4
  81. package/dist/js/precheck.d.ts +2 -2
  82. package/dist/js/replacement-cache.d.ts +5 -0
  83. package/dist/{postcss-w48mGIhe.mjs → postcss-BzNYQUOH.mjs} +54 -114
  84. package/dist/postcss-C7BMYpEF.mjs +169 -0
  85. package/dist/postcss-CiYLsqZn.js +192 -0
  86. package/dist/{postcss-QIXwT40c.js → postcss-DE0TOtV9.js} +60 -121
  87. package/dist/postcss-html-transform.js +1 -1
  88. package/dist/postcss.js +1 -1
  89. package/dist/postcss.mjs +1 -1
  90. package/dist/precheck-BzYPm-EG.js +4842 -0
  91. package/dist/precheck-jZvTVXXG.mjs +4716 -0
  92. package/dist/presets/index.d.ts +1 -0
  93. package/dist/presets/uni-app-x.d.ts +1 -0
  94. package/dist/presets.js +27 -13
  95. package/dist/presets.mjs +25 -13
  96. package/dist/reset.js +1 -1
  97. package/dist/runtime-registry-DpcR3IHI.js +5496 -0
  98. package/dist/shared/mpx.d.ts +1 -0
  99. package/dist/source-candidates-BuTlMabx.mjs +322 -0
  100. package/dist/source-candidates-CxoIaS88.js +335 -0
  101. package/dist/tailwindcss/miniprogram.d.ts +1 -5
  102. package/dist/tailwindcss/remove-unsupported-css.d.ts +1 -2
  103. package/dist/tailwindcss/runtime/cache.d.ts +4 -3
  104. package/dist/tailwindcss/runtime.d.ts +9 -9
  105. package/dist/tailwindcss/source-scan.d.ts +35 -0
  106. package/dist/tailwindcss/v3-engine/types.d.ts +19 -14
  107. package/dist/tailwindcss/v4/css-entries.d.ts +2 -2
  108. package/dist/tailwindcss/v4/patcher.d.ts +1 -1
  109. package/dist/tailwindcss/v4-engine/source.d.ts +2 -2
  110. package/dist/tailwindcss/v4-engine/types.d.ts +18 -5
  111. package/dist/{tailwindcss-C5IgPlQ0.mjs → tailwindcss-CCZcu0lr.mjs} +75 -98
  112. package/dist/{tailwindcss-Bu-RWIHx.js → tailwindcss-DZckITp1.js} +83 -106
  113. package/dist/typedoc.export.d.ts +1 -1
  114. package/dist/types/index.d.ts +51 -41
  115. package/dist/types/shared.d.ts +3 -0
  116. package/dist/types/typedoc-tailwindcss-patch.d.ts +67 -0
  117. package/dist/types/user-defined-options/general.d.ts +25 -22
  118. package/dist/types/user-defined-options/important.d.ts +32 -27
  119. package/dist/types/user-defined-options/lifecycle.d.ts +4 -4
  120. package/dist/types/user-defined-options/matcher.d.ts +6 -6
  121. package/dist/unocss/index.d.ts +2 -0
  122. package/dist/utils/object.d.ts +9 -0
  123. package/dist/utils/options.d.ts +2 -0
  124. package/dist/utils/regex.d.ts +1 -0
  125. package/dist/{utils-BiShvil9.js → utils-D7Ygohep.js} +2 -2
  126. package/dist/{utils-Btw1iOVV.mjs → utils-DsaS975I.mjs} +1 -1
  127. package/dist/v3-engine-DGBhUnjn.mjs +3419 -0
  128. package/dist/v3-engine-M6Aqru5T.js +3714 -0
  129. package/dist/vite-BBcQIJpD.mjs +24493 -0
  130. package/dist/vite-DgRkWVPG.js +24507 -0
  131. package/dist/vite.js +1 -1
  132. package/dist/vite.mjs +1 -1
  133. package/dist/weapp-tw-css-import-rewrite-loader.js +5456 -22
  134. package/dist/weapp-tw-runtime-classset-loader.js +32 -9
  135. package/dist/{webpack-BzN2ly34.js → webpack-D-gb4ZvO.js} +341 -96
  136. package/dist/{webpack-DJazm5sT.mjs → webpack-D43aMQzO.mjs} +323 -79
  137. package/dist/webpack.d.ts +1 -3
  138. package/dist/webpack.js +3 -4
  139. package/dist/webpack.mjs +2 -2
  140. package/dist/wxml/utils/codegen/legacy-visitor.d.ts +2 -4
  141. package/package.json +22 -20
  142. package/dist/bundlers/shared/css-cleanup/color-gamut.d.ts +0 -3
  143. package/dist/bundlers/shared/css-cleanup/root-cleanups.d.ts +0 -4
  144. package/dist/bundlers/shared/css-cleanup/selectors.d.ts +0 -8
  145. package/dist/cache-BVAiJV3J.js +0 -502
  146. package/dist/cache-CHs4DXui.mjs +0 -434
  147. package/dist/constants-BoB_6lFw.js +0 -73
  148. package/dist/constants-E_loJC49.mjs +0 -44
  149. package/dist/generator-DKkhJbOg.js +0 -1531
  150. package/dist/generator-UBmfduYg.mjs +0 -1432
  151. package/dist/generator-css-Bwp3nbrl.js +0 -1381
  152. package/dist/generator-css-DeLLmp2N.mjs +0 -1342
  153. package/dist/lightningcss/index.d.ts +0 -8
  154. package/dist/lightningcss/style-handler/options.d.ts +0 -3
  155. package/dist/lightningcss/style-handler/selector-transform.d.ts +0 -10
  156. package/dist/lightningcss/style-handler/selector-utils.d.ts +0 -10
  157. package/dist/lightningcss/style-handler.d.ts +0 -17
  158. package/dist/precheck-B32p-gLI.js +0 -2736
  159. package/dist/precheck-B4RH6ZNN.mjs +0 -2622
  160. package/dist/run-tasks-B50A3pxt.js +0 -128
  161. package/dist/run-tasks-DdNi-hkk.mjs +0 -91
  162. package/dist/runtime-patch-CwN5ya72.mjs +0 -71
  163. package/dist/runtime-patch-D6mBo_KB.js +0 -85
  164. package/dist/vite-By5KQi9s.js +0 -2419
  165. package/dist/vite-Cyp42bBf.mjs +0 -2406
  166. /package/dist/{logger-Bub1jggA.mjs → logger-BNzxZbZj.mjs} +0 -0
  167. /package/dist/{logger-BRy6XPQ2.js → logger-TlKT3xmR.js} +0 -0
@@ -1,2736 +0,0 @@
1
- const require_chunk = require("./chunk-8l464Juk.js");
2
- const require_cache = require("./cache-BVAiJV3J.js");
3
- const require_runtime_patch = require("./runtime-patch-D6mBo_KB.js");
4
- require("./utils-BiShvil9.js");
5
- const require_defaults = require("./defaults.js");
6
- const require_tailwindcss = require("./tailwindcss-Bu-RWIHx.js");
7
- let node_path = require("node:path");
8
- node_path = require_chunk.__toESM(node_path);
9
- let node_process = require("node:process");
10
- node_process = require_chunk.__toESM(node_process);
11
- let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
12
- let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
13
- let node_buffer = require("node:buffer");
14
- let node_fs_promises = require("node:fs/promises");
15
- let lru_cache = require("lru-cache");
16
- let _weapp_tailwindcss_shared_node = require("@weapp-tailwindcss/shared/node");
17
- let _weapp_core_escape = require("@weapp-core/escape");
18
- let _babel_traverse = require("@babel/traverse");
19
- _babel_traverse = require_chunk.__toESM(_babel_traverse);
20
- let _babel_parser = require("@babel/parser");
21
- let _weapp_core_regex = require("@weapp-core/regex");
22
- let magic_string = require("magic-string");
23
- magic_string = require_chunk.__toESM(magic_string);
24
- let _ast_core_escape = require("@ast-core/escape");
25
- let _weapp_tailwindcss_shared_extractors = require("@weapp-tailwindcss/shared/extractors");
26
- let _babel_types = require("@babel/types");
27
- _babel_types = require_chunk.__toESM(_babel_types);
28
- let htmlparser2 = require("htmlparser2");
29
- let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
30
- //#region src/cache/index.ts
31
- function isProcessResult(value) {
32
- return typeof value === "object" && value !== null && "result" in value;
33
- }
34
- function createCache(options) {
35
- const disabled = options === false;
36
- const hashMap = /* @__PURE__ */ new Map();
37
- const instance = new lru_cache.LRUCache({
38
- max: 1024,
39
- ttl: 0,
40
- ttlAutopurge: false
41
- });
42
- const cache = {
43
- hashMap,
44
- instance,
45
- hasHashKey(key) {
46
- return hashMap.has(key);
47
- },
48
- getHashValue(key) {
49
- return hashMap.get(key);
50
- },
51
- setHashValue(key, value) {
52
- return hashMap.set(key, value);
53
- },
54
- get(key) {
55
- return instance.get(key);
56
- },
57
- set(key, value) {
58
- return instance.set(key, value);
59
- },
60
- computeHash(message) {
61
- return (0, _weapp_tailwindcss_shared_node.md5)(message);
62
- },
63
- calcHashValueChanged(key, hash) {
64
- const hit = hashMap.get(key);
65
- if (hit) hashMap.set(key, {
66
- changed: hash !== hit.hash,
67
- hash
68
- });
69
- else hashMap.set(key, {
70
- changed: true,
71
- hash
72
- });
73
- return cache;
74
- },
75
- has(key) {
76
- return instance.has(key);
77
- },
78
- async process({ key, hashKey, rawSource, hash, resolveCache, transform, onCacheHit }) {
79
- if (disabled) {
80
- const value = await transform();
81
- return isProcessResult(value) ? value.result : value;
82
- }
83
- const cacheHashKey = hashKey ?? key;
84
- let hasChanged = true;
85
- if (hash != null || rawSource != null) {
86
- const nextHash = hash ?? cache.computeHash(rawSource);
87
- cache.calcHashValueChanged(cacheHashKey, nextHash);
88
- hasChanged = cache.getHashValue(cacheHashKey)?.changed ?? true;
89
- }
90
- const readCache = resolveCache ?? (() => cache.get(key));
91
- if (!hasChanged) {
92
- const cached = readCache();
93
- if (cached !== void 0) {
94
- await onCacheHit?.(cached);
95
- return cached;
96
- }
97
- }
98
- const value = await transform();
99
- const normalized = isProcessResult(value) ? value : { result: value };
100
- const stored = normalized.cacheValue ?? normalized.result;
101
- cache.set(key, stored);
102
- return normalized.result;
103
- }
104
- };
105
- return cache;
106
- }
107
- function initializeCache(cacheConfig) {
108
- if (typeof cacheConfig === "boolean" || cacheConfig === void 0) return createCache(cacheConfig);
109
- return cacheConfig;
110
- }
111
- //#endregion
112
- //#region src/tailwindcss/runtime.ts
113
- const debug$1 = require_runtime_patch.createDebug("[tailwindcss:runtime] ");
114
- const refreshTailwindcssPatcherSymbol = Symbol.for("weapp-tailwindcss.refreshTailwindcssPatcher");
115
- function createTailwindRuntimeReadyPromise(twPatcher) {
116
- return Promise.resolve().then(async () => {
117
- await require_runtime_patch.ensureTailwindcssRuntimePatch(twPatcher);
118
- require_cache.invalidateRuntimeClassSet(twPatcher);
119
- });
120
- }
121
- const runtimeClassSetStateCache = /* @__PURE__ */ new WeakMap();
122
- function getRuntimeClassSetStateEntry(state) {
123
- let entry = runtimeClassSetStateCache.get(state);
124
- if (!entry) {
125
- entry = {};
126
- runtimeClassSetStateCache.set(state, entry);
127
- }
128
- return entry;
129
- }
130
- async function refreshTailwindRuntimeState(state, forceOrOptions) {
131
- const normalizedOptions = typeof forceOrOptions === "boolean" ? { force: forceOrOptions } : forceOrOptions;
132
- const force = normalizedOptions.force;
133
- const clearCache = normalizedOptions.clearCache === true;
134
- if (!force) return false;
135
- debug$1("refresh runtime state start, clearCache=%s major=%s", clearCache, state.twPatcher.majorVersion ?? "unknown");
136
- await state.readyPromise;
137
- let refreshed = false;
138
- if (typeof state.refreshTailwindcssPatcher === "function") {
139
- const next = await state.refreshTailwindcssPatcher({ clearCache });
140
- if (next !== state.twPatcher) state.twPatcher = next;
141
- refreshed = true;
142
- }
143
- if (refreshed) state.readyPromise = createTailwindRuntimeReadyPromise(state.twPatcher);
144
- debug$1("refresh runtime state end, refreshed=%s major=%s", refreshed, state.twPatcher.majorVersion ?? "unknown");
145
- return refreshed;
146
- }
147
- async function ensureRuntimeClassSet(state, options = {}) {
148
- const forceRefresh = options.forceRefresh === true;
149
- const forceCollect = options.forceCollect === true;
150
- const clearCache = options.clearCache === true;
151
- const allowEmpty = options.allowEmpty === true;
152
- if (forceRefresh) await refreshTailwindRuntimeState(state, {
153
- force: true,
154
- clearCache
155
- });
156
- await state.readyPromise;
157
- const entry = getRuntimeClassSetStateEntry(state);
158
- const signature = require_cache.getRuntimeClassSetSignature(state.twPatcher);
159
- const signatureChanged = entry.signature !== signature;
160
- const shouldForceCollect = forceCollect || forceRefresh || signatureChanged;
161
- if (!shouldForceCollect) {
162
- if (entry.value && (allowEmpty || entry.value.size > 0)) return entry.value;
163
- if (entry.promise) return entry.promise;
164
- }
165
- const task = (async () => {
166
- const collected = await collectRuntimeClassSet(state.twPatcher, {
167
- force: shouldForceCollect,
168
- skipRefresh: true,
169
- clearCache
170
- });
171
- if (allowEmpty || collected.size > 0) return collected;
172
- await refreshTailwindRuntimeState(state, {
173
- force: true,
174
- clearCache: true
175
- });
176
- await state.readyPromise;
177
- return collectRuntimeClassSet(state.twPatcher, {
178
- force: true,
179
- skipRefresh: true,
180
- clearCache: true
181
- });
182
- })();
183
- entry.promise = task;
184
- try {
185
- const runtimeSet = await task;
186
- entry.value = runtimeSet;
187
- entry.signature = require_cache.getRuntimeClassSetSignature(state.twPatcher);
188
- return runtimeSet;
189
- } finally {
190
- if (entry.promise === task) entry.promise = void 0;
191
- }
192
- }
193
- function shouldPreferSync(majorVersion) {
194
- if (majorVersion == null) return true;
195
- if (majorVersion === 3) return true;
196
- if (majorVersion === 4) return true;
197
- return false;
198
- }
199
- function tryGetRuntimeClassSetSync(twPatcher) {
200
- if (typeof twPatcher.getClassSetSync !== "function") return;
201
- if (!shouldPreferSync(twPatcher.majorVersion)) return;
202
- try {
203
- const set = twPatcher.getClassSetSync();
204
- if (set && set.size === 0) return;
205
- return set;
206
- } catch (error) {
207
- if (twPatcher.majorVersion === 4) debug$1("getClassSetSync() unavailable for tailwindcss v4, fallback to async getClassSet(): %O", error);
208
- else debug$1("getClassSetSync() failed, fallback to async getClassSet(): %O", error);
209
- return;
210
- }
211
- }
212
- async function collectRuntimeClassSet(twPatcher, options = {}) {
213
- let activePatcher = twPatcher;
214
- if (options.force && !options.skipRefresh) {
215
- const refresh = activePatcher[refreshTailwindcssPatcherSymbol];
216
- if (typeof refresh === "function") try {
217
- const refreshed = await refresh({ clearCache: options.clearCache === true });
218
- if (refreshed) activePatcher = refreshed;
219
- } catch (error) {
220
- debug$1("refreshTailwindcssPatcher failed, continuing with existing patcher: %O", error);
221
- }
222
- }
223
- const entry = require_cache.getRuntimeClassSetCacheEntry(activePatcher);
224
- const signature = require_cache.getRuntimeClassSetSignature(activePatcher);
225
- if (!options.force) {
226
- if (entry.value && entry.signature === signature) return entry.value;
227
- if (entry.promise) return entry.promise;
228
- } else entry.value = void 0;
229
- const task = (async () => {
230
- await require_runtime_patch.ensureTailwindcssRuntimePatch(activePatcher);
231
- const preExtractSyncSet = options.force ? tryGetRuntimeClassSetSync(activePatcher) : void 0;
232
- if (preExtractSyncSet) debug$1("runtime class set snapshot via getClassSetSync() before extract(), size=%d", preExtractSyncSet.size);
233
- const preferExtract = options.force === true;
234
- try {
235
- const result = await activePatcher.extract({ write: false });
236
- if (result?.classSet) {
237
- if (result.classSet.size > 0) {
238
- debug$1("runtime class set resolved via extract(), size=%d", result.classSet.size);
239
- return result.classSet;
240
- }
241
- if (preferExtract) debug$1("runtime class set from extract() is empty on force collect, fallback to sync/async class set");
242
- else debug$1("runtime class set from extract() is empty, fallback to sync/async class set");
243
- }
244
- } catch (error) {
245
- debug$1("extract() failed, fallback to getClassSet(): %O", error);
246
- }
247
- if (preExtractSyncSet) {
248
- debug$1("runtime class set fallback to pre-extract sync snapshot, size=%d", preExtractSyncSet.size);
249
- return preExtractSyncSet;
250
- }
251
- const syncSet = tryGetRuntimeClassSetSync(activePatcher);
252
- if (syncSet) {
253
- debug$1("runtime class set resolved via getClassSetSync(), size=%d", syncSet.size);
254
- return syncSet;
255
- }
256
- try {
257
- const fallbackSet = await Promise.resolve(activePatcher.getClassSet());
258
- if (fallbackSet) {
259
- debug$1("runtime class set resolved via getClassSet(), size=%d", fallbackSet.size);
260
- return fallbackSet;
261
- }
262
- } catch (error) {
263
- debug$1("getClassSet() failed, returning empty set: %O", error);
264
- }
265
- return /* @__PURE__ */ new Set();
266
- })();
267
- entry.promise = task;
268
- entry.signature = signature;
269
- try {
270
- const resolved = await task;
271
- entry.value = resolved;
272
- entry.promise = void 0;
273
- entry.signature = signature;
274
- return resolved;
275
- } catch (error) {
276
- entry.promise = void 0;
277
- throw error;
278
- }
279
- }
280
- //#endregion
281
- //#region src/tailwindcss/runtime-logs.ts
282
- const runtimeLogDedupeHolder = globalThis;
283
- const runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
284
- function createRuntimeLogKey(category, baseDir, rootPath, version) {
285
- return JSON.stringify([
286
- category,
287
- baseDir ?? node_process.default.cwd(),
288
- rootPath ?? "",
289
- version ?? ""
290
- ]);
291
- }
292
- function markRuntimeLog(category, baseDir, rootPath, version) {
293
- const key = createRuntimeLogKey(category, baseDir, rootPath, version);
294
- if (runtimeLogDedupe.has(key)) return false;
295
- runtimeLogDedupe.add(key);
296
- return true;
297
- }
298
- function logRuntimeTailwindcssTarget(baseDir, rootPath, version) {
299
- if (!markRuntimeLog("target", baseDir, rootPath, version)) return;
300
- const versionText = version ? ` (v${version})` : "";
301
- _weapp_tailwindcss_logger.logger.info("%s 使用 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
302
- }
303
- function logRuntimeTailwindcssVersion(baseDir, rootPath, version) {
304
- if (version) {
305
- if (!markRuntimeLog("version", baseDir, rootPath, version)) return;
306
- _weapp_tailwindcss_logger.logger.success(`当前使用 ${_weapp_tailwindcss_logger.pc.cyanBright("Tailwind CSS")} 版本为: ${_weapp_tailwindcss_logger.pc.underline(_weapp_tailwindcss_logger.pc.bold(_weapp_tailwindcss_logger.pc.green(version)))}`);
307
- return;
308
- }
309
- if (!markRuntimeLog("missing", baseDir, rootPath, version)) return;
310
- _weapp_tailwindcss_logger.logger.warn(`${_weapp_tailwindcss_logger.pc.cyanBright("Tailwind CSS")} 未安装,已跳过版本检测与运行时初始化。`);
311
- }
312
- //#endregion
313
- //#region src/tailwindcss/targets.ts
314
- function formatRelativeToBase(targetPath, baseDir) {
315
- const normalized = node_path.default.normalize(targetPath);
316
- if (!baseDir) return normalized.replace(/\\/g, "/");
317
- const relative = node_path.default.relative(baseDir, normalized);
318
- if (!relative || relative === ".") return ".";
319
- if (relative.startsWith("..")) return normalized.replace(/\\/g, "/");
320
- return node_path.default.join(".", relative).replace(/\\/g, "/");
321
- }
322
- function logTailwindcssTarget(patcher, baseDir) {
323
- const packageInfo = patcher?.packageInfo;
324
- const label = "Weapp-tailwindcss";
325
- if (!packageInfo?.rootPath) {
326
- _weapp_tailwindcss_logger.logger.warn("%s 未找到 Tailwind CSS 依赖,请检查在 %s 是否已安装 tailwindcss", label, baseDir ?? node_process.default.cwd());
327
- return;
328
- }
329
- const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
330
- const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
331
- logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
332
- _weapp_tailwindcss_logger.logger.debug("%s 解析 Tailwind CSS -> %s%s", label, displayPath, version);
333
- }
334
- //#endregion
335
- //#region src/context/compiler-context-cache.ts
336
- const PAREN_CONTENT_RE = /\(([^)]+)\)/u;
337
- const AT_LOCATION_RE = /at\s+(\S.*)$/u;
338
- const TRAILING_LINE_COL_RE = /:\d+(?::\d+)?$/u;
339
- const globalCacheHolder = globalThis;
340
- const compilerContextCache = globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
341
- const compilerContextKeyCacheByOptions = /* @__PURE__ */ new WeakMap();
342
- const compilerContextKeyCacheWithoutOptions = /* @__PURE__ */ new Map();
343
- function withCircularGuard(value, stack, factory) {
344
- if (stack.has(value)) throw new TypeError("Cannot serialize circular structure in compiler context options");
345
- stack.add(value);
346
- try {
347
- return factory();
348
- } finally {
349
- stack.delete(value);
350
- }
351
- }
352
- function encodeTaggedValue(type, value) {
353
- const record = { __type: type };
354
- if (value !== void 0) record.value = value;
355
- return record;
356
- }
357
- function hasExplicitOptionBasedir(opts) {
358
- return typeof opts?.tailwindcssBasedir === "string" && opts.tailwindcssBasedir.length > 0;
359
- }
360
- function shouldProbeCallerLocation(opts) {
361
- if (hasExplicitOptionBasedir(opts)) return false;
362
- return !(node_process.default.env.WEAPP_TAILWINDCSS_BASEDIR || node_process.default.env.WEAPP_TAILWINDCSS_BASE_DIR || node_process.default.env.TAILWINDCSS_BASEDIR || node_process.default.env.TAILWINDCSS_BASE_DIR);
363
- }
364
- function detectCallerLocation() {
365
- const stack = (/* @__PURE__ */ new Error("compiler-context-cache stack probe")).stack;
366
- if (!stack) return;
367
- const lines = stack.split("\n");
368
- for (const line of lines) {
369
- const location = (line.match(PAREN_CONTENT_RE) ?? line.match(AT_LOCATION_RE))?.[1];
370
- if (!location) continue;
371
- const candidatePath = location.replace(TRAILING_LINE_COL_RE, "");
372
- if (!candidatePath || !node_path.default.isAbsolute(candidatePath)) continue;
373
- if (candidatePath.includes(`${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}src${node_path.default.sep}`) || candidatePath.includes(`${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}dist${node_path.default.sep}`) || candidatePath.includes(`${node_path.default.sep}node_modules${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}`)) continue;
374
- return candidatePath;
375
- }
376
- }
377
- function getRuntimeCacheScope(opts) {
378
- if (hasExplicitOptionBasedir(opts)) return { caller: void 0 };
379
- const runtimeScope = {
380
- caller: void 0,
381
- cwd: node_process.default.cwd(),
382
- init_cwd: node_process.default.env.INIT_CWD,
383
- npm_config_local_prefix: node_process.default.env.npm_config_local_prefix,
384
- npm_package_json: node_process.default.env.npm_package_json,
385
- pnpm_package_name: node_process.default.env.PNPM_PACKAGE_NAME,
386
- pwd: node_process.default.env.PWD,
387
- tailwindcss_base_dir: node_process.default.env.TAILWINDCSS_BASE_DIR,
388
- tailwindcss_basedir: node_process.default.env.TAILWINDCSS_BASEDIR,
389
- uni_app_input_dir: node_process.default.env.UNI_APP_INPUT_DIR,
390
- uni_cli_root: node_process.default.env.UNI_CLI_ROOT,
391
- uni_input_dir: node_process.default.env.UNI_INPUT_DIR,
392
- uni_input_root: node_process.default.env.UNI_INPUT_ROOT,
393
- weapp_tailwindcss_base_dir: node_process.default.env.WEAPP_TAILWINDCSS_BASE_DIR,
394
- weapp_tailwindcss_basedir: node_process.default.env.WEAPP_TAILWINDCSS_BASEDIR
395
- };
396
- if (shouldProbeCallerLocation(opts)) runtimeScope.caller = detectCallerLocation();
397
- return runtimeScope;
398
- }
399
- function serializeNormalizedValue(value) {
400
- return JSON.stringify(value);
401
- }
402
- function createRuntimeCacheScopeKey(opts) {
403
- return serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScope(opts)));
404
- }
405
- function getCompilerContextKeyCacheStore(opts) {
406
- if (!opts) return compilerContextKeyCacheWithoutOptions;
407
- let store = compilerContextKeyCacheByOptions.get(opts);
408
- if (!store) {
409
- store = /* @__PURE__ */ new Map();
410
- compilerContextKeyCacheByOptions.set(opts, store);
411
- }
412
- return store;
413
- }
414
- function createComparableNormalizedValue(rawValue, stack) {
415
- const normalized = normalizeOptionsValue(rawValue, stack);
416
- return {
417
- normalized,
418
- sortKey: serializeNormalizedValue(normalized)
419
- };
420
- }
421
- function getRuntimeCacheScopeValue(opts) {
422
- return {
423
- options: opts ?? {},
424
- runtime: getRuntimeCacheScope(opts)
425
- };
426
- }
427
- function normalizeOptionsValue(rawValue, stack = /* @__PURE__ */ new WeakSet()) {
428
- if (rawValue === null) return null;
429
- if (rawValue === void 0) return encodeTaggedValue("Undefined");
430
- const type = typeof rawValue;
431
- if (type === "string") return rawValue;
432
- if (type === "boolean") return rawValue;
433
- if (type === "number") {
434
- const numericValue = rawValue;
435
- if (Number.isNaN(numericValue)) return encodeTaggedValue("Number", "NaN");
436
- if (!Number.isFinite(numericValue)) return encodeTaggedValue("Number", numericValue > 0 ? "Infinity" : "-Infinity");
437
- if (Object.is(numericValue, -0)) return encodeTaggedValue("Number", "-0");
438
- return numericValue;
439
- }
440
- if (type === "bigint") return encodeTaggedValue("BigInt", rawValue.toString());
441
- if (type === "symbol") {
442
- const symbolValue = rawValue;
443
- return encodeTaggedValue("Symbol", symbolValue.description ?? String(symbolValue));
444
- }
445
- if (type === "function") return encodeTaggedValue("Function", rawValue.toString());
446
- if (Array.isArray(rawValue)) return withCircularGuard(rawValue, stack, () => rawValue.map((item) => normalizeOptionsValue(item, stack)));
447
- if (rawValue instanceof Date) return encodeTaggedValue("Date", rawValue.toISOString());
448
- if (rawValue instanceof RegExp) return {
449
- __type: "RegExp",
450
- source: rawValue.source,
451
- flags: rawValue.flags
452
- };
453
- if (typeof node_buffer.Buffer !== "undefined" && node_buffer.Buffer.isBuffer(rawValue)) return encodeTaggedValue("Buffer", rawValue.toString("base64"));
454
- if (ArrayBuffer.isView(rawValue)) {
455
- const view = rawValue;
456
- const buffer = node_buffer.Buffer.from(view.buffer, view.byteOffset, view.byteLength);
457
- return encodeTaggedValue(view.constructor?.name ?? "ArrayBufferView", buffer.toString("base64"));
458
- }
459
- if (rawValue instanceof ArrayBuffer) return encodeTaggedValue("ArrayBuffer", node_buffer.Buffer.from(rawValue).toString("base64"));
460
- if (rawValue instanceof Set) return withCircularGuard(rawValue, stack, () => {
461
- const normalizedEntries = Array.from(rawValue, (element) => createComparableNormalizedValue(element, stack));
462
- normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
463
- return {
464
- __type: "Set",
465
- value: normalizedEntries.map((entry) => entry.normalized)
466
- };
467
- });
468
- if (rawValue instanceof Map) return withCircularGuard(rawValue, stack, () => {
469
- const normalizedEntries = Array.from(rawValue.entries(), ([key, entryValue]) => {
470
- const normalizedKey = createComparableNormalizedValue(key, stack);
471
- return {
472
- key: normalizedKey.normalized,
473
- sortKey: normalizedKey.sortKey,
474
- value: normalizeOptionsValue(entryValue, stack)
475
- };
476
- });
477
- normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
478
- return {
479
- __type: "Map",
480
- value: normalizedEntries.map((entry) => [entry.key, entry.value])
481
- };
482
- });
483
- if (typeof URL !== "undefined" && rawValue instanceof URL) return encodeTaggedValue("URL", rawValue.toString());
484
- if (rawValue instanceof Error) {
485
- const errorValue = rawValue;
486
- return {
487
- __type: "Error",
488
- name: errorValue.name,
489
- message: errorValue.message,
490
- stack: errorValue.stack ?? ""
491
- };
492
- }
493
- if (rawValue instanceof Promise) return encodeTaggedValue("Promise");
494
- if (rawValue instanceof WeakMap) return encodeTaggedValue("WeakMap");
495
- if (rawValue instanceof WeakSet) return encodeTaggedValue("WeakSet");
496
- if (rawValue && typeof rawValue === "object") return withCircularGuard(rawValue, stack, () => {
497
- const result = {};
498
- const entries = Object.entries(rawValue);
499
- entries.sort(([a], [b]) => a.localeCompare(b));
500
- for (const [key, entryValue] of entries) result[key] = normalizeOptionsValue(entryValue, stack);
501
- return result;
502
- });
503
- return encodeTaggedValue(typeof rawValue, String(rawValue));
504
- }
505
- function createCompilerContextCacheKey(opts) {
506
- try {
507
- const runtimeCacheScopeKey = createRuntimeCacheScopeKey(opts);
508
- const keyStore = getCompilerContextKeyCacheStore(opts);
509
- const cached = keyStore.get(runtimeCacheScopeKey);
510
- if (cached !== void 0) return cached;
511
- const cacheKey = (0, _weapp_tailwindcss_shared_node.md5)(serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScopeValue(opts))));
512
- keyStore.set(runtimeCacheScopeKey, cacheKey);
513
- return cacheKey;
514
- } catch (error) {
515
- _weapp_tailwindcss_logger.logger.debug("skip compiler context cache: %O", error);
516
- return;
517
- }
518
- }
519
- function withCompilerContextCache(opts, factory) {
520
- const cacheKey = createCompilerContextCacheKey(opts);
521
- if (cacheKey) {
522
- const cached = compilerContextCache.get(cacheKey);
523
- if (cached) return cached;
524
- }
525
- const ctx = factory();
526
- if (cacheKey) compilerContextCache.set(cacheKey, ctx);
527
- return ctx;
528
- }
529
- //#endregion
530
- //#region src/context/custom-attributes.ts
531
- function toCustomAttributesEntities(customAttributes) {
532
- if (!customAttributes) return [];
533
- if ((0, _weapp_tailwindcss_shared.isMap)(customAttributes)) return [...customAttributes.entries()];
534
- return Object.entries(customAttributes);
535
- }
536
- //#endregion
537
- //#region src/constants.ts
538
- const pluginName = "weapp-tailwindcss";
539
- const vitePluginName = "weapp-tailwindcss:adaptor";
540
- const DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS = {
541
- "tailwind-merge": "@weapp-tailwindcss/merge",
542
- "class-variance-authority": "@weapp-tailwindcss/cva",
543
- "tailwind-variants": "@weapp-tailwindcss/variants"
544
- };
545
- //#endregion
546
- //#region src/babel/index.ts
547
- function _interopDefaultCompat(e) {
548
- return e && typeof e === "object" && "default" in e ? e.default : e;
549
- }
550
- const traverse = _interopDefaultCompat(_babel_traverse.default);
551
- //#endregion
552
- //#region src/utils/nameMatcher.ts
553
- const NEVER_MATCH_NAME$1 = () => false;
554
- const GLOBAL_FLAG_REGEXP = /g/g;
555
- function buildFuzzyMatcher(fuzzyStrings) {
556
- if (fuzzyStrings.length === 0) return;
557
- if (fuzzyStrings.length === 1) {
558
- const [needle] = fuzzyStrings;
559
- return (value) => value.includes(needle);
560
- }
561
- const unique = [...new Set(fuzzyStrings)];
562
- const pattern = new RegExp(unique.map(_weapp_core_regex.escapeStringRegexp).join("|"));
563
- return (value) => pattern.test(value);
564
- }
565
- function normaliseRegex(regex) {
566
- const { source, flags } = regex;
567
- if (!flags.includes("g")) return regex;
568
- return new RegExp(source, flags.replace(GLOBAL_FLAG_REGEXP, ""));
569
- }
570
- function createNameMatcher(list, { exact = false } = {}) {
571
- if (!list || list.length === 0) return NEVER_MATCH_NAME$1;
572
- const exactStrings = exact ? /* @__PURE__ */ new Set() : void 0;
573
- const fuzzyStrings = [];
574
- const regexList = [];
575
- for (const item of list) if (typeof item === "string") if (exact) exactStrings.add(item);
576
- else fuzzyStrings.push(item);
577
- else regexList.push(normaliseRegex(item));
578
- if (exact) {
579
- const exactStringCount = exactStrings?.size ?? 0;
580
- if (exactStringCount === 1 && regexList.length === 0) {
581
- const [needle] = exactStrings;
582
- return (value) => value === needle;
583
- }
584
- if (regexList.length === 0) return (value) => exactStrings.has(value);
585
- if (exactStringCount === 0 && regexList.length === 1) {
586
- const [regex] = regexList;
587
- return (value) => regex.test(value);
588
- }
589
- return (value) => {
590
- if (exactStrings?.has(value)) return true;
591
- return regexList.some((regex) => regex.test(value));
592
- };
593
- }
594
- const fuzzyMatcher = exact ? void 0 : buildFuzzyMatcher(fuzzyStrings);
595
- const hasRegex = regexList.length > 0;
596
- if (fuzzyMatcher && !hasRegex) return fuzzyMatcher;
597
- if (!fuzzyMatcher && regexList.length === 1) {
598
- const [regex] = regexList;
599
- return (value) => regex.test(value);
600
- }
601
- return (value) => {
602
- if (fuzzyMatcher?.(value)) return true;
603
- if (!hasRegex) return false;
604
- return regexList.some((regex) => regex.test(value));
605
- };
606
- }
607
- //#endregion
608
- //#region src/js/babel/parse.ts
609
- const parseCache = new lru_cache.LRUCache({ max: 1024 });
610
- function genCacheKey(source, options) {
611
- if (typeof options === "string") return source + options;
612
- return source + JSON.stringify(options, (_, val) => typeof val === "function" ? val.toString() : val);
613
- }
614
- function babelParse(code, opts = {}) {
615
- const { cache, cacheKey, ...rest } = opts;
616
- const cacheKeyString = genCacheKey(code, cacheKey ?? rest);
617
- let result;
618
- if (cache) result = parseCache.get(cacheKeyString);
619
- if (!result) {
620
- const { cache: _cache, cacheKey: _cacheKey, ...parseOptions } = opts;
621
- result = (0, _babel_parser.parse)(code, parseOptions);
622
- if (cache) parseCache.set(cacheKeyString, result);
623
- }
624
- return result;
625
- }
626
- //#endregion
627
- //#region src/wxml/shared.ts
628
- const NEWLINE_RE = /[\n\r]+/g;
629
- function replaceWxml(original, options = {
630
- keepEOL: false,
631
- escapeMap: _weapp_core_escape.MappingChars2String
632
- }) {
633
- const { keepEOL, escapeMap, ignoreHead } = options;
634
- let res = original;
635
- if (!keepEOL) res = res.replaceAll(NEWLINE_RE, "");
636
- res = (0, _weapp_core_escape.escape)(res, {
637
- map: escapeMap,
638
- ignoreHead
639
- });
640
- return res;
641
- }
642
- //#endregion
643
- //#region src/shared/classname-transform.ts
644
- const escapedCandidateCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
645
- const defaultEscapedCandidateCache = /* @__PURE__ */ new Map();
646
- let lastEscapedCandidateEscapeMap;
647
- let lastEscapedCandidateCacheStore;
648
- function isUrlLikeCandidate(candidate) {
649
- return candidate.startsWith("//") || candidate.startsWith("http://") || candidate.startsWith("https://");
650
- }
651
- function isArbitraryValueCandidate(candidate) {
652
- let hasOpenBracket = false;
653
- let hasCloseBracket = false;
654
- for (let i = 0; i < candidate.length; i++) {
655
- const char = candidate[i];
656
- if (char === "[") hasOpenBracket = true;
657
- else if (char === "]") hasCloseBracket = true;
658
- if (hasOpenBracket && hasCloseBracket) break;
659
- }
660
- if (!hasOpenBracket || !hasCloseBracket) return false;
661
- if (isUrlLikeCandidate(candidate.trim())) return false;
662
- return true;
663
- }
664
- function shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion) {
665
- if (jsArbitraryValueFallback === true) return true;
666
- if (jsArbitraryValueFallback === false) return false;
667
- return tailwindcssMajorVersion === 4 && (!classNameSet || classNameSet.size === 0);
668
- }
669
- function shouldEnableArbitraryValueFallback({ classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion }) {
670
- return shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion);
671
- }
672
- const SKIP_RESULT = { decision: "skip" };
673
- const DIRECT_RESULT = { decision: "direct" };
674
- const FALLBACK_RESULT = { decision: "fallback" };
675
- function getEscapedCandidateCacheStore(escapeMap) {
676
- if (!escapeMap) return defaultEscapedCandidateCache;
677
- if (escapeMap === lastEscapedCandidateEscapeMap && lastEscapedCandidateCacheStore) return lastEscapedCandidateCacheStore;
678
- let store = escapedCandidateCacheByEscapeMap.get(escapeMap);
679
- if (!store) {
680
- store = /* @__PURE__ */ new Map();
681
- escapedCandidateCacheByEscapeMap.set(escapeMap, store);
682
- }
683
- lastEscapedCandidateEscapeMap = escapeMap;
684
- lastEscapedCandidateCacheStore = store;
685
- return store;
686
- }
687
- function getEscapedCandidate(candidate, escapeMap, store = getEscapedCandidateCacheStore(escapeMap)) {
688
- let cached = store.get(candidate);
689
- if (cached === void 0) {
690
- cached = replaceWxml(candidate, { escapeMap });
691
- store.set(candidate, cached);
692
- }
693
- return cached;
694
- }
695
- /**
696
- * JS 转译严格遵循 runtime class set:
697
- * 1. 直接命中 classNameSet 原始值;
698
- * 2. 兼容命中 classNameSet 中已转义值;
699
- * 3. 仅在受控条件下允许 class 语义兜底。
700
- *
701
- * 返回结构化结果,附带已计算的 escapedValue 以避免下游重复 escape。
702
- */
703
- function resolveClassNameTransformWithResult(candidate, { alwaysEscape, classNameSet, escapeMap, jsArbitraryValueFallback, jsPreserveClass, tailwindcssMajorVersion, classContext }) {
704
- if (alwaysEscape) return DIRECT_RESULT;
705
- if (jsPreserveClass?.(candidate)) return SKIP_RESULT;
706
- if (classNameSet?.has(candidate)) return DIRECT_RESULT;
707
- if (classNameSet && classNameSet.size > 0) {
708
- const escapedCandidate = getEscapedCandidate(candidate, escapeMap);
709
- if (escapedCandidate !== candidate && classNameSet.has(escapedCandidate)) return {
710
- decision: "escaped",
711
- escapedValue: escapedCandidate
712
- };
713
- }
714
- if (classContext && shouldEnableArbitraryValueFallbackByInputs(classNameSet, jsArbitraryValueFallback, tailwindcssMajorVersion) && isArbitraryValueCandidate(candidate)) return FALLBACK_RESULT;
715
- return SKIP_RESULT;
716
- }
717
- //#endregion
718
- //#region src/utils/decode.ts
719
- const unicodeEscapeRE = /\\u([\dA-Fa-f]{4})/g;
720
- const unicodeEscapeTestRE = /\\u[\dA-Fa-f]{4}/;
721
- function decodeUnicode(value) {
722
- if (!unicodeEscapeTestRE.test(value)) return value;
723
- return value.replace(unicodeEscapeRE, (_match, hex) => {
724
- const codePoint = Number.parseInt(hex, 16);
725
- return Number.isNaN(codePoint) ? _match : String.fromCharCode(codePoint);
726
- });
727
- }
728
- function decodeUnicode2(input) {
729
- if (!unicodeEscapeTestRE.test(input)) return input;
730
- try {
731
- return JSON.parse(`"${input}"`);
732
- } catch (_error) {
733
- return decodeUnicode(input);
734
- }
735
- }
736
- //#endregion
737
- //#region src/js/class-context.ts
738
- const CLASS_LIKE_KEYWORDS = new Set([
739
- "class",
740
- "classname",
741
- "hoverclass",
742
- "virtualhostclass",
743
- "rootclass"
744
- ]);
745
- const CLASS_HELPER_IDENTIFIERS = new Set([
746
- "cn",
747
- "clsx",
748
- "classnames",
749
- "twmerge",
750
- "cva",
751
- "tv",
752
- "cx",
753
- "r"
754
- ]);
755
- const DASH_CODE = 45;
756
- const COLON_CODE = 58;
757
- const UPPERCASE_A_CODE = 65;
758
- const UPPERCASE_Z_CODE = 90;
759
- const UNDERSCORE_CODE = 95;
760
- const ASCII_MAX_CODE = 127;
761
- const NORMALIZE_KEYWORD_REGEXP = /[-_:]/g;
762
- function normalizeKeyword(name) {
763
- const length = name.length;
764
- let firstNormalizedIndex = -1;
765
- for (let i = 0; i < length; i++) {
766
- const code = name.charCodeAt(i);
767
- if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE || code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
768
- firstNormalizedIndex = i;
769
- break;
770
- }
771
- if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
772
- }
773
- if (firstNormalizedIndex === -1) return name;
774
- let normalized = name.slice(0, firstNormalizedIndex);
775
- for (let i = firstNormalizedIndex; i < length; i++) {
776
- const code = name.charCodeAt(i);
777
- if (code === DASH_CODE || code === UNDERSCORE_CODE || code === COLON_CODE) continue;
778
- if (code >= UPPERCASE_A_CODE && code <= UPPERCASE_Z_CODE) {
779
- normalized += String.fromCharCode(code + 32);
780
- continue;
781
- }
782
- if (code > ASCII_MAX_CODE) return name.replace(NORMALIZE_KEYWORD_REGEXP, "").toLowerCase();
783
- normalized += name[i];
784
- }
785
- return normalized;
786
- }
787
- function readObjectKeyName(path) {
788
- if (path.isIdentifier()) return path.node.name;
789
- if (path.isStringLiteral()) return path.node.value;
790
- if (path.isTemplateLiteral() && path.node.expressions.length === 0) return path.node.quasis[0]?.value.cooked ?? path.node.quasis[0]?.value.raw;
791
- }
792
- function isClassLikeObjectProperty(path, valuePath) {
793
- if (!path.isObjectProperty()) return false;
794
- if (path.get("value") !== valuePath) return false;
795
- const keyName = readObjectKeyName(path.get("key"));
796
- if (!keyName) return false;
797
- return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(keyName));
798
- }
799
- function isClassLikeJsxAttribute(path) {
800
- if (!path.isJSXAttribute()) return false;
801
- const namePath = path.get("name");
802
- if (!namePath.isJSXIdentifier()) return false;
803
- return CLASS_LIKE_KEYWORDS.has(normalizeKeyword(namePath.node.name));
804
- }
805
- function readCallHelperName(calleePath) {
806
- if (calleePath.isIdentifier()) return calleePath.node.name;
807
- if (calleePath.isMemberExpression()) {
808
- const propertyPath = calleePath.get("property");
809
- if (propertyPath.isIdentifier()) return propertyPath.node.name;
810
- if (propertyPath.isStringLiteral()) return propertyPath.node.value;
811
- }
812
- }
813
- function isClassLikeCallExpression(path, valuePath) {
814
- if (!path.isCallExpression()) return false;
815
- const helperName = readCallHelperName(path.get("callee"));
816
- if (!helperName || !CLASS_HELPER_IDENTIFIERS.has(normalizeKeyword(helperName))) return false;
817
- return path.get("arguments").some((argumentPath) => argumentPath.node === valuePath.node);
818
- }
819
- /**
820
- * 判断字符串字面量是否处于 class 语义上下文。
821
- * 仅用于受控兜底场景,避免将普通业务文本误判为 class。
822
- */
823
- function isClassContextLiteralPath(path) {
824
- let current = path;
825
- while (current.parentPath) {
826
- const parent = current.parentPath;
827
- if (isClassLikeObjectProperty(parent, current)) return true;
828
- if (isClassLikeJsxAttribute(parent)) return true;
829
- if (isClassLikeCallExpression(parent, current)) return true;
830
- current = parent;
831
- }
832
- return false;
833
- }
834
- //#endregion
835
- //#region src/js/handlers.ts
836
- const debug = require_runtime_patch.createDebug("[js:handlers] ");
837
- const replacementCacheByEscapeMap = /* @__PURE__ */ new WeakMap();
838
- const defaultReplacementCache = /* @__PURE__ */ new Map();
839
- const WEAPP_TW_IGNORE_MARKER = "weapp-tw";
840
- const IGNORE_MARKER = "ignore";
841
- function getReplacementCacheStore(escapeMap) {
842
- if (!escapeMap) return defaultReplacementCache;
843
- let store = replacementCacheByEscapeMap.get(escapeMap);
844
- if (!store) {
845
- store = /* @__PURE__ */ new Map();
846
- replacementCacheByEscapeMap.set(escapeMap, store);
847
- }
848
- return store;
849
- }
850
- function getReplacement(candidate, escapeMap, store = getReplacementCacheStore(escapeMap)) {
851
- let cached = store.get(candidate);
852
- if (cached === void 0) {
853
- cached = replaceWxml(candidate, { escapeMap });
854
- store.set(candidate, cached);
855
- }
856
- return cached;
857
- }
858
- function hasIgnoreComment(node) {
859
- const { leadingComments } = node;
860
- if (!Array.isArray(leadingComments) || leadingComments.length === 0) return false;
861
- for (const comment of leadingComments) {
862
- const { value } = comment;
863
- if (value.includes(WEAPP_TW_IGNORE_MARKER) && value.includes(IGNORE_MARKER)) return true;
864
- }
865
- return false;
866
- }
867
- function extractLiteralValue(path, { unescapeUnicode, arbitraryValues }) {
868
- const allowDoubleQuotes = arbitraryValues?.allowDoubleQuotes;
869
- const { node } = path;
870
- let offset = 0;
871
- let original;
872
- if (node.type === "StringLiteral") {
873
- offset = 1;
874
- original = node.value;
875
- } else if (node.type === "TemplateElement") original = node.value.raw;
876
- else original = "";
877
- let literal = original;
878
- if (unescapeUnicode && original.includes("\\u")) literal = decodeUnicode2(original);
879
- return {
880
- allowDoubleQuotes,
881
- literal,
882
- offset,
883
- original
884
- };
885
- }
886
- function createCandidatePlanResolver(options, classContext) {
887
- const { escapeMap } = options;
888
- const replacementCache = getReplacementCacheStore(escapeMap);
889
- const transformOptions = classContext ? {
890
- ...options,
891
- classContext
892
- } : options;
893
- let firstCandidate = "";
894
- let firstPlan;
895
- let cache;
896
- const buildCandidatePlan = (candidate) => {
897
- const result = resolveClassNameTransformWithResult(candidate, transformOptions);
898
- if (result.decision === "skip") return { result };
899
- let replacement;
900
- if (result.decision === "escaped" && result.escapedValue) {
901
- replacement = result.escapedValue;
902
- replacementCache.set(candidate, replacement);
903
- } else replacement = getReplacement(candidate, escapeMap, replacementCache);
904
- return {
905
- result,
906
- replacement
907
- };
908
- };
909
- return (candidate) => {
910
- if (cache) {
911
- const cached = cache.get(candidate);
912
- if (cached) return cached;
913
- } else if (firstPlan && candidate === firstCandidate) return firstPlan;
914
- const plan = buildCandidatePlan(candidate);
915
- if (!firstPlan) {
916
- firstCandidate = candidate;
917
- firstPlan = plan;
918
- return plan;
919
- }
920
- if (!cache) {
921
- cache = /* @__PURE__ */ new Map();
922
- cache.set(firstCandidate, firstPlan);
923
- }
924
- cache.set(candidate, plan);
925
- return plan;
926
- };
927
- }
928
- function replaceHandleValue(path, options) {
929
- const { needEscaped = false } = options;
930
- const { classNameSet, alwaysEscape } = options;
931
- const fallbackEnabled = shouldEnableArbitraryValueFallback(options);
932
- if (!alwaysEscape && !fallbackEnabled && (!classNameSet || classNameSet.size === 0)) return;
933
- if (hasIgnoreComment(path.node)) return;
934
- const { literal, original, allowDoubleQuotes, offset } = extractLiteralValue(path, options);
935
- const candidates = (0, _weapp_tailwindcss_shared_extractors.splitCode)(literal, allowDoubleQuotes);
936
- if (candidates.length === 0) return;
937
- const debugEnabled = debug.enabled;
938
- const classContext = options.wrapExpression || isClassContextLiteralPath(path);
939
- let transformed = literal;
940
- let mutated = false;
941
- let matchedCandidateCount = 0;
942
- let escapedDecisionCount = 0;
943
- let fallbackDecisionCount = 0;
944
- let escapedSamples;
945
- let skippedSamples;
946
- const resolveCandidatePlan = createCandidatePlanResolver(options, classContext);
947
- for (const candidate of candidates) {
948
- const plan = resolveCandidatePlan(candidate);
949
- if (plan.result.decision === "skip") {
950
- if (debugEnabled) {
951
- if (!skippedSamples) skippedSamples = [];
952
- if (skippedSamples.length < 6) skippedSamples.push(candidate);
953
- }
954
- continue;
955
- }
956
- if (debugEnabled) {
957
- matchedCandidateCount += 1;
958
- if (plan.result.decision === "escaped") {
959
- escapedDecisionCount += 1;
960
- if (!escapedSamples) escapedSamples = [];
961
- if (escapedSamples.length < 6) escapedSamples.push(candidate);
962
- }
963
- if (plan.result.decision === "fallback") fallbackDecisionCount += 1;
964
- }
965
- const replaced = transformed.replace(candidate, plan.replacement);
966
- if (replaced !== transformed) {
967
- transformed = replaced;
968
- mutated = true;
969
- }
970
- }
971
- const node = path.node;
972
- if (!mutated || typeof node.start !== "number" || typeof node.end !== "number") return;
973
- if (debugEnabled) debug("runtimeSet size=%d fallbackTriggered=%s candidates=%d matched=%d escapedHits=%d skipped=%d file=%s escapedSamples=%s skippedSamples=%s", classNameSet?.size ?? 0, fallbackDecisionCount > 0, candidates.length, matchedCandidateCount, escapedDecisionCount, skippedSamples?.length ?? 0, options.filename ?? "unknown", escapedSamples?.join(",") || "-", skippedSamples?.join(",") || "-");
974
- const start = node.start + offset;
975
- const end = node.end - offset;
976
- if (start >= end || transformed === original) return;
977
- return {
978
- start,
979
- end,
980
- value: needEscaped ? (0, _ast_core_escape.jsStringEscape)(transformed) : transformed,
981
- path
982
- };
983
- }
984
- //#endregion
985
- //#region src/js/sourceAnalysis.ts
986
- function hasReplacementEntries(replacements) {
987
- for (const key in replacements) if (Object.hasOwn(replacements, key)) return true;
988
- return false;
989
- }
990
- function createModuleSpecifierReplacementToken(path, replacement) {
991
- const node = path.node;
992
- if (node.value === replacement) return;
993
- if (typeof node.start !== "number" || typeof node.end !== "number") return;
994
- const start = node.start + 1;
995
- const end = node.end - 1;
996
- if (start >= end) return;
997
- return {
998
- start,
999
- end,
1000
- value: replacement,
1001
- path
1002
- };
1003
- }
1004
- function collectModuleSpecifierReplacementTokens(analysis, replacements) {
1005
- if (!hasReplacementEntries(replacements)) return [];
1006
- if (analysis.importDeclarations.size === 0 && analysis.exportDeclarations.size === 0 && analysis.requireCallPaths.length === 0 && analysis.walker.imports.size === 0) return [];
1007
- const tokens = [];
1008
- const applyReplacement = (path) => {
1009
- const replacement = replacements[path.node.value];
1010
- if (!replacement) return;
1011
- const token = createModuleSpecifierReplacementToken(path, replacement);
1012
- if (token) tokens.push(token);
1013
- };
1014
- for (const importPath of analysis.importDeclarations) {
1015
- const source = importPath.get("source");
1016
- if (source.isStringLiteral()) applyReplacement(source);
1017
- }
1018
- for (const exportPath of analysis.exportDeclarations) if (exportPath.isExportNamedDeclaration() || exportPath.isExportAllDeclaration()) {
1019
- const source = exportPath.get("source");
1020
- if (source && !Array.isArray(source) && source.isStringLiteral()) applyReplacement(source);
1021
- }
1022
- for (const literalPath of analysis.requireCallPaths) applyReplacement(literalPath);
1023
- for (const token of analysis.walker.imports) {
1024
- const replacement = replacements[token.source];
1025
- if (replacement) token.source = replacement;
1026
- }
1027
- return tokens;
1028
- }
1029
- //#endregion
1030
- //#region src/js/babel/process.ts
1031
- const optionVariantsCache = /* @__PURE__ */ new WeakMap();
1032
- function getNeedEscapedOptions(options, needEscaped) {
1033
- if (options.needEscaped === needEscaped) return options;
1034
- let cached = optionVariantsCache.get(options);
1035
- if (!cached) {
1036
- cached = {};
1037
- optionVariantsCache.set(options, cached);
1038
- }
1039
- if (needEscaped) {
1040
- if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
1041
- ...options,
1042
- needEscaped: true
1043
- };
1044
- return cached.stringLiteralOptions;
1045
- }
1046
- if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
1047
- ...options,
1048
- needEscaped: false
1049
- };
1050
- return cached.templateLiteralOptions;
1051
- }
1052
- function processUpdatedSource(rawSource, options, analysis) {
1053
- const { targetPaths, jsTokenUpdater, ignoredPaths } = analysis;
1054
- if (targetPaths.length === 0 && !options.moduleSpecifierReplacements && jsTokenUpdater.length === 0) return new magic_string.default(rawSource);
1055
- const replacementTokens = [];
1056
- for (const path of targetPaths) {
1057
- if (ignoredPaths.has(path)) continue;
1058
- const token = replaceHandleValue(path, path.isStringLiteral() ? getNeedEscapedOptions(options, true) : getNeedEscapedOptions(options, false));
1059
- if (token) replacementTokens.push(token);
1060
- }
1061
- if (options.moduleSpecifierReplacements) replacementTokens.push(...collectModuleSpecifierReplacementTokens(analysis, options.moduleSpecifierReplacements));
1062
- if (jsTokenUpdater.length + replacementTokens.length === 0) return new magic_string.default(rawSource);
1063
- const ms = new magic_string.default(rawSource);
1064
- jsTokenUpdater.push(...replacementTokens).filter((token) => !ignoredPaths.has(token.path)).updateMagicString(ms);
1065
- return ms;
1066
- }
1067
- //#endregion
1068
- //#region src/js/evalTransforms.ts
1069
- const evalHandlerOptionsCache = /* @__PURE__ */ new WeakMap();
1070
- const EVAL_SCOPE_ERROR_REGEXP = /pass a scope and parentPath|traversing a Program\/File/i;
1071
- function isEvalPath(path) {
1072
- if (path.isCallExpression()) return path.get("callee").isIdentifier({ name: "eval" });
1073
- return false;
1074
- }
1075
- function createEvalReplacementToken(path, updated) {
1076
- const node = path.node;
1077
- let offset = 0;
1078
- let original;
1079
- if (path.isStringLiteral()) {
1080
- offset = 1;
1081
- original = path.node.value;
1082
- } else if (path.isTemplateElement()) original = path.node.value.raw;
1083
- else original = "";
1084
- if (typeof node.start !== "number" || typeof node.end !== "number") return;
1085
- const start = node.start + offset;
1086
- const end = node.end - offset;
1087
- if (start >= end) return;
1088
- if (original === updated) return;
1089
- return {
1090
- start,
1091
- end,
1092
- value: path.isStringLiteral() ? (0, _ast_core_escape.jsStringEscape)(updated) : updated,
1093
- path
1094
- };
1095
- }
1096
- function handleEvalStringLiteral(path, handlerOptions, updater, handler) {
1097
- const { code } = handler(path.node.value, handlerOptions);
1098
- if (!code) return;
1099
- const token = createEvalReplacementToken(path, code);
1100
- if (token) updater.addToken(token);
1101
- }
1102
- function handleEvalTemplateElement(path, handlerOptions, updater, handler) {
1103
- const { code } = handler(path.node.value.raw, handlerOptions);
1104
- if (!code) return;
1105
- const token = createEvalReplacementToken(path, code);
1106
- if (token) updater.addToken(token);
1107
- }
1108
- function getEvalStringHandlerOptions(options) {
1109
- if (options.needEscaped === false && options.generateMap === false) return options;
1110
- let cached = evalHandlerOptionsCache.get(options);
1111
- if (!cached) {
1112
- cached = {};
1113
- evalHandlerOptionsCache.set(options, cached);
1114
- }
1115
- if (!cached.stringLiteralOptions) cached.stringLiteralOptions = {
1116
- ...options,
1117
- needEscaped: false,
1118
- generateMap: false
1119
- };
1120
- return cached.stringLiteralOptions;
1121
- }
1122
- function getEvalTemplateHandlerOptions(options) {
1123
- if (options.generateMap === false) return options;
1124
- let cached = evalHandlerOptionsCache.get(options);
1125
- if (!cached) {
1126
- cached = {};
1127
- evalHandlerOptionsCache.set(options, cached);
1128
- }
1129
- if (!cached.templateLiteralOptions) cached.templateLiteralOptions = {
1130
- ...options,
1131
- generateMap: false
1132
- };
1133
- return cached.templateLiteralOptions;
1134
- }
1135
- function walkEvalExpression(path, options, updater, handler) {
1136
- const stringHandlerOptions = getEvalStringHandlerOptions(options);
1137
- const templateHandlerOptions = getEvalTemplateHandlerOptions(options);
1138
- const maybeTraverse = path?.traverse;
1139
- if (typeof maybeTraverse === "function") try {
1140
- return maybeTraverse.call(path, {
1141
- StringLiteral(innerPath) {
1142
- handleEvalStringLiteral(innerPath, stringHandlerOptions, updater, handler);
1143
- },
1144
- TemplateElement(innerPath) {
1145
- handleEvalTemplateElement(innerPath, templateHandlerOptions, updater, handler);
1146
- }
1147
- });
1148
- } catch (error) {
1149
- const msg = error?.message ?? "";
1150
- if (!EVAL_SCOPE_ERROR_REGEXP.test(msg)) throw error;
1151
- }
1152
- const getArgs = path?.get?.("arguments");
1153
- if (Array.isArray(getArgs)) {
1154
- for (const arg of getArgs) {
1155
- if (arg?.isStringLiteral?.()) {
1156
- handleEvalStringLiteral(arg, stringHandlerOptions, updater, handler);
1157
- continue;
1158
- }
1159
- if (arg?.isTemplateLiteral?.()) for (const quasi of arg.get("quasis")) handleEvalTemplateElement(quasi, templateHandlerOptions, updater, handler);
1160
- }
1161
- return;
1162
- }
1163
- const nodeArgs = path?.node?.arguments;
1164
- if (Array.isArray(nodeArgs)) {
1165
- for (const n of nodeArgs) if (n?.type === "StringLiteral") handleEvalStringLiteral({
1166
- node: n,
1167
- isStringLiteral: () => true
1168
- }, stringHandlerOptions, updater, handler);
1169
- else if (n?.type === "TemplateLiteral" && Array.isArray(n.quasis)) for (const q of n.quasis) handleEvalTemplateElement({
1170
- node: q,
1171
- isStringLiteral: () => false,
1172
- isTemplateElement: () => true
1173
- }, templateHandlerOptions, updater, handler);
1174
- }
1175
- }
1176
- //#endregion
1177
- //#region \0@oxc-project+runtime@0.129.0/helpers/typeof.js
1178
- function _typeof(o) {
1179
- "@babel/helpers - typeof";
1180
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
1181
- return typeof o;
1182
- } : function(o) {
1183
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
1184
- }, _typeof(o);
1185
- }
1186
- //#endregion
1187
- //#region \0@oxc-project+runtime@0.129.0/helpers/toPrimitive.js
1188
- function toPrimitive(t, r) {
1189
- if ("object" != _typeof(t) || !t) return t;
1190
- var e = t[Symbol.toPrimitive];
1191
- if (void 0 !== e) {
1192
- var i = e.call(t, r || "default");
1193
- if ("object" != _typeof(i)) return i;
1194
- throw new TypeError("@@toPrimitive must return a primitive value.");
1195
- }
1196
- return ("string" === r ? String : Number)(t);
1197
- }
1198
- //#endregion
1199
- //#region \0@oxc-project+runtime@0.129.0/helpers/toPropertyKey.js
1200
- function toPropertyKey(t) {
1201
- var i = toPrimitive(t, "string");
1202
- return "symbol" == _typeof(i) ? i : i + "";
1203
- }
1204
- //#endregion
1205
- //#region \0@oxc-project+runtime@0.129.0/helpers/defineProperty.js
1206
- function _defineProperty(e, r, t) {
1207
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
1208
- value: t,
1209
- enumerable: !0,
1210
- configurable: !0,
1211
- writable: !0
1212
- }) : e[r] = t, e;
1213
- }
1214
- //#endregion
1215
- //#region src/js/JsTokenUpdater.ts
1216
- /**
1217
- * Lightweight helper that batches updates to {@link MagicString}.
1218
- * It keeps the transformation logic out of the traversal code and makes
1219
- * it easier to reason about the order in which tokens are written back.
1220
- */
1221
- var JsTokenUpdater = class {
1222
- constructor({ value } = {}) {
1223
- _defineProperty(this, "tokens", void 0);
1224
- this.tokens = value ? [...value] : [];
1225
- }
1226
- addToken(token) {
1227
- if (token) this.tokens.push(token);
1228
- }
1229
- push(...args) {
1230
- this.tokens.push(...args);
1231
- return this;
1232
- }
1233
- /**
1234
- * 待写入的 token 数量。
1235
- */
1236
- get length() {
1237
- return this.tokens.length;
1238
- }
1239
- map(callbackfn) {
1240
- this.tokens = this.tokens.map(callbackfn);
1241
- return this;
1242
- }
1243
- filter(callbackfn) {
1244
- this.tokens = this.tokens.filter(callbackfn);
1245
- return this;
1246
- }
1247
- updateMagicString(ms) {
1248
- for (const { start, end, value } of this.tokens) ms.update(start, end, value);
1249
- return ms;
1250
- }
1251
- };
1252
- //#endregion
1253
- //#region src/js/module-graph/ignored-exports.ts
1254
- var IgnoredExportsTracker = class {
1255
- constructor(options) {
1256
- this.options = options;
1257
- _defineProperty(this, "ignoredExportNames", /* @__PURE__ */ new Map());
1258
- }
1259
- addIgnoredExport(filename, exportName) {
1260
- if (!exportName) return;
1261
- let pending = this.ignoredExportNames.get(filename);
1262
- if (!pending) {
1263
- pending = /* @__PURE__ */ new Set();
1264
- this.ignoredExportNames.set(filename, pending);
1265
- }
1266
- if (pending.has(exportName)) return;
1267
- pending.add(exportName);
1268
- const existing = this.options.modules.get(filename);
1269
- if (existing) this.applyIgnoredExportsToAnalysis(filename, existing.analysis);
1270
- }
1271
- registerIgnoredExportsFromTokens(resolved, tokens) {
1272
- for (const token of tokens) if (token.type === "ImportSpecifier") this.addIgnoredExport(resolved, token.imported);
1273
- else if (token.type === "ImportDefaultSpecifier") this.addIgnoredExport(resolved, "default");
1274
- }
1275
- applyIgnoredExportsToAnalysis(filename, analysis) {
1276
- const pending = this.ignoredExportNames.get(filename);
1277
- if (!pending || pending.size === 0) return;
1278
- const names = new Set(pending);
1279
- pending.clear();
1280
- const propagate = [];
1281
- for (const exportPath of analysis.exportDeclarations) {
1282
- if (names.size === 0) break;
1283
- if (exportPath.isExportDefaultDeclaration()) {
1284
- if (names.has("default")) {
1285
- analysis.walker.walkExportDefaultDeclaration(exportPath);
1286
- names.delete("default");
1287
- }
1288
- continue;
1289
- }
1290
- if (exportPath.isExportNamedDeclaration()) {
1291
- const source = exportPath.node.source?.value;
1292
- if (typeof source === "string") {
1293
- for (const spec of exportPath.get("specifiers")) {
1294
- if (!spec.isExportSpecifier()) continue;
1295
- const exported = spec.get("exported");
1296
- let exportedName;
1297
- if (exported.isIdentifier()) exportedName = exported.node.name;
1298
- else if (exported.isStringLiteral()) exportedName = exported.node.value;
1299
- if (!exportedName || !names.has(exportedName)) continue;
1300
- const local = spec.get("local");
1301
- if (local.isIdentifier()) {
1302
- propagate.push({
1303
- specifier: source,
1304
- exportName: local.node.name
1305
- });
1306
- names.delete(exportedName);
1307
- } else if (local.isStringLiteral()) {
1308
- propagate.push({
1309
- specifier: source,
1310
- exportName: local.node.value
1311
- });
1312
- names.delete(exportedName);
1313
- }
1314
- }
1315
- continue;
1316
- }
1317
- const declaration = exportPath.get("declaration");
1318
- if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) {
1319
- const id = decl.get("id");
1320
- if (id.isIdentifier()) {
1321
- const exportName = id.node.name;
1322
- if (names.has(exportName)) {
1323
- analysis.walker.walkVariableDeclarator(decl);
1324
- names.delete(exportName);
1325
- }
1326
- }
1327
- }
1328
- for (const spec of exportPath.get("specifiers")) {
1329
- if (!spec.isExportSpecifier()) continue;
1330
- const exported = spec.get("exported");
1331
- let exportedName;
1332
- if (exported.isIdentifier()) exportedName = exported.node.name;
1333
- else if (exported.isStringLiteral()) exportedName = exported.node.value;
1334
- if (!exportedName || !names.has(exportedName)) continue;
1335
- const local = spec.get("local");
1336
- analysis.walker.walkNode(local);
1337
- names.delete(exportedName);
1338
- }
1339
- continue;
1340
- }
1341
- if (exportPath.isExportAllDeclaration()) {
1342
- const source = exportPath.node.source?.value;
1343
- if (typeof source === "string") {
1344
- for (const exportName of names) propagate.push({
1345
- specifier: source,
1346
- exportName
1347
- });
1348
- names.clear();
1349
- }
1350
- }
1351
- }
1352
- for (const { specifier, exportName } of propagate) {
1353
- let resolved;
1354
- try {
1355
- resolved = this.options.resolve(specifier, filename);
1356
- } catch {
1357
- resolved = void 0;
1358
- }
1359
- if (!resolved) {
1360
- pending.add(exportName);
1361
- continue;
1362
- }
1363
- if (this.options.filter && !this.options.filter(resolved, specifier, filename)) {
1364
- pending.add(exportName);
1365
- continue;
1366
- }
1367
- this.addIgnoredExport(resolved, exportName);
1368
- }
1369
- for (const name of names) pending.add(name);
1370
- }
1371
- };
1372
- //#endregion
1373
- //#region src/js/ModuleGraph.ts
1374
- var JsModuleGraph = class {
1375
- constructor(entry, graphOptions) {
1376
- _defineProperty(this, "modules", /* @__PURE__ */ new Map());
1377
- _defineProperty(this, "queue", []);
1378
- _defineProperty(this, "resolve", void 0);
1379
- _defineProperty(this, "load", void 0);
1380
- _defineProperty(this, "filter", void 0);
1381
- _defineProperty(this, "maxDepth", void 0);
1382
- _defineProperty(this, "baseOptions", void 0);
1383
- _defineProperty(this, "parserOptions", void 0);
1384
- _defineProperty(this, "rootFilename", void 0);
1385
- _defineProperty(this, "ignoredExports", void 0);
1386
- this.resolve = graphOptions.resolve;
1387
- this.load = graphOptions.load;
1388
- this.filter = graphOptions.filter;
1389
- this.maxDepth = graphOptions.maxDepth ?? Number.POSITIVE_INFINITY;
1390
- const { moduleGraph: _moduleGraph, filename: _ignoredFilename, ...rest } = entry.handlerOptions;
1391
- this.baseOptions = {
1392
- ...rest,
1393
- filename: entry.filename
1394
- };
1395
- this.parserOptions = entry.handlerOptions.babelParserOptions;
1396
- this.rootFilename = entry.filename;
1397
- this.ignoredExports = new IgnoredExportsTracker({
1398
- resolve: this.resolve,
1399
- filter: this.filter,
1400
- modules: this.modules
1401
- });
1402
- this.modules.set(entry.filename, {
1403
- filename: entry.filename,
1404
- source: entry.source,
1405
- analysis: entry.analysis
1406
- });
1407
- this.queue.push({
1408
- filename: entry.filename,
1409
- depth: 0
1410
- });
1411
- }
1412
- build() {
1413
- this.collectDependencies();
1414
- let linked;
1415
- for (const [filename, state] of this.modules) {
1416
- if (filename === this.rootFilename) continue;
1417
- const childOptions = {
1418
- ...this.baseOptions,
1419
- filename
1420
- };
1421
- const code = processUpdatedSource(state.source, childOptions, state.analysis).toString();
1422
- if (code !== state.source) {
1423
- if (!linked) linked = {};
1424
- linked[filename] = { code };
1425
- }
1426
- }
1427
- return linked;
1428
- }
1429
- collectDependencies() {
1430
- while (this.queue.length > 0) {
1431
- const { filename, depth } = this.queue.shift();
1432
- if (depth >= this.maxDepth) continue;
1433
- const state = this.modules.get(filename);
1434
- if (!state) continue;
1435
- const dependencySpecifiers = /* @__PURE__ */ new Map();
1436
- for (const token of state.analysis.walker.imports) {
1437
- if (!dependencySpecifiers.has(token.source)) dependencySpecifiers.set(token.source, []);
1438
- dependencySpecifiers.get(token.source).push(token);
1439
- }
1440
- for (const exportPath of state.analysis.exportDeclarations) if (exportPath.isExportAllDeclaration() || exportPath.isExportNamedDeclaration()) {
1441
- const source = exportPath.node.source?.value;
1442
- if (typeof source === "string" && !dependencySpecifiers.has(source)) dependencySpecifiers.set(source, []);
1443
- }
1444
- for (const [specifier, tokens] of dependencySpecifiers) {
1445
- let resolved;
1446
- try {
1447
- resolved = this.resolve(specifier, filename);
1448
- } catch {
1449
- continue;
1450
- }
1451
- if (!resolved) continue;
1452
- if (this.filter && !this.filter(resolved, specifier, filename)) continue;
1453
- if (tokens.length > 0) this.ignoredExports.registerIgnoredExportsFromTokens(resolved, tokens);
1454
- if (this.modules.has(resolved)) continue;
1455
- let source;
1456
- try {
1457
- source = this.load(resolved);
1458
- } catch {
1459
- continue;
1460
- }
1461
- if (typeof source !== "string") continue;
1462
- let analysis;
1463
- try {
1464
- analysis = analyzeSource(babelParse(source, {
1465
- ...this.parserOptions,
1466
- sourceFilename: resolved
1467
- }), {
1468
- ...this.baseOptions,
1469
- filename: resolved
1470
- });
1471
- this.ignoredExports.applyIgnoredExportsToAnalysis(resolved, analysis);
1472
- } catch {
1473
- continue;
1474
- }
1475
- this.modules.set(resolved, {
1476
- filename: resolved,
1477
- source,
1478
- analysis
1479
- });
1480
- this.queue.push({
1481
- filename: resolved,
1482
- depth: depth + 1
1483
- });
1484
- }
1485
- }
1486
- }
1487
- };
1488
- //#endregion
1489
- //#region src/js/node-path-walker/export-handlers.ts
1490
- function walkExportDeclaration(ctx, path) {
1491
- if (path.isExportDeclaration()) {
1492
- if (path.isExportNamedDeclaration()) walkExportNamedDeclaration(ctx, path);
1493
- else if (path.isExportDefaultDeclaration()) walkExportDefaultDeclaration(ctx, path);
1494
- else if (path.isExportAllDeclaration()) walkExportAllDeclaration(ctx, path);
1495
- }
1496
- }
1497
- function walkExportNamedDeclaration(ctx, path) {
1498
- const declaration = path.get("declaration");
1499
- if (declaration.isVariableDeclaration()) for (const decl of declaration.get("declarations")) ctx.walkNode(decl);
1500
- const specifiers = path.get("specifiers");
1501
- for (const spec of specifiers) if (spec.isExportSpecifier()) {
1502
- const local = spec.get("local");
1503
- if (local.isIdentifier()) ctx.walkNode(local);
1504
- }
1505
- }
1506
- function walkExportDefaultDeclaration(ctx, path) {
1507
- const decl = path.get("declaration");
1508
- if (decl.isIdentifier()) ctx.walkNode(decl);
1509
- else ctx.walkNode(decl);
1510
- }
1511
- function walkExportAllDeclaration(ctx, path) {
1512
- const source = path.get("source");
1513
- if (source.isStringLiteral()) ctx.addImportToken({
1514
- declaration: path,
1515
- source: source.node.value,
1516
- type: "ExportAllDeclaration"
1517
- });
1518
- }
1519
- //#endregion
1520
- //#region src/js/node-path-walker/import-tokens.ts
1521
- function maybeAddImportToken(imports, arg) {
1522
- if (!(arg.isImportSpecifier() && arg.node.importKind !== "type" || arg.isImportDefaultSpecifier())) return false;
1523
- const importDeclaration = arg.parentPath;
1524
- if (!importDeclaration.isImportDeclaration() || importDeclaration.node.importKind === "type") return false;
1525
- if (arg.isImportSpecifier()) {
1526
- const imported = arg.get("imported");
1527
- if (imported.isIdentifier()) imports.add({
1528
- declaration: importDeclaration,
1529
- specifier: arg,
1530
- imported: imported.node.name,
1531
- local: arg.node.local.name,
1532
- source: importDeclaration.node.source.value,
1533
- type: "ImportSpecifier"
1534
- });
1535
- return true;
1536
- }
1537
- imports.add({
1538
- declaration: importDeclaration,
1539
- specifier: arg,
1540
- local: arg.node.local.name,
1541
- source: importDeclaration.node.source.value,
1542
- type: "ImportDefaultSpecifier"
1543
- });
1544
- return true;
1545
- }
1546
- //#endregion
1547
- //#region src/js/NodePathWalker.ts
1548
- const EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS = [];
1549
- const EMPTY_IMPORT_TOKENS = /* @__PURE__ */ new Set();
1550
- function NOOP_STRING_PATH_CALLBACK() {}
1551
- const NEVER_MATCH_NAME = () => false;
1552
- /**
1553
- * 遍历我们关注的调用表达式所关联的绑定,收集后续需要转换的字符串节点。
1554
- */
1555
- var NodePathWalker = class {
1556
- constructor({ ignoreCallExpressionIdentifiers, callback } = {}) {
1557
- _defineProperty(this, "ignoreCallExpressionIdentifiers", void 0);
1558
- _defineProperty(this, "callback", void 0);
1559
- _defineProperty(this, "isIgnoredCallIdentifier", void 0);
1560
- _defineProperty(this, "hasIgnoredCallIdentifiers", void 0);
1561
- _defineProperty(this, "importsStore", void 0);
1562
- _defineProperty(this, "visitedStore", void 0);
1563
- this.hasIgnoredCallIdentifiers = Boolean(ignoreCallExpressionIdentifiers && ignoreCallExpressionIdentifiers.length > 0);
1564
- this.ignoreCallExpressionIdentifiers = ignoreCallExpressionIdentifiers ?? EMPTY_IGNORE_CALL_EXPRESSION_IDENTIFIERS;
1565
- this.callback = callback ?? NOOP_STRING_PATH_CALLBACK;
1566
- this.isIgnoredCallIdentifier = this.hasIgnoredCallIdentifiers ? createNameMatcher(this.ignoreCallExpressionIdentifiers, { exact: true }) : NEVER_MATCH_NAME;
1567
- }
1568
- get imports() {
1569
- return this.importsStore ?? EMPTY_IMPORT_TOKENS;
1570
- }
1571
- getWritableImports() {
1572
- if (!this.importsStore) this.importsStore = /* @__PURE__ */ new Set();
1573
- return this.importsStore;
1574
- }
1575
- addImportToken(token) {
1576
- this.getWritableImports().add(token);
1577
- }
1578
- getVisited() {
1579
- if (!this.visitedStore) this.visitedStore = /* @__PURE__ */ new WeakSet();
1580
- return this.visitedStore;
1581
- }
1582
- walkVariableDeclarator(path) {
1583
- const init = path.get("init");
1584
- this.walkNode(init);
1585
- }
1586
- walkTemplateLiteral(path) {
1587
- for (const exp of path.get("expressions")) this.walkNode(exp);
1588
- for (const quasis of path.get("quasis")) this.callback(quasis);
1589
- }
1590
- walkStringLiteral(path) {
1591
- this.callback(path);
1592
- }
1593
- walkBinaryExpression(path) {
1594
- const left = path.get("left");
1595
- this.walkNode(left);
1596
- const right = path.get("right");
1597
- this.walkNode(right);
1598
- }
1599
- walkLogicalExpression(path) {
1600
- const left = path.get("left");
1601
- this.walkNode(left);
1602
- const right = path.get("right");
1603
- this.walkNode(right);
1604
- }
1605
- walkObjectExpression(path) {
1606
- const props = path.get("properties");
1607
- for (const prop of props) if (prop.isObjectProperty()) {
1608
- const key = prop.get("key");
1609
- this.walkNode(key);
1610
- const value = prop.get("value");
1611
- this.walkNode(value);
1612
- }
1613
- }
1614
- walkArrayExpression(path) {
1615
- const elements = path.get("elements");
1616
- for (const element of elements) this.walkNode(element);
1617
- }
1618
- walkNode(arg) {
1619
- const visited = this.getVisited();
1620
- if (visited.has(arg)) return;
1621
- visited.add(arg);
1622
- if (arg.isIdentifier()) {
1623
- const binding = arg?.scope?.getBinding?.(arg.node.name);
1624
- if (binding) this.walkNode(binding.path);
1625
- } else if (arg.isMemberExpression()) {
1626
- const objectPath = arg.get("object");
1627
- if (objectPath.isIdentifier()) {
1628
- const binding = arg?.scope?.getBinding?.(objectPath.node.name);
1629
- if (binding) {
1630
- if (binding.path.isVariableDeclarator()) this.walkVariableDeclarator(binding.path);
1631
- }
1632
- }
1633
- } else if (arg.isTemplateLiteral()) this.walkTemplateLiteral(arg);
1634
- else if (arg.isStringLiteral()) this.walkStringLiteral(arg);
1635
- else if (arg.isBinaryExpression()) this.walkBinaryExpression(arg);
1636
- else if (arg.isLogicalExpression()) this.walkLogicalExpression(arg);
1637
- else if (arg.isObjectExpression()) this.walkObjectExpression(arg);
1638
- else if (arg.isArrayExpression()) this.walkArrayExpression(arg);
1639
- else if (arg.isVariableDeclarator()) this.walkVariableDeclarator(arg);
1640
- else if (maybeAddImportToken(this.getWritableImports(), arg)) {}
1641
- }
1642
- /**
1643
- * Walk the arguments of a desired call expression so their bindings can be analysed.
1644
- */
1645
- walkCallExpression(path) {
1646
- if (!this.hasIgnoredCallIdentifiers) return;
1647
- const calleePath = path.get("callee");
1648
- if (calleePath.isIdentifier() && this.isIgnoredCallIdentifier(calleePath.node.name)) for (const arg of path.get("arguments")) this.walkNode(arg);
1649
- }
1650
- walkExportDeclaration(path) {
1651
- walkExportDeclaration(this, path);
1652
- }
1653
- walkExportNamedDeclaration(path) {
1654
- walkExportNamedDeclaration(this, path);
1655
- }
1656
- walkExportDefaultDeclaration(path) {
1657
- walkExportDefaultDeclaration(this, path);
1658
- }
1659
- walkExportAllDeclaration(path) {
1660
- walkExportAllDeclaration(this, path);
1661
- }
1662
- };
1663
- //#endregion
1664
- //#region src/js/taggedTemplateIgnore.ts
1665
- function createTaggedTemplateIgnore({ matcher, names }) {
1666
- const bindingIgnoreCache = /* @__PURE__ */ new Map();
1667
- const taggedTemplateIgnoreCache = /* @__PURE__ */ new WeakMap();
1668
- const seenBindings = /* @__PURE__ */ new Set();
1669
- let singleCanonicalIgnoreName;
1670
- let canonicalIgnoreNames;
1671
- for (const item of names ?? []) {
1672
- if (typeof item !== "string") continue;
1673
- if (singleCanonicalIgnoreName === void 0) {
1674
- singleCanonicalIgnoreName = item;
1675
- continue;
1676
- }
1677
- if (item === singleCanonicalIgnoreName) continue;
1678
- if (!canonicalIgnoreNames) {
1679
- canonicalIgnoreNames = new Set([singleCanonicalIgnoreName, item]);
1680
- continue;
1681
- }
1682
- canonicalIgnoreNames.add(item);
1683
- }
1684
- const hasCanonicalIgnoreNames = singleCanonicalIgnoreName !== void 0;
1685
- const matchesIgnoreName = (value) => {
1686
- if (hasCanonicalIgnoreNames) {
1687
- if (canonicalIgnoreNames) {
1688
- if (canonicalIgnoreNames.has(value)) return true;
1689
- } else if (value === singleCanonicalIgnoreName) return true;
1690
- }
1691
- return matcher(value);
1692
- };
1693
- const propertyMatches = (propertyPath) => {
1694
- if (!propertyPath) return false;
1695
- if (propertyPath.isIdentifier()) return matchesIgnoreName(propertyPath.node.name);
1696
- if (propertyPath.isStringLiteral()) return matchesIgnoreName(propertyPath.node.value);
1697
- return false;
1698
- };
1699
- const resolvesMemberExpressionToIgnore = (path, seen) => {
1700
- if (propertyMatches(path.get("property"))) return true;
1701
- const objectPath = path.get("object");
1702
- if (objectPath.isIdentifier()) {
1703
- const binding = (objectPath?.scope)?.getBinding?.(objectPath.node.name);
1704
- if (binding) return resolvesToWeappTwIgnore(binding, seen);
1705
- }
1706
- return false;
1707
- };
1708
- const resolvesToWeappTwIgnore = (binding, seen) => {
1709
- const cached = bindingIgnoreCache.get(binding);
1710
- if (cached !== void 0) return cached;
1711
- if (seen.has(binding)) return false;
1712
- seen.add(binding);
1713
- let result = false;
1714
- const bindingPath = binding.path;
1715
- if (bindingPath.isImportSpecifier()) {
1716
- const imported = bindingPath.node.imported;
1717
- if (imported.type === "Identifier" && matchesIgnoreName(imported.name)) result = true;
1718
- else if (imported.type === "StringLiteral" && matchesIgnoreName(imported.value)) result = true;
1719
- } else if (bindingPath.isVariableDeclarator()) {
1720
- const init = bindingPath.get("init");
1721
- if (init && init.node) {
1722
- if (init.isIdentifier()) {
1723
- const target = binding?.scope?.getBinding?.(init.node.name);
1724
- if (target) result = resolvesToWeappTwIgnore(target, seen);
1725
- } else if (init.isMemberExpression()) result = resolvesMemberExpressionToIgnore(init, seen);
1726
- }
1727
- }
1728
- bindingIgnoreCache.set(binding, result);
1729
- seen.delete(binding);
1730
- return result;
1731
- };
1732
- const getEffectiveTagPath = (tagPath) => {
1733
- let current = tagPath;
1734
- while (true) {
1735
- if (current.isParenthesizedExpression?.() || current.node.type === "ParenthesizedExpression") {
1736
- current = current.get("expression");
1737
- continue;
1738
- }
1739
- if (current.isTSAsExpression() || current.isTSTypeAssertion()) {
1740
- current = current.get("expression");
1741
- continue;
1742
- }
1743
- if (current.isTSNonNullExpression()) {
1744
- current = current.get("expression");
1745
- continue;
1746
- }
1747
- if (current.isTypeCastExpression?.()) {
1748
- current = current.get("expression");
1749
- continue;
1750
- }
1751
- if (current.isSequenceExpression()) {
1752
- const last = current.get("expressions").at(-1);
1753
- if (last) {
1754
- current = last;
1755
- continue;
1756
- }
1757
- }
1758
- if (current.isCallExpression?.() || current.node.type === "CallExpression") {
1759
- current = current.get("callee");
1760
- continue;
1761
- }
1762
- break;
1763
- }
1764
- return current;
1765
- };
1766
- const evaluateTagPath = (tagPath, seen) => {
1767
- if (tagPath.isCallExpression?.() || tagPath.node.type === "CallExpression") return evaluateTagPath(tagPath.get("callee"), seen);
1768
- if (tagPath.isIdentifier()) {
1769
- if (matchesIgnoreName(tagPath.node.name)) return true;
1770
- const binding = tagPath?.scope?.getBinding?.(tagPath.node.name);
1771
- if (binding) return resolvesToWeappTwIgnore(binding, seen);
1772
- return false;
1773
- }
1774
- if (tagPath.isMemberExpression()) return resolvesMemberExpressionToIgnore(tagPath, seen);
1775
- return false;
1776
- };
1777
- const computeIgnore = (tagPath) => {
1778
- const cached = taggedTemplateIgnoreCache.get(tagPath.node);
1779
- if (cached !== void 0) return cached;
1780
- const effectiveTagPath = getEffectiveTagPath(tagPath);
1781
- const effectiveCached = taggedTemplateIgnoreCache.get(effectiveTagPath.node);
1782
- if (effectiveCached !== void 0) {
1783
- taggedTemplateIgnoreCache.set(tagPath.node, effectiveCached);
1784
- return effectiveCached;
1785
- }
1786
- seenBindings.clear();
1787
- const result = evaluateTagPath(effectiveTagPath, seenBindings);
1788
- taggedTemplateIgnoreCache.set(effectiveTagPath.node, result);
1789
- taggedTemplateIgnoreCache.set(tagPath.node, result);
1790
- return result;
1791
- };
1792
- return {
1793
- shouldIgnore(tagPath) {
1794
- return computeIgnore(tagPath);
1795
- },
1796
- getEffectiveTagPath
1797
- };
1798
- }
1799
- //#endregion
1800
- //#region src/js/babel.ts
1801
- const EXPRESSION_WRAPPER_PREFIX = "(\n";
1802
- const EXPRESSION_WRAPPER_SUFFIX = "\n)";
1803
- const EMPTY_IGNORED_PATHS = /* @__PURE__ */ new WeakSet();
1804
- const EMPTY_IMPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1805
- const EMPTY_EXPORT_DECLARATIONS = /* @__PURE__ */ new Set();
1806
- const EMPTY_REQUIRE_CALL_PATHS = [];
1807
- const ignoredTaggedTemplateMatcherCache = /* @__PURE__ */ new WeakMap();
1808
- let defaultEvalHandler;
1809
- function getIgnoredTaggedTemplateMatcher(options) {
1810
- const cached = ignoredTaggedTemplateMatcherCache.get(options);
1811
- if (cached) return cached;
1812
- const created = createNameMatcher(options.ignoreTaggedTemplateExpressionIdentifiers, { exact: true });
1813
- ignoredTaggedTemplateMatcherCache.set(options, created);
1814
- return created;
1815
- }
1816
- function getDefaultEvalHandler() {
1817
- if (!defaultEvalHandler) throw new Error("Default JS eval handler is not initialized.");
1818
- return defaultEvalHandler;
1819
- }
1820
- function analyzeSource(ast, options, handler, collectModuleMetadata = true) {
1821
- const jsTokenUpdater = new JsTokenUpdater();
1822
- const needScope = Boolean(options.ignoreCallExpressionIdentifiers && options.ignoreCallExpressionIdentifiers.length > 0);
1823
- const ignoredPaths = needScope ? /* @__PURE__ */ new WeakSet() : EMPTY_IGNORED_PATHS;
1824
- const walker = needScope ? new NodePathWalker({
1825
- ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
1826
- callback(path) {
1827
- ignoredPaths.add(path);
1828
- }
1829
- }) : new NodePathWalker();
1830
- let taggedTemplateIgnore;
1831
- const hasTaggedTemplateIgnoreIdentifiers = Boolean(options.ignoreTaggedTemplateExpressionIdentifiers && options.ignoreTaggedTemplateExpressionIdentifiers.length > 0);
1832
- function getTaggedTemplateIgnore() {
1833
- if (!taggedTemplateIgnore) taggedTemplateIgnore = createTaggedTemplateIgnore({
1834
- matcher: getIgnoredTaggedTemplateMatcher(options),
1835
- names: options.ignoreTaggedTemplateExpressionIdentifiers
1836
- });
1837
- return taggedTemplateIgnore;
1838
- }
1839
- const targetPaths = [];
1840
- const importDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_IMPORT_DECLARATIONS;
1841
- const exportDeclarations = collectModuleMetadata ? /* @__PURE__ */ new Set() : EMPTY_EXPORT_DECLARATIONS;
1842
- const requireCallPaths = collectModuleMetadata ? [] : EMPTY_REQUIRE_CALL_PATHS;
1843
- const evalHandler = handler ?? getDefaultEvalHandler();
1844
- traverse(ast, {
1845
- StringLiteral: { enter(p) {
1846
- if (isEvalPath(p.parentPath)) return;
1847
- targetPaths.push(p);
1848
- } },
1849
- TemplateElement: { enter: hasTaggedTemplateIgnoreIdentifiers ? (p) => {
1850
- const pp = p.parentPath;
1851
- if (pp.isTemplateLiteral()) {
1852
- const ppp = pp.parentPath;
1853
- if (isEvalPath(ppp)) return;
1854
- if (ppp.isTaggedTemplateExpression()) {
1855
- const tagPath = ppp.get("tag");
1856
- if (getTaggedTemplateIgnore().shouldIgnore(tagPath)) return;
1857
- }
1858
- }
1859
- targetPaths.push(p);
1860
- } : (p) => {
1861
- const pp = p.parentPath;
1862
- if (pp.isTemplateLiteral()) {
1863
- const ppp = pp.parentPath;
1864
- if (isEvalPath(ppp)) return;
1865
- }
1866
- targetPaths.push(p);
1867
- } },
1868
- CallExpression: { enter: !collectModuleMetadata && !needScope ? (p) => {
1869
- if (isEvalPath(p)) walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1870
- } : (p) => {
1871
- if (isEvalPath(p)) {
1872
- walkEvalExpression(p, options, jsTokenUpdater, evalHandler);
1873
- return;
1874
- }
1875
- const calleePath = p.get("callee");
1876
- if (collectModuleMetadata && calleePath.isIdentifier({ name: "require" }) && !p?.scope?.hasBinding?.("require")) {
1877
- const args = p.get("arguments");
1878
- if (Array.isArray(args) && args.length > 0) {
1879
- const first = args[0];
1880
- if (first?.isStringLiteral()) requireCallPaths.push(first);
1881
- }
1882
- }
1883
- if (needScope) walker.walkCallExpression(p);
1884
- } },
1885
- ...collectModuleMetadata ? {
1886
- ImportDeclaration: { enter(p) {
1887
- importDeclarations.add(p);
1888
- } },
1889
- ExportDeclaration: { enter(p) {
1890
- exportDeclarations.add(p);
1891
- } }
1892
- } : {},
1893
- noScope: !needScope
1894
- });
1895
- return {
1896
- walker,
1897
- jsTokenUpdater,
1898
- ast,
1899
- targetPaths,
1900
- importDeclarations,
1901
- exportDeclarations,
1902
- requireCallPaths,
1903
- ignoredPaths
1904
- };
1905
- }
1906
- function jsHandler(rawSource, options) {
1907
- const shouldWrapExpression = Boolean(options.wrapExpression);
1908
- const source = shouldWrapExpression ? `${EXPRESSION_WRAPPER_PREFIX}${rawSource}${EXPRESSION_WRAPPER_SUFFIX}` : rawSource;
1909
- let ast;
1910
- try {
1911
- ast = babelParse(source, options.babelParserOptions);
1912
- } catch (error) {
1913
- return {
1914
- code: rawSource,
1915
- error
1916
- };
1917
- }
1918
- const needsModuleMetadata = Boolean(options.moduleSpecifierReplacements || options.moduleGraph && options.filename);
1919
- const analysis = analyzeSource(ast, options, jsHandler, needsModuleMetadata);
1920
- const ms = processUpdatedSource(source, options, analysis);
1921
- if (shouldWrapExpression) {
1922
- const start = 0;
1923
- const end = source.length;
1924
- const prefixLength = 2;
1925
- const suffixLength = 2;
1926
- ms.remove(start, start + prefixLength);
1927
- ms.remove(end - suffixLength, end);
1928
- }
1929
- const result = { code: ms.toString() };
1930
- if (options.generateMap) Object.defineProperty(result, "map", {
1931
- configurable: true,
1932
- enumerable: true,
1933
- get() {
1934
- return ms.generateMap();
1935
- }
1936
- });
1937
- if (options.moduleGraph && options.filename) {
1938
- const linked = new JsModuleGraph({
1939
- filename: options.filename,
1940
- source: rawSource,
1941
- analysis,
1942
- handlerOptions: options
1943
- }, options.moduleGraph).build();
1944
- if (linked) result.linked = linked;
1945
- }
1946
- return result;
1947
- }
1948
- defaultEvalHandler = jsHandler;
1949
- //#endregion
1950
- //#region src/js/index.ts
1951
- /** 默认 LRU 缓存最大条目数 */
1952
- const RESULT_CACHE_MAX = 512;
1953
- /** 仅对短片段做内层结果缓存,避免 bundler 热路径重复 hash 大块 JS。 */
1954
- const CACHEABLE_SOURCE_MAX_LENGTH = 512;
1955
- /** 为每个 ClassNameSet 实例分配递增 ID */
1956
- const classNameSetIds = /* @__PURE__ */ new WeakMap();
1957
- let nextClassNameSetId = 0;
1958
- /**
1959
- * 获取 ClassNameSet 的唯一身份 ID。
1960
- * 每个 Set 引用分配一个递增整数,用于指纹计算。
1961
- */
1962
- function getClassNameSetId(set) {
1963
- if (!set) return "none";
1964
- const existing = classNameSetIds.get(set);
1965
- if (existing !== void 0) return String(existing);
1966
- const id = nextClassNameSetId++;
1967
- classNameSetIds.set(set, id);
1968
- return String(id);
1969
- }
1970
- /** 缓存 IJsHandlerOptions -> fingerprint 的映射 */
1971
- const fingerprintCache = /* @__PURE__ */ new WeakMap();
1972
- /**
1973
- * 计算选项指纹,包含所有影响转译结果的字段。
1974
- * 不包含 filename、moduleGraph、jsPreserveClass。
1975
- */
1976
- function getOptionsFingerprint(options) {
1977
- const cached = fingerprintCache.get(options);
1978
- if (cached) return cached;
1979
- const fingerprint = [
1980
- getClassNameSetId(options.classNameSet),
1981
- JSON.stringify(options.escapeMap ?? null),
1982
- options.needEscaped ? "1" : "0",
1983
- options.alwaysEscape ? "1" : "0",
1984
- options.unescapeUnicode ? "1" : "0",
1985
- options.generateMap ? "1" : "0",
1986
- options.uniAppX ? "1" : "0",
1987
- options.wrapExpression ? "1" : "0",
1988
- String(options.tailwindcssMajorVersion ?? ""),
1989
- String(options.jsArbitraryValueFallback ?? ""),
1990
- JSON.stringify(options.arbitraryValues ?? null),
1991
- JSON.stringify(options.ignoreCallExpressionIdentifiers ?? null),
1992
- JSON.stringify(options.ignoreTaggedTemplateExpressionIdentifiers?.map((v) => v instanceof RegExp ? v.source : v) ?? null),
1993
- JSON.stringify(options.moduleSpecifierReplacements ?? null),
1994
- JSON.stringify(options.babelParserOptions ?? null)
1995
- ].join("|");
1996
- fingerprintCache.set(options, fingerprint);
1997
- return fingerprint;
1998
- }
1999
- function hasDefinedOverrides(options) {
2000
- if (!options) return false;
2001
- for (const key in options) if (options[key] !== void 0) return true;
2002
- return false;
2003
- }
2004
- function shouldCacheJsResult(rawSource, options) {
2005
- if (rawSource.length === 0 || rawSource.length > CACHEABLE_SOURCE_MAX_LENGTH) return false;
2006
- if (options.moduleGraph || options.filename) return false;
2007
- return true;
2008
- }
2009
- function createJsHandler(options) {
2010
- const defaults = {
2011
- escapeMap: options.escapeMap,
2012
- jsArbitraryValueFallback: options.jsArbitraryValueFallback,
2013
- tailwindcssMajorVersion: options.tailwindcssMajorVersion,
2014
- arbitraryValues: options.arbitraryValues,
2015
- jsPreserveClass: options.jsPreserveClass,
2016
- generateMap: options.generateMap,
2017
- needEscaped: options.needEscaped,
2018
- alwaysEscape: options.alwaysEscape,
2019
- unescapeUnicode: options.unescapeUnicode,
2020
- babelParserOptions: options.babelParserOptions,
2021
- ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
2022
- ignoreTaggedTemplateExpressionIdentifiers: options.ignoreTaggedTemplateExpressionIdentifiers,
2023
- uniAppX: options.uniAppX,
2024
- moduleSpecifierReplacements: options.moduleSpecifierReplacements
2025
- };
2026
- /** 层1: 无 override 时,classNameSet -> resolvedOptions */
2027
- const defaultOptionsCache = /* @__PURE__ */ new WeakMap();
2028
- let resolvedOptionsWithoutClassNameSet;
2029
- /** 层2: 有 override 时,overrideOptions -> { bySet, noSet } */
2030
- const overrideOptionsCache = /* @__PURE__ */ new WeakMap();
2031
- const resultCache = new lru_cache.LRUCache({ max: RESULT_CACHE_MAX });
2032
- function resolveDefaultOptions(classNameSet) {
2033
- if (!classNameSet) {
2034
- if (!resolvedOptionsWithoutClassNameSet) resolvedOptionsWithoutClassNameSet = {
2035
- ...defaults,
2036
- classNameSet
2037
- };
2038
- return resolvedOptionsWithoutClassNameSet;
2039
- }
2040
- const cached = defaultOptionsCache.get(classNameSet);
2041
- if (cached) return cached;
2042
- const created = {
2043
- ...defaults,
2044
- classNameSet
2045
- };
2046
- defaultOptionsCache.set(classNameSet, created);
2047
- return created;
2048
- }
2049
- function getCachedJsResult(rawSource, resolvedOptions) {
2050
- if (!shouldCacheJsResult(rawSource, resolvedOptions)) return;
2051
- const key = `${getOptionsFingerprint(resolvedOptions)}:${(0, _weapp_tailwindcss_shared_node.md5)(rawSource)}`;
2052
- return resultCache.get(key);
2053
- }
2054
- function setCachedJsResult(rawSource, resolvedOptions, result) {
2055
- if (!shouldCacheJsResult(rawSource, resolvedOptions) || result.error || result.linked) return result;
2056
- const key = `${getOptionsFingerprint(resolvedOptions)}:${(0, _weapp_tailwindcss_shared_node.md5)(rawSource)}`;
2057
- resultCache.set(key, result);
2058
- return result;
2059
- }
2060
- function resolveOptions(classNameSet, overrideOptions) {
2061
- if (!hasDefinedOverrides(overrideOptions)) return resolveDefaultOptions(classNameSet);
2062
- let entry = overrideOptionsCache.get(overrideOptions);
2063
- if (!entry) {
2064
- entry = { bySet: /* @__PURE__ */ new WeakMap() };
2065
- overrideOptionsCache.set(overrideOptions, entry);
2066
- }
2067
- if (!classNameSet) {
2068
- if (entry.noSet) return entry.noSet;
2069
- const created = (0, _weapp_tailwindcss_shared.defuOverrideArray)({
2070
- ...overrideOptions,
2071
- classNameSet
2072
- }, defaults);
2073
- entry.noSet = created;
2074
- return created;
2075
- }
2076
- const cached = entry.bySet.get(classNameSet);
2077
- if (cached) return cached;
2078
- const created = (0, _weapp_tailwindcss_shared.defuOverrideArray)({
2079
- ...overrideOptions,
2080
- classNameSet
2081
- }, defaults);
2082
- entry.bySet.set(classNameSet, created);
2083
- return created;
2084
- }
2085
- function handler(rawSource, classNameSet, options) {
2086
- const resolvedOptions = resolveOptions(classNameSet, options);
2087
- const cached = getCachedJsResult(rawSource, resolvedOptions);
2088
- if (cached) return cached;
2089
- return setCachedJsResult(rawSource, resolvedOptions, jsHandler(rawSource, resolvedOptions));
2090
- }
2091
- return handler;
2092
- }
2093
- //#endregion
2094
- //#region src/wxml/custom-attributes.ts
2095
- function regTest(reg, str) {
2096
- reg.lastIndex = 0;
2097
- return reg.test(str);
2098
- }
2099
- function isPropsMatch(props, attr) {
2100
- if (Array.isArray(props)) {
2101
- let lowerAttr;
2102
- for (const prop of props) if (typeof prop === "string") {
2103
- lowerAttr ?? (lowerAttr = attr.toLowerCase());
2104
- if (prop.toLowerCase() === lowerAttr) return true;
2105
- } else if (regTest(prop, attr)) return true;
2106
- return false;
2107
- } else if (typeof props === "string") return props === attr;
2108
- else return regTest(props, attr);
2109
- }
2110
- function createAttributeMatcher(entities) {
2111
- if (!entities || entities.length === 0) return;
2112
- const wildcardAttributeRules = [];
2113
- const tagAttributeRuleMap = /* @__PURE__ */ new Map();
2114
- const regexpAttributeRules = [];
2115
- for (const [selector, props] of entities) if (selector === "*") wildcardAttributeRules.push(props);
2116
- else if (typeof selector === "string") {
2117
- const list = tagAttributeRuleMap.get(selector);
2118
- if (list) list.push(props);
2119
- else tagAttributeRuleMap.set(selector, [props]);
2120
- } else regexpAttributeRules.push([selector, props]);
2121
- return (tag, attr) => {
2122
- for (const props of wildcardAttributeRules) if (isPropsMatch(props, attr)) return true;
2123
- const tagRules = tagAttributeRuleMap.get(tag);
2124
- if (tagRules) {
2125
- for (const props of tagRules) if (isPropsMatch(props, attr)) return true;
2126
- }
2127
- for (const [selector, props] of regexpAttributeRules) if (regTest(selector, tag) && isPropsMatch(props, attr)) return true;
2128
- return false;
2129
- };
2130
- }
2131
- //#endregion
2132
- //#region src/wxml/utils/codegen/legacy-visitor.ts
2133
- function shouldSkipLegacyStringLiteral(path) {
2134
- if (_babel_types.isMemberExpression(path.parent)) return true;
2135
- return Boolean(_babel_types.isBinaryExpression(path.parent) && (_babel_types.isConditionalExpression(path.parentPath?.parent) || _babel_types.isLogicalExpression(path.parentPath?.parent)));
2136
- }
2137
- function createLegacyTraverseOptions(options, jsTokenUpdater) {
2138
- const legacyReplaceOptions = {
2139
- escapeMap: options.escapeMap,
2140
- classNameSet: options.runtimeSet,
2141
- needEscaped: true,
2142
- alwaysEscape: true
2143
- };
2144
- return {
2145
- StringLiteral(path) {
2146
- if (shouldSkipLegacyStringLiteral(path)) return;
2147
- jsTokenUpdater.addToken(replaceHandleValue(path, legacyReplaceOptions));
2148
- },
2149
- noScope: true
2150
- };
2151
- }
2152
- //#endregion
2153
- //#region src/wxml/utils/codegen/legacy-rewriter.ts
2154
- function rewriteLegacyExpression(match, options) {
2155
- const ast = (0, _babel_parser.parseExpression)(match);
2156
- const jsTokenUpdater = new JsTokenUpdater();
2157
- traverse(ast, createLegacyTraverseOptions(options, jsTokenUpdater));
2158
- if (jsTokenUpdater.length === 0) return match;
2159
- const ms = new magic_string.default(match);
2160
- jsTokenUpdater.updateMagicString(ms);
2161
- return ms.toString();
2162
- }
2163
- //#endregion
2164
- //#region src/wxml/utils/codegen.ts
2165
- const WRAP_EXPRESSION_HANDLER_OPTIONS = Object.freeze({ wrapExpression: true });
2166
- function generateCode(match, options = {}) {
2167
- try {
2168
- const { jsHandler, runtimeSet, wrapExpression } = options;
2169
- if (jsHandler && runtimeSet) {
2170
- const initial = jsHandler(match, runtimeSet, wrapExpression ? WRAP_EXPRESSION_HANDLER_OPTIONS : void 0);
2171
- if (!initial.error || wrapExpression) return initial.code;
2172
- return jsHandler(match, runtimeSet, WRAP_EXPRESSION_HANDLER_OPTIONS).code;
2173
- } else return rewriteLegacyExpression(match, options);
2174
- } catch {
2175
- return match;
2176
- }
2177
- }
2178
- //#endregion
2179
- //#region src/wxml/whitespace.ts
2180
- const WHITESPACE_CODES = new Set([
2181
- 9,
2182
- 10,
2183
- 11,
2184
- 12,
2185
- 13,
2186
- 32,
2187
- 160,
2188
- 65279
2189
- ]);
2190
- function isWhitespace(char) {
2191
- if (char.length === 0) return false;
2192
- return WHITESPACE_CODES.has(char.charCodeAt(0));
2193
- }
2194
- function isAllWhitespace(value) {
2195
- for (let i = 0; i < value.length; i++) if (!WHITESPACE_CODES.has(value.charCodeAt(i))) return false;
2196
- return true;
2197
- }
2198
- //#endregion
2199
- //#region src/wxml/Tokenizer.ts
2200
- var Tokenizer = class {
2201
- constructor() {
2202
- _defineProperty(this, "state", void 0);
2203
- _defineProperty(this, "buffer", void 0);
2204
- _defineProperty(this, "tokens", void 0);
2205
- _defineProperty(this, "bufferStartIndex", void 0);
2206
- _defineProperty(this, "expressionStartIndex", void 0);
2207
- _defineProperty(this, "expressionBuffer", void 0);
2208
- _defineProperty(this, "expressions", void 0);
2209
- this.reset();
2210
- }
2211
- processChar(char, index) {
2212
- switch (this.state) {
2213
- case 0:
2214
- if (isWhitespace(char)) {} else if (char === "{") {
2215
- this.state = 2;
2216
- this.bufferStartIndex = index;
2217
- this.buffer += char;
2218
- this.expressionBuffer = char;
2219
- this.expressionStartIndex = index;
2220
- } else {
2221
- this.state = 1;
2222
- this.bufferStartIndex = index;
2223
- this.buffer += char;
2224
- }
2225
- break;
2226
- case 1:
2227
- if (isWhitespace(char)) {
2228
- this.tokens.push({
2229
- start: this.bufferStartIndex,
2230
- end: index,
2231
- value: this.buffer,
2232
- expressions: this.expressions
2233
- });
2234
- this.buffer = "";
2235
- this.expressions = [];
2236
- this.state = 0;
2237
- } else if (char === "{") {
2238
- this.buffer += char;
2239
- this.expressionBuffer = char;
2240
- this.expressionStartIndex = index;
2241
- this.state = 2;
2242
- } else this.buffer += char;
2243
- break;
2244
- case 2:
2245
- if (char === "}") {
2246
- this.buffer += char;
2247
- this.expressionBuffer += char;
2248
- this.state = 3;
2249
- } else {
2250
- this.buffer += char;
2251
- this.expressionBuffer += char;
2252
- }
2253
- break;
2254
- case 3:
2255
- if (char === "}") {
2256
- this.buffer += char;
2257
- this.expressionBuffer += char;
2258
- this.expressions.push({
2259
- start: this.expressionStartIndex,
2260
- end: index + 1,
2261
- value: this.expressionBuffer
2262
- });
2263
- this.expressionBuffer = "";
2264
- this.state = 4;
2265
- } else {
2266
- this.buffer += char;
2267
- this.expressionBuffer += char;
2268
- this.state = 2;
2269
- }
2270
- break;
2271
- case 4:
2272
- if (isWhitespace(char)) {
2273
- this.tokens.push({
2274
- start: this.bufferStartIndex,
2275
- end: index,
2276
- value: this.buffer,
2277
- expressions: this.expressions
2278
- });
2279
- this.buffer = "";
2280
- this.expressions = [];
2281
- this.state = 0;
2282
- } else if (char === "{") {
2283
- this.expressionStartIndex = index;
2284
- this.expressionBuffer = char;
2285
- this.buffer += char;
2286
- this.state = 2;
2287
- } else {
2288
- this.buffer += char;
2289
- this.state = 1;
2290
- }
2291
- break;
2292
- default: throw new Error("Unexpected state");
2293
- }
2294
- }
2295
- run(input) {
2296
- this.reset();
2297
- for (let i = 0; i < input.length; i++) {
2298
- const char = input[i];
2299
- this.processChar(char, i);
2300
- }
2301
- if (this.buffer.length > 0) this.tokens.push({
2302
- start: this.bufferStartIndex,
2303
- end: input.length,
2304
- value: this.buffer,
2305
- expressions: this.expressions
2306
- });
2307
- const tokens = this.tokens;
2308
- this.reset();
2309
- return tokens;
2310
- }
2311
- reset() {
2312
- this.state = 0;
2313
- this.buffer = "";
2314
- this.tokens = [];
2315
- this.bufferStartIndex = 0;
2316
- this.expressionBuffer = "";
2317
- this.expressionStartIndex = 0;
2318
- this.expressions = [];
2319
- }
2320
- };
2321
- //#endregion
2322
- //#region src/wxml/utils/fragment-helpers.ts
2323
- function updateWhitespaceGap(ms, start, end, options) {
2324
- const gap = ms.slice(start, end);
2325
- if (isAllWhitespace(gap)) ms.update(start, end, replaceWxml(gap, {
2326
- keepEOL: false,
2327
- escapeMap: options.escapeMap,
2328
- ignoreHead: true
2329
- }));
2330
- }
2331
- function updateWxmlSegment(ms, start, end, options, keepEOL, ignoreHead) {
2332
- ms.update(start, end, replaceWxml(ms.slice(start, end), {
2333
- keepEOL,
2334
- escapeMap: options.escapeMap,
2335
- ignoreHead
2336
- }));
2337
- }
2338
- function updateExpressionSegment(ms, exp, options) {
2339
- const code = `{{${generateCode(exp.value.slice(2, -2), options)}}}`;
2340
- ms.update(exp.start, exp.end, code);
2341
- }
2342
- //#endregion
2343
- //#region src/wxml/utils/fragment-updater.ts
2344
- function handleEachClassFragment(ms, tokens, options = {}) {
2345
- let previousEnd = 0;
2346
- for (const token of tokens) {
2347
- if (token.start > previousEnd) updateWhitespaceGap(ms, previousEnd, token.start, options);
2348
- let p = token.start;
2349
- if (token.expressions.length > 0) {
2350
- for (const exp of token.expressions) {
2351
- if (exp.start > token.start && p < exp.start) updateWxmlSegment(ms, p, exp.start, options, true, p > 0);
2352
- updateExpressionSegment(ms, exp, options);
2353
- p = exp.end;
2354
- }
2355
- if (token.end > p) updateWxmlSegment(ms, p, token.end, options, false, true);
2356
- } else updateWxmlSegment(ms, token.start, token.end, options, false, false);
2357
- previousEnd = token.end;
2358
- }
2359
- if (tokens.length > 0) {
2360
- const lastToken = tokens[tokens.length - 1];
2361
- if (lastToken.end < ms.original.length) updateWhitespaceGap(ms, lastToken.end, ms.original.length, options);
2362
- }
2363
- }
2364
- //#endregion
2365
- //#region src/wxml/utils/template-fragments.ts
2366
- /**
2367
- * 模块级共享 Tokenizer 实例,避免每次调用都重新创建。
2368
- * Tokenizer.run() 末尾已调用 reset(),天然支持复用。
2369
- */
2370
- const sharedTokenizer = new Tokenizer();
2371
- function templateReplacer(original, options = {}, tokenizer) {
2372
- const ms = new magic_string.default(original);
2373
- handleEachClassFragment(ms, (tokenizer ?? sharedTokenizer).run(ms.original), options);
2374
- return ms.toString();
2375
- }
2376
- //#endregion
2377
- //#region src/wxml/utils/custom-template.ts
2378
- async function customTemplateHandler(rawSource, options, cachedMatcher) {
2379
- const { customAttributesEntities = [], disabledDefaultTemplateHandler, inlineWxs, runtimeSet, jsHandler } = options ?? {};
2380
- const matchCustomAttribute = cachedMatcher ?? createAttributeMatcher(customAttributesEntities);
2381
- const defaultTemplateHandlerEnabled = !disabledDefaultTemplateHandler;
2382
- let replaceOptions;
2383
- let cachedQuote;
2384
- let s;
2385
- let tag = "";
2386
- let wxsArray;
2387
- function getMagicString() {
2388
- if (!s) s = new magic_string.default(rawSource);
2389
- return s;
2390
- }
2391
- function getReplaceOptions(quote) {
2392
- if (!replaceOptions) {
2393
- replaceOptions = {
2394
- ...options,
2395
- quote
2396
- };
2397
- cachedQuote = quote;
2398
- return replaceOptions;
2399
- }
2400
- if (cachedQuote !== quote) {
2401
- replaceOptions.quote = quote;
2402
- cachedQuote = quote;
2403
- }
2404
- return replaceOptions;
2405
- }
2406
- function isDefaultTemplateAttribute(name) {
2407
- if (name === "class" || name === "hover-class" || name === "virtualhostclass") return true;
2408
- const lowerName = name.toLowerCase();
2409
- return lowerName === "class" || lowerName === "hover-class" || lowerName === "virtualhostclass";
2410
- }
2411
- const parser = new htmlparser2.Parser({
2412
- onopentagname(name) {
2413
- tag = name;
2414
- },
2415
- onattribute(name, value, quote) {
2416
- if (!value) return;
2417
- const shouldHandleDefault = defaultTemplateHandlerEnabled && isDefaultTemplateAttribute(name);
2418
- const shouldHandleCustom = matchCustomAttribute?.(tag, name) ?? false;
2419
- if (!shouldHandleDefault && !shouldHandleCustom) return;
2420
- getMagicString().update(parser.startIndex + name.length + 2, parser.endIndex - 1, templateReplacer(value, getReplaceOptions(quote)));
2421
- },
2422
- ontext(data) {
2423
- if (inlineWxs && tag === "wxs") (wxsArray ?? (wxsArray = [])).push({
2424
- data,
2425
- endIndex: parser.endIndex + 1,
2426
- startIndex: parser.startIndex
2427
- });
2428
- },
2429
- onclosetag() {
2430
- tag = "";
2431
- }
2432
- }, { xmlMode: true });
2433
- parser.write(rawSource);
2434
- parser.end();
2435
- for (const { data, endIndex, startIndex } of wxsArray ?? []) {
2436
- const { code } = await jsHandler(data, runtimeSet);
2437
- if (code !== data) getMagicString().update(startIndex, endIndex, code);
2438
- }
2439
- return s?.toString() ?? rawSource;
2440
- }
2441
- //#endregion
2442
- //#region src/wxml/utils.ts
2443
- function createTemplateHandler(options = {}) {
2444
- const cachedMatcher = createAttributeMatcher(options.customAttributesEntities);
2445
- const defaultOptions = options;
2446
- let cachedRuntimeSet;
2447
- let cachedOptionsWithRuntimeSet;
2448
- return (rawSource, opt) => {
2449
- const runtimeSet = opt?.runtimeSet;
2450
- if (runtimeSet === void 0) return customTemplateHandler(rawSource, defaultOptions, cachedMatcher);
2451
- if (cachedRuntimeSet !== runtimeSet || !cachedOptionsWithRuntimeSet) {
2452
- cachedRuntimeSet = runtimeSet;
2453
- cachedOptionsWithRuntimeSet = {
2454
- ...defaultOptions,
2455
- runtimeSet
2456
- };
2457
- }
2458
- return customTemplateHandler(rawSource, cachedOptionsWithRuntimeSet, cachedMatcher);
2459
- };
2460
- }
2461
- //#endregion
2462
- //#region src/context/handlers.ts
2463
- function resolveRuntimePackageReplacements(option) {
2464
- if (!option) return;
2465
- const mapping = option === true ? DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS : option;
2466
- const normalized = {};
2467
- for (const [from, to] of Object.entries(mapping)) {
2468
- if (!from || typeof to !== "string" || to.length === 0) continue;
2469
- normalized[from] = to;
2470
- }
2471
- return Object.keys(normalized).length > 0 ? normalized : void 0;
2472
- }
2473
- function createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindcssMajorVersion) {
2474
- const { cssPreflight, cssPreflightRange, escapeMap, cssChildCombinatorReplaceValue, injectAdditionalCssVarScope, cssSelectorReplacement, rem2rpx, postcssOptions, cssRemoveProperty, cssRemoveHoverPseudoClass, cssPresetEnv, autoprefixer, uniAppX, px2rpx, unitsToPx, arbitraryValues, jsPreserveClass, jsArbitraryValueFallback, babelParserOptions, ignoreCallExpressionIdentifiers, ignoreTaggedTemplateExpressionIdentifiers, inlineWxs, disabledDefaultTemplateHandler, replaceRuntimePackages } = ctx;
2475
- const uniAppXEnabled = require_tailwindcss.isUniAppXEnabled(uniAppX);
2476
- const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(uniAppX);
2477
- const moduleSpecifierReplacements = resolveRuntimePackageReplacements(replaceRuntimePackages);
2478
- const styleHandler = (0, _weapp_tailwindcss_postcss.createStyleHandler)({
2479
- cssPreflight,
2480
- cssPreflightRange,
2481
- escapeMap,
2482
- cssChildCombinatorReplaceValue,
2483
- injectAdditionalCssVarScope,
2484
- cssSelectorReplacement,
2485
- rem2rpx,
2486
- postcssOptions,
2487
- cssRemoveProperty,
2488
- cssRemoveHoverPseudoClass,
2489
- cssPresetEnv,
2490
- autoprefixer,
2491
- uniAppX: uniAppXEnabled,
2492
- uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
2493
- cssCalc: cssCalcOptions,
2494
- px2rpx,
2495
- unitsToPx,
2496
- majorVersion: tailwindcssMajorVersion
2497
- });
2498
- const jsHandler = createJsHandler({
2499
- escapeMap,
2500
- arbitraryValues,
2501
- jsPreserveClass,
2502
- jsArbitraryValueFallback: jsArbitraryValueFallback ?? "auto",
2503
- tailwindcssMajorVersion,
2504
- generateMap: true,
2505
- babelParserOptions,
2506
- ignoreCallExpressionIdentifiers,
2507
- ignoreTaggedTemplateExpressionIdentifiers,
2508
- uniAppX: uniAppXEnabled,
2509
- moduleSpecifierReplacements
2510
- });
2511
- return {
2512
- styleHandler,
2513
- jsHandler,
2514
- templateHandler: createTemplateHandler({
2515
- customAttributesEntities,
2516
- escapeMap,
2517
- inlineWxs,
2518
- jsHandler,
2519
- disabledDefaultTemplateHandler
2520
- })
2521
- };
2522
- }
2523
- //#endregion
2524
- //#region src/context/logger.ts
2525
- const loggerLevelMap = {
2526
- error: 0,
2527
- warn: 1,
2528
- info: 3,
2529
- silent: -999
2530
- };
2531
- function applyLoggerLevel(logLevel) {
2532
- _weapp_tailwindcss_logger.logger.level = loggerLevelMap[logLevel ?? "info"] ?? loggerLevelMap.info;
2533
- }
2534
- //#endregion
2535
- //#region src/context/index.ts
2536
- async function clearTailwindcssPatcherCache(patcher, options) {
2537
- if (!patcher) return;
2538
- const cacheOptions = patcher.options?.cache;
2539
- if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) return;
2540
- if (typeof patcher.clearCache === "function") try {
2541
- await patcher.clearCache({ scope: "all" });
2542
- } catch (error) {
2543
- _weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss patcher cache via clearCache(): %O", error);
2544
- }
2545
- if (!options?.removeDirectory) return;
2546
- const cachePaths = /* @__PURE__ */ new Map();
2547
- const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
2548
- if (normalizedCacheOptions?.path) cachePaths.set(normalizedCacheOptions.path, false);
2549
- const privateCachePath = patcher?.cacheStore?.options?.path;
2550
- if (privateCachePath) cachePaths.set(privateCachePath, false);
2551
- if (options?.removeDirectory && normalizedCacheOptions?.dir) cachePaths.set(normalizedCacheOptions.dir, true);
2552
- if (!cachePaths.size) return;
2553
- for (const [cachePath, recursive] of cachePaths.entries()) try {
2554
- await (0, node_fs_promises.rm)(cachePath, {
2555
- force: true,
2556
- recursive
2557
- });
2558
- } catch (error) {
2559
- const err = error;
2560
- if (err?.code === "ENOENT") continue;
2561
- _weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss patcher cache: %s %O", cachePath, err);
2562
- }
2563
- }
2564
- function createInternalCompilerContext(opts) {
2565
- const ctx = (0, _weapp_tailwindcss_shared.defuOverrideArray)(opts, require_defaults.getDefaultOptions(), {});
2566
- ctx.escapeMap = ctx.customReplaceDictionary;
2567
- applyLoggerLevel(ctx.logLevel);
2568
- const twPatcher = require_tailwindcss.createTailwindcssPatcherFromContext(ctx);
2569
- logTailwindcssTarget(twPatcher, ctx.tailwindcssBasedir);
2570
- logRuntimeTailwindcssVersion(ctx.tailwindcssBasedir, twPatcher.packageInfo?.rootPath, twPatcher.packageInfo?.version);
2571
- if (opts?.__internalDeferMissingCssEntriesWarning !== true) require_tailwindcss.warnMissingCssEntries(ctx, twPatcher);
2572
- ctx.cssPreflight = require_defaults.resolveDefaultCssPreflight(opts?.cssPreflight, twPatcher.majorVersion);
2573
- const cssCalcOptions = require_tailwindcss.applyV4CssCalcDefaults(ctx.cssCalc, twPatcher);
2574
- ctx.cssCalc = cssCalcOptions;
2575
- const { styleHandler, jsHandler, templateHandler } = createHandlersFromContext(ctx, toCustomAttributesEntities(ctx.customAttributes), cssCalcOptions, twPatcher.majorVersion);
2576
- ctx.styleHandler = styleHandler;
2577
- ctx.jsHandler = jsHandler;
2578
- ctx.templateHandler = templateHandler;
2579
- ctx.cache = initializeCache(ctx.cache);
2580
- ctx.twPatcher = twPatcher;
2581
- const refreshTailwindcssPatcher = async (options) => {
2582
- const previousPatcher = ctx.twPatcher;
2583
- if (options?.clearCache !== false) await clearTailwindcssPatcherCache(previousPatcher);
2584
- require_cache.invalidateRuntimeClassSet(previousPatcher);
2585
- const nextPatcher = require_tailwindcss.createTailwindcssPatcherFromContext(ctx);
2586
- Object.assign(previousPatcher, nextPatcher);
2587
- ctx.twPatcher = previousPatcher;
2588
- return previousPatcher;
2589
- };
2590
- ctx.refreshTailwindcssPatcher = refreshTailwindcssPatcher;
2591
- Object.defineProperty(ctx.twPatcher, refreshTailwindcssPatcherSymbol, {
2592
- value: refreshTailwindcssPatcher,
2593
- configurable: true
2594
- });
2595
- return ctx;
2596
- }
2597
- /**
2598
- * 获取用户定义选项的内部表示,并初始化相关的处理程序和 Tailwind 运行时。
2599
- * @param opts - 用户定义的选项,可选。
2600
- * @returns 返回一个包含内部用户定义选项的对象,包括样式、JS 和模板处理程序,以及 Tailwind CSS 运行时。
2601
- */
2602
- function getCompilerContext(opts) {
2603
- return withCompilerContextCache(opts, () => createInternalCompilerContext(opts));
2604
- }
2605
- //#endregion
2606
- //#region src/js/precheck.ts
2607
- /** 用于检测源码中是否包含类名相关模式的正则表达式 */
2608
- const FAST_JS_TRANSFORM_HINT_RE = /className\b|class\s*=|classList\.|\b(?:twMerge|clsx|classnames|cn|cva)\b|\[["'`]class["'`]\]|text-\[|bg-\[|\b(?:[whpm]|px|py|mx|my|rounded|flex|grid|gap)-/;
2609
- /** 用于检测源码中是否包含 import/export/require 语句的正则表达式 */
2610
- const DEPENDENCY_HINT_RE = /\bimport\s*[("'`{*]|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
2611
- /**
2612
- * 判断是否可以跳过 JS 转换。
2613
- * 通过正则快速检测源码内容,避免不必要的 Babel AST 解析。
2614
- *
2615
- * @param rawSource - 原始 JS 源码字符串
2616
- * @param options - 可选的 JS 处理器配置选项
2617
- * @returns 如果可以跳过转换返回 `true`,否则返回 `false`
2618
- */
2619
- function shouldSkipJsTransform(rawSource, options) {
2620
- if (node_process.default.env.WEAPP_TW_DISABLE_JS_PRECHECK === "1") return false;
2621
- if (!rawSource) return true;
2622
- if (options?.alwaysEscape) return false;
2623
- if (options?.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return false;
2624
- if (options?.wrapExpression) return false;
2625
- if (DEPENDENCY_HINT_RE.test(rawSource)) return false;
2626
- return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
2627
- }
2628
- //#endregion
2629
- Object.defineProperty(exports, "JsTokenUpdater", {
2630
- enumerable: true,
2631
- get: function() {
2632
- return JsTokenUpdater;
2633
- }
2634
- });
2635
- Object.defineProperty(exports, "_defineProperty", {
2636
- enumerable: true,
2637
- get: function() {
2638
- return _defineProperty;
2639
- }
2640
- });
2641
- Object.defineProperty(exports, "analyzeSource", {
2642
- enumerable: true,
2643
- get: function() {
2644
- return analyzeSource;
2645
- }
2646
- });
2647
- Object.defineProperty(exports, "babelParse", {
2648
- enumerable: true,
2649
- get: function() {
2650
- return babelParse;
2651
- }
2652
- });
2653
- Object.defineProperty(exports, "collectRuntimeClassSet", {
2654
- enumerable: true,
2655
- get: function() {
2656
- return collectRuntimeClassSet;
2657
- }
2658
- });
2659
- Object.defineProperty(exports, "createAttributeMatcher", {
2660
- enumerable: true,
2661
- get: function() {
2662
- return createAttributeMatcher;
2663
- }
2664
- });
2665
- Object.defineProperty(exports, "createTailwindRuntimeReadyPromise", {
2666
- enumerable: true,
2667
- get: function() {
2668
- return createTailwindRuntimeReadyPromise;
2669
- }
2670
- });
2671
- Object.defineProperty(exports, "ensureRuntimeClassSet", {
2672
- enumerable: true,
2673
- get: function() {
2674
- return ensureRuntimeClassSet;
2675
- }
2676
- });
2677
- Object.defineProperty(exports, "generateCode", {
2678
- enumerable: true,
2679
- get: function() {
2680
- return generateCode;
2681
- }
2682
- });
2683
- Object.defineProperty(exports, "getCompilerContext", {
2684
- enumerable: true,
2685
- get: function() {
2686
- return getCompilerContext;
2687
- }
2688
- });
2689
- Object.defineProperty(exports, "isClassContextLiteralPath", {
2690
- enumerable: true,
2691
- get: function() {
2692
- return isClassContextLiteralPath;
2693
- }
2694
- });
2695
- Object.defineProperty(exports, "pluginName", {
2696
- enumerable: true,
2697
- get: function() {
2698
- return pluginName;
2699
- }
2700
- });
2701
- Object.defineProperty(exports, "refreshTailwindRuntimeState", {
2702
- enumerable: true,
2703
- get: function() {
2704
- return refreshTailwindRuntimeState;
2705
- }
2706
- });
2707
- Object.defineProperty(exports, "replaceWxml", {
2708
- enumerable: true,
2709
- get: function() {
2710
- return replaceWxml;
2711
- }
2712
- });
2713
- Object.defineProperty(exports, "shouldSkipJsTransform", {
2714
- enumerable: true,
2715
- get: function() {
2716
- return shouldSkipJsTransform;
2717
- }
2718
- });
2719
- Object.defineProperty(exports, "toCustomAttributesEntities", {
2720
- enumerable: true,
2721
- get: function() {
2722
- return toCustomAttributesEntities;
2723
- }
2724
- });
2725
- Object.defineProperty(exports, "traverse", {
2726
- enumerable: true,
2727
- get: function() {
2728
- return traverse;
2729
- }
2730
- });
2731
- Object.defineProperty(exports, "vitePluginName", {
2732
- enumerable: true,
2733
- get: function() {
2734
- return vitePluginName;
2735
- }
2736
- });