tailwindcss-patch 4.0.0-alpha.1 → 5.0.0-alpha.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,848 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'fs-extra';
3
- import process from 'node:process';
4
- import { createConsola } from 'consola';
5
- import { gte } from 'semver';
6
- import * as t from '@babel/types';
7
- import _babelGenerate from '@babel/generator';
8
- import _babelTraverse from '@babel/traverse';
9
- import { parse } from '@babel/parser';
10
- import pkg from 'resolve';
11
- import postcss from 'postcss';
12
- import { lilconfig } from 'lilconfig';
13
- import createJiti from 'jiti';
14
- import '@tailwindcss-mangle/config';
15
-
16
-
17
-
18
- // -- Unbuild CommonJS Shims --
19
- import __cjs_url__ from 'url';
20
- import __cjs_path__ from 'path';
21
- import __cjs_mod__ from 'module';
22
- const __filename = __cjs_url__.fileURLToPath(import.meta.url);
23
- const __dirname = __cjs_path__.dirname(__filename);
24
- const require = __cjs_mod__.createRequire(import.meta.url);
25
- const pkgName = "tailwindcss-patch";
26
-
27
- const logger = createConsola();
28
-
29
- var __defProp$1 = Object.defineProperty;
30
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
31
- var __publicField$1 = (obj, key, value) => {
32
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
33
- return value;
34
- };
35
- function getCacheOptions(options) {
36
- let cache;
37
- switch (typeof options) {
38
- case "undefined": {
39
- cache = {
40
- enable: false
41
- };
42
- break;
43
- }
44
- case "boolean": {
45
- cache = {
46
- enable: options
47
- };
48
- break;
49
- }
50
- case "object": {
51
- cache = { ...options, enable: true };
52
- break;
53
- }
54
- }
55
- return cache;
56
- }
57
- class CacheManager {
58
- constructor(options = {}) {
59
- __publicField$1(this, "options");
60
- this.options = this.getOptions(options);
61
- }
62
- getOptions(options = {}) {
63
- const cwd = options.cwd ?? process.cwd();
64
- const dir = options.dir ?? path.resolve(cwd, "node_modules/.cache", pkgName);
65
- const file = options.file ?? "index.json";
66
- const filename = path.resolve(dir, file);
67
- return {
68
- cwd,
69
- dir,
70
- file,
71
- filename,
72
- strategy: "merge"
73
- };
74
- }
75
- write(data) {
76
- try {
77
- const { dir, filename } = this.options;
78
- fs.ensureDirSync(dir);
79
- fs.outputFileSync(filename, JSON.stringify([...data], void 0, 2), "utf8");
80
- return filename;
81
- } catch {
82
- logger.error("write cache file fail!");
83
- }
84
- }
85
- read() {
86
- const { filename } = this.options;
87
- try {
88
- if (fs.existsSync(filename)) {
89
- const data = fs.readFileSync(filename, "utf8");
90
- return new Set(JSON.parse(data));
91
- }
92
- } catch {
93
- logger.error(`parse cache content fail! path:${filename}`);
94
- try {
95
- fs.unlinkSync(filename);
96
- } catch {
97
- logger.error(`delete cache file fail! path:${filename}`);
98
- }
99
- }
100
- }
101
- }
102
-
103
- function _interopDefaultCompat(e) {
104
- return e && typeof e === "object" && "default" in e ? e.default : e;
105
- }
106
- const generate = _interopDefaultCompat(_babelGenerate);
107
- const traverse = _interopDefaultCompat(_babelTraverse);
108
-
109
- function inspectProcessTailwindFeaturesReturnContext$1(content) {
110
- const ast = parse(content);
111
- let hasPatched = false;
112
- traverse(ast, {
113
- FunctionDeclaration(p) {
114
- const n = p.node;
115
- if (n.id?.name === "processTailwindFeatures" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
116
- const rts = n.body.body[0];
117
- if (t.isFunctionExpression(rts.argument)) {
118
- const body = rts.argument.body.body;
119
- const lastStatement = body[body.length - 1];
120
- hasPatched = t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context";
121
- if (!hasPatched) {
122
- const rts2 = t.returnStatement(t.identifier("context"));
123
- body.push(rts2);
124
- }
125
- }
126
- }
127
- }
128
- });
129
- return {
130
- code: hasPatched ? content : generate(ast).code,
131
- hasPatched
132
- };
133
- }
134
- function inspectPostcssPlugin$1(content) {
135
- const ast = parse(content);
136
- const exportKey = "contextRef";
137
- const variableName = "contextRef";
138
- const valueKey = "value";
139
- let hasPatched = false;
140
- traverse(ast, {
141
- Program(p) {
142
- const n = p.node;
143
- const idx = n.body.findIndex((x) => {
144
- return t.isExpressionStatement(x) && t.isAssignmentExpression(x.expression) && t.isMemberExpression(x.expression.left) && t.isFunctionExpression(x.expression.right) && x.expression.right.id?.name === "tailwindcss";
145
- });
146
- if (idx > -1) {
147
- const prevStatement = n.body[idx - 1];
148
- const lastStatement = n.body[n.body.length - 1];
149
- const hasPatchedCondition0 = prevStatement && t.isVariableDeclaration(prevStatement) && prevStatement.declarations.length === 1 && t.isIdentifier(prevStatement.declarations[0].id) && prevStatement.declarations[0].id.name === variableName;
150
- const hasPatchedCondition1 = t.isExpressionStatement(lastStatement) && t.isAssignmentExpression(lastStatement.expression) && t.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === variableName;
151
- hasPatched = hasPatchedCondition0 || hasPatchedCondition1;
152
- if (!hasPatched) {
153
- const statement = t.variableDeclaration("const", [
154
- t.variableDeclarator(t.identifier(variableName), t.objectExpression([t.objectProperty(t.identifier(valueKey), t.arrayExpression())]))
155
- ]);
156
- n.body.splice(idx, 0, statement);
157
- n.body.push(
158
- t.expressionStatement(
159
- t.assignmentExpression(
160
- "=",
161
- t.memberExpression(t.memberExpression(t.identifier("module"), t.identifier("exports")), t.identifier(exportKey)),
162
- t.identifier(variableName)
163
- )
164
- )
165
- );
166
- }
167
- }
168
- },
169
- FunctionExpression(p) {
170
- if (hasPatched) {
171
- return;
172
- }
173
- const n = p.node;
174
- if (n.id?.name === "tailwindcss" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
175
- const returnStatement = n.body.body[0];
176
- if (t.isObjectExpression(returnStatement.argument) && returnStatement.argument.properties.length === 2) {
177
- const properties = returnStatement.argument.properties;
178
- if (t.isObjectProperty(properties[0]) && t.isObjectProperty(properties[1])) {
179
- const keyMatched = t.isIdentifier(properties[0].key) && properties[0].key.name === "postcssPlugin";
180
- const pluginsMatched = t.isIdentifier(properties[1].key) && properties[1].key.name === "plugins";
181
- if (pluginsMatched && keyMatched && t.isCallExpression(properties[1].value) && t.isMemberExpression(properties[1].value.callee) && t.isArrayExpression(properties[1].value.callee.object)) {
182
- const pluginsCode = properties[1].value.callee.object.elements;
183
- if (pluginsCode[1] && t.isFunctionExpression(pluginsCode[1])) {
184
- const targetBlockStatement = pluginsCode[1].body;
185
- const lastStatement = targetBlockStatement.body[targetBlockStatement.body.length - 1];
186
- if (t.isExpressionStatement(lastStatement)) {
187
- const newExpressionStatement = t.expressionStatement(
188
- t.callExpression(
189
- t.memberExpression(
190
- t.memberExpression(t.identifier(variableName), t.identifier("value")),
191
- t.identifier("push")
192
- ),
193
- [lastStatement.expression]
194
- )
195
- );
196
- targetBlockStatement.body[targetBlockStatement.body.length - 1] = newExpressionStatement;
197
- }
198
- const ifIdx = targetBlockStatement.body.findIndex((x) => t.isIfStatement(x));
199
- if (ifIdx > -1) {
200
- const ifRoot = targetBlockStatement.body[ifIdx];
201
- if (t.isBlockStatement(ifRoot.consequent) && ifRoot.consequent.body[1] && t.isForOfStatement(ifRoot.consequent.body[1])) {
202
- const forOf = ifRoot.consequent.body[1];
203
- if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1 && t.isIfStatement(forOf.body.body[0])) {
204
- const if2 = forOf.body.body[0];
205
- if (t.isBlockStatement(if2.consequent) && if2.consequent.body.length === 1 && t.isExpressionStatement(if2.consequent.body[0])) {
206
- const target = if2.consequent.body[0];
207
- const newExpressionStatement = t.expressionStatement(
208
- t.callExpression(t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier("value")), t.identifier("push")), [target.expression])
209
- );
210
- if2.consequent.body[0] = newExpressionStatement;
211
- }
212
- }
213
- }
214
- }
215
- targetBlockStatement.body.unshift(
216
- // contentRef.value = []
217
- // t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression()))
218
- // contentRef.value.length = 0
219
- t.expressionStatement(
220
- t.assignmentExpression(
221
- "=",
222
- t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.identifier("length")),
223
- t.numericLiteral(0)
224
- )
225
- )
226
- );
227
- }
228
- }
229
- }
230
- }
231
- }
232
- }
233
- // BlockStatement(p) {
234
- // const n = p.node
235
- // if (start && p.parent.type === 'FunctionExpression' && !p.parent.id) {
236
- // n.body.unshift(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression())))
237
- // }
238
- // }
239
- });
240
- return {
241
- code: hasPatched ? content : generate(ast).code,
242
- hasPatched
243
- };
244
- }
245
-
246
- function inspectProcessTailwindFeaturesReturnContext(content) {
247
- const ast = parse(content, {
248
- sourceType: "unambiguous"
249
- });
250
- let hasPatched = false;
251
- traverse(ast, {
252
- FunctionDeclaration(p) {
253
- const n = p.node;
254
- if (n.id?.name === "processTailwindFeatures" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
255
- const rts = n.body.body[0];
256
- if (t.isFunctionExpression(rts.argument)) {
257
- const body = rts.argument.body.body;
258
- const lastStatement = body[body.length - 1];
259
- hasPatched = t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context";
260
- if (!hasPatched) {
261
- const rts2 = t.returnStatement(t.identifier("context"));
262
- body.push(rts2);
263
- }
264
- }
265
- }
266
- }
267
- });
268
- return {
269
- code: hasPatched ? content : generate(ast).code,
270
- hasPatched
271
- };
272
- }
273
- function inspectPostcssPlugin(content) {
274
- const ast = parse(content);
275
- const exportKey = "contextRef";
276
- const variableName = "contextRef";
277
- const valueKey = "value";
278
- let hasPatched = false;
279
- traverse(ast, {
280
- Program(p) {
281
- const n = p.node;
282
- const idx = n.body.findIndex((x) => {
283
- return t.isFunctionDeclaration(x) && x.id?.name === "_default";
284
- });
285
- if (idx > -1) {
286
- const prevStatement = n.body[idx - 1];
287
- const lastStatement = n.body[idx - 2];
288
- const hasPatchedCondition0 = prevStatement && t.isVariableDeclaration(prevStatement) && prevStatement.declarations.length === 1 && t.isIdentifier(prevStatement.declarations[0].id) && prevStatement.declarations[0].id.name === variableName;
289
- const hasPatchedCondition1 = t.isExpressionStatement(lastStatement) && t.isAssignmentExpression(lastStatement.expression) && t.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === variableName;
290
- hasPatched = hasPatchedCondition0 || hasPatchedCondition1;
291
- if (!hasPatched) {
292
- const statement = t.variableDeclaration("var", [
293
- t.variableDeclarator(t.identifier(variableName), t.objectExpression([t.objectProperty(t.identifier(valueKey), t.arrayExpression())]))
294
- ]);
295
- n.body.splice(
296
- idx,
297
- 0,
298
- statement,
299
- // exports.contextRef = contextRef;
300
- t.expressionStatement(
301
- t.assignmentExpression(
302
- "=",
303
- t.memberExpression(t.identifier("exports"), t.identifier(exportKey)),
304
- t.identifier(variableName)
305
- )
306
- )
307
- );
308
- }
309
- }
310
- },
311
- FunctionDeclaration(p) {
312
- if (hasPatched) {
313
- return;
314
- }
315
- const n = p.node;
316
- if (n.id?.name === "_default" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
317
- const returnStatement = n.body.body[0];
318
- if (t.isCallExpression(returnStatement.argument) && t.isMemberExpression(returnStatement.argument.callee) && t.isArrayExpression(returnStatement.argument.callee.object)) {
319
- const targetFn = returnStatement.argument.callee.object.elements[1];
320
- if (t.isFunctionExpression(targetFn)) {
321
- const targetBlockStatement = targetFn.body;
322
- if (t.isExpressionStatement(targetBlockStatement.body[0]) && t.isAssignmentExpression(targetBlockStatement.body[0].expression) && t.isNumericLiteral(targetBlockStatement.body[0].expression.right)) {
323
- hasPatched = true;
324
- return;
325
- }
326
- const lastStatement = targetBlockStatement.body[targetBlockStatement.body.length - 1];
327
- if (t.isExpressionStatement(lastStatement)) {
328
- const newExpressionStatement = t.expressionStatement(
329
- t.callExpression(
330
- t.memberExpression(
331
- t.memberExpression(t.identifier(variableName), t.identifier("value")),
332
- t.identifier("push")
333
- ),
334
- [lastStatement.expression]
335
- )
336
- );
337
- targetBlockStatement.body[targetBlockStatement.body.length - 1] = newExpressionStatement;
338
- }
339
- const ifIdx = targetBlockStatement.body.findIndex((x) => t.isIfStatement(x));
340
- if (ifIdx > -1) {
341
- const ifRoot = targetBlockStatement.body[ifIdx];
342
- if (t.isBlockStatement(ifRoot.consequent) && ifRoot.consequent.body[1] && t.isForOfStatement(ifRoot.consequent.body[1])) {
343
- const forOf = ifRoot.consequent.body[1];
344
- if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1 && t.isIfStatement(forOf.body.body[0])) {
345
- const if2 = forOf.body.body[0];
346
- if (t.isBlockStatement(if2.consequent) && if2.consequent.body.length === 1 && t.isExpressionStatement(if2.consequent.body[0])) {
347
- const target = if2.consequent.body[0];
348
- const newExpressionStatement = t.expressionStatement(
349
- t.callExpression(t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier("value")), t.identifier("push")), [target.expression])
350
- );
351
- if2.consequent.body[0] = newExpressionStatement;
352
- }
353
- }
354
- }
355
- }
356
- targetBlockStatement.body.unshift(
357
- // contentRef.value = []
358
- // t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression()))
359
- // contentRef.value.length = 0
360
- t.expressionStatement(
361
- t.assignmentExpression(
362
- "=",
363
- t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.identifier("length")),
364
- t.numericLiteral(0)
365
- )
366
- )
367
- );
368
- }
369
- }
370
- }
371
- }
372
- });
373
- return {
374
- code: hasPatched ? content : generate(ast).code,
375
- hasPatched
376
- };
377
- }
378
-
379
- function monkeyPatchForExposingContextV3(twDir, opt) {
380
- const k0 = "lib/processTailwindFeatures.js";
381
- const processTailwindFeaturesFilePath = path.resolve(twDir, k0);
382
- const processTailwindFeaturesContent = fs.readFileSync(processTailwindFeaturesFilePath, "utf8");
383
- const result = {};
384
- if (processTailwindFeaturesContent) {
385
- const { code, hasPatched } = inspectProcessTailwindFeaturesReturnContext$1(processTailwindFeaturesContent);
386
- if (!hasPatched && opt.overwrite) {
387
- fs.writeFileSync(processTailwindFeaturesFilePath, code, {
388
- encoding: "utf8"
389
- });
390
- logger.success("patch tailwindcss processTailwindFeatures for return content successfully!");
391
- }
392
- result[k0] = code;
393
- }
394
- let injectFilepath;
395
- let k1;
396
- const try0 = "lib/plugin.js";
397
- const try1 = "lib/index.js";
398
- const pluginFilePath = path.resolve(twDir, try0);
399
- const indexFilePath = path.resolve(twDir, try1);
400
- if (fs.existsSync(pluginFilePath)) {
401
- k1 = try0;
402
- injectFilepath = pluginFilePath;
403
- } else if (fs.existsSync(indexFilePath)) {
404
- k1 = try1;
405
- injectFilepath = indexFilePath;
406
- }
407
- if (injectFilepath && k1) {
408
- const pluginContent = fs.readFileSync(injectFilepath, "utf8");
409
- if (pluginContent) {
410
- const { code, hasPatched } = inspectPostcssPlugin$1(pluginContent);
411
- if (!hasPatched && opt.overwrite) {
412
- fs.writeFileSync(injectFilepath, code, {
413
- encoding: "utf8"
414
- });
415
- logger.success("patch tailwindcss for expose runtime context successfully!");
416
- }
417
- result[k1] = code;
418
- }
419
- return result;
420
- }
421
- }
422
- function monkeyPatchForExposingContextV2(twDir, opt) {
423
- const k0 = "lib/jit/processTailwindFeatures.js";
424
- const processTailwindFeaturesFilePath = path.resolve(twDir, k0);
425
- const processTailwindFeaturesContent = fs.readFileSync(processTailwindFeaturesFilePath, "utf8");
426
- const result = {};
427
- if (processTailwindFeaturesContent) {
428
- const { code, hasPatched } = inspectProcessTailwindFeaturesReturnContext(processTailwindFeaturesContent);
429
- if (!hasPatched && opt.overwrite) {
430
- fs.writeFileSync(processTailwindFeaturesFilePath, code, {
431
- encoding: "utf8"
432
- });
433
- logger.success("patch tailwindcss processTailwindFeatures for return content successfully!");
434
- }
435
- result[k0] = code;
436
- }
437
- const k1 = "lib/jit/index.js";
438
- const indexFilePath = path.resolve(twDir, k1);
439
- const pluginContent = fs.readFileSync(indexFilePath, "utf8");
440
- if (pluginContent) {
441
- const { code, hasPatched } = inspectPostcssPlugin(pluginContent);
442
- if (!hasPatched && opt.overwrite) {
443
- fs.writeFileSync(indexFilePath, code, {
444
- encoding: "utf8"
445
- });
446
- logger.success("patch tailwindcss for expose runtime content successfully!");
447
- }
448
- result[k1] = code;
449
- }
450
- return result;
451
- }
452
-
453
- function isPlainObject(value) {
454
- if (value === null || typeof value !== "object") {
455
- return false;
456
- }
457
- const prototype = Object.getPrototypeOf(value);
458
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
459
- return false;
460
- }
461
- if (Symbol.iterator in value) {
462
- return false;
463
- }
464
- if (Symbol.toStringTag in value) {
465
- return Object.prototype.toString.call(value) === "[object Module]";
466
- }
467
- return true;
468
- }
469
-
470
- function _defu(baseObject, defaults, namespace = ".", merger) {
471
- if (!isPlainObject(defaults)) {
472
- return _defu(baseObject, {}, namespace, merger);
473
- }
474
- const object = Object.assign({}, defaults);
475
- for (const key in baseObject) {
476
- if (key === "__proto__" || key === "constructor") {
477
- continue;
478
- }
479
- const value = baseObject[key];
480
- if (value === null || value === void 0) {
481
- continue;
482
- }
483
- if (merger && merger(object, key, value, namespace)) {
484
- continue;
485
- }
486
- if (Array.isArray(value) && Array.isArray(object[key])) {
487
- object[key] = [...value, ...object[key]];
488
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
489
- object[key] = _defu(
490
- value,
491
- object[key],
492
- (namespace ? `${namespace}.` : "") + key.toString(),
493
- merger
494
- );
495
- } else {
496
- object[key] = value;
497
- }
498
- }
499
- return object;
500
- }
501
- function createDefu(merger) {
502
- return (...arguments_) => (
503
- // eslint-disable-next-line unicorn/no-array-reduce
504
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
505
- );
506
- }
507
- const defu = createDefu();
508
-
509
- const { sync } = pkg;
510
- const defuOverrideArray = createDefu((obj, key, value) => {
511
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
512
- obj[key] = value;
513
- return true;
514
- }
515
- });
516
- function requireResolve(id, opts) {
517
- return sync(id, opts);
518
- }
519
- function searchPackageJSON(dir) {
520
- let packageJsonPath;
521
- while (true) {
522
- if (!dir) {
523
- return;
524
- }
525
- const newDir = path.dirname(dir);
526
- if (newDir === dir) {
527
- return;
528
- }
529
- dir = newDir;
530
- packageJsonPath = path.join(dir, "package.json");
531
- if (fs.existsSync(packageJsonPath)) {
532
- break;
533
- }
534
- }
535
- return packageJsonPath;
536
- }
537
- function getTailwindcssEntry(name = "tailwindcss", opts) {
538
- return requireResolve(name, opts);
539
- }
540
- function getPackageJsonPath(name, options = {}) {
541
- const entry = getTailwindcssEntry(name, options);
542
- if (!entry) {
543
- return;
544
- }
545
- return searchPackageJSON(entry);
546
- }
547
- function getPackageInfoSync(name, options = {}) {
548
- const packageJsonPath = getPackageJsonPath(name, options);
549
- if (!packageJsonPath) {
550
- return;
551
- }
552
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
553
- return {
554
- name,
555
- version: packageJson.version,
556
- rootPath: path.dirname(packageJsonPath),
557
- packageJsonPath,
558
- packageJson
559
- };
560
- }
561
- function isObject(val) {
562
- return val != null && typeof val === "object" && Array.isArray(val) === false;
563
- }
564
-
565
- function findAstNode(content, options) {
566
- const { variableName, units } = options;
567
- const ast = parse(content);
568
- let arrayRef;
569
- let changed = false;
570
- traverse(ast, {
571
- Identifier(path2) {
572
- if (path2.node.name === variableName && t.isVariableDeclarator(path2.parent) && t.isArrayExpression(path2.parent.init)) {
573
- arrayRef = path2.parent.init;
574
- const set = new Set(path2.parent.init.elements.map((x) => x.value));
575
- for (let i = 0; i < units.length; i++) {
576
- const unit = units[i];
577
- if (!set.has(unit)) {
578
- path2.parent.init.elements = path2.parent.init.elements.map((x) => {
579
- if (t.isStringLiteral(x)) {
580
- return {
581
- type: x?.type,
582
- value: x?.value
583
- };
584
- }
585
- return x;
586
- });
587
- path2.parent.init.elements.push({
588
- type: "StringLiteral",
589
- value: unit
590
- });
591
- changed = true;
592
- }
593
- }
594
- }
595
- }
596
- });
597
- return {
598
- arrayRef,
599
- changed
600
- };
601
- }
602
- function monkeyPatchForSupportingCustomUnit(rootDir, options) {
603
- const opts = defuOverrideArray(options, {
604
- units: ["rpx"],
605
- lengthUnitsFilePath: "lib/util/dataTypes.js",
606
- variableName: "lengthUnits",
607
- overwrite: true
608
- });
609
- const { lengthUnitsFilePath, overwrite, destPath } = opts;
610
- const dataTypesFilePath = path.resolve(rootDir, lengthUnitsFilePath);
611
- const dataTypesFileContent = fs.readFileSync(dataTypesFilePath, {
612
- encoding: "utf8"
613
- });
614
- const { arrayRef, changed } = findAstNode(dataTypesFileContent, opts);
615
- if (arrayRef && changed) {
616
- const { code } = generate(arrayRef, {
617
- jsescOption: {
618
- quotes: "single"
619
- }
620
- });
621
- if (arrayRef.start && arrayRef.end) {
622
- const prev = dataTypesFileContent.slice(0, arrayRef.start);
623
- const next = dataTypesFileContent.slice(arrayRef.end);
624
- const newCode = prev + code + next;
625
- if (overwrite) {
626
- fs.writeFileSync(destPath ?? dataTypesFilePath, newCode, {
627
- encoding: "utf8"
628
- });
629
- logger.success("patch tailwindcss for custom length unit successfully!");
630
- }
631
- }
632
- return {
633
- [opts.lengthUnitsFilePath]: code
634
- };
635
- }
636
- }
637
-
638
- function internalPatch(pkgJsonPath, options) {
639
- if (pkgJsonPath) {
640
- const pkgJson = require(pkgJsonPath);
641
- const twDir = path.dirname(pkgJsonPath);
642
- options.version = pkgJson.version;
643
- if (gte(pkgJson.version, "3.0.0")) {
644
- let result = {};
645
- if (options.applyPatches?.exportContext) {
646
- result = monkeyPatchForExposingContextV3(twDir, options);
647
- }
648
- if (options.applyPatches?.extendLengthUnits) {
649
- try {
650
- Object.assign(result ?? {}, monkeyPatchForSupportingCustomUnit(twDir, defu(options.applyPatches.extendLengthUnits === true ? void 0 : options.applyPatches.extendLengthUnits, {
651
- overwrite: options.overwrite
652
- })));
653
- } catch {
654
- }
655
- }
656
- return result;
657
- } else if (gte(pkgJson.version, "2.0.0")) {
658
- if (options.applyPatches?.exportContext) {
659
- return monkeyPatchForExposingContextV2(twDir, options);
660
- }
661
- }
662
- }
663
- }
664
-
665
- const jiti = createJiti(__filename);
666
-
667
- async function processTailwindcss(options) {
668
- const { config: userConfig, cwd } = defu(options, {
669
- cwd: process.cwd()
670
- });
671
- let config = userConfig;
672
- if (!(typeof config === "string" && path.isAbsolute(config))) {
673
- const moduleName = "tailwind";
674
- const result = await lilconfig("tailwindcss", {
675
- searchPlaces: [
676
- `${moduleName}.config.js`,
677
- `${moduleName}.config.cjs`,
678
- `${moduleName}.config.mjs`,
679
- `${moduleName}.config.ts`,
680
- `${moduleName}.config.cts`,
681
- `${moduleName}.config.mts`
682
- ],
683
- loaders: {
684
- // 默认支持 js 和 cjs 2种格式
685
- ".js": jiti,
686
- ".cjs": jiti,
687
- ".mjs": jiti,
688
- ".ts": jiti,
689
- ".cts": jiti,
690
- ".mts": jiti
691
- }
692
- }).search(cwd);
693
- if (!result) {
694
- throw new Error(`No TailwindCSS Config found in: ${cwd}`);
695
- }
696
- config = result.filepath;
697
- }
698
- const id = requireResolve("tailwindcss", {
699
- basedir: cwd
700
- });
701
- return await postcss([
702
- // eslint-disable-next-line ts/no-var-requires, ts/no-require-imports
703
- require(id)({
704
- config
705
- })
706
- ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
707
- from: void 0
708
- });
709
- }
710
-
711
- function getDefaultPatchOptions() {
712
- return {
713
- applyPatches: {
714
- exportContext: true,
715
- extendLengthUnits: false
716
- },
717
- overwrite: true
718
- };
719
- }
720
- function getPatchOptions(options) {
721
- return defu(
722
- options,
723
- {
724
- basedir: process.cwd()
725
- },
726
- getDefaultPatchOptions()
727
- );
728
- }
729
-
730
- var __defProp = Object.defineProperty;
731
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
732
- var __publicField = (obj, key, value) => {
733
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
734
- return value;
735
- };
736
- class TailwindcssPatcher {
737
- constructor(options = {}) {
738
- __publicField(this, "rawOptions");
739
- __publicField(this, "cacheOptions");
740
- __publicField(this, "patchOptions");
741
- __publicField(this, "patch");
742
- __publicField(this, "cacheManager");
743
- __publicField(this, "packageInfo");
744
- __publicField(this, "majorVersion");
745
- this.rawOptions = options;
746
- this.cacheOptions = getCacheOptions(options.cache);
747
- this.patchOptions = getPatchOptions(options.patch);
748
- this.cacheManager = new CacheManager(this.cacheOptions);
749
- this.packageInfo = getPackageInfoSync("tailwindcss", { basedir: this.patchOptions.basedir });
750
- if (this.packageInfo && this.packageInfo.version) {
751
- this.majorVersion = Number.parseInt(this.packageInfo.version[0]);
752
- }
753
- this.patch = () => {
754
- try {
755
- return internalPatch(this.packageInfo?.packageJsonPath, this.patchOptions);
756
- } catch (error) {
757
- console.error(`patch tailwindcss failed: ${error.message}`);
758
- }
759
- };
760
- }
761
- setCache(set) {
762
- if (this.cacheOptions.enable) {
763
- return this.cacheManager.write(set);
764
- }
765
- }
766
- getCache() {
767
- return this.cacheManager.read();
768
- }
769
- getContexts() {
770
- if (this.packageInfo) {
771
- const distPath = path.join(this.packageInfo.rootPath, "lib");
772
- let injectFilePath;
773
- if (this.majorVersion === 2) {
774
- injectFilePath = path.join(distPath, "jit/index.js");
775
- } else {
776
- injectFilePath = path.join(distPath, "plugin.js");
777
- if (!fs.existsSync(injectFilePath)) {
778
- injectFilePath = path.join(distPath, "index.js");
779
- }
780
- }
781
- if (injectFilePath) {
782
- const mo = require(injectFilePath);
783
- if (mo.contextRef) {
784
- return mo.contextRef.value;
785
- }
786
- }
787
- }
788
- return [];
789
- }
790
- getClassCaches() {
791
- const contexts = this.getContexts();
792
- return contexts.filter((x) => isObject(x)).map((x) => x.classCache);
793
- }
794
- getClassCacheSet(options) {
795
- const classCaches = this.getClassCaches();
796
- const classSet = /* @__PURE__ */ new Set();
797
- for (const classCacheMap of classCaches) {
798
- const keys = classCacheMap.keys();
799
- for (const key of keys) {
800
- const v = key.toString();
801
- if (options?.removeUniversalSelector && v === "*") {
802
- continue;
803
- }
804
- classSet.add(v);
805
- }
806
- }
807
- return classSet;
808
- }
809
- /**
810
- * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
811
- */
812
- getClassSet(options) {
813
- const { cacheStrategy = this.cacheOptions.strategy ?? "merge", removeUniversalSelector = true } = options ?? {};
814
- const set = this.getClassCacheSet({
815
- removeUniversalSelector
816
- });
817
- if (cacheStrategy === "overwrite") {
818
- set.size > 0 && this.setCache(set);
819
- } else if (cacheStrategy === "merge") {
820
- const cacheSet = this.getCache();
821
- if (cacheSet) {
822
- for (const x of cacheSet) {
823
- set.add(x);
824
- }
825
- }
826
- this.setCache(set);
827
- }
828
- return set;
829
- }
830
- async extract(options) {
831
- const { output, tailwindcss } = options ?? {};
832
- if (output && tailwindcss) {
833
- const { removeUniversalSelector, filename, loose } = output;
834
- await processTailwindcss(tailwindcss);
835
- const set = this.getClassSet({
836
- removeUniversalSelector
837
- });
838
- if (filename) {
839
- await fs.ensureDir(path.dirname(filename));
840
- const classList = [...set];
841
- fs.writeFileSync(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
842
- return filename;
843
- }
844
- }
845
- }
846
- }
847
-
848
- export { CacheManager as C, TailwindcssPatcher as T, monkeyPatchForExposingContextV2 as a, monkeyPatchForSupportingCustomUnit as b, getCacheOptions as c, getPatchOptions as g, internalPatch as i, logger as l, monkeyPatchForExposingContextV3 as m };