tailwindcss-patch 7.1.5 → 8.0.0

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.
@@ -1,1102 +0,0 @@
1
- // ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
2
- function isPlainObject(value) {
3
- if (value === null || typeof value !== "object") {
4
- return false;
5
- }
6
- const prototype = Object.getPrototypeOf(value);
7
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
8
- return false;
9
- }
10
- if (Symbol.iterator in value) {
11
- return false;
12
- }
13
- if (Symbol.toStringTag in value) {
14
- return Object.prototype.toString.call(value) === "[object Module]";
15
- }
16
- return true;
17
- }
18
- function _defu(baseObject, defaults, namespace = ".", merger) {
19
- if (!isPlainObject(defaults)) {
20
- return _defu(baseObject, {}, namespace, merger);
21
- }
22
- const object = Object.assign({}, defaults);
23
- for (const key in baseObject) {
24
- if (key === "__proto__" || key === "constructor") {
25
- continue;
26
- }
27
- const value = baseObject[key];
28
- if (value === null || value === void 0) {
29
- continue;
30
- }
31
- if (merger && merger(object, key, value, namespace)) {
32
- continue;
33
- }
34
- if (Array.isArray(value) && Array.isArray(object[key])) {
35
- object[key] = [...value, ...object[key]];
36
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
37
- object[key] = _defu(
38
- value,
39
- object[key],
40
- (namespace ? `${namespace}.` : "") + key.toString(),
41
- merger
42
- );
43
- } else {
44
- object[key] = value;
45
- }
46
- }
47
- return object;
48
- }
49
- function createDefu(merger) {
50
- return (...arguments_) => (
51
- // eslint-disable-next-line unicorn/no-array-reduce
52
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
53
- );
54
- }
55
- var defu = createDefu();
56
- var defuFn = createDefu((object, key, currentValue) => {
57
- if (object[key] !== void 0 && typeof currentValue === "function") {
58
- object[key] = currentValue(object[key]);
59
- return true;
60
- }
61
- });
62
- var defuArrayFn = createDefu((object, key, currentValue) => {
63
- if (Array.isArray(object[key]) && typeof currentValue === "function") {
64
- object[key] = currentValue(object[key]);
65
- return true;
66
- }
67
- });
68
-
69
- // ../shared/src/utils.ts
70
- var defuOverrideArray = createDefu((obj, key, value) => {
71
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
72
- obj[key] = value;
73
- return true;
74
- }
75
- });
76
- var preserveClassNames = [
77
- // https://tailwindcss.com/docs/transition-timing-function start
78
- // https://github.com/sonofmagic/tailwindcss-mangle/issues/21
79
- "ease-out",
80
- "ease-linear",
81
- "ease-in",
82
- "ease-in-out"
83
- // https://tailwindcss.com/docs/transition-timing-function end
84
- ];
85
- var preserveClassNamesMap = preserveClassNames.reduce((acc, cur) => {
86
- acc[cur] = true;
87
- return acc;
88
- }, {});
89
- var acceptChars = [..."abcdefghijklmnopqrstuvwxyz"];
90
-
91
- // src/logger.ts
92
- import { createConsola } from "consola";
93
- var logger = createConsola();
94
- var logger_default = logger;
95
-
96
- // src/core/cache.ts
97
- import process from "process";
98
- import fs from "fs-extra";
99
- import path from "pathe";
100
-
101
- // src/constants.ts
102
- var pkgName = "tailwindcss-patch";
103
-
104
- // src/core/cache.ts
105
- function getCacheOptions(options) {
106
- let cache;
107
- switch (typeof options) {
108
- case "undefined": {
109
- cache = {
110
- enable: false
111
- };
112
- break;
113
- }
114
- case "boolean": {
115
- cache = {
116
- enable: options
117
- };
118
- break;
119
- }
120
- case "object": {
121
- cache = { ...options, enable: true };
122
- break;
123
- }
124
- }
125
- return cache;
126
- }
127
- var CacheManager = class {
128
- options;
129
- constructor(options = {}) {
130
- this.options = this.getOptions(options);
131
- }
132
- getOptions(options = {}) {
133
- const cwd = options.cwd ?? process.cwd();
134
- const dir = options.dir ?? path.resolve(cwd, "node_modules/.cache", pkgName);
135
- const file = options.file ?? "index.json";
136
- const filename = path.resolve(dir, file);
137
- return {
138
- cwd,
139
- dir,
140
- file,
141
- filename,
142
- strategy: "merge"
143
- };
144
- }
145
- write(data) {
146
- try {
147
- const { filename } = this.options;
148
- fs.outputJSONSync(filename, [...data]);
149
- return filename;
150
- } catch (error) {
151
- logger_default.error(error);
152
- }
153
- }
154
- read() {
155
- const { filename } = this.options;
156
- const isExisted = fs.existsSync(filename);
157
- try {
158
- if (isExisted) {
159
- const data = fs.readJSONSync(filename);
160
- return new Set(data ?? []);
161
- }
162
- } catch {
163
- try {
164
- isExisted && fs.removeSync(filename);
165
- } catch (error) {
166
- logger_default.error(error);
167
- }
168
- }
169
- return /* @__PURE__ */ new Set();
170
- }
171
- };
172
-
173
- // src/defaults.ts
174
- import process2 from "process";
175
- function getDefaultPatchOptions() {
176
- return {
177
- packageName: "tailwindcss",
178
- applyPatches: {
179
- exportContext: true,
180
- extendLengthUnits: false
181
- },
182
- overwrite: true,
183
- filter: () => true
184
- };
185
- }
186
- function getPatchOptions(options) {
187
- return defu(
188
- options,
189
- {
190
- output: {
191
- removeUniversalSelector: true
192
- },
193
- basedir: process2.cwd()
194
- },
195
- getDefaultPatchOptions()
196
- );
197
- }
198
-
199
- // src/core/patches/exportContext/index.ts
200
- import fs2 from "fs-extra";
201
- import path2 from "pathe";
202
-
203
- // src/core/patches/exportContext/postcss-v2.ts
204
- import * as t from "@babel/types";
205
-
206
- // src/babel/index.ts
207
- import _babelGenerate from "@babel/generator";
208
- import _babelTraverse from "@babel/traverse";
209
- import { parse, parseExpression } from "@babel/parser";
210
- function _interopDefaultCompat(e) {
211
- return e && typeof e === "object" && "default" in e ? e.default : e;
212
- }
213
- var generate = _interopDefaultCompat(_babelGenerate);
214
- var traverse = _interopDefaultCompat(_babelTraverse);
215
-
216
- // src/core/patches/exportContext/postcss-v2.ts
217
- function inspectProcessTailwindFeaturesReturnContext(content) {
218
- const ast = parse(content, {
219
- sourceType: "unambiguous"
220
- });
221
- let hasPatched = false;
222
- traverse(ast, {
223
- FunctionDeclaration(p) {
224
- const n = p.node;
225
- if (n.id?.name === "processTailwindFeatures" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
226
- const rts = n.body.body[0];
227
- if (t.isFunctionExpression(rts.argument)) {
228
- const body = rts.argument.body.body;
229
- const lastStatement = body[body.length - 1];
230
- hasPatched = t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context";
231
- if (!hasPatched) {
232
- const rts2 = t.returnStatement(t.identifier("context"));
233
- body.push(rts2);
234
- }
235
- }
236
- }
237
- }
238
- });
239
- return {
240
- code: hasPatched ? content : generate(ast).code,
241
- hasPatched
242
- };
243
- }
244
- function inspectPostcssPlugin(content) {
245
- const ast = parse(content);
246
- const exportKey = "contextRef";
247
- const variableName = "contextRef";
248
- const valueKey = "value";
249
- let hasPatched = false;
250
- traverse(ast, {
251
- Program(p) {
252
- const n = p.node;
253
- const idx = n.body.findIndex((x) => {
254
- return t.isFunctionDeclaration(x) && x.id?.name === "_default";
255
- });
256
- if (idx > -1) {
257
- const prevStatement = n.body[idx - 1];
258
- const lastStatement = n.body[idx - 2];
259
- const hasPatchedCondition0 = prevStatement && t.isVariableDeclaration(prevStatement) && prevStatement.declarations.length === 1 && t.isIdentifier(prevStatement.declarations[0].id) && prevStatement.declarations[0].id.name === variableName;
260
- const hasPatchedCondition1 = t.isExpressionStatement(lastStatement) && t.isAssignmentExpression(lastStatement.expression) && t.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === variableName;
261
- hasPatched = hasPatchedCondition0 || hasPatchedCondition1;
262
- if (!hasPatched) {
263
- const statement = t.variableDeclaration("var", [
264
- t.variableDeclarator(t.identifier(variableName), t.objectExpression([t.objectProperty(t.identifier(valueKey), t.arrayExpression())]))
265
- ]);
266
- n.body.splice(
267
- idx,
268
- 0,
269
- statement,
270
- // exports.contextRef = contextRef;
271
- t.expressionStatement(
272
- t.assignmentExpression(
273
- "=",
274
- t.memberExpression(t.identifier("exports"), t.identifier(exportKey)),
275
- t.identifier(variableName)
276
- )
277
- )
278
- );
279
- }
280
- }
281
- },
282
- FunctionDeclaration(p) {
283
- if (hasPatched) {
284
- return;
285
- }
286
- const n = p.node;
287
- if (n.id?.name === "_default" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
288
- const returnStatement3 = n.body.body[0];
289
- if (t.isCallExpression(returnStatement3.argument) && t.isMemberExpression(returnStatement3.argument.callee) && t.isArrayExpression(returnStatement3.argument.callee.object)) {
290
- const targetFn = returnStatement3.argument.callee.object.elements[1];
291
- if (t.isFunctionExpression(targetFn)) {
292
- const targetBlockStatement = targetFn.body;
293
- if (t.isExpressionStatement(targetBlockStatement.body[0]) && t.isAssignmentExpression(targetBlockStatement.body[0].expression) && t.isNumericLiteral(targetBlockStatement.body[0].expression.right)) {
294
- hasPatched = true;
295
- return;
296
- }
297
- const lastStatement = targetBlockStatement.body[targetBlockStatement.body.length - 1];
298
- if (t.isExpressionStatement(lastStatement)) {
299
- const newExpressionStatement = t.expressionStatement(
300
- t.callExpression(
301
- t.memberExpression(
302
- t.memberExpression(t.identifier(variableName), t.identifier("value")),
303
- t.identifier("push")
304
- ),
305
- [lastStatement.expression]
306
- )
307
- );
308
- targetBlockStatement.body[targetBlockStatement.body.length - 1] = newExpressionStatement;
309
- }
310
- const ifIdx = targetBlockStatement.body.findIndex((x) => t.isIfStatement(x));
311
- if (ifIdx > -1) {
312
- const ifRoot = targetBlockStatement.body[ifIdx];
313
- if (t.isBlockStatement(ifRoot.consequent) && ifRoot.consequent.body[1] && t.isForOfStatement(ifRoot.consequent.body[1])) {
314
- const forOf = ifRoot.consequent.body[1];
315
- if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1 && t.isIfStatement(forOf.body.body[0])) {
316
- const if2 = forOf.body.body[0];
317
- if (t.isBlockStatement(if2.consequent) && if2.consequent.body.length === 1 && t.isExpressionStatement(if2.consequent.body[0])) {
318
- const target = if2.consequent.body[0];
319
- const newExpressionStatement = t.expressionStatement(
320
- t.callExpression(t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier("value")), t.identifier("push")), [target.expression])
321
- );
322
- if2.consequent.body[0] = newExpressionStatement;
323
- }
324
- }
325
- }
326
- }
327
- targetBlockStatement.body.unshift(
328
- // contentRef.value = []
329
- // t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression()))
330
- // contentRef.value.length = 0
331
- t.expressionStatement(
332
- t.assignmentExpression(
333
- "=",
334
- t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.identifier("length")),
335
- t.numericLiteral(0)
336
- )
337
- )
338
- );
339
- }
340
- }
341
- }
342
- }
343
- });
344
- return {
345
- code: hasPatched ? content : generate(ast).code,
346
- hasPatched
347
- };
348
- }
349
-
350
- // src/core/patches/exportContext/postcss-v3.ts
351
- import * as t2 from "@babel/types";
352
- function inspectProcessTailwindFeaturesReturnContext2(content) {
353
- const ast = parse(content);
354
- let hasPatched = false;
355
- traverse(ast, {
356
- FunctionDeclaration(p) {
357
- const n = p.node;
358
- if (n.id?.name === "processTailwindFeatures" && n.body.body.length === 1 && t2.isReturnStatement(n.body.body[0])) {
359
- const rts = n.body.body[0];
360
- if (t2.isFunctionExpression(rts.argument)) {
361
- const body = rts.argument.body.body;
362
- const lastStatement = body[body.length - 1];
363
- hasPatched = t2.isReturnStatement(lastStatement) && t2.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context";
364
- if (!hasPatched) {
365
- const rts2 = t2.returnStatement(t2.identifier("context"));
366
- body.push(rts2);
367
- }
368
- }
369
- }
370
- }
371
- });
372
- return {
373
- code: hasPatched ? content : generate(ast).code,
374
- hasPatched
375
- };
376
- }
377
- function inspectPostcssPlugin2(content) {
378
- const ast = parse(content);
379
- const exportKey = "contextRef";
380
- const variableName = "contextRef";
381
- const valueKey = "value";
382
- let hasPatched = false;
383
- traverse(ast, {
384
- Program(p) {
385
- const n = p.node;
386
- const idx = n.body.findIndex((x) => {
387
- return t2.isExpressionStatement(x) && t2.isAssignmentExpression(x.expression) && t2.isMemberExpression(x.expression.left) && t2.isFunctionExpression(x.expression.right) && x.expression.right.id?.name === "tailwindcss";
388
- });
389
- if (idx > -1) {
390
- const prevStatement = n.body[idx - 1];
391
- const lastStatement = n.body[n.body.length - 1];
392
- const hasPatchedCondition0 = prevStatement && t2.isVariableDeclaration(prevStatement) && prevStatement.declarations.length === 1 && t2.isIdentifier(prevStatement.declarations[0].id) && prevStatement.declarations[0].id.name === variableName;
393
- const hasPatchedCondition1 = t2.isExpressionStatement(lastStatement) && t2.isAssignmentExpression(lastStatement.expression) && t2.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === variableName;
394
- hasPatched = hasPatchedCondition0 || hasPatchedCondition1;
395
- if (!hasPatched) {
396
- const statement = t2.variableDeclaration("const", [
397
- t2.variableDeclarator(t2.identifier(variableName), t2.objectExpression([t2.objectProperty(t2.identifier(valueKey), t2.arrayExpression())]))
398
- ]);
399
- n.body.splice(idx, 0, statement);
400
- n.body.push(
401
- t2.expressionStatement(
402
- t2.assignmentExpression(
403
- "=",
404
- t2.memberExpression(t2.memberExpression(t2.identifier("module"), t2.identifier("exports")), t2.identifier(exportKey)),
405
- t2.identifier(variableName)
406
- )
407
- )
408
- );
409
- }
410
- }
411
- },
412
- FunctionExpression(p) {
413
- if (hasPatched) {
414
- return;
415
- }
416
- const n = p.node;
417
- if (n.id?.name === "tailwindcss" && n.body.body.length === 1 && t2.isReturnStatement(n.body.body[0])) {
418
- const returnStatement3 = n.body.body[0];
419
- if (t2.isObjectExpression(returnStatement3.argument) && returnStatement3.argument.properties.length === 2) {
420
- const properties = returnStatement3.argument.properties;
421
- if (t2.isObjectProperty(properties[0]) && t2.isObjectProperty(properties[1])) {
422
- const keyMatched = t2.isIdentifier(properties[0].key) && properties[0].key.name === "postcssPlugin";
423
- const pluginsMatched = t2.isIdentifier(properties[1].key) && properties[1].key.name === "plugins";
424
- if (pluginsMatched && keyMatched && t2.isCallExpression(properties[1].value) && t2.isMemberExpression(properties[1].value.callee) && t2.isArrayExpression(properties[1].value.callee.object)) {
425
- const pluginsCode = properties[1].value.callee.object.elements;
426
- if (pluginsCode[1] && t2.isFunctionExpression(pluginsCode[1])) {
427
- const targetBlockStatement = pluginsCode[1].body;
428
- const lastStatement = targetBlockStatement.body[targetBlockStatement.body.length - 1];
429
- if (t2.isExpressionStatement(lastStatement)) {
430
- const newExpressionStatement = t2.expressionStatement(
431
- t2.callExpression(
432
- t2.memberExpression(
433
- t2.memberExpression(t2.identifier(variableName), t2.identifier("value")),
434
- t2.identifier("push")
435
- ),
436
- [lastStatement.expression]
437
- )
438
- );
439
- targetBlockStatement.body[targetBlockStatement.body.length - 1] = newExpressionStatement;
440
- }
441
- const ifIdx = targetBlockStatement.body.findIndex((x) => t2.isIfStatement(x));
442
- if (ifIdx > -1) {
443
- const ifRoot = targetBlockStatement.body[ifIdx];
444
- if (t2.isBlockStatement(ifRoot.consequent) && ifRoot.consequent.body[1] && t2.isForOfStatement(ifRoot.consequent.body[1])) {
445
- const forOf = ifRoot.consequent.body[1];
446
- if (t2.isBlockStatement(forOf.body) && forOf.body.body.length === 1 && t2.isIfStatement(forOf.body.body[0])) {
447
- const if2 = forOf.body.body[0];
448
- if (t2.isBlockStatement(if2.consequent) && if2.consequent.body.length === 1 && t2.isExpressionStatement(if2.consequent.body[0])) {
449
- const target = if2.consequent.body[0];
450
- const newExpressionStatement = t2.expressionStatement(
451
- t2.callExpression(t2.memberExpression(t2.memberExpression(t2.identifier(variableName), t2.identifier("value")), t2.identifier("push")), [target.expression])
452
- );
453
- if2.consequent.body[0] = newExpressionStatement;
454
- }
455
- }
456
- }
457
- }
458
- targetBlockStatement.body.unshift(
459
- // contentRef.value = []
460
- // t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression()))
461
- // contentRef.value.length = 0
462
- t2.expressionStatement(
463
- t2.assignmentExpression(
464
- "=",
465
- t2.memberExpression(t2.memberExpression(t2.identifier(variableName), t2.identifier(valueKey)), t2.identifier("length")),
466
- t2.numericLiteral(0)
467
- )
468
- )
469
- );
470
- }
471
- }
472
- }
473
- }
474
- }
475
- }
476
- // BlockStatement(p) {
477
- // const n = p.node
478
- // if (start && p.parent.type === 'FunctionExpression' && !p.parent.id) {
479
- // n.body.unshift(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression())))
480
- // }
481
- // }
482
- });
483
- return {
484
- code: hasPatched ? content : generate(ast).code,
485
- hasPatched
486
- };
487
- }
488
-
489
- // src/core/patches/exportContext/index.ts
490
- function monkeyPatchForExposingContextV3(twDir, opt) {
491
- const k0 = "lib/processTailwindFeatures.js";
492
- const processTailwindFeaturesFilePath = path2.resolve(twDir, k0);
493
- const processTailwindFeaturesContent = fs2.readFileSync(processTailwindFeaturesFilePath, "utf8");
494
- const result = {};
495
- if (processTailwindFeaturesContent) {
496
- const { code, hasPatched } = inspectProcessTailwindFeaturesReturnContext2(processTailwindFeaturesContent);
497
- if (!hasPatched && opt.overwrite) {
498
- fs2.writeFileSync(processTailwindFeaturesFilePath, code, {
499
- encoding: "utf8"
500
- });
501
- logger_default.success("patch tailwindcss processTailwindFeatures for return context successfully!");
502
- }
503
- result[k0] = code;
504
- }
505
- let injectFilepath;
506
- let k1;
507
- const try0 = "lib/plugin.js";
508
- const try1 = "lib/index.js";
509
- const pluginFilePath = path2.resolve(twDir, try0);
510
- const indexFilePath = path2.resolve(twDir, try1);
511
- if (fs2.existsSync(pluginFilePath)) {
512
- k1 = try0;
513
- injectFilepath = pluginFilePath;
514
- } else if (fs2.existsSync(indexFilePath)) {
515
- k1 = try1;
516
- injectFilepath = indexFilePath;
517
- }
518
- if (injectFilepath && k1) {
519
- const pluginContent = fs2.readFileSync(injectFilepath, "utf8");
520
- if (pluginContent) {
521
- const { code, hasPatched } = inspectPostcssPlugin2(pluginContent);
522
- if (!hasPatched && opt.overwrite) {
523
- fs2.writeFileSync(injectFilepath, code, {
524
- encoding: "utf8"
525
- });
526
- logger_default.success("patch tailwindcss for expose runtime context successfully!");
527
- }
528
- result[k1] = code;
529
- }
530
- return result;
531
- }
532
- }
533
- function monkeyPatchForExposingContextV2(twDir, opt) {
534
- const k0 = "lib/jit/processTailwindFeatures.js";
535
- const processTailwindFeaturesFilePath = path2.resolve(twDir, k0);
536
- const processTailwindFeaturesContent = fs2.readFileSync(processTailwindFeaturesFilePath, "utf8");
537
- const result = {};
538
- if (processTailwindFeaturesContent) {
539
- const { code, hasPatched } = inspectProcessTailwindFeaturesReturnContext(processTailwindFeaturesContent);
540
- if (!hasPatched && opt.overwrite) {
541
- fs2.writeFileSync(processTailwindFeaturesFilePath, code, {
542
- encoding: "utf8"
543
- });
544
- logger_default.success("patch tailwindcss processTailwindFeatures for return content successfully!");
545
- }
546
- result[k0] = code;
547
- }
548
- const k1 = "lib/jit/index.js";
549
- const indexFilePath = path2.resolve(twDir, k1);
550
- const pluginContent = fs2.readFileSync(indexFilePath, "utf8");
551
- if (pluginContent) {
552
- const { code, hasPatched } = inspectPostcssPlugin(pluginContent);
553
- if (!hasPatched && opt.overwrite) {
554
- fs2.writeFileSync(indexFilePath, code, {
555
- encoding: "utf8"
556
- });
557
- logger_default.success("patch tailwindcss for expose runtime content successfully!");
558
- }
559
- result[k1] = code;
560
- }
561
- return result;
562
- }
563
-
564
- // src/core/patches/supportCustomUnits/index.ts
565
- import * as t3 from "@babel/types";
566
- import fs3 from "fs-extra";
567
- import path3 from "pathe";
568
-
569
- // src/utils.ts
570
- function isObject(val) {
571
- return val !== null && typeof val === "object" && Array.isArray(val) === false;
572
- }
573
- function spliceChangesIntoString(str, changes) {
574
- if (!changes[0]) {
575
- return str;
576
- }
577
- changes.sort((a, b) => {
578
- return a.end - b.end || a.start - b.start;
579
- });
580
- let result = "";
581
- let previous = changes[0];
582
- result += str.slice(0, previous.start);
583
- result += previous.replacement;
584
- for (let i = 1; i < changes.length; ++i) {
585
- const change = changes[i];
586
- result += str.slice(previous.end, change.start);
587
- result += change.replacement;
588
- previous = change;
589
- }
590
- result += str.slice(previous.end);
591
- return result;
592
- }
593
-
594
- // src/core/patches/supportCustomUnits/index.ts
595
- function findAstNode(content, options) {
596
- const { variableName, units } = options;
597
- const ast = parse(content);
598
- let arrayRef;
599
- let changed = false;
600
- traverse(ast, {
601
- Identifier(path7) {
602
- if (path7.node.name === variableName && t3.isVariableDeclarator(path7.parent) && t3.isArrayExpression(path7.parent.init)) {
603
- arrayRef = path7.parent.init;
604
- const set = new Set(path7.parent.init.elements.map((x) => x.value));
605
- for (const unit of units) {
606
- if (!set.has(unit)) {
607
- path7.parent.init.elements = path7.parent.init.elements.map((x) => {
608
- if (t3.isStringLiteral(x)) {
609
- return {
610
- type: x.type,
611
- value: x.value
612
- };
613
- }
614
- return x;
615
- });
616
- path7.parent.init.elements.push({
617
- type: "StringLiteral",
618
- value: unit
619
- });
620
- changed = true;
621
- }
622
- }
623
- }
624
- }
625
- });
626
- return {
627
- arrayRef,
628
- changed
629
- };
630
- }
631
- function monkeyPatchForSupportingCustomUnitV3(rootDir, options) {
632
- const opts = defuOverrideArray(options, {
633
- units: ["rpx"],
634
- lengthUnitsFilePath: "lib/util/dataTypes.js",
635
- variableName: "lengthUnits",
636
- overwrite: true
637
- });
638
- const { lengthUnitsFilePath, overwrite, destPath } = opts;
639
- const dataTypesFilePath = path3.resolve(rootDir, lengthUnitsFilePath);
640
- const dataTypesFileContent = fs3.readFileSync(dataTypesFilePath, {
641
- encoding: "utf8"
642
- });
643
- const { arrayRef, changed } = findAstNode(dataTypesFileContent, opts);
644
- if (arrayRef && changed) {
645
- const { code } = generate(arrayRef, {
646
- jsescOption: {
647
- quotes: "single"
648
- }
649
- });
650
- if (arrayRef.start && arrayRef.end) {
651
- const prev = dataTypesFileContent.slice(0, arrayRef.start);
652
- const next = dataTypesFileContent.slice(arrayRef.end);
653
- const newCode = prev + code + next;
654
- if (overwrite) {
655
- fs3.writeFileSync(destPath ?? dataTypesFilePath, newCode, {
656
- encoding: "utf8"
657
- });
658
- logger_default.success("patch tailwindcss for custom length unit successfully!");
659
- }
660
- }
661
- return {
662
- [opts.lengthUnitsFilePath]: code
663
- };
664
- }
665
- }
666
- function monkeyPatchForSupportingCustomUnitV4(rootDir, options) {
667
- const opts = defuOverrideArray(options, {
668
- units: ["rpx"],
669
- overwrite: true
670
- });
671
- const distPath = path3.resolve(rootDir, "dist");
672
- const list = fs3.readdirSync(distPath);
673
- const chunks = list.filter((x) => x.endsWith("js"));
674
- const guessUnitStart = /\[\s*["']cm["'],\s*["']mm["'],[\w,"]+\]/;
675
- const guessFiles = chunks.reduce((acc, chunkName) => {
676
- const guessFile = path3.join(distPath, chunkName);
677
- const code = fs3.readFileSync(guessFile, "utf8");
678
- const matches = guessUnitStart.exec(code);
679
- if (matches && code) {
680
- acc.push({
681
- code,
682
- hasPatched: false,
683
- file: guessFile,
684
- matches
685
- });
686
- }
687
- return acc;
688
- }, []);
689
- for (const item of guessFiles) {
690
- const { matches, code, file } = item;
691
- const match = matches[0];
692
- const ast = parse(match, {
693
- sourceType: "unambiguous"
694
- });
695
- traverse(ast, {
696
- ArrayExpression(path7) {
697
- for (const unit of opts.units) {
698
- if (path7.node.elements.some((x) => t3.isStringLiteral(x) && x.value === unit)) {
699
- item.hasPatched = true;
700
- break;
701
- }
702
- path7.node.elements.push(t3.stringLiteral(unit));
703
- }
704
- }
705
- });
706
- if (item.hasPatched) {
707
- continue;
708
- }
709
- const { code: replacement } = generate(ast, {
710
- minified: true
711
- });
712
- item.code = spliceChangesIntoString(code, [
713
- {
714
- start: matches.index,
715
- end: matches.index + match.length,
716
- replacement: replacement.endsWith(";") ? replacement.slice(0, -1) : replacement
717
- }
718
- ]);
719
- if (opts.overwrite && file) {
720
- fs3.writeFileSync(file, item.code, {
721
- encoding: "utf8"
722
- });
723
- }
724
- }
725
- if (guessFiles.some((x) => !x.hasPatched)) {
726
- logger_default.success("patch tailwindcss for custom length unit successfully!");
727
- }
728
- return {
729
- files: guessFiles
730
- };
731
- }
732
-
733
- // src/core/runtime.ts
734
- import { createRequire } from "module";
735
- import path4 from "pathe";
736
- import { gte } from "semver";
737
- var require2 = createRequire(import.meta.url);
738
- function internalPatch(pkgJsonPath, options) {
739
- if (pkgJsonPath) {
740
- let pkgJson;
741
- let twDir;
742
- if (typeof pkgJsonPath === "string") {
743
- pkgJson = require2(pkgJsonPath);
744
- twDir = path4.dirname(pkgJsonPath);
745
- options.version = pkgJson.version;
746
- } else if (typeof pkgJsonPath === "object") {
747
- pkgJson = pkgJsonPath.packageJson;
748
- twDir = pkgJsonPath.rootPath;
749
- options.version = pkgJsonPath.version;
750
- } else {
751
- throw new TypeError("tailwindcss not found");
752
- }
753
- if (gte(pkgJson.version, "4.0.0")) {
754
- try {
755
- if (options.applyPatches?.extendLengthUnits) {
756
- return monkeyPatchForSupportingCustomUnitV4(twDir, options);
757
- }
758
- } catch {
759
- }
760
- } else if (gte(pkgJson.version, "3.0.0")) {
761
- let result = {};
762
- if (options.applyPatches?.exportContext) {
763
- result = monkeyPatchForExposingContextV3(twDir, options);
764
- }
765
- if (options.applyPatches?.extendLengthUnits) {
766
- try {
767
- Object.assign(result ?? {}, monkeyPatchForSupportingCustomUnitV3(twDir, defu(options.applyPatches.extendLengthUnits === true ? void 0 : options.applyPatches.extendLengthUnits, {
768
- overwrite: options.overwrite
769
- })));
770
- } catch {
771
- }
772
- }
773
- return result;
774
- } else if (gte(pkgJson.version, "2.0.0")) {
775
- if (options.applyPatches?.exportContext) {
776
- return monkeyPatchForExposingContextV2(twDir, options);
777
- }
778
- }
779
- }
780
- }
781
-
782
- // src/core/patcher.ts
783
- import { createRequire as createRequire3 } from "module";
784
- import process5 from "process";
785
- import fs4 from "fs-extra";
786
- import { getPackageInfoSync } from "local-pkg";
787
- import path6 from "pathe";
788
-
789
- // src/core/candidates.ts
790
- import process3 from "process";
791
- function importNode() {
792
- return import("@tailwindcss/node");
793
- }
794
- function importOxide() {
795
- return import("@tailwindcss/oxide");
796
- }
797
- async function extractRawCandidates(sources) {
798
- const { Scanner } = await importOxide();
799
- const scanner = new Scanner({
800
- sources
801
- });
802
- const candidates = scanner.scan();
803
- return candidates;
804
- }
805
- async function extractValidCandidates(options) {
806
- const defaultCwd = options?.cwd ?? process3.cwd();
807
- const { sources, base, css } = defuOverrideArray(
808
- // @ts-ignore
809
- options,
810
- {
811
- css: '@import "tailwindcss";',
812
- base: defaultCwd,
813
- sources: [
814
- {
815
- base: defaultCwd,
816
- pattern: "**/*",
817
- negated: false
818
- }
819
- ]
820
- }
821
- );
822
- const { __unstable__loadDesignSystem } = await importNode();
823
- const designSystem = await __unstable__loadDesignSystem(css, { base });
824
- const candidates = await extractRawCandidates(sources);
825
- const validCandidates = candidates.filter(
826
- (rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
827
- );
828
- return validCandidates;
829
- }
830
-
831
- // src/core/postcss.ts
832
- import { createRequire as createRequire2 } from "module";
833
- import process4 from "process";
834
- import path5 from "pathe";
835
- import postcss from "postcss";
836
- import { loadConfig } from "tailwindcss-config";
837
- var require3 = createRequire2(import.meta.url);
838
- async function processTailwindcss(options) {
839
- const { config: userConfig, cwd, majorVersion, postcssPlugin } = defu(options, {
840
- cwd: process4.cwd(),
841
- majorVersion: 3
842
- });
843
- let config = userConfig;
844
- if (!(typeof config === "string" && path5.isAbsolute(config))) {
845
- const result = await loadConfig({
846
- cwd
847
- });
848
- if (!result) {
849
- throw new Error(`No TailwindCSS Config found in: ${cwd}`);
850
- }
851
- config = result.filepath;
852
- }
853
- const targetPostcssPlugin = postcssPlugin ?? (majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
854
- if (majorVersion === 4) {
855
- return await postcss([
856
- require3(targetPostcssPlugin)({
857
- config
858
- })
859
- ]).process("@import 'tailwindcss';", {
860
- from: void 0
861
- });
862
- }
863
- return await postcss([
864
- require3(targetPostcssPlugin)({
865
- config
866
- })
867
- ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
868
- from: void 0
869
- });
870
- }
871
-
872
- // src/core/patcher.ts
873
- var require4 = createRequire3(import.meta.url);
874
- var TailwindcssPatcher = class {
875
- rawOptions;
876
- cacheOptions;
877
- patchOptions;
878
- patch;
879
- cacheManager;
880
- packageInfo;
881
- majorVersion;
882
- filter;
883
- constructor(options = {}) {
884
- this.rawOptions = options;
885
- this.cacheOptions = getCacheOptions(options.cache);
886
- this.patchOptions = getPatchOptions(options.patch);
887
- this.cacheManager = new CacheManager(this.cacheOptions);
888
- this.filter = function filter(className) {
889
- if (this.patchOptions.output?.removeUniversalSelector && className === "*") {
890
- return false;
891
- }
892
- return Boolean(this.patchOptions.filter?.(className));
893
- };
894
- const packageInfo = getPackageInfoSync(
895
- this.patchOptions.packageName ?? "tailwindcss",
896
- this.patchOptions.resolve
897
- );
898
- if (!packageInfo) {
899
- throw new Error("tailwindcss not found");
900
- }
901
- if (packageInfo.version) {
902
- this.majorVersion = Number.parseInt(packageInfo.version[0]);
903
- }
904
- if (this.patchOptions.tailwindcss?.version) {
905
- this.majorVersion = this.patchOptions.tailwindcss.version;
906
- }
907
- this.packageInfo = packageInfo;
908
- this.patch = () => {
909
- try {
910
- return internalPatch(this.packageInfo, this.patchOptions);
911
- } catch (error) {
912
- logger_default.error(`Patch Tailwind CSS Failed: ${error.message}`);
913
- }
914
- };
915
- }
916
- setCache(set) {
917
- if (this.cacheOptions.enable) {
918
- return this.cacheManager.write(set);
919
- }
920
- }
921
- getCache() {
922
- return this.cacheManager.read();
923
- }
924
- getContexts() {
925
- if (this.packageInfo) {
926
- const distPath = path6.join(this.packageInfo.rootPath, "lib");
927
- let injectFilePath;
928
- if (this.majorVersion === 2) {
929
- injectFilePath = path6.join(distPath, "jit/index.js");
930
- } else if (this.majorVersion === 3) {
931
- injectFilePath = path6.join(distPath, "plugin.js");
932
- if (!fs4.existsSync(injectFilePath)) {
933
- injectFilePath = path6.join(distPath, "index.js");
934
- }
935
- }
936
- if (injectFilePath) {
937
- const mo = require4(injectFilePath);
938
- if (mo.contextRef) {
939
- return mo.contextRef.value;
940
- }
941
- }
942
- }
943
- return [];
944
- }
945
- getClassCaches() {
946
- const contexts = this.getContexts();
947
- return contexts.filter((x) => isObject(x)).map((x) => x.classCache);
948
- }
949
- async getClassCacheSet() {
950
- const classSet = /* @__PURE__ */ new Set();
951
- const { tailwindcss, cwd } = this.patchOptions;
952
- if (this.majorVersion === 4) {
953
- const { v4 } = tailwindcss ?? {};
954
- if (Array.isArray(v4?.cssEntries)) {
955
- const results = (await Promise.all(
956
- v4.cssEntries.map(async (x) => {
957
- if (await fs4.exists(x)) {
958
- const css = await fs4.readFile(x, "utf8");
959
- return css;
960
- }
961
- return false;
962
- })
963
- )).filter((x) => x);
964
- for (const css of results) {
965
- const candidates = await extractValidCandidates({
966
- cwd,
967
- base: v4?.base,
968
- css,
969
- sources: v4?.sources?.map((x) => {
970
- return {
971
- base: x.base ?? v4?.base ?? process5.cwd(),
972
- pattern: x.pattern,
973
- negated: x.negated
974
- };
975
- })
976
- });
977
- for (const candidate of candidates) {
978
- this.filter?.(candidate) && classSet.add(candidate);
979
- }
980
- }
981
- } else {
982
- const candidates = await extractValidCandidates({
983
- cwd,
984
- base: v4?.base,
985
- css: v4?.css,
986
- sources: v4?.sources?.map((x) => {
987
- return {
988
- base: x.base ?? v4?.base ?? process5.cwd(),
989
- pattern: x.pattern,
990
- negated: x.negated
991
- };
992
- })
993
- });
994
- for (const candidate of candidates) {
995
- this.filter?.(candidate) && classSet.add(candidate);
996
- }
997
- }
998
- } else {
999
- const classCaches = this.getClassCaches();
1000
- for (const classCacheMap of classCaches) {
1001
- const keys = classCacheMap.keys();
1002
- for (const key of keys) {
1003
- const v = key.toString();
1004
- this.filter?.(v) && classSet.add(v);
1005
- }
1006
- }
1007
- }
1008
- return classSet;
1009
- }
1010
- getClassCacheSetV3() {
1011
- const classSet = /* @__PURE__ */ new Set();
1012
- const classCaches = this.getClassCaches();
1013
- for (const classCacheMap of classCaches) {
1014
- const keys = classCacheMap.keys();
1015
- for (const key of keys) {
1016
- const v = key.toString();
1017
- this.filter?.(v) && classSet.add(v);
1018
- }
1019
- }
1020
- return classSet;
1021
- }
1022
- /**
1023
- * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
1024
- */
1025
- async getClassSet() {
1026
- const cacheStrategy = this.cacheOptions.strategy ?? "merge";
1027
- const set = await this.getClassCacheSet();
1028
- if (cacheStrategy === "overwrite") {
1029
- set.size > 0 && this.setCache(set);
1030
- } else if (cacheStrategy === "merge") {
1031
- const cacheSet = this.getCache();
1032
- if (cacheSet) {
1033
- for (const x of cacheSet) {
1034
- set.add(x);
1035
- }
1036
- }
1037
- this.setCache(set);
1038
- }
1039
- return set;
1040
- }
1041
- getClassSetV3() {
1042
- const cacheStrategy = this.cacheOptions.strategy ?? "merge";
1043
- const set = this.getClassCacheSetV3();
1044
- if (cacheStrategy === "overwrite") {
1045
- set.size > 0 && this.setCache(set);
1046
- } else if (cacheStrategy === "merge") {
1047
- const cacheSet = this.getCache();
1048
- if (cacheSet) {
1049
- for (const x of cacheSet) {
1050
- set.add(x);
1051
- }
1052
- }
1053
- this.setCache(set);
1054
- }
1055
- return set;
1056
- }
1057
- async extract(options) {
1058
- const { write } = defu(options, { write: true });
1059
- const { output, tailwindcss } = this.patchOptions;
1060
- if (tailwindcss) {
1061
- if (this.majorVersion === 3 || this.majorVersion === 2) {
1062
- await processTailwindcss({
1063
- ...tailwindcss,
1064
- majorVersion: this.majorVersion
1065
- });
1066
- }
1067
- const classSet = await this.getClassSet();
1068
- const classList = [...classSet];
1069
- const result = {
1070
- classList,
1071
- classSet
1072
- };
1073
- if (output) {
1074
- const { filename, loose } = output;
1075
- if (filename) {
1076
- if (write) {
1077
- await fs4.outputJSON(filename, classList, {
1078
- spaces: loose ? 2 : void 0
1079
- });
1080
- }
1081
- result.filename = filename;
1082
- }
1083
- }
1084
- return result;
1085
- }
1086
- }
1087
- extractValidCandidates = extractValidCandidates;
1088
- };
1089
-
1090
- export {
1091
- defuOverrideArray,
1092
- logger_default,
1093
- getCacheOptions,
1094
- CacheManager,
1095
- getPatchOptions,
1096
- monkeyPatchForExposingContextV3,
1097
- monkeyPatchForExposingContextV2,
1098
- monkeyPatchForSupportingCustomUnitV3,
1099
- monkeyPatchForSupportingCustomUnitV4,
1100
- internalPatch,
1101
- TailwindcssPatcher
1102
- };