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