tailwindcss-patch 2.0.0 → 2.0.2

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # tailwindcss-patch
2
2
 
3
- get tailwindcss context at runtime ! extract all class to json file!
3
+ get tailwindcss context at runtime ! extract all classes into file!
4
4
 
5
5
  - [tailwindcss-patch](#tailwindcss-patch)
6
6
  - [Setup](#setup)
@@ -10,9 +10,10 @@ get tailwindcss context at runtime ! extract all class to json file!
10
10
  - [Extract all class into a json](#extract-all-class-into-a-json)
11
11
  - [Nodejs](#nodejs)
12
12
  - [Migration form v1 to v2](#migration-form-v1-to-v2)
13
- - [2. cli command change](#2-cli-command-change)
13
+ - [0. cli command change](#0-cli-command-change)
14
14
  - [1. default remove `*` in json array result](#1-default-remove--in-json-array-result)
15
- - [Notice](#notice)
15
+
16
+ > Nodejs version should >= `16.6.0`
16
17
 
17
18
  ## Setup
18
19
 
@@ -77,7 +78,7 @@ twPatcher.getClassSet()
77
78
 
78
79
  ## Migration form v1 to v2
79
80
 
80
- ### 2. cli command change
81
+ ### 0. cli command change
81
82
 
82
83
  ```diff
83
84
  {
@@ -95,11 +96,3 @@ twPatcher.getClassSet()
95
96
  "text-[100px]"
96
97
  ]
97
98
  ```
98
-
99
- ## Notice
100
-
101
- `getContexts`,`getClassCacheSet` should be invoked after `postcss-loader`'s activation.
102
-
103
- which means you may not get tailwindcss contexts at build start time.
104
-
105
- you may call them at `generateBundle` lifetime hook in `vite/webpack plugin`.
package/dist/cli.cjs CHANGED
@@ -1,97 +1,27 @@
1
1
  'use strict';
2
2
 
3
+ const cac = require('cac');
3
4
  const index = require('./index.cjs');
4
- const path = require('node:path');
5
+ require('node:path');
5
6
  require('node:fs');
6
- const fs = require('node:fs/promises');
7
+ require('node:fs/promises');
7
8
  require('resolve');
8
9
  require('@babel/types');
9
10
  require('@babel/generator');
10
11
  require('@babel/traverse');
11
12
  require('@babel/parser');
12
- const cac = require('cac');
13
+ const config = require('@tailwindcss-mangle/config');
13
14
  require('semver');
14
15
  require('postcss');
15
- require('postcss-load-config');
16
- require('c12');
16
+ require('lilconfig');
17
17
 
18
18
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
19
19
 
20
- const path__default = /*#__PURE__*/_interopDefaultCompat(path);
21
- const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
22
20
  const cac__default = /*#__PURE__*/_interopDefaultCompat(cac);
23
21
 
24
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
25
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
26
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
27
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
28
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
29
- const dedent = createDedent({});
30
- function createDedent(options) {
31
- dedent.withOptions = newOptions => createDedent(_objectSpread(_objectSpread({}, options), newOptions));
32
- return dedent;
33
- function dedent(strings, ...values) {
34
- const raw = typeof strings === "string" ? [strings] : strings.raw;
35
- const {
36
- escapeSpecialCharacters = Array.isArray(strings)
37
- } = options;
38
-
39
- // first, perform interpolation
40
- let result = "";
41
- for (let i = 0; i < raw.length; i++) {
42
- let next = raw[i];
43
- if (escapeSpecialCharacters) {
44
- // handle escaped newlines, backticks, and interpolation characters
45
- next = next.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\{/g, "{");
46
- }
47
- result += next;
48
- if (i < values.length) {
49
- // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
50
- result += values[i];
51
- }
52
- }
53
-
54
- // now strip indentation
55
- const lines = result.split("\n");
56
- let mindent = null;
57
- for (const l of lines) {
58
- const m = l.match(/^(\s+)\S+/);
59
- if (m) {
60
- const indent = m[1].length;
61
- if (!mindent) {
62
- // this is the first indented line
63
- mindent = indent;
64
- } else {
65
- mindent = Math.min(mindent, indent);
66
- }
67
- }
68
- }
69
- if (mindent !== null) {
70
- const m = mindent; // appease TypeScript
71
- result = lines
72
- // https://github.com/typescript-eslint/typescript-eslint/issues/7140
73
- // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
74
- .map(l => l[0] === " " || l[0] === "\t" ? l.slice(m) : l).join("\n");
75
- }
76
- return result
77
- // dedent eats leading and trailing whitespace too
78
- .trim()
79
- // handle escaped newlines at the end to ensure they don't get stripped too
80
- .replace(/\\n/g, "\n");
81
- }
82
- }
83
-
84
22
  function init() {
85
23
  const cwd = process.cwd();
86
- return fs__default.writeFile(
87
- path__default.resolve(cwd, "tailwindcss-patch.config.ts"),
88
- dedent`
89
- import { defineConfig } from 'tailwindcss-patch'
90
-
91
- export default defineConfig({})
92
- `,
93
- "utf8"
94
- );
24
+ return config.initConfig(cwd);
95
25
  }
96
26
  const cli = cac__default();
97
27
  cli.command("install", "patch install").action(() => {
@@ -101,13 +31,13 @@ cli.command("install", "patch install").action(() => {
101
31
  });
102
32
  cli.command("init").action(async () => {
103
33
  await init();
104
- console.log("\u2728 tailwindcss-patch config initialized!");
34
+ console.log(`\u2728 ${config.configName}.config.ts initialized!`);
105
35
  });
106
36
  cli.command("extract").action(async () => {
107
- const { config } = await index.getConfig();
108
- if (config) {
37
+ const { config: config$1 } = await config.getConfig();
38
+ if (config$1) {
109
39
  const twPatcher = new index.TailwindcssPatcher();
110
- const p = await twPatcher.extract(config);
40
+ const p = await twPatcher.extract(config$1.patch);
111
41
  console.log("\u2728 tailwindcss-patch extract success! file path:\n" + p);
112
42
  }
113
43
  });
package/dist/cli.mjs CHANGED
@@ -1,89 +1,21 @@
1
- import { getPatchOptions, getConfig, TailwindcssPatcher, createPatch } from './index.mjs';
2
- import path from 'node:path';
1
+ import cac from 'cac';
2
+ import { getPatchOptions, TailwindcssPatcher, createPatch } from './index.mjs';
3
+ import 'node:path';
3
4
  import 'node:fs';
4
- import fs from 'node:fs/promises';
5
+ import 'node:fs/promises';
5
6
  import 'resolve';
6
7
  import '@babel/types';
7
8
  import '@babel/generator';
8
9
  import '@babel/traverse';
9
10
  import '@babel/parser';
10
- import cac from 'cac';
11
+ import { configName, getConfig, initConfig } from '@tailwindcss-mangle/config';
11
12
  import 'semver';
12
13
  import 'postcss';
13
- import 'postcss-load-config';
14
- import 'c12';
15
-
16
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
17
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
18
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
19
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
20
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
21
- const dedent = createDedent({});
22
- function createDedent(options) {
23
- dedent.withOptions = newOptions => createDedent(_objectSpread(_objectSpread({}, options), newOptions));
24
- return dedent;
25
- function dedent(strings, ...values) {
26
- const raw = typeof strings === "string" ? [strings] : strings.raw;
27
- const {
28
- escapeSpecialCharacters = Array.isArray(strings)
29
- } = options;
30
-
31
- // first, perform interpolation
32
- let result = "";
33
- for (let i = 0; i < raw.length; i++) {
34
- let next = raw[i];
35
- if (escapeSpecialCharacters) {
36
- // handle escaped newlines, backticks, and interpolation characters
37
- next = next.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\{/g, "{");
38
- }
39
- result += next;
40
- if (i < values.length) {
41
- // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
42
- result += values[i];
43
- }
44
- }
45
-
46
- // now strip indentation
47
- const lines = result.split("\n");
48
- let mindent = null;
49
- for (const l of lines) {
50
- const m = l.match(/^(\s+)\S+/);
51
- if (m) {
52
- const indent = m[1].length;
53
- if (!mindent) {
54
- // this is the first indented line
55
- mindent = indent;
56
- } else {
57
- mindent = Math.min(mindent, indent);
58
- }
59
- }
60
- }
61
- if (mindent !== null) {
62
- const m = mindent; // appease TypeScript
63
- result = lines
64
- // https://github.com/typescript-eslint/typescript-eslint/issues/7140
65
- // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
66
- .map(l => l[0] === " " || l[0] === "\t" ? l.slice(m) : l).join("\n");
67
- }
68
- return result
69
- // dedent eats leading and trailing whitespace too
70
- .trim()
71
- // handle escaped newlines at the end to ensure they don't get stripped too
72
- .replace(/\\n/g, "\n");
73
- }
74
- }
14
+ import 'lilconfig';
75
15
 
76
16
  function init() {
77
17
  const cwd = process.cwd();
78
- return fs.writeFile(
79
- path.resolve(cwd, "tailwindcss-patch.config.ts"),
80
- dedent`
81
- import { defineConfig } from 'tailwindcss-patch'
82
-
83
- export default defineConfig({})
84
- `,
85
- "utf8"
86
- );
18
+ return initConfig(cwd);
87
19
  }
88
20
  const cli = cac();
89
21
  cli.command("install", "patch install").action(() => {
@@ -93,13 +25,13 @@ cli.command("install", "patch install").action(() => {
93
25
  });
94
26
  cli.command("init").action(async () => {
95
27
  await init();
96
- console.log("\u2728 tailwindcss-patch config initialized!");
28
+ console.log(`\u2728 ${configName}.config.ts initialized!`);
97
29
  });
98
30
  cli.command("extract").action(async () => {
99
31
  const { config } = await getConfig();
100
32
  if (config) {
101
33
  const twPatcher = new TailwindcssPatcher();
102
- const p = await twPatcher.extract(config);
34
+ const p = await twPatcher.extract(config.patch);
103
35
  console.log("\u2728 tailwindcss-patch extract success! file path:\n" + p);
104
36
  }
105
37
  });
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ const fs$1 = require('node:fs/promises');
3
4
  const path = require('node:path');
4
5
  const fs = require('node:fs');
5
- const fs$1 = require('node:fs/promises');
6
6
  const pkg = require('resolve');
7
7
  const semver = require('semver');
8
8
  const t = require('@babel/types');
@@ -10,8 +10,8 @@ const generate = require('@babel/generator');
10
10
  const traverse = require('@babel/traverse');
11
11
  const parser = require('@babel/parser');
12
12
  const postcss = require('postcss');
13
- const postcssrc = require('postcss-load-config');
14
- const c12 = require('c12');
13
+ const lilconfig = require('lilconfig');
14
+ const config = require('@tailwindcss-mangle/config');
15
15
 
16
16
  function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
17
17
 
@@ -27,15 +27,14 @@ function _interopNamespaceCompat(e) {
27
27
  return n;
28
28
  }
29
29
 
30
+ const fs__default$1 = /*#__PURE__*/_interopDefaultCompat(fs$1);
30
31
  const path__default = /*#__PURE__*/_interopDefaultCompat(path);
31
32
  const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
32
- const fs__default$1 = /*#__PURE__*/_interopDefaultCompat(fs$1);
33
33
  const pkg__default = /*#__PURE__*/_interopDefaultCompat(pkg);
34
34
  const t__namespace = /*#__PURE__*/_interopNamespaceCompat(t);
35
35
  const generate__default = /*#__PURE__*/_interopDefaultCompat(generate);
36
36
  const traverse__default = /*#__PURE__*/_interopDefaultCompat(traverse);
37
37
  const postcss__default = /*#__PURE__*/_interopDefaultCompat(postcss);
38
- const postcssrc__default = /*#__PURE__*/_interopDefaultCompat(postcssrc);
39
38
 
40
39
  const { sync } = pkg__default;
41
40
  function ensureFileContent(filepaths) {
@@ -92,10 +91,11 @@ function getClassCacheSet(basedir, options) {
92
91
  for (const classCacheMap of classCaches) {
93
92
  const keys = classCacheMap.keys();
94
93
  for (const key of keys) {
95
- if (options?.removeUniversalSelector && key.toString() === "*") {
94
+ const v = key.toString();
95
+ if (options?.removeUniversalSelector && v === "*") {
96
96
  continue;
97
97
  }
98
- classSet.add(key.toString());
98
+ classSet.add(v);
99
99
  }
100
100
  }
101
101
  return classSet;
@@ -183,6 +183,48 @@ class CacheManager {
183
183
  }
184
184
  }
185
185
 
186
+ function isObject(value) {
187
+ return value !== null && typeof value === "object";
188
+ }
189
+ function _defu(baseObject, defaults, namespace = ".", merger) {
190
+ if (!isObject(defaults)) {
191
+ return _defu(baseObject, {}, namespace, merger);
192
+ }
193
+ const object = Object.assign({}, defaults);
194
+ for (const key in baseObject) {
195
+ if (key === "__proto__" || key === "constructor") {
196
+ continue;
197
+ }
198
+ const value = baseObject[key];
199
+ if (value === null || value === void 0) {
200
+ continue;
201
+ }
202
+ if (merger && merger(object, key, value, namespace)) {
203
+ continue;
204
+ }
205
+ if (Array.isArray(value) && Array.isArray(object[key])) {
206
+ object[key] = [...value, ...object[key]];
207
+ } else if (isObject(value) && isObject(object[key])) {
208
+ object[key] = _defu(
209
+ value,
210
+ object[key],
211
+ (namespace ? `${namespace}.` : "") + key.toString(),
212
+ merger
213
+ );
214
+ } else {
215
+ object[key] = value;
216
+ }
217
+ }
218
+ return object;
219
+ }
220
+ function createDefu(merger) {
221
+ return (...arguments_) => (
222
+ // eslint-disable-next-line unicorn/no-array-reduce
223
+ arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
224
+ );
225
+ }
226
+ const defu = createDefu();
227
+
186
228
  function inspectProcessTailwindFeaturesReturnContext(content) {
187
229
  const ast = parser.parse(content);
188
230
  let hasPatched = false;
@@ -320,61 +362,9 @@ function inspectPostcssPlugin(content) {
320
362
  };
321
363
  }
322
364
 
323
- function isObject(value) {
324
- return value !== null && typeof value === "object";
325
- }
326
- function _defu(baseObject, defaults, namespace = ".", merger) {
327
- if (!isObject(defaults)) {
328
- return _defu(baseObject, {}, namespace, merger);
329
- }
330
- const object = Object.assign({}, defaults);
331
- for (const key in baseObject) {
332
- if (key === "__proto__" || key === "constructor") {
333
- continue;
334
- }
335
- const value = baseObject[key];
336
- if (value === null || value === void 0) {
337
- continue;
338
- }
339
- if (merger && merger(object, key, value, namespace)) {
340
- continue;
341
- }
342
- if (Array.isArray(value) && Array.isArray(object[key])) {
343
- object[key] = [...value, ...object[key]];
344
- } else if (isObject(value) && isObject(object[key])) {
345
- object[key] = _defu(
346
- value,
347
- object[key],
348
- (namespace ? `${namespace}.` : "") + key.toString(),
349
- merger
350
- );
351
- } else {
352
- object[key] = value;
353
- }
354
- }
355
- return object;
356
- }
357
- function createDefu(merger) {
358
- return (...arguments_) => (
359
- // eslint-disable-next-line unicorn/no-array-reduce
360
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
361
- );
362
- }
363
- const defu = createDefu();
364
-
365
- const defaultOptions = {
366
- overwrite: true
367
- };
368
- function getDefaultUserConfig() {
365
+ function getDefaultPatchOptions() {
369
366
  return {
370
- output: {
371
- filename: ".tw-patch/tw-class-list.json",
372
- removeUniversalSelector: true,
373
- loose: true
374
- },
375
- postcss: {
376
- configDir: process.cwd()
377
- }
367
+ overwrite: true
378
368
  };
379
369
  }
380
370
 
@@ -396,7 +386,7 @@ function getPatchOptions(options = {}) {
396
386
  {
397
387
  basedir: process.cwd()
398
388
  },
399
- defaultOptions
389
+ getDefaultPatchOptions()
400
390
  );
401
391
  }
402
392
  function createPatch(opt) {
@@ -451,13 +441,31 @@ function internalPatch(pkgJsonPath, options) {
451
441
  }
452
442
  }
453
443
 
454
- async function getCss(p) {
455
- const { options, plugins } = await postcssrc__default(void 0, p);
456
- const res = await postcss__default(plugins).process("@tailwind base;@tailwind components;@tailwind utilities;", {
457
- from: void 0,
458
- ...options
444
+ async function processTailwindcss(options) {
445
+ options.cwd = options.cwd ?? process.cwd();
446
+ let config = options.config;
447
+ if (!(typeof options.config === "string" && path__default.isAbsolute(options.config))) {
448
+ const moduleName = "tailwind";
449
+ const result = await lilconfig.lilconfig("tailwindcss", {
450
+ searchPlaces: [`${moduleName}.config.js`, `${moduleName}.config.cjs`],
451
+ loaders: {
452
+ // 默认支持 js 和 cjs 2种格式
453
+ ".js": require,
454
+ ".cjs": require
455
+ }
456
+ }).search(options.cwd);
457
+ if (!result) {
458
+ throw new Error(`No TailwindCSS Config found in: ${options.cwd}`);
459
+ }
460
+ config = result.filepath;
461
+ }
462
+ return await postcss__default([
463
+ require("tailwindcss")({
464
+ config
465
+ })
466
+ ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
467
+ from: void 0
459
468
  });
460
- return res;
461
469
  }
462
470
 
463
471
  class TailwindcssPatcher {
@@ -507,42 +515,31 @@ class TailwindcssPatcher {
507
515
  return getContexts(basedir);
508
516
  }
509
517
  async extract(options) {
510
- const { output, postcss } = options;
511
- if (output && postcss) {
518
+ const { output, tailwindcss } = options ?? {};
519
+ if (output && tailwindcss) {
512
520
  const { removeUniversalSelector, filename, loose } = output;
513
- const { configDir } = postcss;
514
- await getCss(configDir);
521
+ await processTailwindcss(tailwindcss);
515
522
  const set = this.getClassSet({
516
523
  removeUniversalSelector
517
524
  });
518
- await ensureDir(path.dirname(filename));
519
- const classList = [...set];
520
- await fs__default$1.writeFile(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
521
- return filename;
525
+ if (filename) {
526
+ await ensureDir(path.dirname(filename));
527
+ const classList = [...set];
528
+ await fs__default$1.writeFile(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
529
+ return filename;
530
+ }
522
531
  }
523
532
  }
524
533
  }
525
534
 
526
- function getConfig() {
527
- return c12.loadConfig({
528
- name: "tailwindcss-patch",
529
- defaults: {
530
- ...getDefaultUserConfig()
531
- }
532
- });
533
- }
534
- const defineConfig = c12.createDefineConfig();
535
-
536
535
  exports.CacheManager = CacheManager;
537
536
  exports.TailwindcssPatcher = TailwindcssPatcher;
538
537
  exports.createPatch = createPatch;
539
- exports.defineConfig = defineConfig;
540
538
  exports.ensureDir = ensureDir;
541
539
  exports.ensureFileContent = ensureFileContent;
542
540
  exports.getCacheOptions = getCacheOptions;
543
541
  exports.getClassCacheSet = getClassCacheSet;
544
542
  exports.getClassCaches = getClassCaches;
545
- exports.getConfig = getConfig;
546
543
  exports.getContexts = getContexts;
547
544
  exports.getInstalledPkgJsonPath = getInstalledPkgJsonPath;
548
545
  exports.getPatchOptions = getPatchOptions;
@@ -552,3 +549,6 @@ exports.inspectProcessTailwindFeaturesReturnContext = inspectProcessTailwindFeat
552
549
  exports.internalPatch = internalPatch;
553
550
  exports.monkeyPatchForExposingContext = monkeyPatchForExposingContext;
554
551
  exports.requireResolve = requireResolve;
552
+ Object.keys(config).forEach(function (k) {
553
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = config[k];
554
+ });
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Rule, Node } from 'postcss';
2
2
  import { Config } from 'tailwindcss';
3
- import * as c12 from 'c12';
3
+ import { UserConfig } from '@tailwindcss-mangle/config';
4
+ export * from '@tailwindcss-mangle/config';
4
5
  import { SyncOpts } from 'resolve';
5
6
 
6
7
  type CacheStrategy = 'merge' | 'overwrite';
@@ -37,7 +38,7 @@ type TailwindcssClassCache = Map<string, ({
37
38
  } | Rule)[]>;
38
39
  type TailwindcssRuntimeContext = {
39
40
  applyClassCache: Map<any, any>;
40
- candidateRuleCache: Map<string | String, Set<[
41
+ candidateRuleCache: Map<string | string, Set<[
41
42
  {
42
43
  arbitrary: any;
43
44
  index: any;
@@ -49,7 +50,7 @@ type TailwindcssRuntimeContext = {
49
50
  },
50
51
  Node
51
52
  ]>>;
52
- candidateRuleMap: Map<string | String, [object, Node][]>;
53
+ candidateRuleMap: Map<string | string, [object, Node][]>;
53
54
  changedContent: any[];
54
55
  classCache: TailwindcssClassCache;
55
56
  disposables: any[];
@@ -58,7 +59,7 @@ type TailwindcssRuntimeContext = {
58
59
  getVariants: Function;
59
60
  markInvalidUtilityCandidate: Function;
60
61
  markInvalidUtilityNode: Function;
61
- notClassCache: Set<String>;
62
+ notClassCache: Set<string>;
62
63
  offsets: {
63
64
  layerPositions: object;
64
65
  offsets: object;
@@ -73,20 +74,6 @@ type TailwindcssRuntimeContext = {
73
74
  variantMap: Map<string, [[object, Function]]>;
74
75
  variantOptions: Map<string, object>;
75
76
  };
76
- interface UserConfig {
77
- output?: {
78
- filename?: string;
79
- loose?: boolean;
80
- /**
81
- * @description remove * in output json
82
- */
83
- removeUniversalSelector?: boolean;
84
- };
85
- postcss?: {
86
- configDir?: string;
87
- };
88
- tailwindcss?: {};
89
- }
90
77
  type DeepRequired<T> = {
91
78
  [K in keyof T]: Required<DeepRequired<T[K]>>;
92
79
  };
@@ -127,7 +114,7 @@ declare class TailwindcssPatcher {
127
114
  removeUniversalSelector?: boolean;
128
115
  }): Set<string>;
129
116
  getContexts(basedir?: string): TailwindcssRuntimeContext[];
130
- extract(options: DeepRequired<UserConfig>): Promise<string | undefined>;
117
+ extract(options: UserConfig['patch']): Promise<string | undefined>;
131
118
  }
132
119
 
133
120
  declare function getTailwindcssEntry(basedir?: string): string;
@@ -155,11 +142,8 @@ declare function monkeyPatchForExposingContext(twDir: string, opt: InternalPatch
155
142
  } & Record<string, any>;
156
143
  declare function internalPatch(pkgJsonPath: string | undefined, options: InternalPatchOptions): any | undefined;
157
144
 
158
- declare function getConfig(): Promise<c12.ResolvedConfig<DeepRequired<UserConfig>, c12.ConfigLayerMeta>>;
159
- declare const defineConfig: c12.DefineConfig<UserConfig, c12.ConfigLayerMeta>;
160
-
161
145
  declare function ensureFileContent(filepaths: string | string[]): string | undefined;
162
146
  declare function requireResolve(id: string, opts?: SyncOpts): string;
163
147
  declare function ensureDir(p: string): Promise<void>;
164
148
 
165
- export { CacheManager, CacheOptions, CacheStrategy, DeepRequired, InternalCacheOptions, InternalPatchOptions, PatchOptions, TailwindcssClassCache, TailwindcssPatcher, TailwindcssPatcherOptions, TailwindcssRuntimeContext, UserConfig, createPatch, defineConfig, ensureDir, ensureFileContent, getCacheOptions, getClassCacheSet, getClassCaches, getConfig, getContexts, getInstalledPkgJsonPath, getPatchOptions, getTailwindcssEntry, inspectPostcssPlugin, inspectProcessTailwindFeaturesReturnContext, internalPatch, monkeyPatchForExposingContext, requireResolve };
149
+ export { CacheManager, CacheOptions, CacheStrategy, DeepRequired, InternalCacheOptions, InternalPatchOptions, PatchOptions, TailwindcssClassCache, TailwindcssPatcher, TailwindcssPatcherOptions, TailwindcssRuntimeContext, createPatch, ensureDir, ensureFileContent, getCacheOptions, getClassCacheSet, getClassCaches, getContexts, getInstalledPkgJsonPath, getPatchOptions, getTailwindcssEntry, inspectPostcssPlugin, inspectProcessTailwindFeaturesReturnContext, internalPatch, monkeyPatchForExposingContext, requireResolve };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
+ import fs$1 from 'node:fs/promises';
1
2
  import path, { dirname } from 'node:path';
2
3
  import fs from 'node:fs';
3
- import fs$1 from 'node:fs/promises';
4
4
  import pkg from 'resolve';
5
5
  import { gte } from 'semver';
6
6
  import * as t from '@babel/types';
@@ -8,9 +8,7 @@ import generate from '@babel/generator';
8
8
  import traverse from '@babel/traverse';
9
9
  import { parse } from '@babel/parser';
10
10
  import postcss from 'postcss';
11
- import postcssrc from 'postcss-load-config';
12
- import { createDefineConfig, loadConfig } from 'c12';
13
-
11
+ import { lilconfig } from 'lilconfig';
14
12
 
15
13
 
16
14
  // -- Unbuild CommonJS Shims --
@@ -20,6 +18,8 @@ import __cjs_mod__ from 'module';
20
18
  const __filename = __cjs_url__.fileURLToPath(import.meta.url);
21
19
  const __dirname = __cjs_path__.dirname(__filename);
22
20
  const require = __cjs_mod__.createRequire(import.meta.url);
21
+ export * from '@tailwindcss-mangle/config';
22
+
23
23
  const { sync } = pkg;
24
24
  function ensureFileContent(filepaths) {
25
25
  if (typeof filepaths === "string") {
@@ -75,10 +75,11 @@ function getClassCacheSet(basedir, options) {
75
75
  for (const classCacheMap of classCaches) {
76
76
  const keys = classCacheMap.keys();
77
77
  for (const key of keys) {
78
- if (options?.removeUniversalSelector && key.toString() === "*") {
78
+ const v = key.toString();
79
+ if (options?.removeUniversalSelector && v === "*") {
79
80
  continue;
80
81
  }
81
- classSet.add(key.toString());
82
+ classSet.add(v);
82
83
  }
83
84
  }
84
85
  return classSet;
@@ -166,6 +167,48 @@ class CacheManager {
166
167
  }
167
168
  }
168
169
 
170
+ function isObject(value) {
171
+ return value !== null && typeof value === "object";
172
+ }
173
+ function _defu(baseObject, defaults, namespace = ".", merger) {
174
+ if (!isObject(defaults)) {
175
+ return _defu(baseObject, {}, namespace, merger);
176
+ }
177
+ const object = Object.assign({}, defaults);
178
+ for (const key in baseObject) {
179
+ if (key === "__proto__" || key === "constructor") {
180
+ continue;
181
+ }
182
+ const value = baseObject[key];
183
+ if (value === null || value === void 0) {
184
+ continue;
185
+ }
186
+ if (merger && merger(object, key, value, namespace)) {
187
+ continue;
188
+ }
189
+ if (Array.isArray(value) && Array.isArray(object[key])) {
190
+ object[key] = [...value, ...object[key]];
191
+ } else if (isObject(value) && isObject(object[key])) {
192
+ object[key] = _defu(
193
+ value,
194
+ object[key],
195
+ (namespace ? `${namespace}.` : "") + key.toString(),
196
+ merger
197
+ );
198
+ } else {
199
+ object[key] = value;
200
+ }
201
+ }
202
+ return object;
203
+ }
204
+ function createDefu(merger) {
205
+ return (...arguments_) => (
206
+ // eslint-disable-next-line unicorn/no-array-reduce
207
+ arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
208
+ );
209
+ }
210
+ const defu = createDefu();
211
+
169
212
  function inspectProcessTailwindFeaturesReturnContext(content) {
170
213
  const ast = parse(content);
171
214
  let hasPatched = false;
@@ -303,61 +346,9 @@ function inspectPostcssPlugin(content) {
303
346
  };
304
347
  }
305
348
 
306
- function isObject(value) {
307
- return value !== null && typeof value === "object";
308
- }
309
- function _defu(baseObject, defaults, namespace = ".", merger) {
310
- if (!isObject(defaults)) {
311
- return _defu(baseObject, {}, namespace, merger);
312
- }
313
- const object = Object.assign({}, defaults);
314
- for (const key in baseObject) {
315
- if (key === "__proto__" || key === "constructor") {
316
- continue;
317
- }
318
- const value = baseObject[key];
319
- if (value === null || value === void 0) {
320
- continue;
321
- }
322
- if (merger && merger(object, key, value, namespace)) {
323
- continue;
324
- }
325
- if (Array.isArray(value) && Array.isArray(object[key])) {
326
- object[key] = [...value, ...object[key]];
327
- } else if (isObject(value) && isObject(object[key])) {
328
- object[key] = _defu(
329
- value,
330
- object[key],
331
- (namespace ? `${namespace}.` : "") + key.toString(),
332
- merger
333
- );
334
- } else {
335
- object[key] = value;
336
- }
337
- }
338
- return object;
339
- }
340
- function createDefu(merger) {
341
- return (...arguments_) => (
342
- // eslint-disable-next-line unicorn/no-array-reduce
343
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
344
- );
345
- }
346
- const defu = createDefu();
347
-
348
- const defaultOptions = {
349
- overwrite: true
350
- };
351
- function getDefaultUserConfig() {
349
+ function getDefaultPatchOptions() {
352
350
  return {
353
- output: {
354
- filename: ".tw-patch/tw-class-list.json",
355
- removeUniversalSelector: true,
356
- loose: true
357
- },
358
- postcss: {
359
- configDir: process.cwd()
360
- }
351
+ overwrite: true
361
352
  };
362
353
  }
363
354
 
@@ -379,7 +370,7 @@ function getPatchOptions(options = {}) {
379
370
  {
380
371
  basedir: process.cwd()
381
372
  },
382
- defaultOptions
373
+ getDefaultPatchOptions()
383
374
  );
384
375
  }
385
376
  function createPatch(opt) {
@@ -434,13 +425,31 @@ function internalPatch(pkgJsonPath, options) {
434
425
  }
435
426
  }
436
427
 
437
- async function getCss(p) {
438
- const { options, plugins } = await postcssrc(void 0, p);
439
- const res = await postcss(plugins).process("@tailwind base;@tailwind components;@tailwind utilities;", {
440
- from: void 0,
441
- ...options
428
+ async function processTailwindcss(options) {
429
+ options.cwd = options.cwd ?? process.cwd();
430
+ let config = options.config;
431
+ if (!(typeof options.config === "string" && path.isAbsolute(options.config))) {
432
+ const moduleName = "tailwind";
433
+ const result = await lilconfig("tailwindcss", {
434
+ searchPlaces: [`${moduleName}.config.js`, `${moduleName}.config.cjs`],
435
+ loaders: {
436
+ // 默认支持 js 和 cjs 2种格式
437
+ ".js": require,
438
+ ".cjs": require
439
+ }
440
+ }).search(options.cwd);
441
+ if (!result) {
442
+ throw new Error(`No TailwindCSS Config found in: ${options.cwd}`);
443
+ }
444
+ config = result.filepath;
445
+ }
446
+ return await postcss([
447
+ require("tailwindcss")({
448
+ config
449
+ })
450
+ ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
451
+ from: void 0
442
452
  });
443
- return res;
444
453
  }
445
454
 
446
455
  class TailwindcssPatcher {
@@ -490,30 +499,21 @@ class TailwindcssPatcher {
490
499
  return getContexts(basedir);
491
500
  }
492
501
  async extract(options) {
493
- const { output, postcss } = options;
494
- if (output && postcss) {
502
+ const { output, tailwindcss } = options ?? {};
503
+ if (output && tailwindcss) {
495
504
  const { removeUniversalSelector, filename, loose } = output;
496
- const { configDir } = postcss;
497
- await getCss(configDir);
505
+ await processTailwindcss(tailwindcss);
498
506
  const set = this.getClassSet({
499
507
  removeUniversalSelector
500
508
  });
501
- await ensureDir(dirname(filename));
502
- const classList = [...set];
503
- await fs$1.writeFile(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
504
- return filename;
509
+ if (filename) {
510
+ await ensureDir(dirname(filename));
511
+ const classList = [...set];
512
+ await fs$1.writeFile(filename, JSON.stringify(classList, null, loose ? 2 : void 0), "utf8");
513
+ return filename;
514
+ }
505
515
  }
506
516
  }
507
517
  }
508
518
 
509
- function getConfig() {
510
- return loadConfig({
511
- name: "tailwindcss-patch",
512
- defaults: {
513
- ...getDefaultUserConfig()
514
- }
515
- });
516
- }
517
- const defineConfig = createDefineConfig();
518
-
519
- export { CacheManager, TailwindcssPatcher, createPatch, defineConfig, ensureDir, ensureFileContent, getCacheOptions, getClassCacheSet, getClassCaches, getConfig, getContexts, getInstalledPkgJsonPath, getPatchOptions, getTailwindcssEntry, inspectPostcssPlugin, inspectProcessTailwindFeaturesReturnContext, internalPatch, monkeyPatchForExposingContext, requireResolve };
519
+ export { CacheManager, TailwindcssPatcher, createPatch, ensureDir, ensureFileContent, getCacheOptions, getClassCacheSet, getClassCaches, getContexts, getInstalledPkgJsonPath, getPatchOptions, getTailwindcssEntry, inspectPostcssPlugin, inspectProcessTailwindFeaturesReturnContext, internalPatch, monkeyPatchForExposingContext, requireResolve };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tailwindcss-patch",
3
- "version": "2.0.0",
4
- "description": "patch tailwindcss for exposing context",
3
+ "version": "2.0.2",
4
+ "description": "patch tailwindcss for exposing context and extract classes",
5
5
  "exports": {
6
6
  ".": {
7
7
  "types": "./dist/index.d.ts",
@@ -30,7 +30,9 @@
30
30
  ],
31
31
  "keywords": [
32
32
  "tailwindcss",
33
- "patch"
33
+ "patch",
34
+ "extract",
35
+ "class"
34
36
  ],
35
37
  "author": "SonOfMagic <qq1324318532@gmail.com>",
36
38
  "license": "MIT",
@@ -38,27 +40,33 @@
38
40
  "access": "public",
39
41
  "registry": "https://registry.npmjs.org/"
40
42
  },
43
+ "peerDependencies": {
44
+ "tailwindcss": ">=3.0.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "tailwindcss": {
48
+ "optional": false
49
+ }
50
+ },
41
51
  "devDependencies": {
42
52
  "@types/babel__generator": "^7.6.4",
43
53
  "@types/babel__traverse": "^7.20.1",
44
54
  "@types/resolve": "^1.20.2",
45
55
  "@types/semver": "^7.5.0",
46
- "dedent": "^1.5.1",
47
- "defu": "^6.1.2",
48
56
  "pkg-types": "^1.0.3",
49
57
  "tailwindcss": "^3.3.3"
50
58
  },
51
59
  "dependencies": {
52
- "@babel/generator": "^7.22.9",
53
- "@babel/parser": "^7.22.7",
54
- "@babel/traverse": "^7.22.8",
55
- "@babel/types": "^7.22.5",
56
- "c12": "^1.4.2",
60
+ "@babel/generator": "^7.22.10",
61
+ "@babel/parser": "^7.22.10",
62
+ "@babel/traverse": "^7.22.10",
63
+ "@babel/types": "^7.22.10",
57
64
  "cac": "^6.7.14",
65
+ "lilconfig": "^2.1.0",
58
66
  "postcss": "^8.4.27",
59
- "postcss-load-config": "^4.0.1",
60
67
  "resolve": "^1.22.4",
61
- "semver": "^7.5.4"
68
+ "semver": "^7.5.4",
69
+ "@tailwindcss-mangle/config": "^1.0.0"
62
70
  },
63
71
  "homepage": "https://github.com/sonofmagic/tailwindcss-mangle",
64
72
  "repository": {