tailwindcss-patch 2.2.4 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,572 +1,15 @@
1
- import fs$1 from 'node:fs/promises';
2
- import path, { dirname } from 'node:path';
3
- import fs from 'node:fs';
4
- import pkg from 'resolve';
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 postcss from 'postcss';
11
- import { lilconfig } from 'lilconfig';
12
- import createJiti from 'jiti';
13
-
14
-
15
- // -- Unbuild CommonJS Shims --
16
- import __cjs_url__ from 'url';
17
- import __cjs_path__ from 'path';
18
- import __cjs_mod__ from 'module';
19
- const __filename = __cjs_url__.fileURLToPath(import.meta.url);
20
- const __dirname = __cjs_path__.dirname(__filename);
21
- const require = __cjs_mod__.createRequire(import.meta.url);
1
+ export { C as CacheManager, T as TailwindcssPatcher, f as ensureDir, e as ensureFileContent, d as getCacheOptions, h as getPackageInfoSync, a as inspectPostcssPlugin, i as inspectProcessTailwindFeaturesReturnContext, c as internalPatch, j as isObject, b as monkeyPatchForExposingContextV2, m as monkeyPatchForExposingContextV3, r as requireResolve } from './shared/tailwindcss-patch.9adeca36.mjs';
22
2
  export { defineConfig } from '@tailwindcss-mangle/config';
23
-
24
- const { sync } = pkg;
25
- function ensureFileContent(filepaths) {
26
- if (typeof filepaths === "string") {
27
- filepaths = [filepaths];
28
- }
29
- let content;
30
- for (const filepath of filepaths) {
31
- if (fs.existsSync(filepath)) {
32
- content = fs.readFileSync(filepath, {
33
- encoding: "utf8"
34
- });
35
- break;
36
- }
37
- }
38
- return content;
39
- }
40
- function requireResolve(id, opts) {
41
- return sync(id, opts);
42
- }
43
- async function ensureDir(p) {
44
- try {
45
- await fs$1.access(p);
46
- } catch {
47
- await fs$1.mkdir(p, {
48
- recursive: true
49
- });
50
- }
51
- }
52
-
53
- function getTailwindcssEntry(basedir) {
54
- return requireResolve("tailwindcss", {
55
- basedir
56
- });
57
- }
58
- function getContexts(basedir) {
59
- const twPath = getTailwindcssEntry(basedir);
60
- const distPath = path.dirname(twPath);
61
- let injectFilePath = path.join(distPath, "plugin.js");
62
- if (!fs.existsSync(injectFilePath)) {
63
- injectFilePath = path.join(distPath, "index.js");
64
- }
65
- const mo = require(injectFilePath);
66
- if (mo.contextRef) {
67
- return mo.contextRef.value;
68
- }
69
- return [];
70
- }
71
- function getClassCaches(basedir) {
72
- const contexts = getContexts(basedir);
73
- return contexts.map((x) => x.classCache);
74
- }
75
- function getClassCacheSet(basedir, options) {
76
- const classCaches = getClassCaches(basedir);
77
- const classSet = /* @__PURE__ */ new Set();
78
- for (const classCacheMap of classCaches) {
79
- const keys = classCacheMap.keys();
80
- for (const key of keys) {
81
- const v = key.toString();
82
- if (options?.removeUniversalSelector && v === "*") {
83
- continue;
84
- }
85
- classSet.add(v);
86
- }
87
- }
88
- return classSet;
89
- }
90
-
91
- const pkgName = "tailwindcss-patch";
92
-
93
- function log(message, ...optionalParams) {
94
- return console.log(`[${pkgName}]:` + message, ...optionalParams);
95
- }
96
-
97
- var __defProp$1 = Object.defineProperty;
98
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
99
- var __publicField$1 = (obj, key, value) => {
100
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
101
- return value;
102
- };
103
- function getCacheOptions(options) {
104
- let cache;
105
- switch (typeof options) {
106
- case "undefined": {
107
- cache = {
108
- enable: false
109
- };
110
- break;
111
- }
112
- case "boolean": {
113
- cache = {
114
- enable: options
115
- };
116
- break;
117
- }
118
- case "object": {
119
- cache = { ...options, enable: true };
120
- break;
121
- }
122
- }
123
- return cache;
124
- }
125
- class CacheManager {
126
- constructor(options = {}) {
127
- __publicField$1(this, "options");
128
- this.options = this.getOptions(options);
129
- }
130
- mkdir(cacheDirectory) {
131
- const exists = fs.existsSync(cacheDirectory);
132
- if (!exists) {
133
- fs.mkdirSync(cacheDirectory, {
134
- recursive: true
135
- });
136
- }
137
- return cacheDirectory;
138
- }
139
- getOptions(options = {}) {
140
- const cwd = options.cwd ?? process.cwd();
141
- const dir = options.dir ?? path.resolve(cwd, "node_modules/.cache", pkgName);
142
- const file = options.file ?? "index.json";
143
- const filename = path.resolve(dir, file);
144
- return {
145
- cwd,
146
- dir,
147
- file,
148
- filename,
149
- strategy: "merge"
150
- };
151
- }
152
- write(data) {
153
- try {
154
- const { dir, filename } = this.options;
155
- this.mkdir(dir);
156
- fs.writeFileSync(filename, JSON.stringify([...data], void 0, 2), "utf8");
157
- return filename;
158
- } catch {
159
- log("write cache file fail!");
160
- }
161
- }
162
- read() {
163
- const { filename } = this.options;
164
- try {
165
- if (fs.existsSync(filename)) {
166
- const data = fs.readFileSync(filename, "utf8");
167
- return new Set(JSON.parse(data));
168
- }
169
- } catch {
170
- log("parse cache content fail! path:" + filename);
171
- try {
172
- fs.unlinkSync(filename);
173
- } catch {
174
- log("delete cache file fail! path:" + filename);
175
- }
176
- }
177
- }
178
- }
179
-
180
- function isPlainObject(value) {
181
- if (value === null || typeof value !== "object") {
182
- return false;
183
- }
184
- const prototype = Object.getPrototypeOf(value);
185
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
186
- return false;
187
- }
188
- if (Symbol.iterator in value) {
189
- return false;
190
- }
191
- if (Symbol.toStringTag in value) {
192
- return Object.prototype.toString.call(value) === "[object Module]";
193
- }
194
- return true;
195
- }
196
-
197
- function _defu(baseObject, defaults, namespace = ".", merger) {
198
- if (!isPlainObject(defaults)) {
199
- return _defu(baseObject, {}, namespace, merger);
200
- }
201
- const object = Object.assign({}, defaults);
202
- for (const key in baseObject) {
203
- if (key === "__proto__" || key === "constructor") {
204
- continue;
205
- }
206
- const value = baseObject[key];
207
- if (value === null || value === void 0) {
208
- continue;
209
- }
210
- if (merger && merger(object, key, value, namespace)) {
211
- continue;
212
- }
213
- if (Array.isArray(value) && Array.isArray(object[key])) {
214
- object[key] = [...value, ...object[key]];
215
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
216
- object[key] = _defu(
217
- value,
218
- object[key],
219
- (namespace ? `${namespace}.` : "") + key.toString(),
220
- merger
221
- );
222
- } else {
223
- object[key] = value;
224
- }
225
- }
226
- return object;
227
- }
228
- function createDefu(merger) {
229
- return (...arguments_) => (
230
- // eslint-disable-next-line unicorn/no-array-reduce
231
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
232
- );
233
- }
234
- const defu = createDefu();
235
-
236
- function _interopDefaultCompat(e) {
237
- return e && typeof e === "object" && "default" in e ? e.default : e;
238
- }
239
- const generate = _interopDefaultCompat(_babelGenerate);
240
- const traverse = _interopDefaultCompat(_babelTraverse);
241
-
242
- function inspectProcessTailwindFeaturesReturnContext(content) {
243
- const ast = parse(content);
244
- let hasPatched = false;
245
- traverse(ast, {
246
- FunctionDeclaration(p) {
247
- const n = p.node;
248
- if (n.id?.name === "processTailwindFeatures" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
249
- const rts = n.body.body[0];
250
- if (t.isFunctionExpression(rts.argument)) {
251
- const body = rts.argument.body.body;
252
- const lastStatement = body[body.length - 1];
253
- hasPatched = t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context";
254
- if (!hasPatched) {
255
- const rts2 = t.returnStatement(t.identifier("context"));
256
- body.push(rts2);
257
- }
258
- }
259
- }
260
- }
261
- });
262
- return {
263
- code: hasPatched ? content : generate(ast).code,
264
- hasPatched
265
- };
266
- }
267
- function inspectPostcssPlugin(content) {
268
- const ast = parse(content);
269
- const exportKey = "contextRef";
270
- const variableName = "contextRef";
271
- const valueKey = "value";
272
- let hasPatched = false;
273
- traverse(ast, {
274
- Program(p) {
275
- const n = p.node;
276
- const idx = n.body.findIndex((x) => {
277
- return t.isExpressionStatement(x) && t.isAssignmentExpression(x.expression) && t.isMemberExpression(x.expression.left) && t.isFunctionExpression(x.expression.right) && x.expression.right.id?.name === "tailwindcss";
278
- });
279
- if (idx > -1) {
280
- const prevStatement = n.body[idx - 1];
281
- const lastStatement = n.body[n.body.length - 1];
282
- const hasPatchedCondition0 = prevStatement && t.isVariableDeclaration(prevStatement) && prevStatement.declarations.length === 1 && t.isIdentifier(prevStatement.declarations[0].id) && prevStatement.declarations[0].id.name === variableName;
283
- const hasPatchedCondition1 = t.isExpressionStatement(lastStatement) && t.isAssignmentExpression(lastStatement.expression) && t.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === variableName;
284
- hasPatched = hasPatchedCondition0 || hasPatchedCondition1;
285
- if (!hasPatched) {
286
- const statement = t.variableDeclaration("const", [
287
- t.variableDeclarator(t.identifier(variableName), t.objectExpression([t.objectProperty(t.identifier(valueKey), t.arrayExpression())]))
288
- ]);
289
- n.body.splice(idx, 0, statement);
290
- n.body.push(
291
- t.expressionStatement(
292
- t.assignmentExpression(
293
- "=",
294
- t.memberExpression(t.memberExpression(t.identifier("module"), t.identifier("exports")), t.identifier(exportKey)),
295
- t.identifier(variableName)
296
- )
297
- )
298
- );
299
- }
300
- }
301
- },
302
- FunctionExpression(p) {
303
- if (hasPatched) {
304
- return;
305
- }
306
- const n = p.node;
307
- if (n.id?.name === "tailwindcss" && n.body.body.length === 1 && t.isReturnStatement(n.body.body[0])) {
308
- const returnStatement = n.body.body[0];
309
- if (t.isObjectExpression(returnStatement.argument) && returnStatement.argument.properties.length === 2) {
310
- const properties = returnStatement.argument.properties;
311
- if (t.isObjectProperty(properties[0]) && t.isObjectProperty(properties[1])) {
312
- const keyMatched = t.isIdentifier(properties[0].key) && properties[0].key.name === "postcssPlugin";
313
- const pluginsMatched = t.isIdentifier(properties[1].key) && properties[1].key.name === "plugins";
314
- if (pluginsMatched && keyMatched && t.isCallExpression(properties[1].value) && t.isMemberExpression(properties[1].value.callee) && t.isArrayExpression(properties[1].value.callee.object)) {
315
- const pluginsCode = properties[1].value.callee.object.elements;
316
- if (pluginsCode[1] && t.isFunctionExpression(pluginsCode[1])) {
317
- const targetBlockStatement = pluginsCode[1].body;
318
- const lastStatement = targetBlockStatement.body[targetBlockStatement.body.length - 1];
319
- if (t.isExpressionStatement(lastStatement)) {
320
- const newExpressionStatement = t.expressionStatement(
321
- t.callExpression(
322
- t.memberExpression(
323
- t.memberExpression(t.identifier(variableName), t.identifier("value")),
324
- t.identifier("push")
325
- ),
326
- [lastStatement.expression]
327
- )
328
- );
329
- targetBlockStatement.body[targetBlockStatement.body.length - 1] = newExpressionStatement;
330
- }
331
- const ifIdx = targetBlockStatement.body.findIndex((x) => t.isIfStatement(x));
332
- if (ifIdx > -1) {
333
- const ifRoot = targetBlockStatement.body[ifIdx];
334
- if (t.isBlockStatement(ifRoot.consequent) && ifRoot.consequent.body[1] && t.isForOfStatement(ifRoot.consequent.body[1])) {
335
- const forOf = ifRoot.consequent.body[1];
336
- if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1 && t.isIfStatement(forOf.body.body[0])) {
337
- const if2 = forOf.body.body[0];
338
- if (t.isBlockStatement(if2.consequent) && if2.consequent.body.length === 1 && t.isExpressionStatement(if2.consequent.body[0])) {
339
- const target = if2.consequent.body[0];
340
- const newExpressionStatement = t.expressionStatement(
341
- t.callExpression(t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier("value")), t.identifier("push")), [target.expression])
342
- );
343
- if2.consequent.body[0] = newExpressionStatement;
344
- }
345
- }
346
- }
347
- }
348
- targetBlockStatement.body.unshift(
349
- // contentRef.value = []
350
- // t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression()))
351
- // contentRef.value.length = 0
352
- t.expressionStatement(
353
- t.assignmentExpression(
354
- "=",
355
- t.memberExpression(t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.identifier("length")),
356
- t.numericLiteral(0)
357
- )
358
- )
359
- );
360
- }
361
- }
362
- }
363
- }
364
- }
365
- }
366
- // BlockStatement(p) {
367
- // const n = p.node
368
- // if (start && p.parent.type === 'FunctionExpression' && !p.parent.id) {
369
- // n.body.unshift(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.identifier(variableName), t.identifier(valueKey)), t.arrayExpression())))
370
- // }
371
- // }
372
- });
373
- return {
374
- code: hasPatched ? content : generate(ast).code,
375
- hasPatched
376
- };
377
- }
378
-
379
- function getDefaultPatchOptions() {
380
- return {
381
- overwrite: true
382
- };
383
- }
384
-
385
- function getInstalledPkgJsonPath(options = {}) {
386
- try {
387
- const tmpJsonPath = requireResolve(`tailwindcss/package.json`, {
388
- paths: options.paths
389
- });
390
- return tmpJsonPath;
391
- } catch (error) {
392
- if (error.code === "MODULE_NOT_FOUND") {
393
- console.warn("Can't find npm pkg: `tailwindcss`, Please ensure it has been installed!");
394
- }
395
- }
396
- }
397
- function getPatchOptions(options = {}) {
398
- return defu(
399
- options,
400
- {
401
- basedir: process.cwd()
402
- },
403
- getDefaultPatchOptions()
404
- );
405
- }
406
- function createPatch(opt) {
407
- return () => {
408
- try {
409
- const pkgJsonPath = getInstalledPkgJsonPath(opt);
410
- return internalPatch(pkgJsonPath, opt);
411
- } catch (error) {
412
- console.warn(`patch tailwindcss failed:` + error.message);
413
- }
414
- };
415
- }
416
- function monkeyPatchForExposingContext(twDir, opt) {
417
- const processTailwindFeaturesFilePath = path.resolve(twDir, "lib/processTailwindFeatures.js");
418
- const processTailwindFeaturesContent = ensureFileContent(processTailwindFeaturesFilePath);
419
- const result = {};
420
- if (processTailwindFeaturesContent) {
421
- const { code, hasPatched } = inspectProcessTailwindFeaturesReturnContext(processTailwindFeaturesContent);
422
- if (!hasPatched && opt.overwrite) {
423
- fs.writeFileSync(processTailwindFeaturesFilePath, code, {
424
- encoding: "utf8"
425
- });
426
- console.log("patch tailwindcss processTailwindFeatures for return content successfully!");
427
- }
428
- result.processTailwindFeatures = code;
429
- }
430
- const pluginFilePath = path.resolve(twDir, "lib/plugin.js");
431
- const indexFilePath = path.resolve(twDir, "lib/index.js");
432
- const pluginContent = ensureFileContent([pluginFilePath, indexFilePath]);
433
- if (pluginContent) {
434
- const { code, hasPatched } = inspectPostcssPlugin(pluginContent);
435
- if (!hasPatched && opt.overwrite) {
436
- fs.writeFileSync(pluginFilePath, code, {
437
- encoding: "utf8"
438
- });
439
- console.log("patch tailwindcss for expose runtime content successfully!");
440
- }
441
- result.plugin = code;
442
- }
443
- opt.custom && typeof opt.custom === "function" && opt.custom(twDir, result);
444
- return result;
445
- }
446
- function internalPatch(pkgJsonPath, options) {
447
- if (pkgJsonPath) {
448
- const pkgJson = require(pkgJsonPath);
449
- const twDir = path.dirname(pkgJsonPath);
450
- if (gte(pkgJson.version, "3.0.0")) {
451
- options.version = pkgJson.version;
452
- const result = monkeyPatchForExposingContext(twDir, options);
453
- return result;
454
- }
455
- }
456
- }
457
-
458
- const jiti = createJiti(__filename);
459
- async function processTailwindcss(options) {
460
- options.cwd = options.cwd ?? process.cwd();
461
- let config = options.config;
462
- if (!(typeof options.config === "string" && path.isAbsolute(options.config))) {
463
- const moduleName = "tailwind";
464
- const result = await lilconfig("tailwindcss", {
465
- searchPlaces: [
466
- `${moduleName}.config.js`,
467
- `${moduleName}.config.cjs`,
468
- `${moduleName}.config.mjs`,
469
- `${moduleName}.config.ts`,
470
- `${moduleName}.config.cts`,
471
- `${moduleName}.config.mts`
472
- ],
473
- loaders: {
474
- // 默认支持 js 和 cjs 2种格式
475
- ".js": jiti,
476
- ".cjs": jiti,
477
- ".mjs": jiti,
478
- ".ts": jiti,
479
- ".cts": jiti,
480
- ".mts": jiti
481
- }
482
- }).search(options.cwd);
483
- if (!result) {
484
- throw new Error(`No TailwindCSS Config found in: ${options.cwd}`);
485
- }
486
- config = result.filepath;
487
- }
488
- return await postcss([
489
- require("tailwindcss")({
490
- config
491
- })
492
- ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
493
- from: void 0
494
- });
495
- }
496
-
497
- var __defProp = Object.defineProperty;
498
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
499
- var __publicField = (obj, key, value) => {
500
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
501
- return value;
502
- };
503
- class TailwindcssPatcher {
504
- constructor(options = {}) {
505
- __publicField(this, "rawOptions");
506
- __publicField(this, "cacheOptions");
507
- __publicField(this, "patchOptions");
508
- __publicField(this, "patch");
509
- __publicField(this, "cacheManager");
510
- this.rawOptions = options;
511
- this.cacheOptions = getCacheOptions(options.cache);
512
- this.patchOptions = getPatchOptions(options.patch);
513
- this.patch = createPatch(this.patchOptions);
514
- this.cacheManager = new CacheManager(this.cacheOptions);
515
- }
516
- getPkgEntry(basedir) {
517
- return getTailwindcssEntry(basedir);
518
- }
519
- setCache(set) {
520
- if (this.cacheOptions.enable) {
521
- return this.cacheManager.write(set);
522
- }
523
- }
524
- getCache() {
525
- return this.cacheManager.read();
526
- }
527
- /**
528
- * @description 在多个 tailwindcss 上下文时,这个方法将被执行多次,所以策略上应该使用 append
529
- * 详见 taro weapp-tailwindcss 独立分包
530
- * @param basedir
531
- * @returns
532
- */
533
- getClassSet(options) {
534
- const { basedir, cacheStrategy = this.cacheOptions.strategy ?? "merge", removeUniversalSelector = true } = options ?? {};
535
- const set = getClassCacheSet(basedir, {
536
- removeUniversalSelector
537
- });
538
- if (cacheStrategy === "overwrite") {
539
- set.size > 0 && this.setCache(set);
540
- } else if (cacheStrategy === "merge") {
541
- const cacheSet = this.getCache();
542
- if (cacheSet) {
543
- for (const x of cacheSet) {
544
- set.add(x);
545
- }
546
- }
547
- this.setCache(set);
548
- }
549
- return set;
550
- }
551
- getContexts(basedir) {
552
- return getContexts(basedir);
553
- }
554
- async extract(options) {
555
- const { output, tailwindcss } = options ?? {};
556
- if (output && tailwindcss) {
557
- const { removeUniversalSelector, filename, loose } = output;
558
- await processTailwindcss(tailwindcss);
559
- const set = this.getClassSet({
560
- removeUniversalSelector
561
- });
562
- if (filename) {
563
- await ensureDir(dirname(filename));
564
- const classList = [...set];
565
- await fs$1.writeFile(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
566
- return filename;
567
- }
568
- }
569
- }
570
- }
571
-
572
- export { CacheManager, TailwindcssPatcher, createPatch, ensureDir, ensureFileContent, getCacheOptions, getClassCacheSet, getClassCaches, getContexts, getInstalledPkgJsonPath, getPatchOptions, getTailwindcssEntry, inspectPostcssPlugin, inspectProcessTailwindFeaturesReturnContext, internalPatch, monkeyPatchForExposingContext, requireResolve };
3
+ import 'node:path';
4
+ import 'node:fs';
5
+ import 'node:process';
6
+ import 'semver';
7
+ import '@babel/types';
8
+ import '@babel/generator';
9
+ import '@babel/traverse';
10
+ import '@babel/parser';
11
+ import 'node:fs/promises';
12
+ import 'resolve';
13
+ import 'postcss';
14
+ import 'lilconfig';
15
+ import 'jiti';