tailwindcss-patch 8.6.0 → 8.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2437 +0,0 @@
1
- // src/logger.ts
2
- import { createConsola } from "consola";
3
- var logger = createConsola();
4
- var logger_default = logger;
5
-
6
- // src/cache/store.ts
7
- import process from "process";
8
- import fs from "fs-extra";
9
- function isErrnoException(error) {
10
- return error instanceof Error && typeof error.code === "string";
11
- }
12
- function isAccessDenied(error) {
13
- return isErrnoException(error) && Boolean(error.code && ["EPERM", "EBUSY", "EACCES"].includes(error.code));
14
- }
15
- var CacheStore = class {
16
- constructor(options) {
17
- this.options = options;
18
- this.driver = options.driver ?? "file";
19
- }
20
- driver;
21
- memoryCache = null;
22
- async ensureDir() {
23
- await fs.ensureDir(this.options.dir);
24
- }
25
- ensureDirSync() {
26
- fs.ensureDirSync(this.options.dir);
27
- }
28
- createTempPath() {
29
- const uniqueSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
30
- return `${this.options.path}.${uniqueSuffix}.tmp`;
31
- }
32
- async replaceCacheFile(tempPath) {
33
- try {
34
- await fs.rename(tempPath, this.options.path);
35
- return true;
36
- } catch (error) {
37
- if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
38
- try {
39
- await fs.remove(this.options.path);
40
- } catch (removeError) {
41
- if (isAccessDenied(removeError)) {
42
- logger_default.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
43
- return false;
44
- }
45
- if (!isErrnoException(removeError) || removeError.code !== "ENOENT") {
46
- throw removeError;
47
- }
48
- }
49
- await fs.rename(tempPath, this.options.path);
50
- return true;
51
- }
52
- throw error;
53
- }
54
- }
55
- replaceCacheFileSync(tempPath) {
56
- try {
57
- fs.renameSync(tempPath, this.options.path);
58
- return true;
59
- } catch (error) {
60
- if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
61
- try {
62
- fs.removeSync(this.options.path);
63
- } catch (removeError) {
64
- if (isAccessDenied(removeError)) {
65
- logger_default.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
66
- return false;
67
- }
68
- if (!isErrnoException(removeError) || removeError.code !== "ENOENT") {
69
- throw removeError;
70
- }
71
- }
72
- fs.renameSync(tempPath, this.options.path);
73
- return true;
74
- }
75
- throw error;
76
- }
77
- }
78
- async cleanupTempFile(tempPath) {
79
- try {
80
- await fs.remove(tempPath);
81
- } catch {
82
- }
83
- }
84
- cleanupTempFileSync(tempPath) {
85
- try {
86
- fs.removeSync(tempPath);
87
- } catch {
88
- }
89
- }
90
- async write(data) {
91
- if (!this.options.enabled) {
92
- return void 0;
93
- }
94
- if (this.driver === "noop") {
95
- return void 0;
96
- }
97
- if (this.driver === "memory") {
98
- this.memoryCache = new Set(data);
99
- return "memory";
100
- }
101
- const tempPath = this.createTempPath();
102
- try {
103
- await this.ensureDir();
104
- await fs.writeJSON(tempPath, Array.from(data));
105
- const replaced = await this.replaceCacheFile(tempPath);
106
- if (replaced) {
107
- return this.options.path;
108
- }
109
- await this.cleanupTempFile(tempPath);
110
- return void 0;
111
- } catch (error) {
112
- await this.cleanupTempFile(tempPath);
113
- logger_default.error("Unable to persist Tailwind class cache", error);
114
- return void 0;
115
- }
116
- }
117
- writeSync(data) {
118
- if (!this.options.enabled) {
119
- return void 0;
120
- }
121
- if (this.driver === "noop") {
122
- return void 0;
123
- }
124
- if (this.driver === "memory") {
125
- this.memoryCache = new Set(data);
126
- return "memory";
127
- }
128
- const tempPath = this.createTempPath();
129
- try {
130
- this.ensureDirSync();
131
- fs.writeJSONSync(tempPath, Array.from(data));
132
- const replaced = this.replaceCacheFileSync(tempPath);
133
- if (replaced) {
134
- return this.options.path;
135
- }
136
- this.cleanupTempFileSync(tempPath);
137
- return void 0;
138
- } catch (error) {
139
- this.cleanupTempFileSync(tempPath);
140
- logger_default.error("Unable to persist Tailwind class cache", error);
141
- return void 0;
142
- }
143
- }
144
- async read() {
145
- if (!this.options.enabled) {
146
- return /* @__PURE__ */ new Set();
147
- }
148
- if (this.driver === "noop") {
149
- return /* @__PURE__ */ new Set();
150
- }
151
- if (this.driver === "memory") {
152
- return new Set(this.memoryCache ?? []);
153
- }
154
- try {
155
- const exists = await fs.pathExists(this.options.path);
156
- if (!exists) {
157
- return /* @__PURE__ */ new Set();
158
- }
159
- const data = await fs.readJSON(this.options.path);
160
- if (Array.isArray(data)) {
161
- return new Set(data.filter((item) => typeof item === "string"));
162
- }
163
- } catch (error) {
164
- if (isErrnoException(error) && error.code === "ENOENT") {
165
- return /* @__PURE__ */ new Set();
166
- }
167
- logger_default.warn("Unable to read Tailwind class cache, removing invalid file.", error);
168
- try {
169
- await fs.remove(this.options.path);
170
- } catch (cleanupError) {
171
- logger_default.error("Failed to clean up invalid cache file", cleanupError);
172
- }
173
- }
174
- return /* @__PURE__ */ new Set();
175
- }
176
- readSync() {
177
- if (!this.options.enabled) {
178
- return /* @__PURE__ */ new Set();
179
- }
180
- if (this.driver === "noop") {
181
- return /* @__PURE__ */ new Set();
182
- }
183
- if (this.driver === "memory") {
184
- return new Set(this.memoryCache ?? []);
185
- }
186
- try {
187
- const exists = fs.pathExistsSync(this.options.path);
188
- if (!exists) {
189
- return /* @__PURE__ */ new Set();
190
- }
191
- const data = fs.readJSONSync(this.options.path);
192
- if (Array.isArray(data)) {
193
- return new Set(data.filter((item) => typeof item === "string"));
194
- }
195
- } catch (error) {
196
- if (isErrnoException(error) && error.code === "ENOENT") {
197
- return /* @__PURE__ */ new Set();
198
- }
199
- logger_default.warn("Unable to read Tailwind class cache, removing invalid file.", error);
200
- try {
201
- fs.removeSync(this.options.path);
202
- } catch (cleanupError) {
203
- logger_default.error("Failed to clean up invalid cache file", cleanupError);
204
- }
205
- }
206
- return /* @__PURE__ */ new Set();
207
- }
208
- };
209
-
210
- // src/extraction/candidate-extractor.ts
211
- import { promises as fs2 } from "fs";
212
- import process2 from "process";
213
- import path from "pathe";
214
- async function importNode() {
215
- return import("@tailwindcss/node");
216
- }
217
- async function importOxide() {
218
- return import("@tailwindcss/oxide");
219
- }
220
- async function extractRawCandidatesWithPositions(content, extension = "html") {
221
- const { Scanner } = await importOxide();
222
- const scanner = new Scanner({});
223
- const result = scanner.getCandidatesWithPositions({ content, extension });
224
- return result.map(({ candidate, position }) => ({
225
- rawCandidate: candidate,
226
- start: position,
227
- end: position + candidate.length
228
- }));
229
- }
230
- async function extractRawCandidates(sources) {
231
- const { Scanner } = await importOxide();
232
- const scanner = new Scanner({
233
- sources
234
- });
235
- return scanner.scan();
236
- }
237
- async function extractValidCandidates(options) {
238
- const providedOptions = options ?? {};
239
- const defaultCwd = providedOptions.cwd ?? process2.cwd();
240
- const base = providedOptions.base ?? defaultCwd;
241
- const css = providedOptions.css ?? '@import "tailwindcss";';
242
- const sources = (providedOptions.sources ?? [
243
- {
244
- base: defaultCwd,
245
- pattern: "**/*",
246
- negated: false
247
- }
248
- ]).map((source) => ({
249
- base: source.base ?? defaultCwd,
250
- pattern: source.pattern,
251
- negated: source.negated
252
- }));
253
- const { __unstable__loadDesignSystem } = await importNode();
254
- const designSystem = await __unstable__loadDesignSystem(css, { base });
255
- const candidates = await extractRawCandidates(sources);
256
- const parsedCandidates = candidates.filter(
257
- (rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
258
- );
259
- if (parsedCandidates.length === 0) {
260
- return parsedCandidates;
261
- }
262
- const cssByCandidate = designSystem.candidatesToCss(parsedCandidates);
263
- const validCandidates = [];
264
- for (let index = 0; index < parsedCandidates.length; index++) {
265
- const css2 = cssByCandidate[index];
266
- if (typeof css2 === "string" && css2.trim().length > 0) {
267
- validCandidates.push(parsedCandidates[index]);
268
- }
269
- }
270
- return validCandidates;
271
- }
272
- function normalizeSources(sources, cwd) {
273
- const baseSources = sources?.length ? sources : [
274
- {
275
- base: cwd,
276
- pattern: "**/*",
277
- negated: false
278
- }
279
- ];
280
- return baseSources.map((source) => ({
281
- base: source.base ?? cwd,
282
- pattern: source.pattern,
283
- negated: source.negated
284
- }));
285
- }
286
- function buildLineOffsets(content) {
287
- const offsets = [0];
288
- for (let i = 0; i < content.length; i++) {
289
- if (content[i] === "\n") {
290
- offsets.push(i + 1);
291
- }
292
- }
293
- if (offsets[offsets.length - 1] !== content.length) {
294
- offsets.push(content.length);
295
- }
296
- return offsets;
297
- }
298
- function resolveLineMeta(content, offsets, index) {
299
- let low = 0;
300
- let high = offsets.length - 1;
301
- while (low <= high) {
302
- const mid = Math.floor((low + high) / 2);
303
- const start = offsets[mid];
304
- const nextStart = offsets[mid + 1] ?? content.length;
305
- if (index < start) {
306
- high = mid - 1;
307
- continue;
308
- }
309
- if (index >= nextStart) {
310
- low = mid + 1;
311
- continue;
312
- }
313
- const line = mid + 1;
314
- const column = index - start + 1;
315
- const lineEnd = content.indexOf("\n", start);
316
- const lineText = content.slice(start, lineEnd === -1 ? content.length : lineEnd);
317
- return { line, column, lineText };
318
- }
319
- const lastStart = offsets[offsets.length - 2] ?? 0;
320
- return {
321
- line: offsets.length - 1,
322
- column: index - lastStart + 1,
323
- lineText: content.slice(lastStart)
324
- };
325
- }
326
- function toExtension(filename) {
327
- const ext = path.extname(filename).replace(/^\./, "");
328
- return ext || "txt";
329
- }
330
- function toRelativeFile(cwd, filename) {
331
- const relative = path.relative(cwd, filename);
332
- return relative === "" ? path.basename(filename) : relative;
333
- }
334
- async function extractProjectCandidatesWithPositions(options) {
335
- const cwd = options?.cwd ? path.resolve(options.cwd) : process2.cwd();
336
- const normalizedSources = normalizeSources(options?.sources, cwd);
337
- const { Scanner } = await importOxide();
338
- const scanner = new Scanner({
339
- sources: normalizedSources
340
- });
341
- const files = scanner.files ?? [];
342
- const entries = [];
343
- const skipped = [];
344
- for (const file of files) {
345
- let content;
346
- try {
347
- content = await fs2.readFile(file, "utf8");
348
- } catch (error) {
349
- skipped.push({
350
- file,
351
- reason: error instanceof Error ? error.message : "Unknown error"
352
- });
353
- continue;
354
- }
355
- const extension = toExtension(file);
356
- const matches = scanner.getCandidatesWithPositions({
357
- file,
358
- content,
359
- extension
360
- });
361
- if (!matches.length) {
362
- continue;
363
- }
364
- const offsets = buildLineOffsets(content);
365
- const relativeFile = toRelativeFile(cwd, file);
366
- for (const match of matches) {
367
- const info = resolveLineMeta(content, offsets, match.position);
368
- entries.push({
369
- rawCandidate: match.candidate,
370
- file,
371
- relativeFile,
372
- extension,
373
- start: match.position,
374
- end: match.position + match.candidate.length,
375
- length: match.candidate.length,
376
- line: info.line,
377
- column: info.column,
378
- lineText: info.lineText
379
- });
380
- }
381
- }
382
- return {
383
- entries,
384
- filesScanned: files.length,
385
- skippedFiles: skipped,
386
- sources: normalizedSources
387
- };
388
- }
389
- function groupTokensByFile(report, options) {
390
- const key = options?.key ?? "relative";
391
- const stripAbsolute = options?.stripAbsolutePaths ?? key !== "absolute";
392
- return report.entries.reduce((acc, entry) => {
393
- const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
394
- if (!acc[bucketKey]) {
395
- acc[bucketKey] = [];
396
- }
397
- const value = stripAbsolute ? {
398
- ...entry,
399
- file: entry.relativeFile
400
- } : entry;
401
- acc[bucketKey].push(value);
402
- return acc;
403
- }, {});
404
- }
405
-
406
- // src/options/normalize.ts
407
- import process3 from "process";
408
- import path2 from "pathe";
409
-
410
- // src/constants.ts
411
- var pkgName = "tailwindcss-patch";
412
-
413
- // src/options/normalize.ts
414
- function toPrettyValue(value) {
415
- if (typeof value === "number") {
416
- return value > 0 ? value : false;
417
- }
418
- if (value === true) {
419
- return 2;
420
- }
421
- return false;
422
- }
423
- function normalizeCacheDriver(driver) {
424
- if (driver === "memory" || driver === "noop") {
425
- return driver;
426
- }
427
- return "file";
428
- }
429
- function normalizeCacheOptions(cache, projectRoot) {
430
- let enabled = false;
431
- let cwd = projectRoot;
432
- let dir = path2.resolve(cwd, "node_modules/.cache", pkgName);
433
- let file = "class-cache.json";
434
- let strategy = "merge";
435
- let driver = "file";
436
- if (typeof cache === "boolean") {
437
- enabled = cache;
438
- } else if (typeof cache === "object" && cache) {
439
- enabled = cache.enabled ?? true;
440
- cwd = cache.cwd ?? cwd;
441
- dir = cache.dir ? path2.resolve(cache.dir) : path2.resolve(cwd, "node_modules/.cache", pkgName);
442
- file = cache.file ?? file;
443
- strategy = cache.strategy ?? strategy;
444
- driver = normalizeCacheDriver(cache.driver);
445
- }
446
- const filename = path2.resolve(dir, file);
447
- return {
448
- enabled,
449
- cwd,
450
- dir,
451
- file,
452
- path: filename,
453
- strategy,
454
- driver
455
- };
456
- }
457
- function normalizeOutputOptions(output) {
458
- const enabled = output?.enabled ?? true;
459
- const file = output?.file ?? ".tw-patch/tw-class-list.json";
460
- const format = output?.format ?? "json";
461
- const pretty = toPrettyValue(output?.pretty ?? true);
462
- const removeUniversalSelector = output?.removeUniversalSelector ?? true;
463
- return {
464
- enabled,
465
- file,
466
- format,
467
- pretty,
468
- removeUniversalSelector
469
- };
470
- }
471
- function normalizeExposeContextOptions(features) {
472
- if (features?.exposeContext === false) {
473
- return {
474
- enabled: false,
475
- refProperty: "contextRef"
476
- };
477
- }
478
- if (typeof features?.exposeContext === "object" && features.exposeContext) {
479
- return {
480
- enabled: true,
481
- refProperty: features.exposeContext.refProperty ?? "contextRef"
482
- };
483
- }
484
- return {
485
- enabled: true,
486
- refProperty: "contextRef"
487
- };
488
- }
489
- function normalizeExtendLengthUnitsOptions(features) {
490
- const extend = features?.extendLengthUnits;
491
- if (extend === false || extend === void 0) {
492
- return null;
493
- }
494
- if (extend.enabled === false) {
495
- return null;
496
- }
497
- const base = {
498
- units: ["rpx"],
499
- overwrite: true
500
- };
501
- return {
502
- ...base,
503
- ...extend,
504
- enabled: extend.enabled ?? true,
505
- units: extend.units ?? base.units,
506
- overwrite: extend.overwrite ?? base.overwrite
507
- };
508
- }
509
- function normalizeTailwindV4Options(v4, fallbackBase) {
510
- const configuredBase = v4?.base ? path2.resolve(v4.base) : void 0;
511
- const base = configuredBase ?? fallbackBase;
512
- const cssEntries = Array.isArray(v4?.cssEntries) ? v4.cssEntries.filter((entry) => Boolean(entry)).map((entry) => path2.resolve(entry)) : [];
513
- const userSources = v4?.sources;
514
- const hasUserDefinedSources = Boolean(userSources?.length);
515
- const sources = hasUserDefinedSources ? userSources : [
516
- {
517
- base: fallbackBase,
518
- pattern: "**/*",
519
- negated: false
520
- }
521
- ];
522
- return {
523
- base,
524
- configuredBase,
525
- css: v4?.css,
526
- cssEntries,
527
- sources,
528
- hasUserDefinedSources
529
- };
530
- }
531
- function normalizeTailwindOptions(tailwind, projectRoot) {
532
- const packageName = tailwind?.packageName ?? "tailwindcss";
533
- const versionHint = tailwind?.version;
534
- const resolve = tailwind?.resolve;
535
- const cwd = tailwind?.cwd ?? projectRoot;
536
- const config = tailwind?.config;
537
- const postcssPlugin = tailwind?.postcssPlugin;
538
- const v4 = normalizeTailwindV4Options(tailwind?.v4, cwd);
539
- return {
540
- packageName,
541
- versionHint,
542
- resolve,
543
- cwd,
544
- config,
545
- postcssPlugin,
546
- v2: tailwind?.v2,
547
- v3: tailwind?.v3,
548
- v4
549
- };
550
- }
551
- function normalizeOptions(options = {}) {
552
- const projectRoot = options.cwd ? path2.resolve(options.cwd) : process3.cwd();
553
- const overwrite = options.overwrite ?? true;
554
- const output = normalizeOutputOptions(options.output);
555
- const cache = normalizeCacheOptions(options.cache, projectRoot);
556
- const tailwind = normalizeTailwindOptions(options.tailwind, projectRoot);
557
- const exposeContext = normalizeExposeContextOptions(options.features);
558
- const extendLengthUnits = normalizeExtendLengthUnitsOptions(options.features);
559
- const filter = (className) => {
560
- if (output.removeUniversalSelector && className === "*") {
561
- return false;
562
- }
563
- if (typeof options.filter === "function") {
564
- return options.filter(className) !== false;
565
- }
566
- return true;
567
- };
568
- return {
569
- projectRoot,
570
- overwrite,
571
- tailwind,
572
- features: {
573
- exposeContext,
574
- extendLengthUnits
575
- },
576
- output,
577
- cache,
578
- filter
579
- };
580
- }
581
-
582
- // src/patching/status.ts
583
- import * as t4 from "@babel/types";
584
- import fs4 from "fs-extra";
585
- import path4 from "pathe";
586
-
587
- // src/babel/index.ts
588
- import _babelGenerate from "@babel/generator";
589
- import _babelTraverse from "@babel/traverse";
590
- import { parse, parseExpression } from "@babel/parser";
591
- function _interopDefaultCompat(e) {
592
- return e && typeof e === "object" && "default" in e ? e.default : e;
593
- }
594
- var generate = _interopDefaultCompat(_babelGenerate);
595
- var traverse = _interopDefaultCompat(_babelTraverse);
596
-
597
- // src/patching/operations/export-context/postcss-v2.ts
598
- import * as t from "@babel/types";
599
- var IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
600
- function toIdentifierName(property) {
601
- if (!property) {
602
- return "contextRef";
603
- }
604
- const sanitized = property.replace(/[^\w$]/gu, "_");
605
- if (/^\d/.test(sanitized)) {
606
- return `_${sanitized}`;
607
- }
608
- return sanitized || "contextRef";
609
- }
610
- function createExportsMember(property) {
611
- if (IDENTIFIER_RE.test(property)) {
612
- return t.memberExpression(t.identifier("exports"), t.identifier(property));
613
- }
614
- return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
615
- }
616
- function transformProcessTailwindFeaturesReturnContextV2(content) {
617
- const ast = parse(content, {
618
- sourceType: "unambiguous"
619
- });
620
- let hasPatched = false;
621
- traverse(ast, {
622
- FunctionDeclaration(path11) {
623
- const node = path11.node;
624
- if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) {
625
- return;
626
- }
627
- const returnStatement3 = node.body.body[0];
628
- if (!t.isFunctionExpression(returnStatement3.argument)) {
629
- return;
630
- }
631
- const body = returnStatement3.argument.body.body;
632
- const lastStatement = body[body.length - 1];
633
- const alreadyReturnsContext = Boolean(
634
- t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context"
635
- );
636
- hasPatched = alreadyReturnsContext;
637
- if (!alreadyReturnsContext) {
638
- body.push(t.returnStatement(t.identifier("context")));
639
- }
640
- }
641
- });
642
- return {
643
- code: hasPatched ? content : generate(ast).code,
644
- hasPatched
645
- };
646
- }
647
- function transformPostcssPluginV2(content, options) {
648
- const refIdentifier = t.identifier(toIdentifierName(options.refProperty));
649
- const exportMember = createExportsMember(options.refProperty);
650
- const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
651
- const ast = parse(content);
652
- let hasPatched = false;
653
- traverse(ast, {
654
- Program(path11) {
655
- const program = path11.node;
656
- const index = program.body.findIndex((statement) => {
657
- return t.isFunctionDeclaration(statement) && statement.id?.name === "_default";
658
- });
659
- if (index === -1) {
660
- return;
661
- }
662
- const previous = program.body[index - 1];
663
- const beforePrevious = program.body[index - 2];
664
- const alreadyHasVariable = Boolean(
665
- previous && t.isVariableDeclaration(previous) && previous.declarations.length === 1 && t.isIdentifier(previous.declarations[0].id) && previous.declarations[0].id.name === refIdentifier.name
666
- );
667
- const alreadyAssignsExports = Boolean(
668
- beforePrevious && t.isExpressionStatement(beforePrevious) && t.isAssignmentExpression(beforePrevious.expression) && t.isMemberExpression(beforePrevious.expression.left) && t.isIdentifier(beforePrevious.expression.right) && beforePrevious.expression.right.name === refIdentifier.name && generate(beforePrevious.expression.left).code === generate(exportMember).code
669
- );
670
- hasPatched = alreadyHasVariable && alreadyAssignsExports;
671
- if (!alreadyHasVariable) {
672
- program.body.splice(
673
- index,
674
- 0,
675
- t.variableDeclaration("var", [
676
- t.variableDeclarator(
677
- refIdentifier,
678
- t.objectExpression([
679
- t.objectProperty(t.identifier("value"), t.arrayExpression())
680
- ])
681
- )
682
- ]),
683
- t.expressionStatement(
684
- t.assignmentExpression("=", exportMember, refIdentifier)
685
- )
686
- );
687
- }
688
- },
689
- FunctionDeclaration(path11) {
690
- if (hasPatched) {
691
- return;
692
- }
693
- const fn = path11.node;
694
- if (fn.id?.name !== "_default") {
695
- return;
696
- }
697
- if (fn.body.body.length !== 1 || !t.isReturnStatement(fn.body.body[0])) {
698
- return;
699
- }
700
- const returnStatement3 = fn.body.body[0];
701
- if (!t.isCallExpression(returnStatement3.argument) || !t.isMemberExpression(returnStatement3.argument.callee) || !t.isArrayExpression(returnStatement3.argument.callee.object)) {
702
- return;
703
- }
704
- const fnExpression = returnStatement3.argument.callee.object.elements[1];
705
- if (!fnExpression || !t.isFunctionExpression(fnExpression)) {
706
- return;
707
- }
708
- const block = fnExpression.body;
709
- const statements = block.body;
710
- if (t.isExpressionStatement(statements[0]) && t.isAssignmentExpression(statements[0].expression) && t.isNumericLiteral(statements[0].expression.right)) {
711
- hasPatched = true;
712
- return;
713
- }
714
- const lastStatement = statements[statements.length - 1];
715
- if (lastStatement && t.isExpressionStatement(lastStatement)) {
716
- statements[statements.length - 1] = t.expressionStatement(
717
- t.callExpression(
718
- t.memberExpression(valueMember, t.identifier("push")),
719
- [lastStatement.expression]
720
- )
721
- );
722
- }
723
- const index = statements.findIndex((statement) => t.isIfStatement(statement));
724
- if (index > -1) {
725
- const ifStatement = statements[index];
726
- if (t.isBlockStatement(ifStatement.consequent) && ifStatement.consequent.body[1] && t.isForOfStatement(ifStatement.consequent.body[1])) {
727
- const forOf = ifStatement.consequent.body[1];
728
- if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1) {
729
- const nestedIf = forOf.body.body[0];
730
- if (nestedIf && t.isIfStatement(nestedIf) && t.isBlockStatement(nestedIf.consequent) && nestedIf.consequent.body.length === 1 && t.isExpressionStatement(nestedIf.consequent.body[0])) {
731
- nestedIf.consequent.body[0] = t.expressionStatement(
732
- t.callExpression(
733
- t.memberExpression(valueMember, t.identifier("push")),
734
- [nestedIf.consequent.body[0].expression]
735
- )
736
- );
737
- }
738
- }
739
- }
740
- }
741
- statements.unshift(
742
- t.expressionStatement(
743
- t.assignmentExpression(
744
- "=",
745
- t.memberExpression(valueMember, t.identifier("length")),
746
- t.numericLiteral(0)
747
- )
748
- )
749
- );
750
- }
751
- });
752
- return {
753
- code: hasPatched ? content : generate(ast).code,
754
- hasPatched
755
- };
756
- }
757
-
758
- // src/patching/operations/export-context/postcss-v3.ts
759
- import * as t2 from "@babel/types";
760
- var IDENTIFIER_RE2 = /^[A-Z_$][\w$]*$/i;
761
- function toIdentifierName2(property) {
762
- if (!property) {
763
- return "contextRef";
764
- }
765
- const sanitized = property.replace(/[^\w$]/gu, "_");
766
- if (/^\d/.test(sanitized)) {
767
- return `_${sanitized}`;
768
- }
769
- return sanitized || "contextRef";
770
- }
771
- function createModuleExportsMember(property) {
772
- const object = t2.memberExpression(t2.identifier("module"), t2.identifier("exports"));
773
- if (IDENTIFIER_RE2.test(property)) {
774
- return t2.memberExpression(object, t2.identifier(property));
775
- }
776
- return t2.memberExpression(object, t2.stringLiteral(property), true);
777
- }
778
- function transformProcessTailwindFeaturesReturnContext(content) {
779
- const ast = parse(content);
780
- let hasPatched = false;
781
- traverse(ast, {
782
- FunctionDeclaration(path11) {
783
- const node = path11.node;
784
- if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1) {
785
- return;
786
- }
787
- const [returnStatement3] = node.body.body;
788
- if (!t2.isReturnStatement(returnStatement3) || !t2.isFunctionExpression(returnStatement3.argument)) {
789
- return;
790
- }
791
- const expression = returnStatement3.argument;
792
- const body = expression.body.body;
793
- const lastStatement = body[body.length - 1];
794
- const alreadyReturnsContext = Boolean(
795
- t2.isReturnStatement(lastStatement) && t2.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context"
796
- );
797
- hasPatched = alreadyReturnsContext;
798
- if (!alreadyReturnsContext) {
799
- body.push(t2.returnStatement(t2.identifier("context")));
800
- }
801
- }
802
- });
803
- return {
804
- code: hasPatched ? content : generate(ast).code,
805
- hasPatched
806
- };
807
- }
808
- function transformPostcssPlugin(content, { refProperty }) {
809
- const ast = parse(content);
810
- const refIdentifier = t2.identifier(toIdentifierName2(refProperty));
811
- const moduleExportsMember = createModuleExportsMember(refProperty);
812
- const valueMember = t2.memberExpression(refIdentifier, t2.identifier("value"));
813
- let hasPatched = false;
814
- traverse(ast, {
815
- Program(path11) {
816
- const program = path11.node;
817
- const index = program.body.findIndex((statement) => {
818
- return t2.isExpressionStatement(statement) && t2.isAssignmentExpression(statement.expression) && t2.isMemberExpression(statement.expression.left) && t2.isFunctionExpression(statement.expression.right) && statement.expression.right.id?.name === "tailwindcss";
819
- });
820
- if (index === -1) {
821
- return;
822
- }
823
- const previousStatement = program.body[index - 1];
824
- const lastStatement = program.body[program.body.length - 1];
825
- const alreadyHasVariable = Boolean(
826
- previousStatement && t2.isVariableDeclaration(previousStatement) && previousStatement.declarations.length === 1 && t2.isIdentifier(previousStatement.declarations[0].id) && previousStatement.declarations[0].id.name === refIdentifier.name
827
- );
828
- const alreadyAssignsModuleExports = Boolean(
829
- t2.isExpressionStatement(lastStatement) && t2.isAssignmentExpression(lastStatement.expression) && t2.isMemberExpression(lastStatement.expression.left) && t2.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === refIdentifier.name && generate(lastStatement.expression.left).code === generate(moduleExportsMember).code
830
- );
831
- hasPatched = alreadyHasVariable && alreadyAssignsModuleExports;
832
- if (!alreadyHasVariable) {
833
- program.body.splice(
834
- index,
835
- 0,
836
- t2.variableDeclaration("const", [
837
- t2.variableDeclarator(
838
- refIdentifier,
839
- t2.objectExpression([
840
- t2.objectProperty(t2.identifier("value"), t2.arrayExpression())
841
- ])
842
- )
843
- ])
844
- );
845
- }
846
- if (!alreadyAssignsModuleExports) {
847
- program.body.push(
848
- t2.expressionStatement(
849
- t2.assignmentExpression("=", moduleExportsMember, refIdentifier)
850
- )
851
- );
852
- }
853
- },
854
- FunctionExpression(path11) {
855
- if (hasPatched) {
856
- return;
857
- }
858
- const fn = path11.node;
859
- if (fn.id?.name !== "tailwindcss" || fn.body.body.length !== 1) {
860
- return;
861
- }
862
- const [returnStatement3] = fn.body.body;
863
- if (!returnStatement3 || !t2.isReturnStatement(returnStatement3) || !t2.isObjectExpression(returnStatement3.argument)) {
864
- return;
865
- }
866
- const properties = returnStatement3.argument.properties;
867
- if (properties.length !== 2) {
868
- return;
869
- }
870
- const pluginsProperty = properties.find(
871
- (prop) => t2.isObjectProperty(prop) && t2.isIdentifier(prop.key) && prop.key.name === "plugins"
872
- );
873
- if (!pluginsProperty || !t2.isObjectProperty(pluginsProperty) || !t2.isCallExpression(pluginsProperty.value) || !t2.isMemberExpression(pluginsProperty.value.callee) || !t2.isArrayExpression(pluginsProperty.value.callee.object)) {
874
- return;
875
- }
876
- const pluginsArray = pluginsProperty.value.callee.object.elements;
877
- const targetPlugin = pluginsArray[1];
878
- if (!targetPlugin || !t2.isFunctionExpression(targetPlugin)) {
879
- return;
880
- }
881
- const block = targetPlugin.body;
882
- const statements = block.body;
883
- const last = statements[statements.length - 1];
884
- if (last && t2.isExpressionStatement(last)) {
885
- statements[statements.length - 1] = t2.expressionStatement(
886
- t2.callExpression(
887
- t2.memberExpression(valueMember, t2.identifier("push")),
888
- [last.expression]
889
- )
890
- );
891
- }
892
- const index = statements.findIndex((s) => t2.isIfStatement(s));
893
- if (index > -1) {
894
- const ifStatement = statements[index];
895
- if (t2.isBlockStatement(ifStatement.consequent)) {
896
- const [, second] = ifStatement.consequent.body;
897
- if (second && t2.isForOfStatement(second) && t2.isBlockStatement(second.body)) {
898
- const bodyStatement = second.body.body[0];
899
- if (bodyStatement && t2.isIfStatement(bodyStatement) && t2.isBlockStatement(bodyStatement.consequent) && bodyStatement.consequent.body.length === 1 && t2.isExpressionStatement(bodyStatement.consequent.body[0])) {
900
- bodyStatement.consequent.body[0] = t2.expressionStatement(
901
- t2.callExpression(
902
- t2.memberExpression(valueMember, t2.identifier("push")),
903
- [bodyStatement.consequent.body[0].expression]
904
- )
905
- );
906
- }
907
- }
908
- }
909
- }
910
- statements.unshift(
911
- t2.expressionStatement(
912
- t2.assignmentExpression(
913
- "=",
914
- t2.memberExpression(valueMember, t2.identifier("length")),
915
- t2.numericLiteral(0)
916
- )
917
- )
918
- );
919
- }
920
- });
921
- return {
922
- code: hasPatched ? content : generate(ast).code,
923
- hasPatched
924
- };
925
- }
926
-
927
- // src/patching/operations/extend-length-units.ts
928
- import * as t3 from "@babel/types";
929
- import fs3 from "fs-extra";
930
- import path3 from "pathe";
931
-
932
- // src/utils.ts
933
- function isObject(val) {
934
- return val !== null && typeof val === "object" && Array.isArray(val) === false;
935
- }
936
- function spliceChangesIntoString(str, changes) {
937
- if (!changes[0]) {
938
- return str;
939
- }
940
- changes.sort((a, b) => {
941
- return a.end - b.end || a.start - b.start;
942
- });
943
- let result = "";
944
- let previous = changes[0];
945
- result += str.slice(0, previous.start);
946
- result += previous.replacement;
947
- for (let i = 1; i < changes.length; ++i) {
948
- const change = changes[i];
949
- result += str.slice(previous.end, change.start);
950
- result += change.replacement;
951
- previous = change;
952
- }
953
- result += str.slice(previous.end);
954
- return result;
955
- }
956
-
957
- // src/patching/operations/extend-length-units.ts
958
- function updateLengthUnitsArray(content, options) {
959
- const { variableName = "lengthUnits", units } = options;
960
- const ast = parse(content);
961
- let arrayRef;
962
- let changed = false;
963
- traverse(ast, {
964
- Identifier(path11) {
965
- if (path11.node.name === variableName && t3.isVariableDeclarator(path11.parent) && t3.isArrayExpression(path11.parent.init)) {
966
- arrayRef = path11.parent.init;
967
- const existing = new Set(
968
- path11.parent.init.elements.map((element) => t3.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
969
- );
970
- for (const unit of units) {
971
- if (!existing.has(unit)) {
972
- path11.parent.init.elements = path11.parent.init.elements.map((element) => {
973
- if (t3.isStringLiteral(element)) {
974
- return t3.stringLiteral(element.value);
975
- }
976
- return element;
977
- });
978
- path11.parent.init.elements.push(t3.stringLiteral(unit));
979
- changed = true;
980
- }
981
- }
982
- }
983
- }
984
- });
985
- return {
986
- arrayRef,
987
- changed
988
- };
989
- }
990
- function applyExtendLengthUnitsPatchV3(rootDir, options) {
991
- if (!options.enabled) {
992
- return { changed: false, code: void 0 };
993
- }
994
- const opts = {
995
- ...options,
996
- lengthUnitsFilePath: options.lengthUnitsFilePath ?? "lib/util/dataTypes.js",
997
- variableName: options.variableName ?? "lengthUnits"
998
- };
999
- const dataTypesFilePath = path3.resolve(rootDir, opts.lengthUnitsFilePath);
1000
- const exists = fs3.existsSync(dataTypesFilePath);
1001
- if (!exists) {
1002
- return { changed: false, code: void 0 };
1003
- }
1004
- const content = fs3.readFileSync(dataTypesFilePath, "utf8");
1005
- const { arrayRef, changed } = updateLengthUnitsArray(content, opts);
1006
- if (!arrayRef || !changed) {
1007
- return { changed: false, code: void 0 };
1008
- }
1009
- const { code } = generate(arrayRef, {
1010
- jsescOption: { quotes: "single" }
1011
- });
1012
- if (arrayRef.start != null && arrayRef.end != null) {
1013
- const nextCode = `${content.slice(0, arrayRef.start)}${code}${content.slice(arrayRef.end)}`;
1014
- if (opts.overwrite) {
1015
- const target = opts.destPath ? path3.resolve(opts.destPath) : dataTypesFilePath;
1016
- fs3.writeFileSync(target, nextCode, "utf8");
1017
- logger_default.success("Patched Tailwind CSS length unit list (v3).");
1018
- }
1019
- return {
1020
- changed: true,
1021
- code: nextCode
1022
- };
1023
- }
1024
- return {
1025
- changed: false,
1026
- code: void 0
1027
- };
1028
- }
1029
- function applyExtendLengthUnitsPatchV4(rootDir, options) {
1030
- if (!options.enabled) {
1031
- return { files: [], changed: false };
1032
- }
1033
- const opts = { ...options };
1034
- const distDir = path3.resolve(rootDir, "dist");
1035
- if (!fs3.existsSync(distDir)) {
1036
- return { files: [], changed: false };
1037
- }
1038
- const entries = fs3.readdirSync(distDir);
1039
- const chunkNames = entries.filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs"));
1040
- const pattern = /\[\s*["']cm["'],\s*["']mm["'],[\w,"']+\]/;
1041
- const candidates = chunkNames.map((chunkName) => {
1042
- const file = path3.join(distDir, chunkName);
1043
- const code = fs3.readFileSync(file, "utf8");
1044
- const match = pattern.exec(code);
1045
- if (!match) {
1046
- return null;
1047
- }
1048
- return {
1049
- file,
1050
- code,
1051
- match,
1052
- hasPatched: false
1053
- };
1054
- }).filter((candidate) => candidate !== null);
1055
- for (const item of candidates) {
1056
- const { code, file, match } = item;
1057
- const ast = parse(match[0], { sourceType: "unambiguous" });
1058
- traverse(ast, {
1059
- ArrayExpression(path11) {
1060
- for (const unit of opts.units) {
1061
- if (path11.node.elements.some((element) => t3.isStringLiteral(element) && element.value === unit)) {
1062
- item.hasPatched = true;
1063
- return;
1064
- }
1065
- path11.node.elements.push(t3.stringLiteral(unit));
1066
- }
1067
- }
1068
- });
1069
- if (item.hasPatched) {
1070
- continue;
1071
- }
1072
- const { code: replacement } = generate(ast, { minified: true });
1073
- const start = match.index ?? 0;
1074
- const end = start + match[0].length;
1075
- item.code = spliceChangesIntoString(code, [
1076
- {
1077
- start,
1078
- end,
1079
- replacement: replacement.endsWith(";") ? replacement.slice(0, -1) : replacement
1080
- }
1081
- ]);
1082
- if (opts.overwrite) {
1083
- fs3.writeFileSync(file, item.code, "utf8");
1084
- }
1085
- }
1086
- if (candidates.some((file) => !file.hasPatched)) {
1087
- logger_default.success("Patched Tailwind CSS length unit list (v4).");
1088
- }
1089
- return {
1090
- changed: candidates.some((file) => !file.hasPatched),
1091
- files: candidates
1092
- };
1093
- }
1094
-
1095
- // src/patching/status.ts
1096
- function inspectLengthUnitsArray(content, variableName, units) {
1097
- const ast = parse(content);
1098
- let found = false;
1099
- let missingUnits = [];
1100
- traverse(ast, {
1101
- Identifier(path11) {
1102
- if (path11.node.name === variableName && t4.isVariableDeclarator(path11.parent) && t4.isArrayExpression(path11.parent.init)) {
1103
- found = true;
1104
- const existing = new Set(
1105
- path11.parent.init.elements.map((element) => t4.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
1106
- );
1107
- missingUnits = units.filter((unit) => !existing.has(unit));
1108
- path11.stop();
1109
- }
1110
- }
1111
- });
1112
- return {
1113
- found,
1114
- missingUnits
1115
- };
1116
- }
1117
- function checkExposeContextPatch(context) {
1118
- const { packageInfo, options, majorVersion } = context;
1119
- const refProperty = options.features.exposeContext.refProperty;
1120
- if (!options.features.exposeContext.enabled) {
1121
- return {
1122
- name: "exposeContext",
1123
- status: "skipped",
1124
- reason: "exposeContext feature disabled",
1125
- files: []
1126
- };
1127
- }
1128
- if (majorVersion === 4) {
1129
- return {
1130
- name: "exposeContext",
1131
- status: "unsupported",
1132
- reason: "Context export patch is only required for Tailwind v2/v3",
1133
- files: []
1134
- };
1135
- }
1136
- const checks = [];
1137
- function inspectFile(relative, transform) {
1138
- const filePath = path4.resolve(packageInfo.rootPath, relative);
1139
- if (!fs4.existsSync(filePath)) {
1140
- checks.push({ relative, exists: false, patched: false });
1141
- return;
1142
- }
1143
- const content = fs4.readFileSync(filePath, "utf8");
1144
- const { hasPatched } = transform(content);
1145
- checks.push({
1146
- relative,
1147
- exists: true,
1148
- patched: hasPatched
1149
- });
1150
- }
1151
- if (majorVersion === 3) {
1152
- inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
1153
- const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
1154
- const pluginRelative = pluginCandidates.find((candidate) => fs4.existsSync(path4.resolve(packageInfo.rootPath, candidate)));
1155
- if (pluginRelative) {
1156
- inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
1157
- } else {
1158
- checks.push({ relative: "lib/plugin.js", exists: false, patched: false });
1159
- }
1160
- } else {
1161
- inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
1162
- inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
1163
- }
1164
- const files = checks.filter((check) => check.exists).map((check) => check.relative);
1165
- const missingFiles = checks.filter((check) => !check.exists);
1166
- const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
1167
- const reasons = [];
1168
- if (missingFiles.length) {
1169
- reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
1170
- }
1171
- if (unpatchedFiles.length) {
1172
- reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
1173
- }
1174
- return {
1175
- name: "exposeContext",
1176
- status: reasons.length ? "not-applied" : "applied",
1177
- reason: reasons.length ? reasons.join("; ") : void 0,
1178
- files
1179
- };
1180
- }
1181
- function checkExtendLengthUnitsV3(rootDir, options) {
1182
- const lengthUnitsFilePath = options.lengthUnitsFilePath ?? "lib/util/dataTypes.js";
1183
- const variableName = options.variableName ?? "lengthUnits";
1184
- const target = path4.resolve(rootDir, lengthUnitsFilePath);
1185
- const files = fs4.existsSync(target) ? [path4.relative(rootDir, target)] : [];
1186
- if (!fs4.existsSync(target)) {
1187
- return {
1188
- name: "extendLengthUnits",
1189
- status: "not-applied",
1190
- reason: `missing ${lengthUnitsFilePath}`,
1191
- files
1192
- };
1193
- }
1194
- const content = fs4.readFileSync(target, "utf8");
1195
- const { found, missingUnits } = inspectLengthUnitsArray(content, variableName, options.units);
1196
- if (!found) {
1197
- return {
1198
- name: "extendLengthUnits",
1199
- status: "not-applied",
1200
- reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
1201
- files
1202
- };
1203
- }
1204
- if (missingUnits.length) {
1205
- return {
1206
- name: "extendLengthUnits",
1207
- status: "not-applied",
1208
- reason: `missing units: ${missingUnits.join(", ")}`,
1209
- files
1210
- };
1211
- }
1212
- return {
1213
- name: "extendLengthUnits",
1214
- status: "applied",
1215
- files
1216
- };
1217
- }
1218
- function checkExtendLengthUnitsV4(rootDir, options) {
1219
- const distDir = path4.resolve(rootDir, "dist");
1220
- if (!fs4.existsSync(distDir)) {
1221
- return {
1222
- name: "extendLengthUnits",
1223
- status: "not-applied",
1224
- reason: "dist directory not found for Tailwind v4 package",
1225
- files: []
1226
- };
1227
- }
1228
- const result = applyExtendLengthUnitsPatchV4(rootDir, {
1229
- ...options,
1230
- enabled: true,
1231
- overwrite: false
1232
- });
1233
- if (result.files.length === 0) {
1234
- return {
1235
- name: "extendLengthUnits",
1236
- status: "not-applied",
1237
- reason: "no bundle chunks matched the length unit pattern",
1238
- files: []
1239
- };
1240
- }
1241
- const files = result.files.map((file) => path4.relative(rootDir, file.file));
1242
- const pending = result.files.filter((file) => !file.hasPatched);
1243
- if (pending.length) {
1244
- return {
1245
- name: "extendLengthUnits",
1246
- status: "not-applied",
1247
- reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
1248
- files: pending.map((file) => path4.relative(rootDir, file.file))
1249
- };
1250
- }
1251
- return {
1252
- name: "extendLengthUnits",
1253
- status: "applied",
1254
- files
1255
- };
1256
- }
1257
- function checkExtendLengthUnitsPatch(context) {
1258
- const { packageInfo, options, majorVersion } = context;
1259
- if (!options.features.extendLengthUnits) {
1260
- return {
1261
- name: "extendLengthUnits",
1262
- status: "skipped",
1263
- reason: "extendLengthUnits feature disabled",
1264
- files: []
1265
- };
1266
- }
1267
- if (majorVersion === 2) {
1268
- return {
1269
- name: "extendLengthUnits",
1270
- status: "unsupported",
1271
- reason: "length unit extension is only applied for Tailwind v3/v4",
1272
- files: []
1273
- };
1274
- }
1275
- if (majorVersion === 3) {
1276
- return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
1277
- }
1278
- return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
1279
- }
1280
- function getPatchStatusReport(context) {
1281
- return {
1282
- package: {
1283
- name: context.packageInfo.name ?? context.packageInfo.packageJson?.name,
1284
- version: context.packageInfo.version,
1285
- root: context.packageInfo.rootPath
1286
- },
1287
- majorVersion: context.majorVersion,
1288
- entries: [
1289
- checkExposeContextPatch(context),
1290
- checkExtendLengthUnitsPatch(context)
1291
- ]
1292
- };
1293
- }
1294
-
1295
- // src/runtime/class-collector.ts
1296
- import process4 from "process";
1297
- import fs5 from "fs-extra";
1298
- import path5 from "pathe";
1299
- function collectClassesFromContexts(contexts, filter) {
1300
- const set = /* @__PURE__ */ new Set();
1301
- for (const context of contexts) {
1302
- if (!isObject(context) || !context.classCache) {
1303
- continue;
1304
- }
1305
- for (const key of context.classCache.keys()) {
1306
- const className = key.toString();
1307
- if (filter(className)) {
1308
- set.add(className);
1309
- }
1310
- }
1311
- }
1312
- return set;
1313
- }
1314
- async function collectClassesFromTailwindV4(options) {
1315
- const set = /* @__PURE__ */ new Set();
1316
- const v4Options = options.tailwind.v4;
1317
- if (!v4Options) {
1318
- return set;
1319
- }
1320
- const toAbsolute = (value) => {
1321
- if (!value) {
1322
- return void 0;
1323
- }
1324
- return path5.isAbsolute(value) ? value : path5.resolve(options.projectRoot, value);
1325
- };
1326
- const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
1327
- const resolvedDefaultBase = toAbsolute(v4Options.base) ?? process4.cwd();
1328
- const resolveSources = (base) => {
1329
- if (!v4Options.sources?.length) {
1330
- return void 0;
1331
- }
1332
- return v4Options.sources.map((source) => ({
1333
- base: source.base ?? base,
1334
- pattern: source.pattern,
1335
- negated: source.negated
1336
- }));
1337
- };
1338
- if (v4Options.cssEntries.length > 0) {
1339
- for (const entry of v4Options.cssEntries) {
1340
- const filePath = path5.isAbsolute(entry) ? entry : path5.resolve(options.projectRoot, entry);
1341
- if (!await fs5.pathExists(filePath)) {
1342
- continue;
1343
- }
1344
- const css = await fs5.readFile(filePath, "utf8");
1345
- const entryDir = path5.dirname(filePath);
1346
- const baseForEntry = resolvedConfiguredBase ?? entryDir;
1347
- const sources = resolveSources(baseForEntry);
1348
- const candidates = await extractValidCandidates({
1349
- cwd: options.projectRoot,
1350
- base: baseForEntry,
1351
- css,
1352
- sources
1353
- });
1354
- for (const candidate of candidates) {
1355
- if (options.filter(candidate)) {
1356
- set.add(candidate);
1357
- }
1358
- }
1359
- }
1360
- } else {
1361
- const baseForCss = resolvedConfiguredBase ?? resolvedDefaultBase;
1362
- const sources = resolveSources(baseForCss);
1363
- const candidates = await extractValidCandidates({
1364
- cwd: options.projectRoot,
1365
- base: baseForCss,
1366
- css: v4Options.css,
1367
- sources
1368
- });
1369
- for (const candidate of candidates) {
1370
- if (options.filter(candidate)) {
1371
- set.add(candidate);
1372
- }
1373
- }
1374
- }
1375
- return set;
1376
- }
1377
-
1378
- // src/runtime/context-registry.ts
1379
- import { createRequire } from "module";
1380
- import fs6 from "fs-extra";
1381
- import path6 from "pathe";
1382
- var require2 = createRequire(import.meta.url);
1383
- function resolveRuntimeEntry(packageInfo, majorVersion) {
1384
- const root = packageInfo.rootPath;
1385
- if (majorVersion === 2) {
1386
- const jitIndex = path6.join(root, "lib/jit/index.js");
1387
- if (fs6.existsSync(jitIndex)) {
1388
- return jitIndex;
1389
- }
1390
- } else if (majorVersion === 3) {
1391
- const plugin = path6.join(root, "lib/plugin.js");
1392
- const index = path6.join(root, "lib/index.js");
1393
- if (fs6.existsSync(plugin)) {
1394
- return plugin;
1395
- }
1396
- if (fs6.existsSync(index)) {
1397
- return index;
1398
- }
1399
- }
1400
- return void 0;
1401
- }
1402
- function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
1403
- if (majorVersion === 4) {
1404
- return [];
1405
- }
1406
- const entry = resolveRuntimeEntry(packageInfo, majorVersion);
1407
- if (!entry) {
1408
- return [];
1409
- }
1410
- const moduleExports = require2(entry);
1411
- if (!moduleExports) {
1412
- return [];
1413
- }
1414
- const ref = moduleExports[refProperty];
1415
- if (!ref) {
1416
- return [];
1417
- }
1418
- if (Array.isArray(ref)) {
1419
- return ref;
1420
- }
1421
- if (typeof ref === "object" && Array.isArray(ref.value)) {
1422
- return ref.value;
1423
- }
1424
- return [];
1425
- }
1426
-
1427
- // src/runtime/process-tailwindcss.ts
1428
- import { createRequire as createRequire2 } from "module";
1429
- import path7 from "pathe";
1430
- import postcss from "postcss";
1431
- import { loadConfig } from "tailwindcss-config";
1432
- var require3 = createRequire2(import.meta.url);
1433
- async function resolveConfigPath(options) {
1434
- if (options.config && path7.isAbsolute(options.config)) {
1435
- return options.config;
1436
- }
1437
- const result = await loadConfig({ cwd: options.cwd });
1438
- if (!result) {
1439
- throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
1440
- }
1441
- return result.filepath;
1442
- }
1443
- async function runTailwindBuild(options) {
1444
- const configPath = await resolveConfigPath(options);
1445
- const pluginName = options.postcssPlugin ?? (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
1446
- if (options.majorVersion === 4) {
1447
- return postcss([
1448
- require3(pluginName)({
1449
- config: configPath
1450
- })
1451
- ]).process("@import 'tailwindcss';", {
1452
- from: void 0
1453
- });
1454
- }
1455
- return postcss([
1456
- require3(pluginName)({
1457
- config: configPath
1458
- })
1459
- ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
1460
- from: void 0
1461
- });
1462
- }
1463
-
1464
- // src/api/tailwindcss-patcher.ts
1465
- import process5 from "process";
1466
- import fs8 from "fs-extra";
1467
- import { getPackageInfoSync } from "local-pkg";
1468
- import path9 from "pathe";
1469
- import { coerce } from "semver";
1470
-
1471
- // src/options/legacy.ts
1472
- function normalizeLegacyFeatures(patch) {
1473
- const apply = patch?.applyPatches;
1474
- const extend = apply?.extendLengthUnits;
1475
- let extendOption = false;
1476
- if (extend && typeof extend === "object") {
1477
- extendOption = {
1478
- ...extend,
1479
- enabled: true
1480
- };
1481
- } else if (extend === true) {
1482
- extendOption = {
1483
- enabled: true,
1484
- units: ["rpx"],
1485
- overwrite: patch?.overwrite
1486
- };
1487
- }
1488
- return {
1489
- exposeContext: apply?.exportContext ?? true,
1490
- extendLengthUnits: extendOption
1491
- };
1492
- }
1493
- function fromLegacyOptions(options) {
1494
- if (!options) {
1495
- return {};
1496
- }
1497
- const patch = options.patch;
1498
- const features = normalizeLegacyFeatures(patch);
1499
- const output = patch?.output;
1500
- const tailwindConfig = patch?.tailwindcss;
1501
- const tailwindVersion = tailwindConfig?.version;
1502
- const tailwindV2 = tailwindConfig?.v2;
1503
- const tailwindV3 = tailwindConfig?.v3;
1504
- const tailwindV4 = tailwindConfig?.v4;
1505
- const tailwindConfigPath = tailwindV3?.config ?? tailwindV2?.config;
1506
- const tailwindCwd = tailwindV3?.cwd ?? tailwindV2?.cwd ?? patch?.cwd;
1507
- return {
1508
- cwd: patch?.cwd,
1509
- overwrite: patch?.overwrite,
1510
- filter: patch?.filter,
1511
- cache: typeof options.cache === "boolean" ? options.cache : options.cache ? {
1512
- ...options.cache,
1513
- enabled: options.cache.enabled ?? true
1514
- } : void 0,
1515
- output: output ? {
1516
- file: output.filename,
1517
- pretty: output.loose ? 2 : false,
1518
- removeUniversalSelector: output.removeUniversalSelector
1519
- } : void 0,
1520
- tailwind: {
1521
- packageName: patch?.packageName,
1522
- version: tailwindVersion,
1523
- resolve: patch?.resolve,
1524
- config: tailwindConfigPath,
1525
- cwd: tailwindCwd,
1526
- v2: tailwindV2,
1527
- v3: tailwindV3,
1528
- v4: tailwindV4
1529
- },
1530
- features: {
1531
- exposeContext: features.exposeContext,
1532
- extendLengthUnits: features.extendLengthUnits
1533
- }
1534
- };
1535
- }
1536
- function fromUnifiedConfig(registry) {
1537
- if (!registry) {
1538
- return {};
1539
- }
1540
- const tailwind = registry.tailwind;
1541
- const output = registry.output;
1542
- const pretty = (() => {
1543
- if (output?.pretty === void 0) {
1544
- return void 0;
1545
- }
1546
- if (typeof output.pretty === "boolean") {
1547
- return output.pretty ? 2 : false;
1548
- }
1549
- return output.pretty;
1550
- })();
1551
- return {
1552
- output: output ? {
1553
- file: output.file,
1554
- pretty,
1555
- removeUniversalSelector: output.stripUniversalSelector
1556
- } : void 0,
1557
- tailwind: tailwind ? {
1558
- version: tailwind.version,
1559
- packageName: tailwind.package,
1560
- resolve: tailwind.resolve,
1561
- config: tailwind.config,
1562
- cwd: tailwind.cwd,
1563
- v2: tailwind.legacy,
1564
- v3: tailwind.classic,
1565
- v4: tailwind.next
1566
- } : void 0
1567
- };
1568
- }
1569
-
1570
- // src/patching/operations/export-context/index.ts
1571
- import fs7 from "fs-extra";
1572
- import path8 from "pathe";
1573
- function writeFileIfRequired(filePath, code, overwrite, successMessage) {
1574
- if (!overwrite) {
1575
- return;
1576
- }
1577
- fs7.writeFileSync(filePath, code, {
1578
- encoding: "utf8"
1579
- });
1580
- logger_default.success(successMessage);
1581
- }
1582
- function applyExposeContextPatch(params) {
1583
- const { rootDir, refProperty, overwrite, majorVersion } = params;
1584
- const result = {
1585
- applied: false,
1586
- files: {}
1587
- };
1588
- if (majorVersion === 3) {
1589
- const processFileRelative = "lib/processTailwindFeatures.js";
1590
- const processFilePath = path8.resolve(rootDir, processFileRelative);
1591
- if (fs7.existsSync(processFilePath)) {
1592
- const content = fs7.readFileSync(processFilePath, "utf8");
1593
- const { code, hasPatched } = transformProcessTailwindFeaturesReturnContext(content);
1594
- result.files[processFileRelative] = code;
1595
- if (!hasPatched) {
1596
- writeFileIfRequired(
1597
- processFilePath,
1598
- code,
1599
- overwrite,
1600
- "Patched Tailwind CSS processTailwindFeatures to expose runtime context."
1601
- );
1602
- result.applied = true;
1603
- }
1604
- }
1605
- const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
1606
- const pluginRelative = pluginCandidates.find((candidate) => fs7.existsSync(path8.resolve(rootDir, candidate)));
1607
- if (pluginRelative) {
1608
- const pluginPath = path8.resolve(rootDir, pluginRelative);
1609
- const content = fs7.readFileSync(pluginPath, "utf8");
1610
- const { code, hasPatched } = transformPostcssPlugin(content, { refProperty });
1611
- result.files[pluginRelative] = code;
1612
- if (!hasPatched) {
1613
- writeFileIfRequired(
1614
- pluginPath,
1615
- code,
1616
- overwrite,
1617
- "Patched Tailwind CSS plugin entry to collect runtime contexts."
1618
- );
1619
- result.applied = true;
1620
- }
1621
- }
1622
- } else if (majorVersion === 2) {
1623
- const processFileRelative = "lib/jit/processTailwindFeatures.js";
1624
- const processFilePath = path8.resolve(rootDir, processFileRelative);
1625
- if (fs7.existsSync(processFilePath)) {
1626
- const content = fs7.readFileSync(processFilePath, "utf8");
1627
- const { code, hasPatched } = transformProcessTailwindFeaturesReturnContextV2(content);
1628
- result.files[processFileRelative] = code;
1629
- if (!hasPatched) {
1630
- writeFileIfRequired(
1631
- processFilePath,
1632
- code,
1633
- overwrite,
1634
- "Patched Tailwind CSS JIT processTailwindFeatures to expose runtime context."
1635
- );
1636
- result.applied = true;
1637
- }
1638
- }
1639
- const pluginRelative = "lib/jit/index.js";
1640
- const pluginPath = path8.resolve(rootDir, pluginRelative);
1641
- if (fs7.existsSync(pluginPath)) {
1642
- const content = fs7.readFileSync(pluginPath, "utf8");
1643
- const { code, hasPatched } = transformPostcssPluginV2(content, { refProperty });
1644
- result.files[pluginRelative] = code;
1645
- if (!hasPatched) {
1646
- writeFileIfRequired(
1647
- pluginPath,
1648
- code,
1649
- overwrite,
1650
- "Patched Tailwind CSS JIT entry to collect runtime contexts."
1651
- );
1652
- result.applied = true;
1653
- }
1654
- }
1655
- }
1656
- return result;
1657
- }
1658
-
1659
- // src/patching/patch-runner.ts
1660
- function applyTailwindPatches(context) {
1661
- const { packageInfo, options, majorVersion } = context;
1662
- const results = {};
1663
- if (options.features.exposeContext.enabled && (majorVersion === 2 || majorVersion === 3)) {
1664
- results.exposeContext = applyExposeContextPatch({
1665
- rootDir: packageInfo.rootPath,
1666
- refProperty: options.features.exposeContext.refProperty,
1667
- overwrite: options.overwrite,
1668
- majorVersion
1669
- });
1670
- }
1671
- if (options.features.extendLengthUnits?.enabled) {
1672
- if (majorVersion === 3) {
1673
- results.extendLengthUnits = applyExtendLengthUnitsPatchV3(
1674
- packageInfo.rootPath,
1675
- options.features.extendLengthUnits
1676
- );
1677
- } else if (majorVersion === 4) {
1678
- results.extendLengthUnits = applyExtendLengthUnitsPatchV4(
1679
- packageInfo.rootPath,
1680
- options.features.extendLengthUnits
1681
- );
1682
- }
1683
- }
1684
- return results;
1685
- }
1686
-
1687
- // src/api/tailwindcss-patcher.ts
1688
- function resolveMajorVersion(version, hint) {
1689
- if (hint && [2, 3, 4].includes(hint)) {
1690
- return hint;
1691
- }
1692
- if (version) {
1693
- const coerced = coerce(version);
1694
- if (coerced) {
1695
- const major = coerced.major;
1696
- if (major === 2 || major === 3 || major === 4) {
1697
- return major;
1698
- }
1699
- if (major >= 4) {
1700
- return 4;
1701
- }
1702
- }
1703
- }
1704
- return 3;
1705
- }
1706
- function resolveTailwindExecutionOptions(normalized, majorVersion) {
1707
- const base = normalized.tailwind;
1708
- if (majorVersion === 2 && base.v2) {
1709
- return {
1710
- cwd: base.v2.cwd ?? base.cwd ?? normalized.projectRoot,
1711
- config: base.v2.config ?? base.config,
1712
- postcssPlugin: base.v2.postcssPlugin ?? base.postcssPlugin
1713
- };
1714
- }
1715
- if (majorVersion === 3 && base.v3) {
1716
- return {
1717
- cwd: base.v3.cwd ?? base.cwd ?? normalized.projectRoot,
1718
- config: base.v3.config ?? base.config,
1719
- postcssPlugin: base.v3.postcssPlugin ?? base.postcssPlugin
1720
- };
1721
- }
1722
- return {
1723
- cwd: base.cwd ?? normalized.projectRoot,
1724
- config: base.config,
1725
- postcssPlugin: base.postcssPlugin
1726
- };
1727
- }
1728
- var TailwindcssPatcher = class {
1729
- options;
1730
- packageInfo;
1731
- majorVersion;
1732
- cacheStore;
1733
- constructor(options = {}) {
1734
- const resolvedOptions = options && typeof options === "object" && "patch" in options ? fromLegacyOptions(options) : options;
1735
- this.options = normalizeOptions(resolvedOptions);
1736
- const packageInfo = getPackageInfoSync(
1737
- this.options.tailwind.packageName,
1738
- this.options.tailwind.resolve
1739
- );
1740
- if (!packageInfo) {
1741
- throw new Error(`Unable to locate Tailwind CSS package "${this.options.tailwind.packageName}".`);
1742
- }
1743
- this.packageInfo = packageInfo;
1744
- this.majorVersion = resolveMajorVersion(
1745
- this.packageInfo.version,
1746
- this.options.tailwind.versionHint
1747
- );
1748
- this.cacheStore = new CacheStore(this.options.cache);
1749
- }
1750
- async patch() {
1751
- return applyTailwindPatches({
1752
- packageInfo: this.packageInfo,
1753
- options: this.options,
1754
- majorVersion: this.majorVersion
1755
- });
1756
- }
1757
- async getPatchStatus() {
1758
- return getPatchStatusReport({
1759
- packageInfo: this.packageInfo,
1760
- options: this.options,
1761
- majorVersion: this.majorVersion
1762
- });
1763
- }
1764
- getContexts() {
1765
- return loadRuntimeContexts(
1766
- this.packageInfo,
1767
- this.majorVersion,
1768
- this.options.features.exposeContext.refProperty
1769
- );
1770
- }
1771
- async runTailwindBuildIfNeeded() {
1772
- if (this.majorVersion === 2 || this.majorVersion === 3) {
1773
- const executionOptions = resolveTailwindExecutionOptions(this.options, this.majorVersion);
1774
- await runTailwindBuild({
1775
- cwd: executionOptions.cwd,
1776
- config: executionOptions.config,
1777
- majorVersion: this.majorVersion,
1778
- postcssPlugin: executionOptions.postcssPlugin
1779
- });
1780
- }
1781
- }
1782
- async collectClassSet() {
1783
- if (this.majorVersion === 4) {
1784
- return collectClassesFromTailwindV4(this.options);
1785
- }
1786
- const contexts = this.getContexts();
1787
- return collectClassesFromContexts(contexts, this.options.filter);
1788
- }
1789
- async mergeWithCache(set) {
1790
- if (!this.options.cache.enabled) {
1791
- return set;
1792
- }
1793
- const existing = await this.cacheStore.read();
1794
- if (this.options.cache.strategy === "merge") {
1795
- for (const value of existing) {
1796
- set.add(value);
1797
- }
1798
- await this.cacheStore.write(set);
1799
- } else {
1800
- if (set.size > 0) {
1801
- await this.cacheStore.write(set);
1802
- } else {
1803
- return existing;
1804
- }
1805
- }
1806
- return set;
1807
- }
1808
- mergeWithCacheSync(set) {
1809
- if (!this.options.cache.enabled) {
1810
- return set;
1811
- }
1812
- const existing = this.cacheStore.readSync();
1813
- if (this.options.cache.strategy === "merge") {
1814
- for (const value of existing) {
1815
- set.add(value);
1816
- }
1817
- this.cacheStore.writeSync(set);
1818
- } else {
1819
- if (set.size > 0) {
1820
- this.cacheStore.writeSync(set);
1821
- } else {
1822
- return existing;
1823
- }
1824
- }
1825
- return set;
1826
- }
1827
- async getClassSet() {
1828
- await this.runTailwindBuildIfNeeded();
1829
- const set = await this.collectClassSet();
1830
- return this.mergeWithCache(set);
1831
- }
1832
- getClassSetSync() {
1833
- if (this.majorVersion === 4) {
1834
- throw new Error("getClassSetSync is not supported for Tailwind CSS v4 projects. Use getClassSet instead.");
1835
- }
1836
- const contexts = this.getContexts();
1837
- const set = collectClassesFromContexts(contexts, this.options.filter);
1838
- const merged = this.mergeWithCacheSync(set);
1839
- if (contexts.length === 0 && merged.size === 0) {
1840
- return void 0;
1841
- }
1842
- return merged;
1843
- }
1844
- async extract(options) {
1845
- const shouldWrite = options?.write ?? this.options.output.enabled;
1846
- const classSet = await this.getClassSet();
1847
- const classList = Array.from(classSet);
1848
- const result = {
1849
- classList,
1850
- classSet
1851
- };
1852
- if (!shouldWrite || !this.options.output.file) {
1853
- return result;
1854
- }
1855
- const target = path9.resolve(this.options.output.file);
1856
- await fs8.ensureDir(path9.dirname(target));
1857
- if (this.options.output.format === "json") {
1858
- const spaces = typeof this.options.output.pretty === "number" ? this.options.output.pretty : void 0;
1859
- await fs8.writeJSON(target, classList, { spaces });
1860
- } else {
1861
- await fs8.writeFile(target, `${classList.join("\n")}
1862
- `, "utf8");
1863
- }
1864
- logger_default.success(`Tailwind CSS class list saved to ${target.replace(process5.cwd(), ".")}`);
1865
- return {
1866
- ...result,
1867
- filename: target
1868
- };
1869
- }
1870
- // Backwards compatibility helper used by tests and API consumers.
1871
- extractValidCandidates = extractValidCandidates;
1872
- async collectContentTokens(options) {
1873
- return extractProjectCandidatesWithPositions({
1874
- cwd: options?.cwd ?? this.options.projectRoot,
1875
- sources: options?.sources ?? this.options.tailwind.v4?.sources ?? []
1876
- });
1877
- }
1878
- async collectContentTokensByFile(options) {
1879
- const report = await this.collectContentTokens({
1880
- cwd: options?.cwd,
1881
- sources: options?.sources
1882
- });
1883
- return groupTokensByFile(report, {
1884
- key: options?.key,
1885
- stripAbsolutePaths: options?.stripAbsolutePaths
1886
- });
1887
- }
1888
- };
1889
-
1890
- // src/cli/commands.ts
1891
- import process6 from "process";
1892
- import { CONFIG_NAME, getConfig, initConfig } from "@tailwindcss-mangle/config";
1893
-
1894
- // ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
1895
- function isPlainObject(value) {
1896
- if (value === null || typeof value !== "object") {
1897
- return false;
1898
- }
1899
- const prototype = Object.getPrototypeOf(value);
1900
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
1901
- return false;
1902
- }
1903
- if (Symbol.iterator in value) {
1904
- return false;
1905
- }
1906
- if (Symbol.toStringTag in value) {
1907
- return Object.prototype.toString.call(value) === "[object Module]";
1908
- }
1909
- return true;
1910
- }
1911
- function _defu(baseObject, defaults, namespace = ".", merger) {
1912
- if (!isPlainObject(defaults)) {
1913
- return _defu(baseObject, {}, namespace, merger);
1914
- }
1915
- const object = Object.assign({}, defaults);
1916
- for (const key in baseObject) {
1917
- if (key === "__proto__" || key === "constructor") {
1918
- continue;
1919
- }
1920
- const value = baseObject[key];
1921
- if (value === null || value === void 0) {
1922
- continue;
1923
- }
1924
- if (merger && merger(object, key, value, namespace)) {
1925
- continue;
1926
- }
1927
- if (Array.isArray(value) && Array.isArray(object[key])) {
1928
- object[key] = [...value, ...object[key]];
1929
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
1930
- object[key] = _defu(
1931
- value,
1932
- object[key],
1933
- (namespace ? `${namespace}.` : "") + key.toString(),
1934
- merger
1935
- );
1936
- } else {
1937
- object[key] = value;
1938
- }
1939
- }
1940
- return object;
1941
- }
1942
- function createDefu(merger) {
1943
- return (...arguments_) => (
1944
- // eslint-disable-next-line unicorn/no-array-reduce
1945
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
1946
- );
1947
- }
1948
- var defu = createDefu();
1949
- var defuFn = createDefu((object, key, currentValue) => {
1950
- if (object[key] !== void 0 && typeof currentValue === "function") {
1951
- object[key] = currentValue(object[key]);
1952
- return true;
1953
- }
1954
- });
1955
- var defuArrayFn = createDefu((object, key, currentValue) => {
1956
- if (Array.isArray(object[key]) && typeof currentValue === "function") {
1957
- object[key] = currentValue(object[key]);
1958
- return true;
1959
- }
1960
- });
1961
-
1962
- // ../shared/src/utils.ts
1963
- var defuOverrideArray = createDefu((obj, key, value) => {
1964
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
1965
- obj[key] = value;
1966
- return true;
1967
- }
1968
- });
1969
- var preserveClassNames = [
1970
- // https://tailwindcss.com/docs/transition-timing-function start
1971
- // https://github.com/sonofmagic/tailwindcss-mangle/issues/21
1972
- "ease-out",
1973
- "ease-linear",
1974
- "ease-in",
1975
- "ease-in-out"
1976
- // https://tailwindcss.com/docs/transition-timing-function end
1977
- ];
1978
- var preserveClassNamesMap = preserveClassNames.reduce((acc, cur) => {
1979
- acc[cur] = true;
1980
- return acc;
1981
- }, {});
1982
- var acceptChars = [..."abcdefghijklmnopqrstuvwxyz"];
1983
-
1984
- // src/cli/commands.ts
1985
- import cac from "cac";
1986
- import fs9 from "fs-extra";
1987
- import path10 from "pathe";
1988
- var tailwindcssPatchCommands = ["install", "extract", "tokens", "init", "status"];
1989
- var TOKEN_FORMATS = ["json", "lines", "grouped-json"];
1990
- var DEFAULT_TOKEN_REPORT = ".tw-patch/tw-token-report.json";
1991
- function formatTokenLine(entry) {
1992
- return `${entry.relativeFile}:${entry.line}:${entry.column} ${entry.rawCandidate} (${entry.start}-${entry.end})`;
1993
- }
1994
- function formatGroupedPreview(map, limit = 3) {
1995
- const files = Object.keys(map);
1996
- if (!files.length) {
1997
- return { preview: "", moreFiles: 0 };
1998
- }
1999
- const lines = files.slice(0, limit).map((file) => {
2000
- const tokens = map[file];
2001
- const sample = tokens.slice(0, 3).map((token) => token.rawCandidate).join(", ");
2002
- const suffix = tokens.length > 3 ? ", \u2026" : "";
2003
- return `${file}: ${tokens.length} tokens (${sample}${suffix})`;
2004
- });
2005
- return {
2006
- preview: lines.join("\n"),
2007
- moreFiles: Math.max(0, files.length - limit)
2008
- };
2009
- }
2010
- function resolveCwd(rawCwd) {
2011
- if (!rawCwd) {
2012
- return process6.cwd();
2013
- }
2014
- return path10.resolve(rawCwd);
2015
- }
2016
- function createDefaultRunner(factory) {
2017
- let promise;
2018
- return () => {
2019
- if (!promise) {
2020
- promise = factory();
2021
- }
2022
- return promise;
2023
- };
2024
- }
2025
- async function loadPatchOptionsForCwd(cwd, overrides) {
2026
- const { config } = await getConfig(cwd);
2027
- const legacyConfig = config;
2028
- const base = config?.registry ? fromUnifiedConfig(config.registry) : legacyConfig?.patch ? fromLegacyOptions({ patch: legacyConfig.patch }) : {};
2029
- const merged = defu(overrides ?? {}, base);
2030
- return merged;
2031
- }
2032
- function createCommandContext(cli, command, commandName, args, cwd) {
2033
- let cachedOptions;
2034
- let cachedPatcher;
2035
- let cachedConfig;
2036
- const loadPatchOptionsForContext = (overrides) => {
2037
- if (overrides) {
2038
- return loadPatchOptionsForCwd(cwd, overrides);
2039
- }
2040
- if (!cachedOptions) {
2041
- cachedOptions = loadPatchOptionsForCwd(cwd);
2042
- }
2043
- return cachedOptions;
2044
- };
2045
- const createPatcherForContext = async (overrides) => {
2046
- if (overrides) {
2047
- const patchOptions = await loadPatchOptionsForCwd(cwd, overrides);
2048
- return new TailwindcssPatcher(patchOptions);
2049
- }
2050
- if (!cachedPatcher) {
2051
- cachedPatcher = loadPatchOptionsForContext().then((options) => new TailwindcssPatcher(options));
2052
- }
2053
- return cachedPatcher;
2054
- };
2055
- return {
2056
- cli,
2057
- command,
2058
- commandName,
2059
- args,
2060
- cwd,
2061
- logger: logger_default,
2062
- loadConfig: () => {
2063
- if (!cachedConfig) {
2064
- cachedConfig = getConfig(cwd);
2065
- }
2066
- return cachedConfig;
2067
- },
2068
- loadPatchOptions: loadPatchOptionsForContext,
2069
- createPatcher: createPatcherForContext
2070
- };
2071
- }
2072
- function createCwdOptionDefinition(description = "Working directory") {
2073
- return {
2074
- flags: "--cwd <dir>",
2075
- description,
2076
- config: { default: process6.cwd() }
2077
- };
2078
- }
2079
- function buildDefaultCommandDefinitions() {
2080
- return {
2081
- install: {
2082
- description: "Apply Tailwind CSS runtime patches",
2083
- optionDefs: [createCwdOptionDefinition()]
2084
- },
2085
- extract: {
2086
- description: "Collect generated class names into a cache file",
2087
- optionDefs: [
2088
- createCwdOptionDefinition(),
2089
- { flags: "--output <file>", description: "Override output file path" },
2090
- { flags: "--format <format>", description: "Output format (json|lines)" },
2091
- { flags: "--css <file>", description: "Tailwind CSS entry CSS when using v4" },
2092
- { flags: "--no-write", description: "Skip writing to disk" }
2093
- ]
2094
- },
2095
- tokens: {
2096
- description: "Extract Tailwind tokens with file/position metadata",
2097
- optionDefs: [
2098
- createCwdOptionDefinition(),
2099
- { flags: "--output <file>", description: "Override output file path", config: { default: DEFAULT_TOKEN_REPORT } },
2100
- {
2101
- flags: "--format <format>",
2102
- description: "Output format (json|lines|grouped-json)",
2103
- config: { default: "json" }
2104
- },
2105
- {
2106
- flags: "--group-key <key>",
2107
- description: "Grouping key for grouped-json output (relative|absolute)",
2108
- config: { default: "relative" }
2109
- },
2110
- { flags: "--no-write", description: "Skip writing to disk" }
2111
- ]
2112
- },
2113
- init: {
2114
- description: "Generate a tailwindcss-patch config file",
2115
- optionDefs: [createCwdOptionDefinition()]
2116
- },
2117
- status: {
2118
- description: "Check which Tailwind patches are applied",
2119
- optionDefs: [
2120
- createCwdOptionDefinition(),
2121
- { flags: "--json", description: "Print a JSON report of patch status" }
2122
- ]
2123
- }
2124
- };
2125
- }
2126
- function addPrefixIfMissing(value, prefix) {
2127
- if (!prefix || value.startsWith(prefix)) {
2128
- return value;
2129
- }
2130
- return `${prefix}${value}`;
2131
- }
2132
- function resolveCommandNames(command, mountOptions, prefix) {
2133
- const override = mountOptions.commandOptions?.[command];
2134
- const baseName = override?.name ?? command;
2135
- const name = addPrefixIfMissing(baseName, prefix);
2136
- const aliases = (override?.aliases ?? []).map((alias) => addPrefixIfMissing(alias, prefix));
2137
- return { name, aliases };
2138
- }
2139
- function resolveOptionDefinitions(defaults, override) {
2140
- if (!override) {
2141
- return defaults;
2142
- }
2143
- const appendDefaults = override.appendDefaultOptions ?? true;
2144
- const customDefs = override.optionDefs ?? [];
2145
- if (!appendDefaults) {
2146
- return customDefs;
2147
- }
2148
- if (customDefs.length === 0) {
2149
- return defaults;
2150
- }
2151
- return [...defaults, ...customDefs];
2152
- }
2153
- function applyCommandOptions(command, optionDefs) {
2154
- for (const option of optionDefs) {
2155
- command.option(option.flags, option.description ?? "", option.config);
2156
- }
2157
- }
2158
- function runWithCommandHandler(cli, command, commandName, args, handler, defaultHandler) {
2159
- const cwd = resolveCwd(args.cwd);
2160
- const context = createCommandContext(cli, command, commandName, args, cwd);
2161
- const runDefault = createDefaultRunner(() => defaultHandler(context));
2162
- if (!handler) {
2163
- return runDefault();
2164
- }
2165
- return handler(context, runDefault);
2166
- }
2167
- function resolveCommandMetadata(command, mountOptions, prefix, defaults) {
2168
- const names = resolveCommandNames(command, mountOptions, prefix);
2169
- const definition = defaults[command];
2170
- const override = mountOptions.commandOptions?.[command];
2171
- const description = override?.description ?? definition.description;
2172
- const optionDefs = resolveOptionDefinitions(definition.optionDefs, override);
2173
- return { ...names, description, optionDefs };
2174
- }
2175
- async function installCommandDefaultHandler(ctx) {
2176
- const patcher = await ctx.createPatcher();
2177
- await patcher.patch();
2178
- logger_default.success("Tailwind CSS runtime patched successfully.");
2179
- }
2180
- async function extractCommandDefaultHandler(ctx) {
2181
- const { args } = ctx;
2182
- const overrides = {};
2183
- let hasOverrides = false;
2184
- if (args.output || args.format) {
2185
- overrides.output = {
2186
- file: args.output,
2187
- format: args.format
2188
- };
2189
- hasOverrides = true;
2190
- }
2191
- if (args.css) {
2192
- overrides.tailwind = {
2193
- v4: {
2194
- cssEntries: [args.css]
2195
- }
2196
- };
2197
- hasOverrides = true;
2198
- }
2199
- const patcher = await ctx.createPatcher(hasOverrides ? overrides : void 0);
2200
- const result = await patcher.extract({ write: args.write });
2201
- if (result.filename) {
2202
- logger_default.success(`Collected ${result.classList.length} classes \u2192 ${result.filename}`);
2203
- } else {
2204
- logger_default.success(`Collected ${result.classList.length} classes.`);
2205
- }
2206
- return result;
2207
- }
2208
- async function tokensCommandDefaultHandler(ctx) {
2209
- const { args } = ctx;
2210
- const patcher = await ctx.createPatcher();
2211
- const report = await patcher.collectContentTokens();
2212
- const shouldWrite = args.write ?? true;
2213
- let format = args.format ?? "json";
2214
- if (!TOKEN_FORMATS.includes(format)) {
2215
- format = "json";
2216
- }
2217
- const targetFile = args.output ?? DEFAULT_TOKEN_REPORT;
2218
- const groupKey = args.groupKey === "absolute" ? "absolute" : "relative";
2219
- const buildGrouped = () => groupTokensByFile(report, {
2220
- key: groupKey,
2221
- stripAbsolutePaths: groupKey !== "absolute"
2222
- });
2223
- const grouped = format === "grouped-json" ? buildGrouped() : null;
2224
- const resolveGrouped = () => grouped ?? buildGrouped();
2225
- if (shouldWrite) {
2226
- const target = path10.resolve(targetFile);
2227
- await fs9.ensureDir(path10.dirname(target));
2228
- if (format === "json") {
2229
- await fs9.writeJSON(target, report, { spaces: 2 });
2230
- } else if (format === "grouped-json") {
2231
- await fs9.writeJSON(target, resolveGrouped(), { spaces: 2 });
2232
- } else {
2233
- const lines = report.entries.map(formatTokenLine);
2234
- await fs9.writeFile(target, `${lines.join("\n")}
2235
- `, "utf8");
2236
- }
2237
- logger_default.success(`Collected ${report.entries.length} tokens (${format}) \u2192 ${target.replace(process6.cwd(), ".")}`);
2238
- } else {
2239
- logger_default.success(`Collected ${report.entries.length} tokens from ${report.filesScanned} files.`);
2240
- if (format === "lines") {
2241
- const preview = report.entries.slice(0, 5).map(formatTokenLine).join("\n");
2242
- if (preview) {
2243
- logger_default.log("");
2244
- logger_default.info(preview);
2245
- if (report.entries.length > 5) {
2246
- logger_default.info(`\u2026and ${report.entries.length - 5} more.`);
2247
- }
2248
- }
2249
- } else if (format === "grouped-json") {
2250
- const map = resolveGrouped();
2251
- const { preview, moreFiles } = formatGroupedPreview(map);
2252
- if (preview) {
2253
- logger_default.log("");
2254
- logger_default.info(preview);
2255
- if (moreFiles > 0) {
2256
- logger_default.info(`\u2026and ${moreFiles} more files.`);
2257
- }
2258
- }
2259
- } else {
2260
- const previewEntries = report.entries.slice(0, 3);
2261
- if (previewEntries.length) {
2262
- logger_default.log("");
2263
- logger_default.info(JSON.stringify(previewEntries, null, 2));
2264
- }
2265
- }
2266
- }
2267
- if (report.skippedFiles.length) {
2268
- logger_default.warn("Skipped files:");
2269
- for (const skipped of report.skippedFiles) {
2270
- logger_default.warn(` \u2022 ${skipped.file} (${skipped.reason})`);
2271
- }
2272
- }
2273
- return report;
2274
- }
2275
- async function initCommandDefaultHandler(ctx) {
2276
- await initConfig(ctx.cwd);
2277
- logger_default.success(`\u2728 ${CONFIG_NAME}.config.ts initialized!`);
2278
- }
2279
- function formatFilesHint(entry) {
2280
- if (!entry.files.length) {
2281
- return "";
2282
- }
2283
- return ` (${entry.files.join(", ")})`;
2284
- }
2285
- async function statusCommandDefaultHandler(ctx) {
2286
- const patcher = await ctx.createPatcher();
2287
- const report = await patcher.getPatchStatus();
2288
- if (ctx.args.json) {
2289
- logger_default.log(JSON.stringify(report, null, 2));
2290
- return report;
2291
- }
2292
- const applied = report.entries.filter((entry) => entry.status === "applied");
2293
- const pending = report.entries.filter((entry) => entry.status === "not-applied");
2294
- const skipped = report.entries.filter((entry) => entry.status === "skipped" || entry.status === "unsupported");
2295
- const packageLabel = `${report.package.name ?? "tailwindcss"}@${report.package.version ?? "unknown"}`;
2296
- logger_default.info(`Patch status for ${packageLabel} (v${report.majorVersion})`);
2297
- if (applied.length) {
2298
- logger_default.success("Applied:");
2299
- applied.forEach((entry) => logger_default.success(` \u2022 ${entry.name}${formatFilesHint(entry)}`));
2300
- }
2301
- if (pending.length) {
2302
- logger_default.warn("Needs attention:");
2303
- pending.forEach((entry) => {
2304
- const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
2305
- logger_default.warn(` \u2022 ${entry.name}${formatFilesHint(entry)}${details}`);
2306
- });
2307
- } else {
2308
- logger_default.success("All applicable patches are applied.");
2309
- }
2310
- if (skipped.length) {
2311
- logger_default.info("Skipped:");
2312
- skipped.forEach((entry) => {
2313
- const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
2314
- logger_default.info(` \u2022 ${entry.name}${details}`);
2315
- });
2316
- }
2317
- return report;
2318
- }
2319
- function mountTailwindcssPatchCommands(cli, options = {}) {
2320
- const prefix = options.commandPrefix ?? "";
2321
- const selectedCommands = options.commands ?? tailwindcssPatchCommands;
2322
- const defaultDefinitions = buildDefaultCommandDefinitions();
2323
- const registrars = {
2324
- install: () => {
2325
- const metadata = resolveCommandMetadata("install", options, prefix, defaultDefinitions);
2326
- const command = cli.command(metadata.name, metadata.description);
2327
- applyCommandOptions(command, metadata.optionDefs);
2328
- command.action(async (args) => {
2329
- return runWithCommandHandler(
2330
- cli,
2331
- command,
2332
- "install",
2333
- args,
2334
- options.commandHandlers?.install,
2335
- installCommandDefaultHandler
2336
- );
2337
- });
2338
- metadata.aliases.forEach((alias) => command.alias(alias));
2339
- },
2340
- extract: () => {
2341
- const metadata = resolveCommandMetadata("extract", options, prefix, defaultDefinitions);
2342
- const command = cli.command(metadata.name, metadata.description);
2343
- applyCommandOptions(command, metadata.optionDefs);
2344
- command.action(async (args) => {
2345
- return runWithCommandHandler(
2346
- cli,
2347
- command,
2348
- "extract",
2349
- args,
2350
- options.commandHandlers?.extract,
2351
- extractCommandDefaultHandler
2352
- );
2353
- });
2354
- metadata.aliases.forEach((alias) => command.alias(alias));
2355
- },
2356
- tokens: () => {
2357
- const metadata = resolveCommandMetadata("tokens", options, prefix, defaultDefinitions);
2358
- const command = cli.command(metadata.name, metadata.description);
2359
- applyCommandOptions(command, metadata.optionDefs);
2360
- command.action(async (args) => {
2361
- return runWithCommandHandler(
2362
- cli,
2363
- command,
2364
- "tokens",
2365
- args,
2366
- options.commandHandlers?.tokens,
2367
- tokensCommandDefaultHandler
2368
- );
2369
- });
2370
- metadata.aliases.forEach((alias) => command.alias(alias));
2371
- },
2372
- init: () => {
2373
- const metadata = resolveCommandMetadata("init", options, prefix, defaultDefinitions);
2374
- const command = cli.command(metadata.name, metadata.description);
2375
- applyCommandOptions(command, metadata.optionDefs);
2376
- command.action(async (args) => {
2377
- return runWithCommandHandler(
2378
- cli,
2379
- command,
2380
- "init",
2381
- args,
2382
- options.commandHandlers?.init,
2383
- initCommandDefaultHandler
2384
- );
2385
- });
2386
- metadata.aliases.forEach((alias) => command.alias(alias));
2387
- },
2388
- status: () => {
2389
- const metadata = resolveCommandMetadata("status", options, prefix, defaultDefinitions);
2390
- const command = cli.command(metadata.name, metadata.description);
2391
- applyCommandOptions(command, metadata.optionDefs);
2392
- command.action(async (args) => {
2393
- return runWithCommandHandler(
2394
- cli,
2395
- command,
2396
- "status",
2397
- args,
2398
- options.commandHandlers?.status,
2399
- statusCommandDefaultHandler
2400
- );
2401
- });
2402
- metadata.aliases.forEach((alias) => command.alias(alias));
2403
- }
2404
- };
2405
- for (const name of selectedCommands) {
2406
- const register = registrars[name];
2407
- if (register) {
2408
- register();
2409
- }
2410
- }
2411
- return cli;
2412
- }
2413
- function createTailwindcssPatchCli(options = {}) {
2414
- const cli = cac(options.name ?? "tw-patch");
2415
- mountTailwindcssPatchCommands(cli, options.mountOptions);
2416
- return cli;
2417
- }
2418
-
2419
- export {
2420
- logger_default,
2421
- CacheStore,
2422
- extractRawCandidatesWithPositions,
2423
- extractRawCandidates,
2424
- extractValidCandidates,
2425
- extractProjectCandidatesWithPositions,
2426
- groupTokensByFile,
2427
- normalizeOptions,
2428
- getPatchStatusReport,
2429
- collectClassesFromContexts,
2430
- collectClassesFromTailwindV4,
2431
- loadRuntimeContexts,
2432
- runTailwindBuild,
2433
- TailwindcssPatcher,
2434
- tailwindcssPatchCommands,
2435
- mountTailwindcssPatchCommands,
2436
- createTailwindcssPatchCli
2437
- };