weapp-tailwindcss 4.10.3 → 4.11.0-alpha.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 (64) hide show
  1. package/dist/{chunk-3XVUGMTY.mjs → chunk-2LH6PZH3.mjs} +8 -4
  2. package/dist/{chunk-3WUHHFLF.mjs → chunk-35EI5JMK.mjs} +4 -2
  3. package/dist/{chunk-RYC23C3K.js → chunk-4LPOQMFS.js} +203 -198
  4. package/dist/{chunk-5U24PLVV.js → chunk-ACTJYB33.js} +4 -2
  5. package/dist/chunk-CZLXTEHN.js +1936 -0
  6. package/dist/{chunk-TNYEOBAC.mjs → chunk-DOH7FULQ.mjs} +1 -1
  7. package/dist/{chunk-E7775SFS.mjs → chunk-FZNYV7VH.mjs} +914 -334
  8. package/dist/{chunk-6Z4GEN2Y.js → chunk-G3G437UE.js} +2 -2
  9. package/dist/{chunk-DEIJXHGJ.js → chunk-G5NLM3AL.js} +978 -398
  10. package/dist/{chunk-W2N6G2QQ.js → chunk-GWDHNCL2.js} +60 -46
  11. package/dist/{chunk-QOTLDKI4.mjs → chunk-IEZ5RBMG.mjs} +197 -192
  12. package/dist/{chunk-RM3SY4S4.mjs → chunk-JBM3HGHP.mjs} +52 -12
  13. package/dist/{chunk-WXT2GI5R.mjs → chunk-KKT2DKMW.mjs} +30 -16
  14. package/dist/chunk-LD7LZ4IK.mjs +1933 -0
  15. package/dist/{chunk-GCRL3ZYP.js → chunk-NOKJXG3W.js} +5 -5
  16. package/dist/{chunk-YUTKX7JZ.js → chunk-OV7FX6XR.js} +1 -1
  17. package/dist/{chunk-SR4GC2F4.js → chunk-OYSABARD.js} +8 -4
  18. package/dist/{chunk-LICQ6EGN.mjs → chunk-QYZCRG7F.mjs} +2 -2
  19. package/dist/{chunk-UYTCZXNE.mjs → chunk-R6KEYO3F.mjs} +6 -5
  20. package/dist/{chunk-WF636Q5E.js → chunk-SQG2MOFQ.js} +10 -9
  21. package/dist/{chunk-L7OBNTRI.js → chunk-W2EMGF7H.js} +57 -17
  22. package/dist/cli.js +45 -42
  23. package/dist/cli.mjs +9 -6
  24. package/dist/core.d.mts +4 -3
  25. package/dist/core.d.ts +4 -3
  26. package/dist/core.js +124 -30
  27. package/dist/core.mjs +119 -25
  28. package/dist/css-macro/postcss.js +6 -5
  29. package/dist/css-macro/postcss.mjs +4 -3
  30. package/dist/css-macro.js +5 -5
  31. package/dist/css-macro.mjs +2 -2
  32. package/dist/defaults.js +3 -3
  33. package/dist/defaults.mjs +2 -2
  34. package/dist/escape.js +2 -1
  35. package/dist/escape.mjs +2 -1
  36. package/dist/gulp.d.mts +1 -1
  37. package/dist/gulp.d.ts +1 -1
  38. package/dist/gulp.js +8 -7
  39. package/dist/gulp.mjs +8 -7
  40. package/dist/index.js +11 -11
  41. package/dist/index.mjs +9 -9
  42. package/dist/postcss-html-transform.js +1 -1
  43. package/dist/postcss-html-transform.mjs +1 -1
  44. package/dist/presets.js +5 -5
  45. package/dist/presets.mjs +2 -2
  46. package/dist/reset.js +1 -1
  47. package/dist/reset.mjs +1 -1
  48. package/dist/types.js +1 -1
  49. package/dist/types.mjs +1 -1
  50. package/dist/vite.d.mts +1 -1
  51. package/dist/vite.d.ts +1 -1
  52. package/dist/vite.js +9 -8
  53. package/dist/vite.mjs +8 -7
  54. package/dist/webpack.d.mts +1 -1
  55. package/dist/webpack.d.ts +1 -1
  56. package/dist/webpack.js +10 -9
  57. package/dist/webpack.mjs +8 -7
  58. package/dist/webpack4.d.mts +1 -1
  59. package/dist/webpack4.d.ts +1 -1
  60. package/dist/webpack4.js +64 -49
  61. package/dist/webpack4.mjs +33 -18
  62. package/package.json +7 -7
  63. package/dist/chunk-PALDKVKG.mjs +0 -1291
  64. package/dist/chunk-YJSFFRNZ.js +0 -1291
@@ -1,1291 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
- var _chunk6Z4GEN2Yjs = require('./chunk-6Z4GEN2Y.js');
10
-
11
-
12
- var _chunkLTJQUORKjs = require('./chunk-LTJQUORK.js');
13
-
14
-
15
- var _chunkGCRL3ZYPjs = require('./chunk-GCRL3ZYP.js');
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
- var _chunkDEIJXHGJjs = require('./chunk-DEIJXHGJ.js');
28
-
29
-
30
- var _chunkDYLQ6UOIjs = require('./chunk-DYLQ6UOI.js');
31
-
32
- // src/bundlers/vite/index.ts
33
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
34
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
35
- var _htmltransform = require('@weapp-tailwindcss/postcss/html-transform'); var _htmltransform2 = _interopRequireDefault(_htmltransform);
36
-
37
- // src/uni-app-x/transform.ts
38
- var _compilerdom = require('@vue/compiler-dom');
39
- var _compilersfc = require('@vue/compiler-sfc');
40
- var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
41
- function traverse(node, visitor) {
42
- visitor(node);
43
- if (Array.isArray(node.children)) {
44
- for (const child of node.children) {
45
- if (child && typeof child === "object" && "type" in child) {
46
- traverse(child, visitor);
47
- }
48
- }
49
- }
50
- }
51
- function updateStaticAttribute(ms, prop) {
52
- if (!prop.value) {
53
- return;
54
- }
55
- const start = prop.value.loc.start.offset + 1;
56
- const end = prop.value.loc.end.offset - 1;
57
- if (start < end) {
58
- ms.update(start, end, _chunkDEIJXHGJjs.replaceWxml.call(void 0, prop.value.content));
59
- }
60
- }
61
- function updateDirectiveExpression(ms, prop, jsHandler, runtimeSet) {
62
- if (_optionalChain([prop, 'access', _ => _.exp, 'optionalAccess', _2 => _2.type]) !== _compilerdom.NodeTypes.SIMPLE_EXPRESSION) {
63
- return;
64
- }
65
- const start = prop.exp.loc.start.offset;
66
- const end = prop.exp.loc.end.offset;
67
- if (start >= end) {
68
- return;
69
- }
70
- const generated = _chunkDEIJXHGJjs.generateCode.call(void 0, prop.exp.content, {
71
- jsHandler,
72
- runtimeSet,
73
- wrapExpression: true
74
- });
75
- ms.update(start, end, generated);
76
- }
77
- function shouldHandleAttribute(tag, attrName, disabledDefaultTemplateHandler, matchCustomAttribute) {
78
- const lowerName = attrName.toLowerCase();
79
- const shouldHandleDefault = !disabledDefaultTemplateHandler && lowerName === "class";
80
- const shouldHandleCustom = _nullishCoalesce(_optionalChain([matchCustomAttribute, 'optionalCall', _3 => _3(tag, attrName)]), () => ( false));
81
- return {
82
- shouldHandleDefault,
83
- shouldHandleCustom,
84
- shouldHandle: shouldHandleDefault || shouldHandleCustom
85
- };
86
- }
87
- var defaultCreateJsHandlerOptions = {
88
- babelParserOptions: {
89
- plugins: [
90
- "typescript"
91
- ]
92
- }
93
- };
94
- function transformUVue(code, id, jsHandler, runtimeSet, options = {}) {
95
- if (!/\.(?:uvue|nvue)(?:\?.*)?$/.test(id)) {
96
- return;
97
- }
98
- const { customAttributesEntities, disabledDefaultTemplateHandler = false } = options;
99
- const matchCustomAttribute = _chunkDEIJXHGJjs.createAttributeMatcher.call(void 0, customAttributesEntities);
100
- const ms = new (0, _magicstring2.default)(code);
101
- const { descriptor, errors } = _compilersfc.parse.call(void 0, code);
102
- if (errors.length === 0) {
103
- if (_optionalChain([descriptor, 'access', _4 => _4.template, 'optionalAccess', _5 => _5.ast])) {
104
- traverse(descriptor.template.ast, (node) => {
105
- if (node.type !== _compilerdom.NodeTypes.ELEMENT) {
106
- return;
107
- }
108
- const tag = node.tag;
109
- for (const prop of node.props) {
110
- if (prop.type === _compilerdom.NodeTypes.ATTRIBUTE) {
111
- const { shouldHandle, shouldHandleDefault } = shouldHandleAttribute(
112
- tag,
113
- prop.name,
114
- disabledDefaultTemplateHandler,
115
- matchCustomAttribute
116
- );
117
- if (!shouldHandle) {
118
- continue;
119
- }
120
- updateStaticAttribute(ms, prop);
121
- if (shouldHandleDefault) {
122
- continue;
123
- }
124
- } else if (prop.type === _compilerdom.NodeTypes.DIRECTIVE && prop.name === "bind" && _optionalChain([prop, 'access', _6 => _6.arg, 'optionalAccess', _7 => _7.type]) === _compilerdom.NodeTypes.SIMPLE_EXPRESSION && prop.arg.isStatic) {
125
- const attrName = prop.arg.content;
126
- const { shouldHandle } = shouldHandleAttribute(
127
- tag,
128
- attrName,
129
- disabledDefaultTemplateHandler,
130
- matchCustomAttribute
131
- );
132
- if (!shouldHandle) {
133
- continue;
134
- }
135
- updateDirectiveExpression(ms, prop, jsHandler, runtimeSet);
136
- }
137
- }
138
- });
139
- }
140
- if (descriptor.script) {
141
- const { code: code2 } = jsHandler(descriptor.script.content, _nullishCoalesce(runtimeSet, () => ( /* @__PURE__ */ new Set())), defaultCreateJsHandlerOptions);
142
- ms.update(descriptor.script.loc.start.offset, descriptor.script.loc.end.offset, code2);
143
- }
144
- if (descriptor.scriptSetup) {
145
- const { code: code2 } = jsHandler(descriptor.scriptSetup.content, _nullishCoalesce(runtimeSet, () => ( /* @__PURE__ */ new Set())), defaultCreateJsHandlerOptions);
146
- ms.update(descriptor.scriptSetup.loc.start.offset, descriptor.scriptSetup.loc.end.offset, code2);
147
- }
148
- }
149
- return {
150
- code: ms.toString(),
151
- // @ts-ignore
152
- get map() {
153
- return ms.generateMap();
154
- }
155
- };
156
- }
157
-
158
- // src/bundlers/vite/query.ts
159
- function parseVueRequest(id) {
160
- const [filename, rawQuery] = id.split(`?`, 2);
161
- const searchParams = new URLSearchParams(rawQuery);
162
- const query = Object.fromEntries(searchParams);
163
- if (query.vue != null) {
164
- query.vue = true;
165
- }
166
- if (query.index != null) {
167
- query.index = Number(query.index);
168
- }
169
- if (query.raw != null) {
170
- query.raw = true;
171
- }
172
- if (query.url != null) {
173
- query.url = true;
174
- }
175
- if (query.scoped != null) {
176
- query.scoped = true;
177
- }
178
- const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
179
- const langType = query.lang || (langTypeMatch ? langTypeMatch.slice("lang.".length) : void 0);
180
- if (langType) {
181
- query.lang = langType;
182
- }
183
- return {
184
- filename,
185
- query
186
- };
187
- }
188
-
189
- // src/bundlers/vite/utils.ts
190
-
191
-
192
- var _shared = require('@weapp-tailwindcss/shared');
193
- function slash(p) {
194
- return _shared.ensurePosix.call(void 0, p);
195
- }
196
- var isWindows = _process2.default.platform === "win32";
197
- var cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
198
- var cssLangRE = new RegExp(cssLangs);
199
- function isCSSRequest(request) {
200
- return cssLangRE.test(request);
201
- }
202
- function normalizePath(id) {
203
- return _path2.default.posix.normalize(isWindows ? _shared.ensurePosix.call(void 0, id) : id);
204
- }
205
- async function formatPostcssSourceMap(rawMap, file) {
206
- const inputFileDir = _path2.default.dirname(file);
207
- const sources = rawMap.sources.map((source) => {
208
- const cleanSource = _shared.cleanUrl.call(void 0, decodeURIComponent(source));
209
- if (cleanSource[0] === "<" && cleanSource.endsWith(">")) {
210
- return `\0${cleanSource}`;
211
- }
212
- return normalizePath(_path2.default.resolve(inputFileDir, cleanSource));
213
- });
214
- return {
215
- file,
216
- mappings: rawMap.mappings,
217
- names: rawMap.names,
218
- sources,
219
- sourcesContent: rawMap.sourcesContent,
220
- version: rawMap.version
221
- };
222
- }
223
-
224
- // src/uni-app-x/vite.ts
225
- var preprocessorLangs = /* @__PURE__ */ new Set(["scss", "sass", "less", "styl", "stylus"]);
226
- function isPreprocessorRequest(id, lang) {
227
- const normalizedLang = _optionalChain([lang, 'optionalAccess', _8 => _8.toLowerCase, 'call', _9 => _9()]);
228
- if (normalizedLang && preprocessorLangs.has(normalizedLang)) {
229
- return true;
230
- }
231
- const inlineLangMatch = id.match(/lang\.([a-z]+)/i);
232
- if (inlineLangMatch && preprocessorLangs.has(inlineLangMatch[1].toLowerCase())) {
233
- return true;
234
- }
235
- return /\.(?:scss|sass|less|styl|stylus)(?:\?|$)/i.test(id);
236
- }
237
- function createUniAppXPlugins(options) {
238
- const {
239
- appType,
240
- customAttributesEntities,
241
- disabledDefaultTemplateHandler,
242
- isIosPlatform: providedIosPlatform,
243
- mainCssChunkMatcher,
244
- runtimeState,
245
- styleHandler,
246
- jsHandler,
247
- ensureRuntimeClassSet,
248
- getResolvedConfig
249
- } = options;
250
- const isIosPlatform = _nullishCoalesce(providedIosPlatform, () => ( _chunkDYLQ6UOIjs.resolveUniUtsPlatform.call(void 0, ).isAppIos));
251
- async function transformStyle(code, id, query) {
252
- const parsed = _nullishCoalesce(query, () => ( parseVueRequest(id).query));
253
- if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
254
- const postcssResult = await styleHandler(code, {
255
- isMainChunk: mainCssChunkMatcher(id, appType),
256
- postcssOptions: {
257
- options: {
258
- from: id,
259
- map: {
260
- inline: false,
261
- annotation: false,
262
- // PostCSS 可能返回虚拟文件,因此需要启用这一项以获取源内容
263
- sourcesContent: true
264
- // 若上游预处理器已经生成 source map,sources 中可能出现重复条目
265
- }
266
- }
267
- }
268
- });
269
- const rawPostcssMap = postcssResult.map.toJSON();
270
- const postcssMap = await formatPostcssSourceMap(
271
- rawPostcssMap,
272
- _shared.cleanUrl.call(void 0, id)
273
- );
274
- return {
275
- code: postcssResult.css,
276
- map: postcssMap
277
- };
278
- }
279
- }
280
- const cssPrePlugin = {
281
- name: "weapp-tailwindcss:uni-app-x:css:pre",
282
- enforce: "pre",
283
- async transform(code, id) {
284
- await runtimeState.patchPromise;
285
- const { query } = parseVueRequest(id);
286
- const lang = query.lang;
287
- if (isIosPlatform && isPreprocessorRequest(id, lang)) {
288
- return;
289
- }
290
- return transformStyle(code, id, query);
291
- }
292
- };
293
- const cssPlugin = {
294
- name: "weapp-tailwindcss:uni-app-x:css",
295
- async transform(code, id) {
296
- await runtimeState.patchPromise;
297
- return transformStyle(code, id);
298
- }
299
- };
300
- const cssPlugins = [cssPlugin, cssPrePlugin];
301
- const nvuePlugin = {
302
- name: "weapp-tailwindcss:uni-app-x:nvue",
303
- enforce: "pre",
304
- async buildStart() {
305
- await ensureRuntimeClassSet(true);
306
- },
307
- async transform(code, id) {
308
- if (!/\.(?:uvue|nvue)(?:\?.*)?$/.test(id)) {
309
- return;
310
- }
311
- const resolvedConfig = getResolvedConfig();
312
- const isServeCommand = _optionalChain([resolvedConfig, 'optionalAccess', _10 => _10.command]) === "serve";
313
- const isWatchBuild = _optionalChain([resolvedConfig, 'optionalAccess', _11 => _11.command]) === "build" && !!_optionalChain([resolvedConfig, 'access', _12 => _12.build, 'optionalAccess', _13 => _13.watch]);
314
- const isNonWatchBuild = _optionalChain([resolvedConfig, 'optionalAccess', _14 => _14.command]) === "build" && !_optionalChain([resolvedConfig, 'access', _15 => _15.build, 'optionalAccess', _16 => _16.watch]);
315
- const shouldForceRefresh = isServeCommand || isWatchBuild || isNonWatchBuild;
316
- const currentRuntimeSet = shouldForceRefresh ? await ensureRuntimeClassSet(true) : await ensureRuntimeClassSet();
317
- const extraOptions = customAttributesEntities.length > 0 || disabledDefaultTemplateHandler ? {
318
- customAttributesEntities,
319
- disabledDefaultTemplateHandler
320
- } : void 0;
321
- if (extraOptions) {
322
- return transformUVue(code, id, jsHandler, currentRuntimeSet, extraOptions);
323
- }
324
- return transformUVue(code, id, jsHandler, currentRuntimeSet);
325
- },
326
- async handleHotUpdate(ctx) {
327
- const resolvedConfig = getResolvedConfig();
328
- if (_optionalChain([resolvedConfig, 'optionalAccess', _17 => _17.command]) !== "serve") {
329
- return;
330
- }
331
- if (!/\.(?:uvue|nvue)$/.test(ctx.file)) {
332
- return;
333
- }
334
- await ensureRuntimeClassSet(true);
335
- },
336
- async watchChange(id) {
337
- const resolvedConfig = getResolvedConfig();
338
- if (_optionalChain([resolvedConfig, 'optionalAccess', _18 => _18.command]) !== "build" || !_optionalChain([resolvedConfig, 'access', _19 => _19.build, 'optionalAccess', _20 => _20.watch])) {
339
- return;
340
- }
341
- if (!/\.(?:uvue|nvue)(?:\?.*)?$/.test(id)) {
342
- return;
343
- }
344
- await ensureRuntimeClassSet(true);
345
- }
346
- };
347
- return [
348
- ...cssPlugins,
349
- nvuePlugin
350
- ];
351
- }
352
- function createUniAppXAssetTask(file, originalSource, outDir, options) {
353
- return async () => {
354
- const {
355
- cache,
356
- hashKey,
357
- createHandlerOptions,
358
- debug: debug2,
359
- jsHandler,
360
- onUpdate,
361
- runtimeSet,
362
- applyLinkedResults: applyLinkedResults2
363
- } = options;
364
- const absoluteFile = _chunk6Z4GEN2Yjs.toAbsoluteOutputPath.call(void 0, file, outDir);
365
- const rawSource = originalSource.source.toString();
366
- const rawHashSource = options.hashSalt ? `${rawSource}
367
- /*${options.hashSalt}*/` : rawSource;
368
- await _chunkLTJQUORKjs.processCachedTask.call(void 0, {
369
- cache,
370
- cacheKey: file,
371
- hashKey,
372
- rawSource: rawHashSource,
373
- applyResult(source) {
374
- originalSource.source = source;
375
- },
376
- onCacheHit() {
377
- debug2("js cache hit: %s", file);
378
- },
379
- async transform() {
380
- const currentSource = originalSource.source.toString();
381
- const { code, linked } = await jsHandler(currentSource, runtimeSet, createHandlerOptions(absoluteFile, {
382
- uniAppX: _nullishCoalesce(options.uniAppX, () => ( true)),
383
- babelParserOptions: {
384
- plugins: [
385
- "typescript"
386
- ],
387
- sourceType: "unambiguous"
388
- }
389
- }));
390
- onUpdate(file, currentSource, code);
391
- debug2("js handle: %s", file);
392
- applyLinkedResults2(linked);
393
- return {
394
- result: code
395
- };
396
- }
397
- });
398
- };
399
- }
400
-
401
- // src/bundlers/vite/generate-bundle.ts
402
-
403
-
404
-
405
- // src/bundlers/vite/bundle-entries.ts
406
- var _buffer = require('buffer');
407
- function readOutputEntry(entry) {
408
- if (entry.output.type === "chunk") {
409
- return entry.output.code;
410
- }
411
- const source = entry.output.source;
412
- if (typeof source === "string") {
413
- return source;
414
- }
415
- if (source instanceof Uint8Array) {
416
- return _buffer.Buffer.from(source).toString();
417
- }
418
- const fallbackSource = source;
419
- if (fallbackSource == null) {
420
- return void 0;
421
- }
422
- if (typeof fallbackSource.toString === "function") {
423
- return fallbackSource.toString();
424
- }
425
- return void 0;
426
- }
427
- function isJavaScriptEntry(entry) {
428
- if (entry.output.type === "chunk") {
429
- return true;
430
- }
431
- return entry.fileName.endsWith(".js");
432
- }
433
- function createBundleModuleGraphOptions(outputDir, entries) {
434
- return {
435
- resolve(specifier, importer) {
436
- return _chunk6Z4GEN2Yjs.resolveOutputSpecifier.call(void 0, specifier, importer, outputDir, (candidate) => entries.has(candidate));
437
- },
438
- load(id) {
439
- const entry = entries.get(id);
440
- if (!entry) {
441
- return void 0;
442
- }
443
- return readOutputEntry(entry);
444
- },
445
- filter(id) {
446
- return entries.has(id);
447
- }
448
- };
449
- }
450
- function applyLinkedResults(linked, entries, onLinkedUpdate, onApplied) {
451
- if (!linked) {
452
- return;
453
- }
454
- for (const [id, { code }] of Object.entries(linked)) {
455
- const entry = entries.get(id);
456
- if (!entry) {
457
- continue;
458
- }
459
- const previous = readOutputEntry(entry);
460
- if (previous == null || previous === code) {
461
- continue;
462
- }
463
- if (entry.output.type === "chunk") {
464
- entry.output.code = code;
465
- } else {
466
- entry.output.source = code;
467
- }
468
- _optionalChain([onApplied, 'optionalCall', _21 => _21(entry, code)]);
469
- onLinkedUpdate(entry.fileName, previous, code);
470
- }
471
- }
472
-
473
- // src/bundlers/vite/js-precheck.ts
474
- var 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)-/;
475
- var DEPENDENCY_HINT_RE = /\bimport\s*[("'`{*]|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
476
- function shouldSkipViteJsTransform(rawSource, options) {
477
- if (!rawSource) {
478
- return true;
479
- }
480
- if (_optionalChain([options, 'optionalAccess', _22 => _22.alwaysEscape])) {
481
- return false;
482
- }
483
- if (_optionalChain([options, 'optionalAccess', _23 => _23.moduleSpecifierReplacements]) && Object.keys(options.moduleSpecifierReplacements).length > 0) {
484
- return false;
485
- }
486
- if (_optionalChain([options, 'optionalAccess', _24 => _24.wrapExpression])) {
487
- return false;
488
- }
489
- if (DEPENDENCY_HINT_RE.test(rawSource)) {
490
- return false;
491
- }
492
- return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
493
- }
494
-
495
- // src/bundlers/vite/generate-bundle.ts
496
- function formatDebugFileList(files, limit = 8) {
497
- if (files.size === 0) {
498
- return "-";
499
- }
500
- const sorted = [...files].sort();
501
- if (sorted.length <= limit) {
502
- return sorted.join(",");
503
- }
504
- return `${sorted.slice(0, limit).join(",")},...(+${sorted.length - limit})`;
505
- }
506
- function createEmptyMetric() {
507
- return {
508
- total: 0,
509
- transformed: 0,
510
- cacheHits: 0,
511
- elapsed: 0
512
- };
513
- }
514
- function createEmptyMetrics() {
515
- return {
516
- runtimeSet: 0,
517
- html: createEmptyMetric(),
518
- js: createEmptyMetric(),
519
- css: createEmptyMetric()
520
- };
521
- }
522
- function classifyEntry(file, opts) {
523
- if (opts.cssMatcher(file)) {
524
- return "css";
525
- }
526
- if (opts.htmlMatcher(file)) {
527
- return "html";
528
- }
529
- if (opts.jsMatcher(file) || opts.wxsMatcher(file)) {
530
- return "js";
531
- }
532
- return "other";
533
- }
534
- function readEntrySource(output) {
535
- if (output.type === "chunk") {
536
- return output.code;
537
- }
538
- return output.source.toString();
539
- }
540
- function toJsAbsoluteFilename(file, outDir) {
541
- return _chunk6Z4GEN2Yjs.toAbsoluteOutputPath.call(void 0, file, outDir);
542
- }
543
- function computeDirtyEntries(entries, opts, state) {
544
- const nextSourceHashByFile = /* @__PURE__ */ new Map();
545
- const changedByType = {
546
- html: /* @__PURE__ */ new Set(),
547
- js: /* @__PURE__ */ new Set(),
548
- css: /* @__PURE__ */ new Set(),
549
- other: /* @__PURE__ */ new Set()
550
- };
551
- for (const [file, output] of entries) {
552
- const type = classifyEntry(file, opts);
553
- const source = readEntrySource(output);
554
- const hash = opts.cache.computeHash(source);
555
- nextSourceHashByFile.set(file, hash);
556
- const previousHash = state.previousSourceHashByFile.get(file);
557
- if (previousHash == null || previousHash !== hash) {
558
- changedByType[type].add(file);
559
- }
560
- }
561
- return {
562
- sourceHashByFile: nextSourceHashByFile,
563
- changedByType
564
- };
565
- }
566
- function buildProcessSets(entries, opts, changedByType, previousLinkedByEntry, forceAll = false) {
567
- const processFiles = {
568
- html: /* @__PURE__ */ new Set(),
569
- js: /* @__PURE__ */ new Set(),
570
- css: /* @__PURE__ */ new Set()
571
- };
572
- const linkedImpactsByEntry = /* @__PURE__ */ new Map();
573
- if (forceAll) {
574
- for (const [file] of entries) {
575
- const type = classifyEntry(file, opts);
576
- if (type === "html" || type === "js" || type === "css") {
577
- processFiles[type].add(file);
578
- }
579
- }
580
- return {
581
- files: processFiles,
582
- linkedImpactsByEntry
583
- };
584
- }
585
- const firstRun = previousLinkedByEntry.size === 0;
586
- if (firstRun) {
587
- for (const [file] of entries) {
588
- const type = classifyEntry(file, opts);
589
- if (type === "html" || type === "js" || type === "css") {
590
- processFiles[type].add(file);
591
- }
592
- }
593
- return {
594
- files: processFiles,
595
- linkedImpactsByEntry
596
- };
597
- }
598
- for (const [file] of entries) {
599
- if (classifyEntry(file, opts) === "html") {
600
- processFiles.html.add(file);
601
- }
602
- }
603
- for (const file of changedByType.css) {
604
- processFiles.css.add(file);
605
- }
606
- for (const file of changedByType.js) {
607
- processFiles.js.add(file);
608
- }
609
- for (const changedFile of changedByType.js) {
610
- for (const [entryFile, linkedFiles] of previousLinkedByEntry.entries()) {
611
- if (linkedFiles.has(changedFile)) {
612
- processFiles.js.add(entryFile);
613
- let impacts = linkedImpactsByEntry.get(entryFile);
614
- if (!impacts) {
615
- impacts = /* @__PURE__ */ new Set();
616
- linkedImpactsByEntry.set(entryFile, impacts);
617
- }
618
- impacts.add(changedFile);
619
- }
620
- }
621
- }
622
- return {
623
- files: processFiles,
624
- linkedImpactsByEntry
625
- };
626
- }
627
- function measureElapsed(start) {
628
- return performance.now() - start;
629
- }
630
- function formatCacheHitRate(metric) {
631
- if (metric.total === 0) {
632
- return "0.00%";
633
- }
634
- return `${(metric.cacheHits / metric.total * 100).toFixed(2)}%`;
635
- }
636
- function formatMs(value) {
637
- return value.toFixed(2);
638
- }
639
- function summarizeStringDiff(previous, next) {
640
- if (previous === next) {
641
- return "same";
642
- }
643
- const previousLength = previous.length;
644
- const nextLength = next.length;
645
- const minLength = Math.min(previousLength, nextLength);
646
- let prefixLength = 0;
647
- while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) {
648
- prefixLength += 1;
649
- }
650
- let previousSuffixCursor = previousLength - 1;
651
- let nextSuffixCursor = nextLength - 1;
652
- while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) {
653
- previousSuffixCursor -= 1;
654
- nextSuffixCursor -= 1;
655
- }
656
- const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0;
657
- const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0;
658
- return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`;
659
- }
660
- function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) {
661
- const changedLinkedFiles = linkedImpactsByEntry.get(entry);
662
- if (!changedLinkedFiles || changedLinkedFiles.size === 0) {
663
- return void 0;
664
- }
665
- const parts = [...changedLinkedFiles].sort().map((file) => {
666
- const hash = _nullishCoalesce(sourceHashByFile.get(file), () => ( "missing"));
667
- return `${file}:${hash}`;
668
- });
669
- return parts.join(",");
670
- }
671
- function createJsHashSalt(runtimeSignature, linkedImpactSignature) {
672
- if (!linkedImpactSignature) {
673
- return runtimeSignature;
674
- }
675
- return `${runtimeSignature}:linked:${linkedImpactSignature}`;
676
- }
677
- function hasRuntimeAffectingSourceChanges(changedByType) {
678
- return changedByType.html.size > 0 || changedByType.js.size > 0;
679
- }
680
- function createGenerateBundleHook(context) {
681
- const state = {
682
- iteration: 0,
683
- previousSourceHashByFile: /* @__PURE__ */ new Map(),
684
- previousLinkedByEntry: /* @__PURE__ */ new Map(),
685
- changedByType: {
686
- html: /* @__PURE__ */ new Set(),
687
- js: /* @__PURE__ */ new Set(),
688
- css: /* @__PURE__ */ new Set(),
689
- other: /* @__PURE__ */ new Set()
690
- }
691
- };
692
- return async function generateBundle(_opt, bundle) {
693
- const {
694
- opts,
695
- runtimeState,
696
- ensureRuntimeClassSet,
697
- debug: debug2,
698
- getResolvedConfig
699
- } = context;
700
- const {
701
- appType,
702
- cache,
703
- mainCssChunkMatcher,
704
- onEnd,
705
- onStart,
706
- onUpdate,
707
- styleHandler,
708
- templateHandler,
709
- jsHandler,
710
- uniAppX
711
- } = opts;
712
- await runtimeState.patchPromise;
713
- debug2("start");
714
- onStart();
715
- const metrics = createEmptyMetrics();
716
- const forceRuntimeRefreshByEnv = _process2.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
717
- const disableDirtyOptimization = _process2.default.env.WEAPP_TW_VITE_DISABLE_DIRTY === "1";
718
- const disableJsPrecheck = _process2.default.env.WEAPP_TW_VITE_DISABLE_JS_PRECHECK === "1";
719
- const debugCssDiff = _process2.default.env.WEAPP_TW_VITE_DEBUG_CSS_DIFF === "1";
720
- const entries = Object.entries(bundle);
721
- const dirtyEntries = computeDirtyEntries(entries, opts, state);
722
- const forceRuntimeRefreshBySource = hasRuntimeAffectingSourceChanges(dirtyEntries.changedByType);
723
- const forceRuntimeRefresh = forceRuntimeRefreshByEnv || forceRuntimeRefreshBySource;
724
- const processSets = buildProcessSets(entries, opts, dirtyEntries.changedByType, state.previousLinkedByEntry, disableDirtyOptimization);
725
- const processFiles = processSets.files;
726
- debug2(
727
- "dirty iteration=%d html=%d[%s] js=%d[%s] css=%d[%s] other=%d[%s]",
728
- state.iteration + 1,
729
- dirtyEntries.changedByType.html.size,
730
- formatDebugFileList(dirtyEntries.changedByType.html),
731
- dirtyEntries.changedByType.js.size,
732
- formatDebugFileList(dirtyEntries.changedByType.js),
733
- dirtyEntries.changedByType.css.size,
734
- formatDebugFileList(dirtyEntries.changedByType.css),
735
- dirtyEntries.changedByType.other.size,
736
- formatDebugFileList(dirtyEntries.changedByType.other)
737
- );
738
- debug2(
739
- "process iteration=%d html=%d[%s] js=%d[%s] css=%d[%s]",
740
- state.iteration + 1,
741
- processFiles.html.size,
742
- formatDebugFileList(processFiles.html),
743
- processFiles.js.size,
744
- formatDebugFileList(processFiles.js),
745
- processFiles.css.size,
746
- formatDebugFileList(processFiles.css)
747
- );
748
- const resolvedConfig = getResolvedConfig();
749
- const rootDir = _optionalChain([resolvedConfig, 'optionalAccess', _25 => _25.root]) ? _path2.default.resolve(resolvedConfig.root) : _process2.default.cwd();
750
- const outDir = _optionalChain([resolvedConfig, 'optionalAccess', _26 => _26.build, 'optionalAccess', _27 => _27.outDir]) ? _path2.default.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
751
- const jsEntries = /* @__PURE__ */ new Map();
752
- for (const [fileName, output] of entries) {
753
- const entry = { fileName, output };
754
- if (isJavaScriptEntry(entry)) {
755
- const absolute = toJsAbsoluteFilename(fileName, outDir);
756
- jsEntries.set(absolute, entry);
757
- }
758
- }
759
- const moduleGraphOptions = createBundleModuleGraphOptions(outDir, jsEntries);
760
- const runtimeStart = performance.now();
761
- const runtime = await ensureRuntimeClassSet(forceRuntimeRefresh);
762
- metrics.runtimeSet = measureElapsed(runtimeStart);
763
- if (forceRuntimeRefreshBySource) {
764
- debug2(
765
- "runtimeSet forced refresh due to source changes: html=%d js=%d",
766
- dirtyEntries.changedByType.html.size,
767
- dirtyEntries.changedByType.js.size
768
- );
769
- }
770
- debug2("get runtimeSet, class count: %d", runtime.size);
771
- const runtimeSignature = _nullishCoalesce(_chunkDEIJXHGJjs.getRuntimeClassSetSignature.call(void 0, runtimeState.twPatcher), () => ( "runtime:missing"));
772
- const handleLinkedUpdate = (fileName, previous, next) => {
773
- onUpdate(fileName, previous, next);
774
- debug2("js linked handle: %s", fileName);
775
- };
776
- const pendingLinkedUpdates = [];
777
- const scheduleLinkedApply = (entry, code) => {
778
- pendingLinkedUpdates.push(() => {
779
- if (entry.output.type === "chunk") {
780
- entry.output.code = code;
781
- } else {
782
- entry.output.source = code;
783
- }
784
- });
785
- };
786
- const applyLinkedUpdates = (linked) => {
787
- applyLinkedResults(linked, jsEntries, handleLinkedUpdate, scheduleLinkedApply);
788
- };
789
- const createHandlerOptions = (absoluteFilename, extra) => ({
790
- ...extra,
791
- filename: absoluteFilename,
792
- tailwindcssMajorVersion: runtimeState.twPatcher.majorVersion,
793
- moduleGraph: moduleGraphOptions,
794
- babelParserOptions: {
795
- ..._nullishCoalesce(_optionalChain([extra, 'optionalAccess', _28 => _28.babelParserOptions]), () => ( {})),
796
- sourceFilename: absoluteFilename
797
- }
798
- });
799
- const linkedByEntry = /* @__PURE__ */ new Map();
800
- const tasks = [];
801
- const jsTaskFactories = [];
802
- for (const [file, originalSource] of entries) {
803
- const type = classifyEntry(file, opts);
804
- if (type === "html" && originalSource.type === "asset") {
805
- metrics.html.total++;
806
- if (!processFiles.html.has(file)) {
807
- continue;
808
- }
809
- const rawSource = originalSource.source.toString();
810
- tasks.push(
811
- _chunkLTJQUORKjs.processCachedTask.call(void 0, {
812
- cache,
813
- cacheKey: file,
814
- rawSource,
815
- hashKey: `${file}:html:${runtimeSignature}`,
816
- applyResult(source) {
817
- originalSource.source = source;
818
- },
819
- onCacheHit() {
820
- metrics.html.cacheHits++;
821
- debug2("html cache hit: %s", file);
822
- },
823
- async transform() {
824
- const start = performance.now();
825
- const transformed = await templateHandler(rawSource, {
826
- runtimeSet: runtime
827
- });
828
- metrics.html.elapsed += measureElapsed(start);
829
- metrics.html.transformed++;
830
- onUpdate(file, rawSource, transformed);
831
- debug2("html handle: %s", file);
832
- return {
833
- result: transformed
834
- };
835
- }
836
- })
837
- );
838
- continue;
839
- }
840
- if (type === "css" && originalSource.type === "asset") {
841
- metrics.css.total++;
842
- const rawSource = originalSource.source.toString();
843
- tasks.push(
844
- _chunkLTJQUORKjs.processCachedTask.call(void 0, {
845
- cache,
846
- cacheKey: file,
847
- rawSource,
848
- hashKey: `${file}:css:${runtimeSignature}:${_nullishCoalesce(runtimeState.twPatcher.majorVersion, () => ( "unknown"))}`,
849
- applyResult(source) {
850
- originalSource.source = source;
851
- },
852
- onCacheHit() {
853
- metrics.css.cacheHits++;
854
- debug2("css cache hit: %s", file);
855
- },
856
- async transform() {
857
- const start = performance.now();
858
- await runtimeState.patchPromise;
859
- const { css } = await styleHandler(rawSource, {
860
- isMainChunk: mainCssChunkMatcher(originalSource.fileName, appType),
861
- postcssOptions: {
862
- options: {
863
- from: file
864
- }
865
- },
866
- majorVersion: runtimeState.twPatcher.majorVersion
867
- });
868
- if (debugCssDiff) {
869
- debug2("css diff %s: %s", file, summarizeStringDiff(rawSource, css));
870
- }
871
- metrics.css.elapsed += measureElapsed(start);
872
- metrics.css.transformed++;
873
- onUpdate(file, rawSource, css);
874
- debug2("css handle: %s", file);
875
- return {
876
- result: css
877
- };
878
- }
879
- })
880
- );
881
- continue;
882
- }
883
- if (type !== "js") {
884
- continue;
885
- }
886
- metrics.js.total++;
887
- const shouldTransformJs = processFiles.js.has(file);
888
- if (!shouldTransformJs) {
889
- debug2("js skip transform (clean), replay cache: %s", file);
890
- }
891
- if (originalSource.type === "chunk") {
892
- const absoluteFile = toJsAbsoluteFilename(file, outDir);
893
- const initialRawSource = originalSource.code;
894
- const linkedSet = /* @__PURE__ */ new Set();
895
- linkedByEntry.set(file, linkedSet);
896
- jsTaskFactories.push(async () => {
897
- const linkedImpactSignature = createLinkedImpactSignature(
898
- file,
899
- processSets.linkedImpactsByEntry,
900
- dirtyEntries.sourceHashByFile
901
- );
902
- const hashSalt = createJsHashSalt(runtimeSignature, linkedImpactSignature);
903
- await _chunkLTJQUORKjs.processCachedTask.call(void 0, {
904
- cache,
905
- cacheKey: file,
906
- hashKey: `${file}:js`,
907
- rawSource: `${initialRawSource}
908
- /*${hashSalt}*/`,
909
- applyResult(source) {
910
- originalSource.code = source;
911
- },
912
- onCacheHit() {
913
- metrics.js.cacheHits++;
914
- debug2("js cache hit: %s", file);
915
- },
916
- async transform() {
917
- const start = performance.now();
918
- const rawSource = originalSource.code;
919
- if (!shouldTransformJs) {
920
- debug2("js cache replay miss, fallback transform: %s", file);
921
- }
922
- const handlerOptions = createHandlerOptions(absoluteFile);
923
- if (!disableJsPrecheck && shouldSkipViteJsTransform(rawSource, handlerOptions)) {
924
- metrics.js.elapsed += measureElapsed(start);
925
- metrics.js.transformed++;
926
- return {
927
- result: rawSource
928
- };
929
- }
930
- const { code, linked } = await jsHandler(rawSource, runtime, handlerOptions);
931
- metrics.js.elapsed += measureElapsed(start);
932
- metrics.js.transformed++;
933
- onUpdate(file, rawSource, code);
934
- debug2("js handle: %s", file);
935
- if (linked) {
936
- for (const id of Object.keys(linked)) {
937
- const linkedEntry = jsEntries.get(id);
938
- if (linkedEntry) {
939
- linkedSet.add(linkedEntry.fileName);
940
- }
941
- }
942
- }
943
- applyLinkedUpdates(linked);
944
- return {
945
- result: code
946
- };
947
- }
948
- });
949
- });
950
- } else if (uniAppX && originalSource.type === "asset") {
951
- const linkedSet = /* @__PURE__ */ new Set();
952
- linkedByEntry.set(file, linkedSet);
953
- const baseApplyLinkedUpdates = applyLinkedUpdates;
954
- const wrappedApplyLinkedUpdates = (linked) => {
955
- if (linked) {
956
- for (const id of Object.keys(linked)) {
957
- const linkedEntry = jsEntries.get(id);
958
- if (linkedEntry) {
959
- linkedSet.add(linkedEntry.fileName);
960
- }
961
- }
962
- }
963
- baseApplyLinkedUpdates(linked);
964
- };
965
- const factory = createUniAppXAssetTask(
966
- file,
967
- originalSource,
968
- outDir,
969
- {
970
- cache,
971
- hashKey: `${file}:js`,
972
- hashSalt: createJsHashSalt(
973
- runtimeSignature,
974
- createLinkedImpactSignature(
975
- file,
976
- processSets.linkedImpactsByEntry,
977
- dirtyEntries.sourceHashByFile
978
- )
979
- ),
980
- createHandlerOptions,
981
- debug: debug2,
982
- jsHandler,
983
- onUpdate,
984
- runtimeSet: runtime,
985
- applyLinkedResults: wrappedApplyLinkedUpdates,
986
- uniAppX
987
- }
988
- );
989
- jsTaskFactories.push(async () => {
990
- const start = performance.now();
991
- if (!shouldTransformJs) {
992
- debug2("js skip transform (clean, uni-app-x), replay cache: %s", file);
993
- await factory();
994
- metrics.js.elapsed += measureElapsed(start);
995
- metrics.js.transformed++;
996
- return;
997
- }
998
- const currentSource = originalSource.source.toString();
999
- const absoluteFile = toJsAbsoluteFilename(file, outDir);
1000
- const precheckOptions = createHandlerOptions(absoluteFile, {
1001
- uniAppX: _nullishCoalesce(uniAppX, () => ( true)),
1002
- babelParserOptions: {
1003
- plugins: ["typescript"],
1004
- sourceType: "unambiguous"
1005
- }
1006
- });
1007
- if (!disableJsPrecheck && shouldSkipViteJsTransform(currentSource, precheckOptions)) {
1008
- metrics.js.elapsed += measureElapsed(start);
1009
- metrics.js.transformed++;
1010
- return;
1011
- }
1012
- await factory();
1013
- metrics.js.elapsed += measureElapsed(start);
1014
- metrics.js.transformed++;
1015
- });
1016
- }
1017
- }
1018
- _chunk6Z4GEN2Yjs.pushConcurrentTaskFactories.call(void 0, tasks, jsTaskFactories);
1019
- await Promise.all(tasks);
1020
- for (const apply of pendingLinkedUpdates) {
1021
- apply();
1022
- }
1023
- state.iteration += 1;
1024
- state.previousSourceHashByFile = dirtyEntries.sourceHashByFile;
1025
- state.changedByType = dirtyEntries.changedByType;
1026
- const nextLinkedByEntry = new Map(state.previousLinkedByEntry);
1027
- for (const [entryFile, linkedFiles] of linkedByEntry.entries()) {
1028
- nextLinkedByEntry.set(entryFile, linkedFiles);
1029
- }
1030
- for (const entryFile of [...nextLinkedByEntry.keys()]) {
1031
- const exists = entries.some(([fileName]) => fileName === entryFile);
1032
- if (!exists) {
1033
- nextLinkedByEntry.delete(entryFile);
1034
- }
1035
- }
1036
- state.previousLinkedByEntry = nextLinkedByEntry;
1037
- debug2(
1038
- "metrics iteration=%d runtime=%sms html(total=%d transform=%d hit=%d rate=%s elapsed=%sms) js(total=%d transform=%d hit=%d rate=%s elapsed=%sms) css(total=%d transform=%d hit=%d rate=%s elapsed=%sms)",
1039
- state.iteration,
1040
- formatMs(metrics.runtimeSet),
1041
- metrics.html.total,
1042
- metrics.html.transformed,
1043
- metrics.html.cacheHits,
1044
- formatCacheHitRate(metrics.html),
1045
- formatMs(metrics.html.elapsed),
1046
- metrics.js.total,
1047
- metrics.js.transformed,
1048
- metrics.js.cacheHits,
1049
- formatCacheHitRate(metrics.js),
1050
- formatMs(metrics.js.elapsed),
1051
- metrics.css.total,
1052
- metrics.css.transformed,
1053
- metrics.css.cacheHits,
1054
- formatCacheHitRate(metrics.css),
1055
- formatMs(metrics.css.elapsed)
1056
- );
1057
- onEnd();
1058
- debug2("end");
1059
- };
1060
- }
1061
-
1062
- // src/bundlers/vite/rewrite-css-imports.ts
1063
- function joinPosixPath(base, subpath) {
1064
- if (base.endsWith("/")) {
1065
- return `${base}${subpath}`;
1066
- }
1067
- return `${base}/${subpath}`;
1068
- }
1069
- function isCssLikeImporter(importer) {
1070
- if (!importer) {
1071
- return false;
1072
- }
1073
- const normalized = _shared.cleanUrl.call(void 0, importer);
1074
- return isCSSRequest(normalized);
1075
- }
1076
- function createRewriteCssImportsPlugins(options) {
1077
- if (!options.shouldRewrite) {
1078
- return [];
1079
- }
1080
- const { appType, weappTailwindcssDirPosix: weappTailwindcssDirPosix2 } = options;
1081
- return [
1082
- {
1083
- name: `${_chunkDEIJXHGJjs.vitePluginName}:rewrite-css-imports`,
1084
- enforce: "pre",
1085
- resolveId: {
1086
- order: "pre",
1087
- handler(id, importer) {
1088
- const replacement = _chunk6Z4GEN2Yjs.resolveTailwindcssImport.call(void 0, id, weappTailwindcssDirPosix2, {
1089
- join: joinPosixPath,
1090
- appType
1091
- });
1092
- if (!replacement) {
1093
- return null;
1094
- }
1095
- if (importer && !isCssLikeImporter(importer)) {
1096
- return null;
1097
- }
1098
- return replacement;
1099
- }
1100
- },
1101
- transform: {
1102
- order: "pre",
1103
- handler(code, id) {
1104
- if (!isCSSRequest(id)) {
1105
- return null;
1106
- }
1107
- const rewritten = _chunk6Z4GEN2Yjs.rewriteTailwindcssImportsInCode.call(void 0, code, weappTailwindcssDirPosix2, {
1108
- join: joinPosixPath,
1109
- appType
1110
- });
1111
- if (!rewritten) {
1112
- return null;
1113
- }
1114
- return {
1115
- code: rewritten,
1116
- map: null
1117
- };
1118
- }
1119
- }
1120
- }
1121
- ];
1122
- }
1123
-
1124
- // src/bundlers/vite/index.ts
1125
- var debug = _chunkDEIJXHGJjs.createDebug.call(void 0, );
1126
- var weappTailwindcssPackageDir = _chunk6Z4GEN2Yjs.resolvePackageDir.call(void 0, "weapp-tailwindcss");
1127
- var weappTailwindcssDirPosix = slash(weappTailwindcssPackageDir);
1128
- function UnifiedViteWeappTailwindcssPlugin(options = {}) {
1129
- const rewriteCssImportsSpecified = Object.prototype.hasOwnProperty.call(options, "rewriteCssImports");
1130
- const hasExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
1131
- const opts = _chunkDEIJXHGJjs.getCompilerContext.call(void 0, options);
1132
- const {
1133
- disabled,
1134
- customAttributes,
1135
- onLoad,
1136
- mainCssChunkMatcher,
1137
- appType,
1138
- styleHandler,
1139
- jsHandler,
1140
- twPatcher: initialTwPatcher,
1141
- refreshTailwindcssPatcher,
1142
- uniAppX,
1143
- disabledDefaultTemplateHandler
1144
- } = opts;
1145
- const disabledOptions = _chunk6Z4GEN2Yjs.resolveDisabledOptions.call(void 0, disabled);
1146
- const tailwindcssMajorVersion = _nullishCoalesce(initialTwPatcher.majorVersion, () => ( 0));
1147
- const shouldRewriteCssImports = opts.rewriteCssImports !== false && !disabledOptions.rewriteCssImports && (rewriteCssImportsSpecified || tailwindcssMajorVersion >= 4);
1148
- const rewritePlugins = createRewriteCssImportsPlugins({
1149
- appType,
1150
- shouldRewrite: shouldRewriteCssImports,
1151
- weappTailwindcssDirPosix
1152
- });
1153
- if (disabledOptions.plugin) {
1154
- return rewritePlugins.length ? rewritePlugins : void 0;
1155
- }
1156
- const customAttributesEntities = _chunkDEIJXHGJjs.toCustomAttributesEntities.call(void 0, customAttributes);
1157
- const patchRecorderState = _chunkGCRL3ZYPjs.setupPatchRecorder.call(void 0, initialTwPatcher, opts.tailwindcssBasedir, {
1158
- source: "runtime",
1159
- cwd: _nullishCoalesce(opts.tailwindcssBasedir, () => ( _process2.default.cwd()))
1160
- });
1161
- const runtimeState = {
1162
- twPatcher: initialTwPatcher,
1163
- patchPromise: patchRecorderState.patchPromise,
1164
- refreshTailwindcssPatcher,
1165
- onPatchCompleted: patchRecorderState.onPatchCompleted
1166
- };
1167
- let runtimeSet;
1168
- let runtimeSetPromise;
1169
- let resolvedConfig;
1170
- let runtimeRefreshSignature;
1171
- let runtimeRefreshOptionsKey;
1172
- function resolveRuntimeRefreshOptions() {
1173
- const configPath = _optionalChain([runtimeState, 'access', _29 => _29.twPatcher, 'access', _30 => _30.options, 'optionalAccess', _31 => _31.tailwind, 'optionalAccess', _32 => _32.config]);
1174
- const signature = _chunkDEIJXHGJjs.getRuntimeClassSetSignature.call(void 0, runtimeState.twPatcher);
1175
- const optionsKey = JSON.stringify({
1176
- appType,
1177
- uniAppX: Boolean(uniAppX),
1178
- customAttributesEntities,
1179
- disabledDefaultTemplateHandler,
1180
- configPath,
1181
- rewriteCssImports: shouldRewriteCssImports
1182
- });
1183
- const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
1184
- runtimeRefreshSignature = signature;
1185
- runtimeRefreshOptionsKey = optionsKey;
1186
- return {
1187
- changed,
1188
- signature,
1189
- optionsKey
1190
- };
1191
- }
1192
- async function refreshRuntimeState(force) {
1193
- const invalidation = resolveRuntimeRefreshOptions();
1194
- const shouldRefresh = force || invalidation.changed;
1195
- const refreshed = await _chunkDEIJXHGJjs.refreshTailwindRuntimeState.call(void 0, runtimeState, {
1196
- force: shouldRefresh,
1197
- clearCache: force || invalidation.changed
1198
- });
1199
- if (invalidation.changed) {
1200
- debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
1201
- }
1202
- if (refreshed) {
1203
- runtimeSet = void 0;
1204
- runtimeSetPromise = void 0;
1205
- }
1206
- }
1207
- async function ensureRuntimeClassSet(force = false) {
1208
- const forceRuntimeRefresh = force || _process2.default.env.WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH === "1";
1209
- await refreshRuntimeState(force);
1210
- await runtimeState.patchPromise;
1211
- if (!forceRuntimeRefresh && runtimeSet) {
1212
- return runtimeSet;
1213
- }
1214
- if (forceRuntimeRefresh || !runtimeSetPromise) {
1215
- const invalidation = resolveRuntimeRefreshOptions();
1216
- const task2 = _chunkDEIJXHGJjs.collectRuntimeClassSet.call(void 0, runtimeState.twPatcher, {
1217
- force: forceRuntimeRefresh || invalidation.changed,
1218
- skipRefresh: forceRuntimeRefresh,
1219
- clearCache: forceRuntimeRefresh || invalidation.changed
1220
- });
1221
- runtimeSetPromise = task2;
1222
- }
1223
- const task = runtimeSetPromise;
1224
- try {
1225
- runtimeSet = await task;
1226
- return runtimeSet;
1227
- } finally {
1228
- if (runtimeSetPromise === task) {
1229
- runtimeSetPromise = void 0;
1230
- }
1231
- }
1232
- }
1233
- onLoad();
1234
- const getResolvedConfig = () => resolvedConfig;
1235
- const utsPlatform = _chunkDYLQ6UOIjs.resolveUniUtsPlatform.call(void 0, );
1236
- const isIosPlatform = utsPlatform.isAppIos;
1237
- const uniAppXPlugins = uniAppX ? createUniAppXPlugins({
1238
- appType,
1239
- customAttributesEntities,
1240
- disabledDefaultTemplateHandler,
1241
- isIosPlatform,
1242
- mainCssChunkMatcher,
1243
- runtimeState,
1244
- styleHandler,
1245
- jsHandler,
1246
- ensureRuntimeClassSet,
1247
- getResolvedConfig
1248
- }) : void 0;
1249
- const plugins = [
1250
- ...rewritePlugins,
1251
- {
1252
- name: `${_chunkDEIJXHGJjs.vitePluginName}:post`,
1253
- enforce: "post",
1254
- async configResolved(config) {
1255
- resolvedConfig = config;
1256
- const resolvedRoot = config.root ? _path2.default.resolve(config.root) : void 0;
1257
- if (!hasExplicitTailwindcssBasedir && resolvedRoot && opts.tailwindcssBasedir !== resolvedRoot) {
1258
- const previousBasedir = opts.tailwindcssBasedir;
1259
- opts.tailwindcssBasedir = resolvedRoot;
1260
- debug("align tailwindcss basedir with vite root: %s -> %s", _nullishCoalesce(previousBasedir, () => ( "undefined")), resolvedRoot);
1261
- await refreshRuntimeState(true);
1262
- }
1263
- if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
1264
- const idx = config.css.postcss.plugins.findIndex((x) => (
1265
- // @ts-ignore
1266
- x.postcssPlugin === "postcss-html-transform"
1267
- ));
1268
- if (idx > -1) {
1269
- config.css.postcss.plugins.splice(idx, 1, _htmltransform2.default.call(void 0, ));
1270
- debug("remove postcss-html-transform plugin from vite config");
1271
- }
1272
- }
1273
- },
1274
- generateBundle: createGenerateBundleHook({
1275
- opts,
1276
- runtimeState,
1277
- ensureRuntimeClassSet,
1278
- debug,
1279
- getResolvedConfig
1280
- })
1281
- }
1282
- ];
1283
- if (uniAppXPlugins) {
1284
- plugins.push(...uniAppXPlugins);
1285
- }
1286
- return plugins;
1287
- }
1288
-
1289
-
1290
-
1291
- exports.UnifiedViteWeappTailwindcssPlugin = UnifiedViteWeappTailwindcssPlugin;