tailwindcss-patch 8.7.2 → 8.7.4-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;// ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/cjs_shims.js
2
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
3
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;
2
+
3
+ var _chunk5CWNAWKPjs = require('./chunk-5CWNAWKP.js');
4
4
 
5
5
  // src/logger.ts
6
6
  var _consola = require('consola');
@@ -20,7 +20,7 @@ var _pathe = require('pathe'); var _pathe2 = _interopRequireDefault(_pathe);
20
20
  // package.json
21
21
  var package_default = {
22
22
  name: "tailwindcss-patch",
23
- version: "8.7.2",
23
+ version: "8.7.4-alpha.0",
24
24
  description: "patch tailwindcss for exposing context and extract classes",
25
25
  author: "ice breaker <1324318532@qq.com>",
26
26
  license: "MIT",
@@ -41,17 +41,17 @@ var package_default = {
41
41
  ],
42
42
  exports: {
43
43
  ".": {
44
- types: "./src/index.ts",
45
- import: "./src/index.ts",
46
- require: "./src/index.ts"
44
+ types: "./dist/index.d.ts",
45
+ import: "./dist/index.mjs",
46
+ require: "./dist/index.js"
47
47
  },
48
48
  "./migration-report.schema.json": "./schema/migration-report.schema.json",
49
49
  "./restore-result.schema.json": "./schema/restore-result.schema.json",
50
50
  "./validate-result.schema.json": "./schema/validate-result.schema.json"
51
51
  },
52
- main: "./src/index.ts",
53
- module: "./src/index.ts",
54
- types: "./src/index.ts",
52
+ main: "./dist/index.js",
53
+ module: "./dist/index.mjs",
54
+ types: "./dist/index.d.ts",
55
55
  bin: {
56
56
  "tw-patch": "dev/bin.ts",
57
57
  "tailwindcss-patch": "dev/bin.ts"
@@ -66,6 +66,7 @@ var package_default = {
66
66
  build: "tsup",
67
67
  test: "vitest run",
68
68
  "test:dev": "vitest",
69
+ "bench:cold-start": "node --import tsx bench/cold-start.ts",
69
70
  patch: "tsx dev/bin.ts install",
70
71
  r0: "tsx dev/bin.ts extract",
71
72
  r1: "tsx dev/bin.ts extract --css index.css"
@@ -106,12 +107,12 @@ var package_default = {
106
107
  "@babel/types": "^7.29.0",
107
108
  "@tailwindcss-mangle/config": "workspace:*",
108
109
  "@tailwindcss/node": "^4.2.1",
109
- cac: "^6.7.14",
110
+ cac: "^7.0.0",
110
111
  consola: "^3.4.2",
111
- "fs-extra": "^11.3.3",
112
+ "fs-extra": "^11.3.4",
112
113
  "local-pkg": "^1.1.2",
113
114
  pathe: "^2.0.3",
114
- postcss: "^8.5.6",
115
+ postcss: "^8.5.8",
115
116
  semver: "^7.7.4",
116
117
  "tailwindcss-config": "^1.1.4"
117
118
  },
@@ -1511,226 +1512,6 @@ ${Date.now()}`, { flag: "wx" });
1511
1512
  }
1512
1513
  }, _class);
1513
1514
 
1514
- // src/extraction/candidate-extractor.ts
1515
- var _fs = require('fs');
1516
-
1517
-
1518
- async function importNode() {
1519
- return Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss/node")));
1520
- }
1521
- async function importOxide() {
1522
- return Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss/oxide")));
1523
- }
1524
- async function loadDesignSystem(css, bases) {
1525
- const uniqueBases = Array.from(new Set(bases.filter(Boolean)));
1526
- if (uniqueBases.length === 0) {
1527
- throw new Error("No base directories provided for Tailwind CSS design system.");
1528
- }
1529
- const { __unstable__loadDesignSystem } = await importNode();
1530
- let lastError;
1531
- for (const base of uniqueBases) {
1532
- try {
1533
- return await __unstable__loadDesignSystem(css, { base });
1534
- } catch (error) {
1535
- lastError = error;
1536
- }
1537
- }
1538
- if (lastError instanceof Error) {
1539
- throw lastError;
1540
- }
1541
- throw new Error("Failed to load Tailwind CSS design system.");
1542
- }
1543
- async function extractRawCandidatesWithPositions(content, extension = "html") {
1544
- const { Scanner } = await importOxide();
1545
- const scanner = new Scanner({});
1546
- const result = scanner.getCandidatesWithPositions({ content, extension });
1547
- return result.map(({ candidate, position }) => ({
1548
- rawCandidate: candidate,
1549
- start: position,
1550
- end: position + candidate.length
1551
- }));
1552
- }
1553
- async function extractRawCandidates(sources) {
1554
- const { Scanner } = await importOxide();
1555
- const scanner = new Scanner(sources === void 0 ? {} : { sources });
1556
- return scanner.scan();
1557
- }
1558
- async function extractValidCandidates(options) {
1559
- const providedOptions = _nullishCoalesce(options, () => ( {}));
1560
- const defaultCwd = _nullishCoalesce(providedOptions.cwd, () => ( _process2.default.cwd()));
1561
- const base = _nullishCoalesce(providedOptions.base, () => ( defaultCwd));
1562
- const baseFallbacks = _nullishCoalesce(providedOptions.baseFallbacks, () => ( []));
1563
- const css = _nullishCoalesce(providedOptions.css, () => ( '@import "tailwindcss";'));
1564
- const sources = (_nullishCoalesce(providedOptions.sources, () => ( [
1565
- {
1566
- base: defaultCwd,
1567
- pattern: "**/*",
1568
- negated: false
1569
- }
1570
- ]))).map((source) => ({
1571
- base: _nullishCoalesce(source.base, () => ( defaultCwd)),
1572
- pattern: source.pattern,
1573
- negated: source.negated
1574
- }));
1575
- const designSystem = await loadDesignSystem(css, [base, ...baseFallbacks]);
1576
- const candidates = await extractRawCandidates(sources);
1577
- const parsedCandidates = candidates.filter(
1578
- (rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
1579
- );
1580
- if (parsedCandidates.length === 0) {
1581
- return parsedCandidates;
1582
- }
1583
- const cssByCandidate = designSystem.candidatesToCss(parsedCandidates);
1584
- const validCandidates = [];
1585
- for (let index = 0; index < parsedCandidates.length; index++) {
1586
- const candidate = parsedCandidates[index];
1587
- if (candidate === void 0) {
1588
- continue;
1589
- }
1590
- const css2 = cssByCandidate[index];
1591
- if (typeof css2 === "string" && css2.trim().length > 0) {
1592
- validCandidates.push(candidate);
1593
- }
1594
- }
1595
- return validCandidates;
1596
- }
1597
- function normalizeSources(sources, cwd) {
1598
- const baseSources = _optionalChain([sources, 'optionalAccess', _23 => _23.length]) ? sources : [
1599
- {
1600
- base: cwd,
1601
- pattern: "**/*",
1602
- negated: false
1603
- }
1604
- ];
1605
- return baseSources.map((source) => ({
1606
- base: _nullishCoalesce(source.base, () => ( cwd)),
1607
- pattern: source.pattern,
1608
- negated: source.negated
1609
- }));
1610
- }
1611
- function buildLineOffsets(content) {
1612
- const offsets = [0];
1613
- for (let i = 0; i < content.length; i++) {
1614
- if (content[i] === "\n") {
1615
- offsets.push(i + 1);
1616
- }
1617
- }
1618
- if (offsets[offsets.length - 1] !== content.length) {
1619
- offsets.push(content.length);
1620
- }
1621
- return offsets;
1622
- }
1623
- function resolveLineMeta(content, offsets, index) {
1624
- let low = 0;
1625
- let high = offsets.length - 1;
1626
- while (low <= high) {
1627
- const mid = Math.floor((low + high) / 2);
1628
- const start = offsets[mid];
1629
- if (start === void 0) {
1630
- break;
1631
- }
1632
- const nextStart = _nullishCoalesce(offsets[mid + 1], () => ( content.length));
1633
- if (index < start) {
1634
- high = mid - 1;
1635
- continue;
1636
- }
1637
- if (index >= nextStart) {
1638
- low = mid + 1;
1639
- continue;
1640
- }
1641
- const line = mid + 1;
1642
- const column = index - start + 1;
1643
- const lineEnd = content.indexOf("\n", start);
1644
- const lineText = content.slice(start, lineEnd === -1 ? content.length : lineEnd);
1645
- return { line, column, lineText };
1646
- }
1647
- const lastStart = _nullishCoalesce(offsets[offsets.length - 2], () => ( 0));
1648
- return {
1649
- line: offsets.length - 1,
1650
- column: index - lastStart + 1,
1651
- lineText: content.slice(lastStart)
1652
- };
1653
- }
1654
- function toExtension(filename) {
1655
- const ext = _pathe2.default.extname(filename).replace(/^\./, "");
1656
- return ext || "txt";
1657
- }
1658
- function toRelativeFile(cwd, filename) {
1659
- const relative = _pathe2.default.relative(cwd, filename);
1660
- return relative === "" ? _pathe2.default.basename(filename) : relative;
1661
- }
1662
- async function extractProjectCandidatesWithPositions(options) {
1663
- const cwd = _optionalChain([options, 'optionalAccess', _24 => _24.cwd]) ? _pathe2.default.resolve(options.cwd) : _process2.default.cwd();
1664
- const normalizedSources = normalizeSources(_optionalChain([options, 'optionalAccess', _25 => _25.sources]), cwd);
1665
- const { Scanner } = await importOxide();
1666
- const scanner = new Scanner({
1667
- sources: normalizedSources
1668
- });
1669
- const files = _nullishCoalesce(scanner.files, () => ( []));
1670
- const entries = [];
1671
- const skipped = [];
1672
- for (const file of files) {
1673
- let content;
1674
- try {
1675
- content = await _fs.promises.readFile(file, "utf8");
1676
- } catch (error) {
1677
- skipped.push({
1678
- file,
1679
- reason: error instanceof Error ? error.message : "Unknown error"
1680
- });
1681
- continue;
1682
- }
1683
- const extension = toExtension(file);
1684
- const matches = scanner.getCandidatesWithPositions({
1685
- file,
1686
- content,
1687
- extension
1688
- });
1689
- if (!matches.length) {
1690
- continue;
1691
- }
1692
- const offsets = buildLineOffsets(content);
1693
- const relativeFile = toRelativeFile(cwd, file);
1694
- for (const match of matches) {
1695
- const info = resolveLineMeta(content, offsets, match.position);
1696
- entries.push({
1697
- rawCandidate: match.candidate,
1698
- file,
1699
- relativeFile,
1700
- extension,
1701
- start: match.position,
1702
- end: match.position + match.candidate.length,
1703
- length: match.candidate.length,
1704
- line: info.line,
1705
- column: info.column,
1706
- lineText: info.lineText
1707
- });
1708
- }
1709
- }
1710
- return {
1711
- entries,
1712
- filesScanned: files.length,
1713
- skippedFiles: skipped,
1714
- sources: normalizedSources
1715
- };
1716
- }
1717
- function groupTokensByFile(report, options) {
1718
- const key = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _26 => _26.key]), () => ( "relative"));
1719
- const stripAbsolute = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _27 => _27.stripAbsolutePaths]), () => ( key !== "absolute"));
1720
- return report.entries.reduce((acc, entry) => {
1721
- const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
1722
- if (!acc[bucketKey]) {
1723
- acc[bucketKey] = [];
1724
- }
1725
- const value = stripAbsolute ? {
1726
- ...entry,
1727
- file: entry.relativeFile
1728
- } : entry;
1729
- acc[bucketKey].push(value);
1730
- return acc;
1731
- }, {});
1732
- }
1733
-
1734
1515
  // src/options/normalize.ts
1735
1516
 
1736
1517
 
@@ -1795,11 +1576,11 @@ function normalizeCacheOptions(cache, projectRoot) {
1795
1576
  };
1796
1577
  }
1797
1578
  function normalizeOutputOptions(output) {
1798
- const enabled = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _28 => _28.write]), () => ( true));
1799
- const file = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _29 => _29.file]), () => ( ".tw-patch/tw-class-list.json"));
1800
- const format = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _30 => _30.format]), () => ( "json"));
1801
- const pretty = toPrettyValue(_nullishCoalesce(_optionalChain([output, 'optionalAccess', _31 => _31.pretty]), () => ( true)));
1802
- const removeUniversalSelector = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _32 => _32.removeUniversalSelector]), () => ( true));
1579
+ const enabled = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _23 => _23.write]), () => ( true));
1580
+ const file = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _24 => _24.file]), () => ( ".tw-patch/tw-class-list.json"));
1581
+ const format = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _25 => _25.format]), () => ( "json"));
1582
+ const pretty = toPrettyValue(_nullishCoalesce(_optionalChain([output, 'optionalAccess', _26 => _26.pretty]), () => ( true)));
1583
+ const removeUniversalSelector = _nullishCoalesce(_optionalChain([output, 'optionalAccess', _27 => _27.removeUniversalSelector]), () => ( true));
1803
1584
  return {
1804
1585
  enabled,
1805
1586
  file,
@@ -1846,11 +1627,11 @@ function normalizeExtendLengthUnitsOptions(extend) {
1846
1627
  };
1847
1628
  }
1848
1629
  function normalizeTailwindV4Options(v4, fallbackBase) {
1849
- const configuredBase = _optionalChain([v4, 'optionalAccess', _33 => _33.base]) ? _pathe2.default.resolve(v4.base) : void 0;
1630
+ const configuredBase = _optionalChain([v4, 'optionalAccess', _28 => _28.base]) ? _pathe2.default.resolve(v4.base) : void 0;
1850
1631
  const base = _nullishCoalesce(configuredBase, () => ( fallbackBase));
1851
- const cssEntries = Array.isArray(_optionalChain([v4, 'optionalAccess', _34 => _34.cssEntries])) ? v4.cssEntries.filter((entry) => Boolean(entry)).map((entry) => _pathe2.default.resolve(entry)) : [];
1852
- const userSources = _optionalChain([v4, 'optionalAccess', _35 => _35.sources]);
1853
- const hasUserDefinedSources = Boolean(_optionalChain([userSources, 'optionalAccess', _36 => _36.length]));
1632
+ const cssEntries = Array.isArray(_optionalChain([v4, 'optionalAccess', _29 => _29.cssEntries])) ? v4.cssEntries.filter((entry) => Boolean(entry)).map((entry) => _pathe2.default.resolve(entry)) : [];
1633
+ const userSources = _optionalChain([v4, 'optionalAccess', _30 => _30.sources]);
1634
+ const hasUserDefinedSources = Boolean(_optionalChain([userSources, 'optionalAccess', _31 => _31.length]));
1854
1635
  const sources = hasUserDefinedSources ? userSources : [
1855
1636
  {
1856
1637
  base: fallbackBase,
@@ -1861,20 +1642,20 @@ function normalizeTailwindV4Options(v4, fallbackBase) {
1861
1642
  return {
1862
1643
  base,
1863
1644
  ...configuredBase === void 0 ? {} : { configuredBase },
1864
- ..._optionalChain([v4, 'optionalAccess', _37 => _37.css]) === void 0 ? {} : { css: v4.css },
1645
+ ..._optionalChain([v4, 'optionalAccess', _32 => _32.css]) === void 0 ? {} : { css: v4.css },
1865
1646
  cssEntries,
1866
1647
  sources,
1867
1648
  hasUserDefinedSources
1868
1649
  };
1869
1650
  }
1870
1651
  function normalizeTailwindOptions(tailwind, projectRoot) {
1871
- const packageName = _nullishCoalesce(_optionalChain([tailwind, 'optionalAccess', _38 => _38.packageName]), () => ( "tailwindcss"));
1872
- const versionHint = _optionalChain([tailwind, 'optionalAccess', _39 => _39.version]);
1873
- const resolve = _optionalChain([tailwind, 'optionalAccess', _40 => _40.resolve]);
1874
- const cwd = _nullishCoalesce(_optionalChain([tailwind, 'optionalAccess', _41 => _41.cwd]), () => ( projectRoot));
1875
- const config = _optionalChain([tailwind, 'optionalAccess', _42 => _42.config]);
1876
- const postcssPlugin = _optionalChain([tailwind, 'optionalAccess', _43 => _43.postcssPlugin]);
1877
- const v4 = normalizeTailwindV4Options(_optionalChain([tailwind, 'optionalAccess', _44 => _44.v4]), cwd);
1652
+ const packageName = _nullishCoalesce(_optionalChain([tailwind, 'optionalAccess', _33 => _33.packageName]), () => ( "tailwindcss"));
1653
+ const versionHint = _optionalChain([tailwind, 'optionalAccess', _34 => _34.version]);
1654
+ const resolve = _optionalChain([tailwind, 'optionalAccess', _35 => _35.resolve]);
1655
+ const cwd = _nullishCoalesce(_optionalChain([tailwind, 'optionalAccess', _36 => _36.cwd]), () => ( projectRoot));
1656
+ const config = _optionalChain([tailwind, 'optionalAccess', _37 => _37.config]);
1657
+ const postcssPlugin = _optionalChain([tailwind, 'optionalAccess', _38 => _38.postcssPlugin]);
1658
+ const v4 = normalizeTailwindV4Options(_optionalChain([tailwind, 'optionalAccess', _39 => _39.v4]), cwd);
1878
1659
  return {
1879
1660
  packageName,
1880
1661
  cwd,
@@ -1882,22 +1663,22 @@ function normalizeTailwindOptions(tailwind, projectRoot) {
1882
1663
  ...resolve === void 0 ? {} : { resolve },
1883
1664
  ...config === void 0 ? {} : { config },
1884
1665
  ...postcssPlugin === void 0 ? {} : { postcssPlugin },
1885
- ..._optionalChain([tailwind, 'optionalAccess', _45 => _45.v2]) === void 0 ? {} : { v2: tailwind.v2 },
1886
- ..._optionalChain([tailwind, 'optionalAccess', _46 => _46.v3]) === void 0 ? {} : { v3: tailwind.v3 },
1666
+ ..._optionalChain([tailwind, 'optionalAccess', _40 => _40.v2]) === void 0 ? {} : { v2: tailwind.v2 },
1667
+ ..._optionalChain([tailwind, 'optionalAccess', _41 => _41.v3]) === void 0 ? {} : { v3: tailwind.v3 },
1887
1668
  v4
1888
1669
  };
1889
1670
  }
1890
1671
  function resolveOptionSlices(options) {
1891
1672
  const projectRoot = _nullishCoalesce(options.projectRoot, () => ( options.cwd));
1892
- const overwrite = _nullishCoalesce(_optionalChain([options, 'access', _47 => _47.apply, 'optionalAccess', _48 => _48.overwrite]), () => ( options.overwrite));
1673
+ const overwrite = _nullishCoalesce(_optionalChain([options, 'access', _42 => _42.apply, 'optionalAccess', _43 => _43.overwrite]), () => ( options.overwrite));
1893
1674
  const tailwind = _nullishCoalesce(options.tailwindcss, () => ( options.tailwind));
1894
- const exposeContext = _optionalChain([options, 'access', _49 => _49.apply, 'optionalAccess', _50 => _50.exposeContext]) !== void 0 ? options.apply.exposeContext : _optionalChain([options, 'access', _51 => _51.features, 'optionalAccess', _52 => _52.exposeContext]);
1895
- const extendLengthUnits = _optionalChain([options, 'access', _53 => _53.apply, 'optionalAccess', _54 => _54.extendLengthUnits]) !== void 0 ? options.apply.extendLengthUnits : _optionalChain([options, 'access', _55 => _55.features, 'optionalAccess', _56 => _56.extendLengthUnits]);
1896
- const write = _nullishCoalesce(_optionalChain([options, 'access', _57 => _57.extract, 'optionalAccess', _58 => _58.write]), () => ( _optionalChain([options, 'access', _59 => _59.output, 'optionalAccess', _60 => _60.enabled])));
1897
- const file = _nullishCoalesce(_optionalChain([options, 'access', _61 => _61.extract, 'optionalAccess', _62 => _62.file]), () => ( _optionalChain([options, 'access', _63 => _63.output, 'optionalAccess', _64 => _64.file])));
1898
- const format = _nullishCoalesce(_optionalChain([options, 'access', _65 => _65.extract, 'optionalAccess', _66 => _66.format]), () => ( _optionalChain([options, 'access', _67 => _67.output, 'optionalAccess', _68 => _68.format])));
1899
- const pretty = _nullishCoalesce(_optionalChain([options, 'access', _69 => _69.extract, 'optionalAccess', _70 => _70.pretty]), () => ( _optionalChain([options, 'access', _71 => _71.output, 'optionalAccess', _72 => _72.pretty])));
1900
- const removeUniversalSelector = _nullishCoalesce(_optionalChain([options, 'access', _73 => _73.extract, 'optionalAccess', _74 => _74.removeUniversalSelector]), () => ( _optionalChain([options, 'access', _75 => _75.output, 'optionalAccess', _76 => _76.removeUniversalSelector])));
1675
+ const exposeContext = _optionalChain([options, 'access', _44 => _44.apply, 'optionalAccess', _45 => _45.exposeContext]) !== void 0 ? options.apply.exposeContext : _optionalChain([options, 'access', _46 => _46.features, 'optionalAccess', _47 => _47.exposeContext]);
1676
+ const extendLengthUnits = _optionalChain([options, 'access', _48 => _48.apply, 'optionalAccess', _49 => _49.extendLengthUnits]) !== void 0 ? options.apply.extendLengthUnits : _optionalChain([options, 'access', _50 => _50.features, 'optionalAccess', _51 => _51.extendLengthUnits]);
1677
+ const write = _nullishCoalesce(_optionalChain([options, 'access', _52 => _52.extract, 'optionalAccess', _53 => _53.write]), () => ( _optionalChain([options, 'access', _54 => _54.output, 'optionalAccess', _55 => _55.enabled])));
1678
+ const file = _nullishCoalesce(_optionalChain([options, 'access', _56 => _56.extract, 'optionalAccess', _57 => _57.file]), () => ( _optionalChain([options, 'access', _58 => _58.output, 'optionalAccess', _59 => _59.file])));
1679
+ const format = _nullishCoalesce(_optionalChain([options, 'access', _60 => _60.extract, 'optionalAccess', _61 => _61.format]), () => ( _optionalChain([options, 'access', _62 => _62.output, 'optionalAccess', _63 => _63.format])));
1680
+ const pretty = _nullishCoalesce(_optionalChain([options, 'access', _64 => _64.extract, 'optionalAccess', _65 => _65.pretty]), () => ( _optionalChain([options, 'access', _66 => _66.output, 'optionalAccess', _67 => _67.pretty])));
1681
+ const removeUniversalSelector = _nullishCoalesce(_optionalChain([options, 'access', _68 => _68.extract, 'optionalAccess', _69 => _69.removeUniversalSelector]), () => ( _optionalChain([options, 'access', _70 => _70.output, 'optionalAccess', _71 => _71.removeUniversalSelector])));
1901
1682
  const extract = {
1902
1683
  ...write === void 0 ? {} : { write },
1903
1684
  ...file === void 0 ? {} : { file },
@@ -1970,54 +1751,750 @@ function normalizeOptions(options = {}) {
1970
1751
  };
1971
1752
  }
1972
1753
 
1973
- // src/patching/status.ts
1974
- var _types = require('@babel/types'); var t4 = _interopRequireWildcard(_types); var t = _interopRequireWildcard(_types); var t2 = _interopRequireWildcard(_types); var t3 = _interopRequireWildcard(_types); var t5 = _interopRequireWildcard(_types);
1975
-
1976
-
1977
-
1978
- // src/babel/index.ts
1979
- var _generator = require('@babel/generator'); var _generator2 = _interopRequireDefault(_generator);
1980
- var _traverse = require('@babel/traverse'); var _traverse2 = _interopRequireDefault(_traverse);
1981
- var _parser = require('@babel/parser');
1982
- function _interopDefaultCompat(e) {
1983
- return e && typeof e === "object" && "default" in e ? e.default : e;
1984
- }
1985
- var generate = _interopDefaultCompat(_generator2.default);
1986
- var traverse = _interopDefaultCompat(_traverse2.default);
1987
-
1988
- // src/patching/operations/export-context/postcss-v2.ts
1989
-
1990
- var IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
1991
- function toIdentifierName(property) {
1992
- if (!property) {
1993
- return "contextRef";
1994
- }
1995
- const sanitized = property.replace(/[^\w$]/gu, "_");
1996
- if (/^\d/.test(sanitized)) {
1997
- return `_${sanitized}`;
1754
+ // src/options/legacy.ts
1755
+ function normalizeLegacyFeatures(patch) {
1756
+ const apply = _optionalChain([patch, 'optionalAccess', _72 => _72.applyPatches]);
1757
+ const extend = _optionalChain([apply, 'optionalAccess', _73 => _73.extendLengthUnits]);
1758
+ let extendOption = false;
1759
+ if (extend && typeof extend === "object") {
1760
+ extendOption = {
1761
+ ...extend,
1762
+ enabled: true
1763
+ };
1764
+ } else if (extend === true) {
1765
+ extendOption = {
1766
+ enabled: true,
1767
+ units: ["rpx"],
1768
+ ..._optionalChain([patch, 'optionalAccess', _74 => _74.overwrite]) === void 0 ? {} : { overwrite: patch.overwrite }
1769
+ };
1998
1770
  }
1999
- return sanitized || "contextRef";
1771
+ return {
1772
+ exposeContext: _nullishCoalesce(_optionalChain([apply, 'optionalAccess', _75 => _75.exportContext]), () => ( true)),
1773
+ extendLengthUnits: extendOption
1774
+ };
2000
1775
  }
2001
- function createExportsMember(property) {
2002
- if (IDENTIFIER_RE.test(property)) {
2003
- return t.memberExpression(t.identifier("exports"), t.identifier(property));
1776
+ function fromLegacyOptions(options) {
1777
+ if (!options) {
1778
+ return {};
2004
1779
  }
2005
- return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
2006
- }
2007
- function transformProcessTailwindFeaturesReturnContextV2(content) {
2008
- const ast = _parser.parse.call(void 0, content, {
2009
- sourceType: "unambiguous"
2010
- });
2011
- let hasPatched = false;
2012
- traverse(ast, {
2013
- FunctionDeclaration(path13) {
2014
- const node = path13.node;
2015
- if (_optionalChain([node, 'access', _77 => _77.id, 'optionalAccess', _78 => _78.name]) !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) {
2016
- return;
2017
- }
2018
- const returnStatement3 = node.body.body[0];
2019
- if (!t.isFunctionExpression(returnStatement3.argument)) {
2020
- return;
1780
+ const patch = options.patch;
1781
+ const features = normalizeLegacyFeatures(patch);
1782
+ const output = _optionalChain([patch, 'optionalAccess', _76 => _76.output]);
1783
+ const tailwindConfig = _optionalChain([patch, 'optionalAccess', _77 => _77.tailwindcss]);
1784
+ const tailwindVersion = _optionalChain([tailwindConfig, 'optionalAccess', _78 => _78.version]);
1785
+ const tailwindV2 = _optionalChain([tailwindConfig, 'optionalAccess', _79 => _79.v2]);
1786
+ const tailwindV3 = _optionalChain([tailwindConfig, 'optionalAccess', _80 => _80.v3]);
1787
+ const tailwindV4 = _optionalChain([tailwindConfig, 'optionalAccess', _81 => _81.v4]);
1788
+ const tailwindConfigPath = _nullishCoalesce(_optionalChain([tailwindV3, 'optionalAccess', _82 => _82.config]), () => ( _optionalChain([tailwindV2, 'optionalAccess', _83 => _83.config])));
1789
+ const tailwindCwd = _nullishCoalesce(_nullishCoalesce(_optionalChain([tailwindV3, 'optionalAccess', _84 => _84.cwd]), () => ( _optionalChain([tailwindV2, 'optionalAccess', _85 => _85.cwd]))), () => ( _optionalChain([patch, 'optionalAccess', _86 => _86.cwd])));
1790
+ const normalizedExtract = output ? {
1791
+ ...output.filename === void 0 ? {} : { file: output.filename },
1792
+ pretty: output.loose ? 2 : false,
1793
+ ...output.removeUniversalSelector === void 0 ? {} : { removeUniversalSelector: output.removeUniversalSelector }
1794
+ } : void 0;
1795
+ const normalizedTailwindcss = {
1796
+ ..._optionalChain([patch, 'optionalAccess', _87 => _87.packageName]) === void 0 ? {} : { packageName: patch.packageName },
1797
+ ...tailwindVersion === void 0 ? {} : { version: tailwindVersion },
1798
+ ..._optionalChain([patch, 'optionalAccess', _88 => _88.resolve]) === void 0 ? {} : { resolve: patch.resolve },
1799
+ ...tailwindConfigPath === void 0 ? {} : { config: tailwindConfigPath },
1800
+ ...tailwindCwd === void 0 ? {} : { cwd: tailwindCwd },
1801
+ ...tailwindV2 === void 0 ? {} : { v2: tailwindV2 },
1802
+ ...tailwindV3 === void 0 ? {} : { v3: tailwindV3 },
1803
+ ...tailwindV4 === void 0 ? {} : { v4: tailwindV4 }
1804
+ };
1805
+ const normalizedCache = typeof options.cache === "boolean" ? options.cache : options.cache ? {
1806
+ ...options.cache,
1807
+ enabled: _nullishCoalesce(options.cache.enabled, () => ( true))
1808
+ } : void 0;
1809
+ const normalizedApply = {
1810
+ ..._optionalChain([patch, 'optionalAccess', _89 => _89.overwrite]) === void 0 ? {} : { overwrite: patch.overwrite },
1811
+ exposeContext: features.exposeContext,
1812
+ extendLengthUnits: features.extendLengthUnits
1813
+ };
1814
+ return {
1815
+ ..._optionalChain([patch, 'optionalAccess', _90 => _90.cwd]) === void 0 ? {} : { projectRoot: patch.cwd },
1816
+ ..._optionalChain([patch, 'optionalAccess', _91 => _91.filter]) === void 0 ? {} : { filter: patch.filter },
1817
+ ...normalizedCache === void 0 ? {} : { cache: normalizedCache },
1818
+ ...normalizedExtract === void 0 ? {} : { extract: normalizedExtract },
1819
+ ...Object.keys(normalizedTailwindcss).length === 0 ? {} : { tailwindcss: normalizedTailwindcss },
1820
+ apply: normalizedApply
1821
+ };
1822
+ }
1823
+ function fromUnifiedConfig(registry) {
1824
+ if (!registry) {
1825
+ return {};
1826
+ }
1827
+ const tailwind = _nullishCoalesce(registry.tailwindcss, () => ( registry.tailwind));
1828
+ const modernExtract = registry.extract;
1829
+ const legacyOutput = registry.output;
1830
+ const pretty = (() => {
1831
+ const value = _nullishCoalesce(_optionalChain([modernExtract, 'optionalAccess', _92 => _92.pretty]), () => ( _optionalChain([legacyOutput, 'optionalAccess', _93 => _93.pretty])));
1832
+ if (value === void 0) {
1833
+ return void 0;
1834
+ }
1835
+ if (typeof value === "boolean") {
1836
+ return value ? 2 : false;
1837
+ }
1838
+ return value;
1839
+ })();
1840
+ const removeUniversalSelector = _nullishCoalesce(_optionalChain([modernExtract, 'optionalAccess', _94 => _94.removeUniversalSelector]), () => ( _optionalChain([legacyOutput, 'optionalAccess', _95 => _95.stripUniversalSelector])));
1841
+ const outputFile = _nullishCoalesce(_optionalChain([modernExtract, 'optionalAccess', _96 => _96.file]), () => ( _optionalChain([legacyOutput, 'optionalAccess', _97 => _97.file])));
1842
+ const normalizedExtract = modernExtract || legacyOutput ? {
1843
+ ..._optionalChain([modernExtract, 'optionalAccess', _98 => _98.write]) === void 0 ? {} : { write: modernExtract.write },
1844
+ ...outputFile === void 0 ? {} : { file: outputFile },
1845
+ ...pretty === void 0 ? {} : { pretty },
1846
+ ...removeUniversalSelector === void 0 ? {} : { removeUniversalSelector },
1847
+ ..._optionalChain([modernExtract, 'optionalAccess', _99 => _99.format]) === void 0 ? {} : { format: modernExtract.format }
1848
+ } : void 0;
1849
+ const normalizedTailwindcss = tailwind ? {
1850
+ ...tailwind.version === void 0 ? {} : { version: tailwind.version },
1851
+ ...tailwind.packageName === void 0 ? tailwind.package === void 0 ? {} : { packageName: tailwind.package } : { packageName: tailwind.packageName },
1852
+ ...tailwind.resolve === void 0 ? {} : { resolve: tailwind.resolve },
1853
+ ...tailwind.config === void 0 ? {} : { config: tailwind.config },
1854
+ ...tailwind.cwd === void 0 ? {} : { cwd: tailwind.cwd },
1855
+ ...tailwind.v2 === void 0 ? tailwind.legacy === void 0 ? {} : { v2: tailwind.legacy } : { v2: tailwind.v2 },
1856
+ ...tailwind.v3 === void 0 ? tailwind.classic === void 0 ? {} : { v3: tailwind.classic } : { v3: tailwind.v3 },
1857
+ ...tailwind.v4 === void 0 ? tailwind.next === void 0 ? {} : { v4: tailwind.next } : { v4: tailwind.v4 }
1858
+ } : void 0;
1859
+ const normalizedApply = registry.apply ? {
1860
+ ...registry.apply.overwrite === void 0 ? {} : { overwrite: registry.apply.overwrite },
1861
+ ...registry.apply.exposeContext === void 0 ? {} : { exposeContext: registry.apply.exposeContext },
1862
+ ...registry.apply.extendLengthUnits === void 0 ? {} : { extendLengthUnits: registry.apply.extendLengthUnits }
1863
+ } : void 0;
1864
+ return {
1865
+ ...registry.projectRoot === void 0 ? {} : { projectRoot: registry.projectRoot },
1866
+ ...normalizedApply === void 0 ? {} : { apply: normalizedApply },
1867
+ ...registry.cache === void 0 ? {} : { cache: registry.cache },
1868
+ ...registry.filter === void 0 ? {} : { filter: registry.filter },
1869
+ ...normalizedExtract === void 0 ? {} : { extract: normalizedExtract },
1870
+ ...normalizedTailwindcss === void 0 ? {} : { tailwindcss: normalizedTailwindcss }
1871
+ };
1872
+ }
1873
+
1874
+ // src/config/workspace.ts
1875
+ var _url = require('url');
1876
+
1877
+ var configModulePromise;
1878
+ var defuPromise;
1879
+ function isNodeError(error) {
1880
+ return !!error && typeof error === "object" && ("code" in error || "message" in error);
1881
+ }
1882
+ function isMissingConfigModuleError(error) {
1883
+ if (!isNodeError(error) || error.code !== "MODULE_NOT_FOUND") {
1884
+ return false;
1885
+ }
1886
+ const message = _nullishCoalesce(error.message, () => ( ""));
1887
+ return message.includes("@tailwindcss-mangle/config");
1888
+ }
1889
+ function isMissingSharedModuleError(error) {
1890
+ if (!isNodeError(error) || error.code !== "MODULE_NOT_FOUND") {
1891
+ return false;
1892
+ }
1893
+ const message = _nullishCoalesce(error.message, () => ( ""));
1894
+ return message.includes("@tailwindcss-mangle/shared");
1895
+ }
1896
+ async function loadWorkspaceConfigModule() {
1897
+ if (!configModulePromise) {
1898
+ configModulePromise = Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss-mangle/config"))).catch(async (error) => {
1899
+ if (!isMissingConfigModuleError(error)) {
1900
+ throw error;
1901
+ }
1902
+ const fallback = _pathe2.default.resolve(__dirname, "../../../config/src/index.ts");
1903
+ return Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, fallback).href)));
1904
+ });
1905
+ }
1906
+ return configModulePromise;
1907
+ }
1908
+ async function loadWorkspaceDefu() {
1909
+ if (!defuPromise) {
1910
+ defuPromise = Promise.resolve().then(() => _interopRequireWildcard(require("./dist-7O2232CU.js"))).then((mod) => mod.defu).catch(async (error) => {
1911
+ if (!isMissingSharedModuleError(error)) {
1912
+ throw error;
1913
+ }
1914
+ const fallback = _pathe2.default.resolve(__dirname, "../../../shared/src/utils.ts");
1915
+ const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, fallback).href)));
1916
+ return mod.defu;
1917
+ });
1918
+ }
1919
+ return defuPromise;
1920
+ }
1921
+ async function loadPatchOptionsForWorkspace(cwd, overrides) {
1922
+ const merge = await loadWorkspaceDefu();
1923
+ const configModule = await loadWorkspaceConfigModule();
1924
+ const { config } = await configModule.getConfig(cwd);
1925
+ const legacyConfig = config;
1926
+ const base = _optionalChain([config, 'optionalAccess', _100 => _100.registry]) ? fromUnifiedConfig(config.registry) : _optionalChain([legacyConfig, 'optionalAccess', _101 => _101.patch]) ? fromLegacyOptions({ patch: legacyConfig.patch }) : {};
1927
+ const merged = merge(_nullishCoalesce(overrides, () => ( {})), base);
1928
+ return merged;
1929
+ }
1930
+
1931
+ // src/extraction/candidate-extractor.ts
1932
+ var _fs = require('fs');
1933
+
1934
+
1935
+ var nodeImportPromise;
1936
+ var oxideImportPromise;
1937
+ var designSystemPromiseCache = /* @__PURE__ */ new Map();
1938
+ var designSystemCandidateCache = /* @__PURE__ */ new Map();
1939
+ async function importNode() {
1940
+ return Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss/node")));
1941
+ }
1942
+ async function importOxide() {
1943
+ return Promise.resolve().then(() => _interopRequireWildcard(require("@tailwindcss/oxide")));
1944
+ }
1945
+ function getNodeModule() {
1946
+ nodeImportPromise ??= importNode();
1947
+ return nodeImportPromise;
1948
+ }
1949
+ function getOxideModule() {
1950
+ oxideImportPromise ??= importOxide();
1951
+ return oxideImportPromise;
1952
+ }
1953
+ function createDesignSystemCacheKey(css, bases) {
1954
+ return JSON.stringify({
1955
+ css,
1956
+ bases: Array.from(new Set(bases.filter(Boolean)))
1957
+ });
1958
+ }
1959
+ async function loadDesignSystem(css, bases) {
1960
+ const uniqueBases = Array.from(new Set(bases.filter(Boolean)));
1961
+ if (uniqueBases.length === 0) {
1962
+ throw new Error("No base directories provided for Tailwind CSS design system.");
1963
+ }
1964
+ const cacheKey = createDesignSystemCacheKey(css, uniqueBases);
1965
+ const cached = designSystemPromiseCache.get(cacheKey);
1966
+ if (cached) {
1967
+ return cached;
1968
+ }
1969
+ const promise = (async () => {
1970
+ const { __unstable__loadDesignSystem } = await getNodeModule();
1971
+ let lastError;
1972
+ for (const base of uniqueBases) {
1973
+ try {
1974
+ return await __unstable__loadDesignSystem(css, { base });
1975
+ } catch (error) {
1976
+ lastError = error;
1977
+ }
1978
+ }
1979
+ if (lastError instanceof Error) {
1980
+ throw lastError;
1981
+ }
1982
+ throw new Error("Failed to load Tailwind CSS design system.");
1983
+ })();
1984
+ designSystemPromiseCache.set(cacheKey, promise);
1985
+ promise.catch(() => {
1986
+ if (designSystemPromiseCache.get(cacheKey) === promise) {
1987
+ designSystemPromiseCache.delete(cacheKey);
1988
+ designSystemCandidateCache.delete(cacheKey);
1989
+ }
1990
+ });
1991
+ return promise;
1992
+ }
1993
+ async function extractRawCandidatesWithPositions(content, extension = "html") {
1994
+ const { Scanner } = await getOxideModule();
1995
+ const scanner = new Scanner({});
1996
+ const result = scanner.getCandidatesWithPositions({ content, extension });
1997
+ return result.map(({ candidate, position }) => ({
1998
+ rawCandidate: candidate,
1999
+ start: position,
2000
+ end: position + candidate.length
2001
+ }));
2002
+ }
2003
+ async function extractRawCandidates(sources) {
2004
+ const { Scanner } = await getOxideModule();
2005
+ const scanner = new Scanner(sources === void 0 ? {} : { sources });
2006
+ return scanner.scan();
2007
+ }
2008
+ async function extractValidCandidates(options) {
2009
+ const providedOptions = _nullishCoalesce(options, () => ( {}));
2010
+ const defaultCwd = _nullishCoalesce(providedOptions.cwd, () => ( _process2.default.cwd()));
2011
+ const base = _nullishCoalesce(providedOptions.base, () => ( defaultCwd));
2012
+ const baseFallbacks = _nullishCoalesce(providedOptions.baseFallbacks, () => ( []));
2013
+ const css = _nullishCoalesce(providedOptions.css, () => ( '@import "tailwindcss";'));
2014
+ const sources = (_nullishCoalesce(providedOptions.sources, () => ( [
2015
+ {
2016
+ base: defaultCwd,
2017
+ pattern: "**/*",
2018
+ negated: false
2019
+ }
2020
+ ]))).map((source) => ({
2021
+ base: _nullishCoalesce(source.base, () => ( defaultCwd)),
2022
+ pattern: source.pattern,
2023
+ negated: source.negated
2024
+ }));
2025
+ const designSystemKey = createDesignSystemCacheKey(css, [base, ...baseFallbacks]);
2026
+ const designSystem = await loadDesignSystem(css, [base, ...baseFallbacks]);
2027
+ const candidateCache = _nullishCoalesce(designSystemCandidateCache.get(designSystemKey), () => ( /* @__PURE__ */ new Map()));
2028
+ designSystemCandidateCache.set(designSystemKey, candidateCache);
2029
+ const candidates = await extractRawCandidates(sources);
2030
+ const validCandidates = [];
2031
+ const uncachedCandidates = [];
2032
+ for (const rawCandidate of candidates) {
2033
+ const cached = candidateCache.get(rawCandidate);
2034
+ if (cached === true) {
2035
+ validCandidates.push(rawCandidate);
2036
+ continue;
2037
+ }
2038
+ if (cached === false) {
2039
+ continue;
2040
+ }
2041
+ if (designSystem.parseCandidate(rawCandidate).length > 0) {
2042
+ uncachedCandidates.push(rawCandidate);
2043
+ continue;
2044
+ }
2045
+ candidateCache.set(rawCandidate, false);
2046
+ }
2047
+ if (uncachedCandidates.length === 0) {
2048
+ return validCandidates;
2049
+ }
2050
+ const cssByCandidate = designSystem.candidatesToCss(uncachedCandidates);
2051
+ for (let index = 0; index < uncachedCandidates.length; index++) {
2052
+ const candidate = uncachedCandidates[index];
2053
+ if (candidate === void 0) {
2054
+ continue;
2055
+ }
2056
+ const candidateCss = cssByCandidate[index];
2057
+ const isValid = typeof candidateCss === "string" && candidateCss.trim().length > 0;
2058
+ candidateCache.set(candidate, isValid);
2059
+ if (!isValid) {
2060
+ continue;
2061
+ }
2062
+ validCandidates.push(candidate);
2063
+ }
2064
+ return validCandidates;
2065
+ }
2066
+ function normalizeSources(sources, cwd) {
2067
+ const baseSources = _optionalChain([sources, 'optionalAccess', _102 => _102.length]) ? sources : [
2068
+ {
2069
+ base: cwd,
2070
+ pattern: "**/*",
2071
+ negated: false
2072
+ }
2073
+ ];
2074
+ return baseSources.map((source) => ({
2075
+ base: _nullishCoalesce(source.base, () => ( cwd)),
2076
+ pattern: source.pattern,
2077
+ negated: source.negated
2078
+ }));
2079
+ }
2080
+ function buildLineOffsets(content) {
2081
+ const offsets = [0];
2082
+ for (let i = 0; i < content.length; i++) {
2083
+ if (content[i] === "\n") {
2084
+ offsets.push(i + 1);
2085
+ }
2086
+ }
2087
+ if (offsets[offsets.length - 1] !== content.length) {
2088
+ offsets.push(content.length);
2089
+ }
2090
+ return offsets;
2091
+ }
2092
+ function resolveLineMeta(content, offsets, index) {
2093
+ let low = 0;
2094
+ let high = offsets.length - 1;
2095
+ while (low <= high) {
2096
+ const mid = Math.floor((low + high) / 2);
2097
+ const start = offsets[mid];
2098
+ if (start === void 0) {
2099
+ break;
2100
+ }
2101
+ const nextStart = _nullishCoalesce(offsets[mid + 1], () => ( content.length));
2102
+ if (index < start) {
2103
+ high = mid - 1;
2104
+ continue;
2105
+ }
2106
+ if (index >= nextStart) {
2107
+ low = mid + 1;
2108
+ continue;
2109
+ }
2110
+ const line = mid + 1;
2111
+ const column = index - start + 1;
2112
+ const lineEnd = content.indexOf("\n", start);
2113
+ const lineText = content.slice(start, lineEnd === -1 ? content.length : lineEnd);
2114
+ return { line, column, lineText };
2115
+ }
2116
+ const lastStart = _nullishCoalesce(offsets[offsets.length - 2], () => ( 0));
2117
+ return {
2118
+ line: offsets.length - 1,
2119
+ column: index - lastStart + 1,
2120
+ lineText: content.slice(lastStart)
2121
+ };
2122
+ }
2123
+ function toExtension(filename) {
2124
+ const ext = _pathe2.default.extname(filename).replace(/^\./, "");
2125
+ return ext || "txt";
2126
+ }
2127
+ function toRelativeFile(cwd, filename) {
2128
+ const relative = _pathe2.default.relative(cwd, filename);
2129
+ return relative === "" ? _pathe2.default.basename(filename) : relative;
2130
+ }
2131
+ async function extractProjectCandidatesWithPositions(options) {
2132
+ const cwd = _optionalChain([options, 'optionalAccess', _103 => _103.cwd]) ? _pathe2.default.resolve(options.cwd) : _process2.default.cwd();
2133
+ const normalizedSources = normalizeSources(_optionalChain([options, 'optionalAccess', _104 => _104.sources]), cwd);
2134
+ const { Scanner } = await getOxideModule();
2135
+ const scanner = new Scanner({
2136
+ sources: normalizedSources
2137
+ });
2138
+ const files = _nullishCoalesce(scanner.files, () => ( []));
2139
+ const entries = [];
2140
+ const skipped = [];
2141
+ for (const file of files) {
2142
+ let content;
2143
+ try {
2144
+ content = await _fs.promises.readFile(file, "utf8");
2145
+ } catch (error) {
2146
+ skipped.push({
2147
+ file,
2148
+ reason: error instanceof Error ? error.message : "Unknown error"
2149
+ });
2150
+ continue;
2151
+ }
2152
+ const extension = toExtension(file);
2153
+ const matches = scanner.getCandidatesWithPositions({
2154
+ file,
2155
+ content,
2156
+ extension
2157
+ });
2158
+ if (!matches.length) {
2159
+ continue;
2160
+ }
2161
+ const offsets = buildLineOffsets(content);
2162
+ const relativeFile = toRelativeFile(cwd, file);
2163
+ for (const match of matches) {
2164
+ const info = resolveLineMeta(content, offsets, match.position);
2165
+ entries.push({
2166
+ rawCandidate: match.candidate,
2167
+ file,
2168
+ relativeFile,
2169
+ extension,
2170
+ start: match.position,
2171
+ end: match.position + match.candidate.length,
2172
+ length: match.candidate.length,
2173
+ line: info.line,
2174
+ column: info.column,
2175
+ lineText: info.lineText
2176
+ });
2177
+ }
2178
+ }
2179
+ return {
2180
+ entries,
2181
+ filesScanned: files.length,
2182
+ skippedFiles: skipped,
2183
+ sources: normalizedSources
2184
+ };
2185
+ }
2186
+ function groupTokensByFile(report, options) {
2187
+ const key = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _105 => _105.key]), () => ( "relative"));
2188
+ const stripAbsolute = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _106 => _106.stripAbsolutePaths]), () => ( key !== "absolute"));
2189
+ return report.entries.reduce((acc, entry) => {
2190
+ const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
2191
+ if (!acc[bucketKey]) {
2192
+ acc[bucketKey] = [];
2193
+ }
2194
+ const value = stripAbsolute ? {
2195
+ ...entry,
2196
+ file: entry.relativeFile
2197
+ } : entry;
2198
+ acc[bucketKey].push(value);
2199
+ return acc;
2200
+ }, {});
2201
+ }
2202
+
2203
+ // src/runtime/class-collector.ts
2204
+
2205
+
2206
+
2207
+
2208
+ // src/utils.ts
2209
+ function isObject(val) {
2210
+ return val !== null && typeof val === "object" && Array.isArray(val) === false;
2211
+ }
2212
+ function spliceChangesIntoString(str, changes) {
2213
+ if (!changes[0]) {
2214
+ return str;
2215
+ }
2216
+ changes.sort((a, b) => {
2217
+ return a.end - b.end || a.start - b.start;
2218
+ });
2219
+ let result = "";
2220
+ let previous = changes[0];
2221
+ result += str.slice(0, previous.start);
2222
+ result += previous.replacement;
2223
+ for (let i = 1; i < changes.length; ++i) {
2224
+ const change = changes[i];
2225
+ result += str.slice(previous.end, change.start);
2226
+ result += change.replacement;
2227
+ previous = change;
2228
+ }
2229
+ result += str.slice(previous.end);
2230
+ return result;
2231
+ }
2232
+
2233
+ // src/runtime/class-collector.ts
2234
+ function collectClassesFromContexts(contexts, filter) {
2235
+ const set = /* @__PURE__ */ new Set();
2236
+ for (const context of contexts) {
2237
+ if (!isObject(context) || !context.classCache) {
2238
+ continue;
2239
+ }
2240
+ for (const key of context.classCache.keys()) {
2241
+ const className = key.toString();
2242
+ if (filter(className)) {
2243
+ set.add(className);
2244
+ }
2245
+ }
2246
+ }
2247
+ return set;
2248
+ }
2249
+ async function collectClassesFromTailwindV4(options) {
2250
+ const set = /* @__PURE__ */ new Set();
2251
+ const v4Options = options.tailwind.v4;
2252
+ if (!v4Options) {
2253
+ return set;
2254
+ }
2255
+ const toAbsolute = (value) => {
2256
+ if (!value) {
2257
+ return void 0;
2258
+ }
2259
+ return _pathe2.default.isAbsolute(value) ? value : _pathe2.default.resolve(options.projectRoot, value);
2260
+ };
2261
+ const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
2262
+ const resolvedDefaultBase = _nullishCoalesce(toAbsolute(v4Options.base), () => ( _process2.default.cwd()));
2263
+ const resolveSources = (base) => {
2264
+ if (!_optionalChain([v4Options, 'access', _107 => _107.sources, 'optionalAccess', _108 => _108.length])) {
2265
+ return void 0;
2266
+ }
2267
+ return v4Options.sources.map((source) => ({
2268
+ base: _nullishCoalesce(source.base, () => ( base)),
2269
+ pattern: source.pattern,
2270
+ negated: source.negated
2271
+ }));
2272
+ };
2273
+ if (v4Options.cssEntries.length > 0) {
2274
+ for (const entry of v4Options.cssEntries) {
2275
+ const filePath = _pathe2.default.isAbsolute(entry) ? entry : _pathe2.default.resolve(options.projectRoot, entry);
2276
+ if (!await _fsextra2.default.pathExists(filePath)) {
2277
+ continue;
2278
+ }
2279
+ const css = await _fsextra2.default.readFile(filePath, "utf8");
2280
+ const entryDir = _pathe2.default.dirname(filePath);
2281
+ const designSystemBases = resolvedConfiguredBase && resolvedConfiguredBase !== entryDir ? [entryDir, resolvedConfiguredBase] : [entryDir];
2282
+ const sourcesBase = _nullishCoalesce(resolvedConfiguredBase, () => ( entryDir));
2283
+ const sources = resolveSources(sourcesBase);
2284
+ const firstBase = _nullishCoalesce(designSystemBases[0], () => ( entryDir));
2285
+ const extractOptions = {
2286
+ cwd: options.projectRoot,
2287
+ base: firstBase,
2288
+ baseFallbacks: designSystemBases.slice(1),
2289
+ css,
2290
+ ...sources === void 0 ? {} : { sources }
2291
+ };
2292
+ const candidates = await extractValidCandidates(extractOptions);
2293
+ for (const candidate of candidates) {
2294
+ if (options.filter(candidate)) {
2295
+ set.add(candidate);
2296
+ }
2297
+ }
2298
+ }
2299
+ } else {
2300
+ const baseForCss = _nullishCoalesce(resolvedConfiguredBase, () => ( resolvedDefaultBase));
2301
+ const sources = resolveSources(baseForCss);
2302
+ const extractOptions = {
2303
+ cwd: options.projectRoot,
2304
+ base: baseForCss,
2305
+ ...v4Options.css === void 0 ? {} : { css: v4Options.css },
2306
+ ...sources === void 0 ? {} : { sources }
2307
+ };
2308
+ const candidates = await extractValidCandidates(extractOptions);
2309
+ for (const candidate of candidates) {
2310
+ if (options.filter(candidate)) {
2311
+ set.add(candidate);
2312
+ }
2313
+ }
2314
+ }
2315
+ return set;
2316
+ }
2317
+
2318
+ // src/runtime/context-registry.ts
2319
+ var _module = require('module');
2320
+
2321
+
2322
+ var require2 = _module.createRequire.call(void 0, _chunk5CWNAWKPjs.importMetaUrl);
2323
+ function resolveRuntimeEntry(packageInfo, majorVersion) {
2324
+ const root = packageInfo.rootPath;
2325
+ if (majorVersion === 2) {
2326
+ const jitIndex = _pathe2.default.join(root, "lib/jit/index.js");
2327
+ if (_fsextra2.default.existsSync(jitIndex)) {
2328
+ return jitIndex;
2329
+ }
2330
+ } else if (majorVersion === 3) {
2331
+ const plugin = _pathe2.default.join(root, "lib/plugin.js");
2332
+ const index = _pathe2.default.join(root, "lib/index.js");
2333
+ if (_fsextra2.default.existsSync(plugin)) {
2334
+ return plugin;
2335
+ }
2336
+ if (_fsextra2.default.existsSync(index)) {
2337
+ return index;
2338
+ }
2339
+ }
2340
+ return void 0;
2341
+ }
2342
+ function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
2343
+ if (majorVersion === 4) {
2344
+ return [];
2345
+ }
2346
+ const entry = resolveRuntimeEntry(packageInfo, majorVersion);
2347
+ if (!entry) {
2348
+ return [];
2349
+ }
2350
+ const moduleExports = require2(entry);
2351
+ if (!moduleExports) {
2352
+ return [];
2353
+ }
2354
+ const ref = moduleExports[refProperty];
2355
+ if (!ref) {
2356
+ return [];
2357
+ }
2358
+ if (Array.isArray(ref)) {
2359
+ return ref;
2360
+ }
2361
+ if (typeof ref === "object" && Array.isArray(ref.value)) {
2362
+ return ref.value;
2363
+ }
2364
+ return [];
2365
+ }
2366
+
2367
+ // src/runtime/process-tailwindcss.ts
2368
+
2369
+
2370
+
2371
+ var _postcss = require('postcss'); var _postcss2 = _interopRequireDefault(_postcss);
2372
+ var _tailwindcssconfig = require('tailwindcss-config');
2373
+ var require3 = _module.createRequire.call(void 0, _chunk5CWNAWKPjs.importMetaUrl);
2374
+ function resolveModuleEntry(id) {
2375
+ return _pathe2.default.isAbsolute(id) ? id : require3.resolve(id);
2376
+ }
2377
+ function resolvePackageRootFromEntry(entry) {
2378
+ let current = _pathe2.default.dirname(entry);
2379
+ while (current && current !== _pathe2.default.dirname(current)) {
2380
+ const packageJsonPath = _pathe2.default.join(current, "package.json");
2381
+ if (_fsextra2.default.pathExistsSync(packageJsonPath)) {
2382
+ return current;
2383
+ }
2384
+ current = _pathe2.default.dirname(current);
2385
+ }
2386
+ return void 0;
2387
+ }
2388
+ function clearTailwindV3RuntimeState(pluginName) {
2389
+ try {
2390
+ const entry = resolveModuleEntry(pluginName);
2391
+ const root = resolvePackageRootFromEntry(entry);
2392
+ if (!root) {
2393
+ return;
2394
+ }
2395
+ const sharedStatePath = _pathe2.default.join(root, "lib/lib/sharedState.js");
2396
+ if (!_fsextra2.default.pathExistsSync(sharedStatePath)) {
2397
+ return;
2398
+ }
2399
+ const sharedState = _optionalChain([require3, 'access', _109 => _109.cache, 'access', _110 => _110[sharedStatePath], 'optionalAccess', _111 => _111.exports]);
2400
+ _optionalChain([sharedState, 'optionalAccess', _112 => _112.contextMap, 'optionalAccess', _113 => _113.clear, 'call', _114 => _114()]);
2401
+ _optionalChain([sharedState, 'optionalAccess', _115 => _115.configContextMap, 'optionalAccess', _116 => _116.clear, 'call', _117 => _117()]);
2402
+ _optionalChain([sharedState, 'optionalAccess', _118 => _118.contextSourcesMap, 'optionalAccess', _119 => _119.clear, 'call', _120 => _120()]);
2403
+ _optionalChain([sharedState, 'optionalAccess', _121 => _121.sourceHashMap, 'optionalAccess', _122 => _122.clear, 'call', _123 => _123()]);
2404
+ for (const candidate of ["lib/plugin.js", "lib/index.js"]) {
2405
+ const runtimeEntry = _pathe2.default.join(root, candidate);
2406
+ if (!_fsextra2.default.pathExistsSync(runtimeEntry)) {
2407
+ continue;
2408
+ }
2409
+ const runtimeModule = _optionalChain([require3, 'access', _124 => _124.cache, 'access', _125 => _125[runtimeEntry], 'optionalAccess', _126 => _126.exports]);
2410
+ _optionalChain([runtimeModule, 'optionalAccess', _127 => _127.contextRef, 'optionalAccess', _128 => _128.value, 'optionalAccess', _129 => _129.splice, 'call', _130 => _130(0, runtimeModule.contextRef.value.length)]);
2411
+ break;
2412
+ }
2413
+ } catch (e10) {
2414
+ }
2415
+ }
2416
+ async function resolveConfigPath(options) {
2417
+ if (options.config && _pathe2.default.isAbsolute(options.config)) {
2418
+ return options.config;
2419
+ }
2420
+ const result = await _tailwindcssconfig.loadConfig.call(void 0, { cwd: options.cwd });
2421
+ if (!result) {
2422
+ throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
2423
+ }
2424
+ return result.filepath;
2425
+ }
2426
+ async function runTailwindBuild(options) {
2427
+ const configPath = await resolveConfigPath(options);
2428
+ const pluginName = _nullishCoalesce(options.postcssPlugin, () => ( (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss")));
2429
+ if (options.majorVersion === 3) {
2430
+ clearTailwindV3RuntimeState(pluginName);
2431
+ }
2432
+ if (options.majorVersion === 4) {
2433
+ return _postcss2.default.call(void 0, [
2434
+ require3(pluginName)({
2435
+ config: configPath
2436
+ })
2437
+ ]).process("@import 'tailwindcss';", {
2438
+ from: void 0
2439
+ });
2440
+ }
2441
+ return _postcss2.default.call(void 0, [
2442
+ require3(pluginName)({
2443
+ config: configPath
2444
+ })
2445
+ ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
2446
+ from: void 0
2447
+ });
2448
+ }
2449
+
2450
+ // src/patching/status.ts
2451
+ var _types = require('@babel/types'); var t4 = _interopRequireWildcard(_types); var t = _interopRequireWildcard(_types); var t2 = _interopRequireWildcard(_types); var t3 = _interopRequireWildcard(_types); var t5 = _interopRequireWildcard(_types);
2452
+
2453
+
2454
+
2455
+ // src/babel/index.ts
2456
+ var _generator = require('@babel/generator'); var _generator2 = _interopRequireDefault(_generator);
2457
+ var _traverse = require('@babel/traverse'); var _traverse2 = _interopRequireDefault(_traverse);
2458
+ var _parser = require('@babel/parser');
2459
+ function _interopDefaultCompat(e) {
2460
+ return e && typeof e === "object" && "default" in e ? e.default : e;
2461
+ }
2462
+ var generate = _interopDefaultCompat(_generator2.default);
2463
+ var traverse = _interopDefaultCompat(_traverse2.default);
2464
+
2465
+ // src/patching/operations/export-context/postcss-v2.ts
2466
+
2467
+ var IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
2468
+ function toIdentifierName(property) {
2469
+ if (!property) {
2470
+ return "contextRef";
2471
+ }
2472
+ const sanitized = property.replace(/[^\w$]/gu, "_");
2473
+ if (/^\d/.test(sanitized)) {
2474
+ return `_${sanitized}`;
2475
+ }
2476
+ return sanitized || "contextRef";
2477
+ }
2478
+ function createExportsMember(property) {
2479
+ if (IDENTIFIER_RE.test(property)) {
2480
+ return t.memberExpression(t.identifier("exports"), t.identifier(property));
2481
+ }
2482
+ return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
2483
+ }
2484
+ function transformProcessTailwindFeaturesReturnContextV2(content) {
2485
+ const ast = _parser.parse.call(void 0, content, {
2486
+ sourceType: "unambiguous"
2487
+ });
2488
+ let hasPatched = false;
2489
+ traverse(ast, {
2490
+ FunctionDeclaration(path18) {
2491
+ const node = path18.node;
2492
+ if (_optionalChain([node, 'access', _131 => _131.id, 'optionalAccess', _132 => _132.name]) !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) {
2493
+ return;
2494
+ }
2495
+ const returnStatement3 = node.body.body[0];
2496
+ if (!t.isFunctionExpression(returnStatement3.argument)) {
2497
+ return;
2021
2498
  }
2022
2499
  const body = returnStatement3.argument.body.body;
2023
2500
  const lastStatement = body[body.length - 1];
@@ -2042,10 +2519,10 @@ function transformPostcssPluginV2(content, options) {
2042
2519
  const ast = _parser.parse.call(void 0, content);
2043
2520
  let hasPatched = false;
2044
2521
  traverse(ast, {
2045
- Program(path13) {
2046
- const program = path13.node;
2522
+ Program(path18) {
2523
+ const program = path18.node;
2047
2524
  const index = program.body.findIndex((statement) => {
2048
- return t.isFunctionDeclaration(statement) && _optionalChain([statement, 'access', _79 => _79.id, 'optionalAccess', _80 => _80.name]) === "_default";
2525
+ return t.isFunctionDeclaration(statement) && _optionalChain([statement, 'access', _133 => _133.id, 'optionalAccess', _134 => _134.name]) === "_default";
2049
2526
  });
2050
2527
  if (index === -1) {
2051
2528
  return;
@@ -2077,12 +2554,12 @@ function transformPostcssPluginV2(content, options) {
2077
2554
  );
2078
2555
  }
2079
2556
  },
2080
- FunctionDeclaration(path13) {
2557
+ FunctionDeclaration(path18) {
2081
2558
  if (hasPatched) {
2082
2559
  return;
2083
2560
  }
2084
- const fn = path13.node;
2085
- if (_optionalChain([fn, 'access', _81 => _81.id, 'optionalAccess', _82 => _82.name]) !== "_default") {
2561
+ const fn = path18.node;
2562
+ if (_optionalChain([fn, 'access', _135 => _135.id, 'optionalAccess', _136 => _136.name]) !== "_default") {
2086
2563
  return;
2087
2564
  }
2088
2565
  if (fn.body.body.length !== 1 || !t.isReturnStatement(fn.body.body[0])) {
@@ -2170,9 +2647,9 @@ function transformProcessTailwindFeaturesReturnContext(content) {
2170
2647
  const ast = _parser.parse.call(void 0, content);
2171
2648
  let hasPatched = false;
2172
2649
  traverse(ast, {
2173
- FunctionDeclaration(path13) {
2174
- const node = path13.node;
2175
- if (_optionalChain([node, 'access', _83 => _83.id, 'optionalAccess', _84 => _84.name]) !== "processTailwindFeatures" || node.body.body.length !== 1) {
2650
+ FunctionDeclaration(path18) {
2651
+ const node = path18.node;
2652
+ if (_optionalChain([node, 'access', _137 => _137.id, 'optionalAccess', _138 => _138.name]) !== "processTailwindFeatures" || node.body.body.length !== 1) {
2176
2653
  return;
2177
2654
  }
2178
2655
  const [returnStatement3] = node.body.body;
@@ -2203,10 +2680,10 @@ function transformPostcssPlugin(content, { refProperty }) {
2203
2680
  const valueMember = t2.memberExpression(refIdentifier, t2.identifier("value"));
2204
2681
  let hasPatched = false;
2205
2682
  traverse(ast, {
2206
- Program(path13) {
2207
- const program = path13.node;
2683
+ Program(path18) {
2684
+ const program = path18.node;
2208
2685
  const index = program.body.findIndex((statement) => {
2209
- return t2.isExpressionStatement(statement) && t2.isAssignmentExpression(statement.expression) && t2.isMemberExpression(statement.expression.left) && t2.isFunctionExpression(statement.expression.right) && _optionalChain([statement, 'access', _85 => _85.expression, 'access', _86 => _86.right, 'access', _87 => _87.id, 'optionalAccess', _88 => _88.name]) === "tailwindcss";
2686
+ return t2.isExpressionStatement(statement) && t2.isAssignmentExpression(statement.expression) && t2.isMemberExpression(statement.expression.left) && t2.isFunctionExpression(statement.expression.right) && _optionalChain([statement, 'access', _139 => _139.expression, 'access', _140 => _140.right, 'access', _141 => _141.id, 'optionalAccess', _142 => _142.name]) === "tailwindcss";
2210
2687
  });
2211
2688
  if (index === -1) {
2212
2689
  return;
@@ -2242,12 +2719,12 @@ function transformPostcssPlugin(content, { refProperty }) {
2242
2719
  );
2243
2720
  }
2244
2721
  },
2245
- FunctionExpression(path13) {
2722
+ FunctionExpression(path18) {
2246
2723
  if (hasPatched) {
2247
2724
  return;
2248
2725
  }
2249
- const fn = path13.node;
2250
- if (_optionalChain([fn, 'access', _89 => _89.id, 'optionalAccess', _90 => _90.name]) !== "tailwindcss" || fn.body.body.length !== 1) {
2726
+ const fn = path18.node;
2727
+ if (_optionalChain([fn, 'access', _143 => _143.id, 'optionalAccess', _144 => _144.name]) !== "tailwindcss" || fn.body.body.length !== 1) {
2251
2728
  return;
2252
2729
  }
2253
2730
  const [returnStatement3] = fn.body.body;
@@ -2319,54 +2796,27 @@ function transformPostcssPlugin(content, { refProperty }) {
2319
2796
 
2320
2797
 
2321
2798
 
2322
-
2323
- // src/utils.ts
2324
- function isObject(val) {
2325
- return val !== null && typeof val === "object" && Array.isArray(val) === false;
2326
- }
2327
- function spliceChangesIntoString(str, changes) {
2328
- if (!changes[0]) {
2329
- return str;
2330
- }
2331
- changes.sort((a, b) => {
2332
- return a.end - b.end || a.start - b.start;
2333
- });
2334
- let result = "";
2335
- let previous = changes[0];
2336
- result += str.slice(0, previous.start);
2337
- result += previous.replacement;
2338
- for (let i = 1; i < changes.length; ++i) {
2339
- const change = changes[i];
2340
- result += str.slice(previous.end, change.start);
2341
- result += change.replacement;
2342
- previous = change;
2343
- }
2344
- result += str.slice(previous.end);
2345
- return result;
2346
- }
2347
-
2348
- // src/patching/operations/extend-length-units.ts
2349
2799
  function updateLengthUnitsArray(content, options) {
2350
2800
  const { variableName = "lengthUnits", units } = options;
2351
2801
  const ast = _parser.parse.call(void 0, content);
2352
2802
  let arrayRef;
2353
2803
  let changed = false;
2354
2804
  traverse(ast, {
2355
- Identifier(path13) {
2356
- if (path13.node.name === variableName && t3.isVariableDeclarator(path13.parent) && t3.isArrayExpression(path13.parent.init)) {
2357
- arrayRef = path13.parent.init;
2805
+ Identifier(path18) {
2806
+ if (path18.node.name === variableName && t3.isVariableDeclarator(path18.parent) && t3.isArrayExpression(path18.parent.init)) {
2807
+ arrayRef = path18.parent.init;
2358
2808
  const existing = new Set(
2359
- path13.parent.init.elements.map((element) => t3.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
2809
+ path18.parent.init.elements.map((element) => t3.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
2360
2810
  );
2361
2811
  for (const unit of units) {
2362
2812
  if (!existing.has(unit)) {
2363
- path13.parent.init.elements = path13.parent.init.elements.map((element) => {
2813
+ path18.parent.init.elements = path18.parent.init.elements.map((element) => {
2364
2814
  if (t3.isStringLiteral(element)) {
2365
2815
  return t3.stringLiteral(element.value);
2366
2816
  }
2367
2817
  return element;
2368
2818
  });
2369
- path13.parent.init.elements.push(t3.stringLiteral(unit));
2819
+ path18.parent.init.elements.push(t3.stringLiteral(unit));
2370
2820
  changed = true;
2371
2821
  }
2372
2822
  }
@@ -2447,13 +2897,13 @@ function applyExtendLengthUnitsPatchV4(rootDir, options) {
2447
2897
  const { code, file, match } = item;
2448
2898
  const ast = _parser.parse.call(void 0, match[0], { sourceType: "unambiguous" });
2449
2899
  traverse(ast, {
2450
- ArrayExpression(path13) {
2900
+ ArrayExpression(path18) {
2451
2901
  for (const unit of opts.units) {
2452
- if (path13.node.elements.some((element) => t3.isStringLiteral(element) && element.value === unit)) {
2902
+ if (path18.node.elements.some((element) => t3.isStringLiteral(element) && element.value === unit)) {
2453
2903
  item.hasPatched = true;
2454
2904
  return;
2455
2905
  }
2456
- path13.node.elements.push(t3.stringLiteral(unit));
2906
+ path18.node.elements.push(t3.stringLiteral(unit));
2457
2907
  }
2458
2908
  }
2459
2909
  });
@@ -2489,501 +2939,207 @@ function inspectLengthUnitsArray(content, variableName, units) {
2489
2939
  let found = false;
2490
2940
  let missingUnits = [];
2491
2941
  traverse(ast, {
2492
- Identifier(path13) {
2493
- if (path13.node.name === variableName && t4.isVariableDeclarator(path13.parent) && t4.isArrayExpression(path13.parent.init)) {
2942
+ Identifier(path18) {
2943
+ if (path18.node.name === variableName && t4.isVariableDeclarator(path18.parent) && t4.isArrayExpression(path18.parent.init)) {
2494
2944
  found = true;
2495
2945
  const existing = new Set(
2496
- path13.parent.init.elements.map((element) => t4.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
2946
+ path18.parent.init.elements.map((element) => t4.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
2497
2947
  );
2498
2948
  missingUnits = units.filter((unit) => !existing.has(unit));
2499
- path13.stop();
2949
+ path18.stop();
2500
2950
  }
2501
- }
2502
- });
2503
- return {
2504
- found,
2505
- missingUnits
2506
- };
2507
- }
2508
- function checkExposeContextPatch(context) {
2509
- const { packageInfo, options, majorVersion } = context;
2510
- const refProperty = options.features.exposeContext.refProperty;
2511
- if (!options.features.exposeContext.enabled) {
2512
- return {
2513
- name: "exposeContext",
2514
- status: "skipped",
2515
- reason: "exposeContext feature disabled",
2516
- files: []
2517
- };
2518
- }
2519
- if (majorVersion === 4) {
2520
- return {
2521
- name: "exposeContext",
2522
- status: "unsupported",
2523
- reason: "Context export patch is only required for Tailwind v2/v3",
2524
- files: []
2525
- };
2526
- }
2527
- const checks = [];
2528
- function inspectFile(relative, transform) {
2529
- const filePath = _pathe2.default.resolve(packageInfo.rootPath, relative);
2530
- if (!_fsextra2.default.existsSync(filePath)) {
2531
- checks.push({ relative, exists: false, patched: false });
2532
- return;
2533
- }
2534
- const content = _fsextra2.default.readFileSync(filePath, "utf8");
2535
- const { hasPatched } = transform(content);
2536
- checks.push({
2537
- relative,
2538
- exists: true,
2539
- patched: hasPatched
2540
- });
2541
- }
2542
- if (majorVersion === 3) {
2543
- inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
2544
- const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
2545
- const pluginRelative = pluginCandidates.find((candidate) => _fsextra2.default.existsSync(_pathe2.default.resolve(packageInfo.rootPath, candidate)));
2546
- if (pluginRelative) {
2547
- inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
2548
- } else {
2549
- checks.push({ relative: "lib/plugin.js", exists: false, patched: false });
2550
- }
2551
- } else {
2552
- inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
2553
- inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
2554
- }
2555
- const files = checks.filter((check) => check.exists).map((check) => check.relative);
2556
- const missingFiles = checks.filter((check) => !check.exists);
2557
- const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
2558
- const reasons = [];
2559
- if (missingFiles.length) {
2560
- reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
2561
- }
2562
- if (unpatchedFiles.length) {
2563
- reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
2564
- }
2565
- return {
2566
- name: "exposeContext",
2567
- status: reasons.length ? "not-applied" : "applied",
2568
- ...reasons.length ? { reason: reasons.join("; ") } : {},
2569
- files
2570
- };
2571
- }
2572
- function checkExtendLengthUnitsV3(rootDir, options) {
2573
- const lengthUnitsFilePath = _nullishCoalesce(options.lengthUnitsFilePath, () => ( "lib/util/dataTypes.js"));
2574
- const variableName = _nullishCoalesce(options.variableName, () => ( "lengthUnits"));
2575
- const target = _pathe2.default.resolve(rootDir, lengthUnitsFilePath);
2576
- const files = _fsextra2.default.existsSync(target) ? [_pathe2.default.relative(rootDir, target)] : [];
2577
- if (!_fsextra2.default.existsSync(target)) {
2578
- return {
2579
- name: "extendLengthUnits",
2580
- status: "not-applied",
2581
- reason: `missing ${lengthUnitsFilePath}`,
2582
- files
2583
- };
2584
- }
2585
- const content = _fsextra2.default.readFileSync(target, "utf8");
2586
- const { found, missingUnits } = inspectLengthUnitsArray(content, variableName, options.units);
2587
- if (!found) {
2588
- return {
2589
- name: "extendLengthUnits",
2590
- status: "not-applied",
2591
- reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
2592
- files
2593
- };
2594
- }
2595
- if (missingUnits.length) {
2596
- return {
2597
- name: "extendLengthUnits",
2598
- status: "not-applied",
2599
- reason: `missing units: ${missingUnits.join(", ")}`,
2600
- files
2601
- };
2602
- }
2603
- return {
2604
- name: "extendLengthUnits",
2605
- status: "applied",
2606
- files
2607
- };
2608
- }
2609
- function checkExtendLengthUnitsV4(rootDir, options) {
2610
- const distDir = _pathe2.default.resolve(rootDir, "dist");
2611
- if (!_fsextra2.default.existsSync(distDir)) {
2612
- return {
2613
- name: "extendLengthUnits",
2614
- status: "not-applied",
2615
- reason: "dist directory not found for Tailwind v4 package",
2616
- files: []
2617
- };
2618
- }
2619
- const result = applyExtendLengthUnitsPatchV4(rootDir, {
2620
- ...options,
2621
- enabled: true,
2622
- overwrite: false
2623
- });
2624
- if (result.files.length === 0) {
2625
- return {
2626
- name: "extendLengthUnits",
2627
- status: "not-applied",
2628
- reason: "no bundle chunks matched the length unit pattern",
2629
- files: []
2630
- };
2631
- }
2632
- const files = result.files.map((file) => _pathe2.default.relative(rootDir, file.file));
2633
- const pending = result.files.filter((file) => !file.hasPatched);
2634
- if (pending.length) {
2635
- return {
2636
- name: "extendLengthUnits",
2637
- status: "not-applied",
2638
- reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
2639
- files: pending.map((file) => _pathe2.default.relative(rootDir, file.file))
2640
- };
2641
- }
2951
+ }
2952
+ });
2642
2953
  return {
2643
- name: "extendLengthUnits",
2644
- status: "applied",
2645
- files
2954
+ found,
2955
+ missingUnits
2646
2956
  };
2647
2957
  }
2648
- function checkExtendLengthUnitsPatch(context) {
2958
+ function checkExposeContextPatch(context) {
2649
2959
  const { packageInfo, options, majorVersion } = context;
2650
- if (!options.features.extendLengthUnits) {
2960
+ const refProperty = options.features.exposeContext.refProperty;
2961
+ if (!options.features.exposeContext.enabled) {
2651
2962
  return {
2652
- name: "extendLengthUnits",
2963
+ name: "exposeContext",
2653
2964
  status: "skipped",
2654
- reason: "extendLengthUnits feature disabled",
2965
+ reason: "exposeContext feature disabled",
2655
2966
  files: []
2656
2967
  };
2657
2968
  }
2658
- if (majorVersion === 2) {
2969
+ if (majorVersion === 4) {
2659
2970
  return {
2660
- name: "extendLengthUnits",
2971
+ name: "exposeContext",
2661
2972
  status: "unsupported",
2662
- reason: "length unit extension is only applied for Tailwind v3/v4",
2973
+ reason: "Context export patch is only required for Tailwind v2/v3",
2663
2974
  files: []
2664
2975
  };
2665
2976
  }
2666
- if (majorVersion === 3) {
2667
- return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
2668
- }
2669
- return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
2670
- }
2671
- function getPatchStatusReport(context) {
2672
- return {
2673
- package: {
2674
- name: _nullishCoalesce(context.packageInfo.name, () => ( _optionalChain([context, 'access', _91 => _91.packageInfo, 'access', _92 => _92.packageJson, 'optionalAccess', _93 => _93.name]))),
2675
- version: context.packageInfo.version,
2676
- root: context.packageInfo.rootPath
2677
- },
2678
- majorVersion: context.majorVersion,
2679
- entries: [
2680
- checkExposeContextPatch(context),
2681
- checkExtendLengthUnitsPatch(context)
2682
- ]
2683
- };
2684
- }
2685
-
2686
- // src/runtime/class-collector.ts
2687
-
2688
-
2689
-
2690
- function collectClassesFromContexts(contexts, filter) {
2691
- const set = /* @__PURE__ */ new Set();
2692
- for (const context of contexts) {
2693
- if (!isObject(context) || !context.classCache) {
2694
- continue;
2695
- }
2696
- for (const key of context.classCache.keys()) {
2697
- const className = key.toString();
2698
- if (filter(className)) {
2699
- set.add(className);
2700
- }
2977
+ const checks = [];
2978
+ function inspectFile(relative, transform) {
2979
+ const filePath = _pathe2.default.resolve(packageInfo.rootPath, relative);
2980
+ if (!_fsextra2.default.existsSync(filePath)) {
2981
+ checks.push({ relative, exists: false, patched: false });
2982
+ return;
2701
2983
  }
2984
+ const content = _fsextra2.default.readFileSync(filePath, "utf8");
2985
+ const { hasPatched } = transform(content);
2986
+ checks.push({
2987
+ relative,
2988
+ exists: true,
2989
+ patched: hasPatched
2990
+ });
2702
2991
  }
2703
- return set;
2704
- }
2705
- async function collectClassesFromTailwindV4(options) {
2706
- const set = /* @__PURE__ */ new Set();
2707
- const v4Options = options.tailwind.v4;
2708
- if (!v4Options) {
2709
- return set;
2710
- }
2711
- const toAbsolute = (value) => {
2712
- if (!value) {
2713
- return void 0;
2714
- }
2715
- return _pathe2.default.isAbsolute(value) ? value : _pathe2.default.resolve(options.projectRoot, value);
2716
- };
2717
- const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
2718
- const resolvedDefaultBase = _nullishCoalesce(toAbsolute(v4Options.base), () => ( _process2.default.cwd()));
2719
- const resolveSources = (base) => {
2720
- if (!_optionalChain([v4Options, 'access', _94 => _94.sources, 'optionalAccess', _95 => _95.length])) {
2721
- return void 0;
2722
- }
2723
- return v4Options.sources.map((source) => ({
2724
- base: _nullishCoalesce(source.base, () => ( base)),
2725
- pattern: source.pattern,
2726
- negated: source.negated
2727
- }));
2728
- };
2729
- if (v4Options.cssEntries.length > 0) {
2730
- for (const entry of v4Options.cssEntries) {
2731
- const filePath = _pathe2.default.isAbsolute(entry) ? entry : _pathe2.default.resolve(options.projectRoot, entry);
2732
- if (!await _fsextra2.default.pathExists(filePath)) {
2733
- continue;
2734
- }
2735
- const css = await _fsextra2.default.readFile(filePath, "utf8");
2736
- const entryDir = _pathe2.default.dirname(filePath);
2737
- const designSystemBases = resolvedConfiguredBase && resolvedConfiguredBase !== entryDir ? [entryDir, resolvedConfiguredBase] : [entryDir];
2738
- const sourcesBase = _nullishCoalesce(resolvedConfiguredBase, () => ( entryDir));
2739
- const sources = resolveSources(sourcesBase);
2740
- const firstBase = _nullishCoalesce(designSystemBases[0], () => ( entryDir));
2741
- const extractOptions = {
2742
- cwd: options.projectRoot,
2743
- base: firstBase,
2744
- baseFallbacks: designSystemBases.slice(1),
2745
- css,
2746
- ...sources === void 0 ? {} : { sources }
2747
- };
2748
- const candidates = await extractValidCandidates(extractOptions);
2749
- for (const candidate of candidates) {
2750
- if (options.filter(candidate)) {
2751
- set.add(candidate);
2752
- }
2753
- }
2992
+ if (majorVersion === 3) {
2993
+ inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
2994
+ const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
2995
+ const pluginRelative = pluginCandidates.find((candidate) => _fsextra2.default.existsSync(_pathe2.default.resolve(packageInfo.rootPath, candidate)));
2996
+ if (pluginRelative) {
2997
+ inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
2998
+ } else {
2999
+ checks.push({ relative: "lib/plugin.js", exists: false, patched: false });
2754
3000
  }
2755
3001
  } else {
2756
- const baseForCss = _nullishCoalesce(resolvedConfiguredBase, () => ( resolvedDefaultBase));
2757
- const sources = resolveSources(baseForCss);
2758
- const extractOptions = {
2759
- cwd: options.projectRoot,
2760
- base: baseForCss,
2761
- ...v4Options.css === void 0 ? {} : { css: v4Options.css },
2762
- ...sources === void 0 ? {} : { sources }
2763
- };
2764
- const candidates = await extractValidCandidates(extractOptions);
2765
- for (const candidate of candidates) {
2766
- if (options.filter(candidate)) {
2767
- set.add(candidate);
2768
- }
2769
- }
2770
- }
2771
- return set;
2772
- }
2773
-
2774
- // src/runtime/context-registry.ts
2775
- var _module = require('module');
2776
-
2777
-
2778
- var require2 = _module.createRequire.call(void 0, importMetaUrl);
2779
- function resolveRuntimeEntry(packageInfo, majorVersion) {
2780
- const root = packageInfo.rootPath;
2781
- if (majorVersion === 2) {
2782
- const jitIndex = _pathe2.default.join(root, "lib/jit/index.js");
2783
- if (_fsextra2.default.existsSync(jitIndex)) {
2784
- return jitIndex;
2785
- }
2786
- } else if (majorVersion === 3) {
2787
- const plugin = _pathe2.default.join(root, "lib/plugin.js");
2788
- const index = _pathe2.default.join(root, "lib/index.js");
2789
- if (_fsextra2.default.existsSync(plugin)) {
2790
- return plugin;
2791
- }
2792
- if (_fsextra2.default.existsSync(index)) {
2793
- return index;
2794
- }
2795
- }
2796
- return void 0;
2797
- }
2798
- function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
2799
- if (majorVersion === 4) {
2800
- return [];
2801
- }
2802
- const entry = resolveRuntimeEntry(packageInfo, majorVersion);
2803
- if (!entry) {
2804
- return [];
2805
- }
2806
- const moduleExports = require2(entry);
2807
- if (!moduleExports) {
2808
- return [];
2809
- }
2810
- const ref = moduleExports[refProperty];
2811
- if (!ref) {
2812
- return [];
2813
- }
2814
- if (Array.isArray(ref)) {
2815
- return ref;
2816
- }
2817
- if (typeof ref === "object" && Array.isArray(ref.value)) {
2818
- return ref.value;
2819
- }
2820
- return [];
2821
- }
2822
-
2823
- // src/runtime/process-tailwindcss.ts
2824
-
2825
-
2826
- var _postcss = require('postcss'); var _postcss2 = _interopRequireDefault(_postcss);
2827
- var _tailwindcssconfig = require('tailwindcss-config');
2828
- var require3 = _module.createRequire.call(void 0, importMetaUrl);
2829
- async function resolveConfigPath(options) {
2830
- if (options.config && _pathe2.default.isAbsolute(options.config)) {
2831
- return options.config;
3002
+ inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
3003
+ inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
2832
3004
  }
2833
- const result = await _tailwindcssconfig.loadConfig.call(void 0, { cwd: options.cwd });
2834
- if (!result) {
2835
- throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
3005
+ const files = checks.filter((check) => check.exists).map((check) => check.relative);
3006
+ const missingFiles = checks.filter((check) => !check.exists);
3007
+ const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
3008
+ const reasons = [];
3009
+ if (missingFiles.length) {
3010
+ reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
2836
3011
  }
2837
- return result.filepath;
2838
- }
2839
- async function runTailwindBuild(options) {
2840
- const configPath = await resolveConfigPath(options);
2841
- const pluginName = _nullishCoalesce(options.postcssPlugin, () => ( (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss")));
2842
- if (options.majorVersion === 4) {
2843
- return _postcss2.default.call(void 0, [
2844
- require3(pluginName)({
2845
- config: configPath
2846
- })
2847
- ]).process("@import 'tailwindcss';", {
2848
- from: void 0
2849
- });
3012
+ if (unpatchedFiles.length) {
3013
+ reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
2850
3014
  }
2851
- return _postcss2.default.call(void 0, [
2852
- require3(pluginName)({
2853
- config: configPath
2854
- })
2855
- ]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
2856
- from: void 0
2857
- });
2858
- }
2859
-
2860
- // src/api/tailwindcss-patcher.ts
2861
-
2862
-
2863
- var _localpkg = require('local-pkg');
2864
-
2865
- var _semver = require('semver');
2866
-
2867
- // src/options/legacy.ts
2868
- function normalizeLegacyFeatures(patch) {
2869
- const apply = _optionalChain([patch, 'optionalAccess', _96 => _96.applyPatches]);
2870
- const extend = _optionalChain([apply, 'optionalAccess', _97 => _97.extendLengthUnits]);
2871
- let extendOption = false;
2872
- if (extend && typeof extend === "object") {
2873
- extendOption = {
2874
- ...extend,
2875
- enabled: true
3015
+ return {
3016
+ name: "exposeContext",
3017
+ status: reasons.length ? "not-applied" : "applied",
3018
+ ...reasons.length ? { reason: reasons.join("; ") } : {},
3019
+ files
3020
+ };
3021
+ }
3022
+ function checkExtendLengthUnitsV3(rootDir, options) {
3023
+ const lengthUnitsFilePath = _nullishCoalesce(options.lengthUnitsFilePath, () => ( "lib/util/dataTypes.js"));
3024
+ const variableName = _nullishCoalesce(options.variableName, () => ( "lengthUnits"));
3025
+ const target = _pathe2.default.resolve(rootDir, lengthUnitsFilePath);
3026
+ const files = _fsextra2.default.existsSync(target) ? [_pathe2.default.relative(rootDir, target)] : [];
3027
+ if (!_fsextra2.default.existsSync(target)) {
3028
+ return {
3029
+ name: "extendLengthUnits",
3030
+ status: "not-applied",
3031
+ reason: `missing ${lengthUnitsFilePath}`,
3032
+ files
2876
3033
  };
2877
- } else if (extend === true) {
2878
- extendOption = {
2879
- enabled: true,
2880
- units: ["rpx"],
2881
- ..._optionalChain([patch, 'optionalAccess', _98 => _98.overwrite]) === void 0 ? {} : { overwrite: patch.overwrite }
3034
+ }
3035
+ const content = _fsextra2.default.readFileSync(target, "utf8");
3036
+ const { found, missingUnits } = inspectLengthUnitsArray(content, variableName, options.units);
3037
+ if (!found) {
3038
+ return {
3039
+ name: "extendLengthUnits",
3040
+ status: "not-applied",
3041
+ reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
3042
+ files
3043
+ };
3044
+ }
3045
+ if (missingUnits.length) {
3046
+ return {
3047
+ name: "extendLengthUnits",
3048
+ status: "not-applied",
3049
+ reason: `missing units: ${missingUnits.join(", ")}`,
3050
+ files
2882
3051
  };
2883
3052
  }
2884
3053
  return {
2885
- exposeContext: _nullishCoalesce(_optionalChain([apply, 'optionalAccess', _99 => _99.exportContext]), () => ( true)),
2886
- extendLengthUnits: extendOption
3054
+ name: "extendLengthUnits",
3055
+ status: "applied",
3056
+ files
2887
3057
  };
2888
3058
  }
2889
- function fromLegacyOptions(options) {
2890
- if (!options) {
2891
- return {};
3059
+ function checkExtendLengthUnitsV4(rootDir, options) {
3060
+ const distDir = _pathe2.default.resolve(rootDir, "dist");
3061
+ if (!_fsextra2.default.existsSync(distDir)) {
3062
+ return {
3063
+ name: "extendLengthUnits",
3064
+ status: "not-applied",
3065
+ reason: "dist directory not found for Tailwind v4 package",
3066
+ files: []
3067
+ };
3068
+ }
3069
+ const result = applyExtendLengthUnitsPatchV4(rootDir, {
3070
+ ...options,
3071
+ enabled: true,
3072
+ overwrite: false
3073
+ });
3074
+ if (result.files.length === 0) {
3075
+ return {
3076
+ name: "extendLengthUnits",
3077
+ status: "not-applied",
3078
+ reason: "no bundle chunks matched the length unit pattern",
3079
+ files: []
3080
+ };
3081
+ }
3082
+ const files = result.files.map((file) => _pathe2.default.relative(rootDir, file.file));
3083
+ const pending = result.files.filter((file) => !file.hasPatched);
3084
+ if (pending.length) {
3085
+ return {
3086
+ name: "extendLengthUnits",
3087
+ status: "not-applied",
3088
+ reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
3089
+ files: pending.map((file) => _pathe2.default.relative(rootDir, file.file))
3090
+ };
2892
3091
  }
2893
- const patch = options.patch;
2894
- const features = normalizeLegacyFeatures(patch);
2895
- const output = _optionalChain([patch, 'optionalAccess', _100 => _100.output]);
2896
- const tailwindConfig = _optionalChain([patch, 'optionalAccess', _101 => _101.tailwindcss]);
2897
- const tailwindVersion = _optionalChain([tailwindConfig, 'optionalAccess', _102 => _102.version]);
2898
- const tailwindV2 = _optionalChain([tailwindConfig, 'optionalAccess', _103 => _103.v2]);
2899
- const tailwindV3 = _optionalChain([tailwindConfig, 'optionalAccess', _104 => _104.v3]);
2900
- const tailwindV4 = _optionalChain([tailwindConfig, 'optionalAccess', _105 => _105.v4]);
2901
- const tailwindConfigPath = _nullishCoalesce(_optionalChain([tailwindV3, 'optionalAccess', _106 => _106.config]), () => ( _optionalChain([tailwindV2, 'optionalAccess', _107 => _107.config])));
2902
- const tailwindCwd = _nullishCoalesce(_nullishCoalesce(_optionalChain([tailwindV3, 'optionalAccess', _108 => _108.cwd]), () => ( _optionalChain([tailwindV2, 'optionalAccess', _109 => _109.cwd]))), () => ( _optionalChain([patch, 'optionalAccess', _110 => _110.cwd])));
2903
- const normalizedExtract = output ? {
2904
- ...output.filename === void 0 ? {} : { file: output.filename },
2905
- pretty: output.loose ? 2 : false,
2906
- ...output.removeUniversalSelector === void 0 ? {} : { removeUniversalSelector: output.removeUniversalSelector }
2907
- } : void 0;
2908
- const normalizedTailwindcss = {
2909
- ..._optionalChain([patch, 'optionalAccess', _111 => _111.packageName]) === void 0 ? {} : { packageName: patch.packageName },
2910
- ...tailwindVersion === void 0 ? {} : { version: tailwindVersion },
2911
- ..._optionalChain([patch, 'optionalAccess', _112 => _112.resolve]) === void 0 ? {} : { resolve: patch.resolve },
2912
- ...tailwindConfigPath === void 0 ? {} : { config: tailwindConfigPath },
2913
- ...tailwindCwd === void 0 ? {} : { cwd: tailwindCwd },
2914
- ...tailwindV2 === void 0 ? {} : { v2: tailwindV2 },
2915
- ...tailwindV3 === void 0 ? {} : { v3: tailwindV3 },
2916
- ...tailwindV4 === void 0 ? {} : { v4: tailwindV4 }
2917
- };
2918
- const normalizedCache = typeof options.cache === "boolean" ? options.cache : options.cache ? {
2919
- ...options.cache,
2920
- enabled: _nullishCoalesce(options.cache.enabled, () => ( true))
2921
- } : void 0;
2922
- const normalizedApply = {
2923
- ..._optionalChain([patch, 'optionalAccess', _113 => _113.overwrite]) === void 0 ? {} : { overwrite: patch.overwrite },
2924
- exposeContext: features.exposeContext,
2925
- extendLengthUnits: features.extendLengthUnits
2926
- };
2927
3092
  return {
2928
- ..._optionalChain([patch, 'optionalAccess', _114 => _114.cwd]) === void 0 ? {} : { projectRoot: patch.cwd },
2929
- ..._optionalChain([patch, 'optionalAccess', _115 => _115.filter]) === void 0 ? {} : { filter: patch.filter },
2930
- ...normalizedCache === void 0 ? {} : { cache: normalizedCache },
2931
- ...normalizedExtract === void 0 ? {} : { extract: normalizedExtract },
2932
- ...Object.keys(normalizedTailwindcss).length === 0 ? {} : { tailwindcss: normalizedTailwindcss },
2933
- apply: normalizedApply
3093
+ name: "extendLengthUnits",
3094
+ status: "applied",
3095
+ files
2934
3096
  };
2935
3097
  }
2936
- function fromUnifiedConfig(registry) {
2937
- if (!registry) {
2938
- return {};
3098
+ function checkExtendLengthUnitsPatch(context) {
3099
+ const { packageInfo, options, majorVersion } = context;
3100
+ if (!options.features.extendLengthUnits) {
3101
+ return {
3102
+ name: "extendLengthUnits",
3103
+ status: "skipped",
3104
+ reason: "extendLengthUnits feature disabled",
3105
+ files: []
3106
+ };
2939
3107
  }
2940
- const tailwind = _nullishCoalesce(registry.tailwindcss, () => ( registry.tailwind));
2941
- const modernExtract = registry.extract;
2942
- const legacyOutput = registry.output;
2943
- const pretty = (() => {
2944
- const value = _nullishCoalesce(_optionalChain([modernExtract, 'optionalAccess', _116 => _116.pretty]), () => ( _optionalChain([legacyOutput, 'optionalAccess', _117 => _117.pretty])));
2945
- if (value === void 0) {
2946
- return void 0;
2947
- }
2948
- if (typeof value === "boolean") {
2949
- return value ? 2 : false;
2950
- }
2951
- return value;
2952
- })();
2953
- const removeUniversalSelector = _nullishCoalesce(_optionalChain([modernExtract, 'optionalAccess', _118 => _118.removeUniversalSelector]), () => ( _optionalChain([legacyOutput, 'optionalAccess', _119 => _119.stripUniversalSelector])));
2954
- const outputFile = _nullishCoalesce(_optionalChain([modernExtract, 'optionalAccess', _120 => _120.file]), () => ( _optionalChain([legacyOutput, 'optionalAccess', _121 => _121.file])));
2955
- const normalizedExtract = modernExtract || legacyOutput ? {
2956
- ..._optionalChain([modernExtract, 'optionalAccess', _122 => _122.write]) === void 0 ? {} : { write: modernExtract.write },
2957
- ...outputFile === void 0 ? {} : { file: outputFile },
2958
- ...pretty === void 0 ? {} : { pretty },
2959
- ...removeUniversalSelector === void 0 ? {} : { removeUniversalSelector },
2960
- ..._optionalChain([modernExtract, 'optionalAccess', _123 => _123.format]) === void 0 ? {} : { format: modernExtract.format }
2961
- } : void 0;
2962
- const normalizedTailwindcss = tailwind ? {
2963
- ...tailwind.version === void 0 ? {} : { version: tailwind.version },
2964
- ...tailwind.packageName === void 0 ? tailwind.package === void 0 ? {} : { packageName: tailwind.package } : { packageName: tailwind.packageName },
2965
- ...tailwind.resolve === void 0 ? {} : { resolve: tailwind.resolve },
2966
- ...tailwind.config === void 0 ? {} : { config: tailwind.config },
2967
- ...tailwind.cwd === void 0 ? {} : { cwd: tailwind.cwd },
2968
- ...tailwind.v2 === void 0 ? tailwind.legacy === void 0 ? {} : { v2: tailwind.legacy } : { v2: tailwind.v2 },
2969
- ...tailwind.v3 === void 0 ? tailwind.classic === void 0 ? {} : { v3: tailwind.classic } : { v3: tailwind.v3 },
2970
- ...tailwind.v4 === void 0 ? tailwind.next === void 0 ? {} : { v4: tailwind.next } : { v4: tailwind.v4 }
2971
- } : void 0;
2972
- const normalizedApply = registry.apply ? {
2973
- ...registry.apply.overwrite === void 0 ? {} : { overwrite: registry.apply.overwrite },
2974
- ...registry.apply.exposeContext === void 0 ? {} : { exposeContext: registry.apply.exposeContext },
2975
- ...registry.apply.extendLengthUnits === void 0 ? {} : { extendLengthUnits: registry.apply.extendLengthUnits }
2976
- } : void 0;
3108
+ if (majorVersion === 2) {
3109
+ return {
3110
+ name: "extendLengthUnits",
3111
+ status: "unsupported",
3112
+ reason: "length unit extension is only applied for Tailwind v3/v4",
3113
+ files: []
3114
+ };
3115
+ }
3116
+ if (majorVersion === 3) {
3117
+ return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
3118
+ }
3119
+ return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
3120
+ }
3121
+ function getPatchStatusReport(context) {
2977
3122
  return {
2978
- ...registry.projectRoot === void 0 ? {} : { projectRoot: registry.projectRoot },
2979
- ...normalizedApply === void 0 ? {} : { apply: normalizedApply },
2980
- ...registry.cache === void 0 ? {} : { cache: registry.cache },
2981
- ...registry.filter === void 0 ? {} : { filter: registry.filter },
2982
- ...normalizedExtract === void 0 ? {} : { extract: normalizedExtract },
2983
- ...normalizedTailwindcss === void 0 ? {} : { tailwindcss: normalizedTailwindcss }
3123
+ package: {
3124
+ name: _nullishCoalesce(context.packageInfo.name, () => ( _optionalChain([context, 'access', _145 => _145.packageInfo, 'access', _146 => _146.packageJson, 'optionalAccess', _147 => _147.name]))),
3125
+ version: context.packageInfo.version,
3126
+ root: context.packageInfo.rootPath
3127
+ },
3128
+ majorVersion: context.majorVersion,
3129
+ entries: [
3130
+ checkExposeContextPatch(context),
3131
+ checkExtendLengthUnitsPatch(context)
3132
+ ]
2984
3133
  };
2985
3134
  }
2986
3135
 
3136
+ // src/api/tailwindcss-patcher.ts
3137
+
3138
+
3139
+ var _localpkg = require('local-pkg');
3140
+
3141
+ var _semver = require('semver');
3142
+
2987
3143
  // src/patching/operations/export-context/index.ts
2988
3144
 
2989
3145
 
@@ -3085,7 +3241,7 @@ function applyTailwindPatches(context) {
3085
3241
  majorVersion
3086
3242
  });
3087
3243
  }
3088
- if (_optionalChain([options, 'access', _124 => _124.features, 'access', _125 => _125.extendLengthUnits, 'optionalAccess', _126 => _126.enabled])) {
3244
+ if (_optionalChain([options, 'access', _148 => _148.features, 'access', _149 => _149.extendLengthUnits, 'optionalAccess', _150 => _150.enabled])) {
3089
3245
  if (majorVersion === 3) {
3090
3246
  results.extendLengthUnits = applyExtendLengthUnitsPatchV3(
3091
3247
  packageInfo.rootPath,
@@ -3148,6 +3304,8 @@ var TailwindcssPatcher = (_class2 = class {
3148
3304
 
3149
3305
 
3150
3306
 
3307
+
3308
+
3151
3309
  constructor(options = {}) {;_class2.prototype.__init4.call(this);
3152
3310
  const resolvedOptions = options && typeof options === "object" && "patch" in options ? fromLegacyOptions(options) : options;
3153
3311
  this.options = normalizeOptions(resolvedOptions);
@@ -3171,11 +3329,20 @@ var TailwindcssPatcher = (_class2 = class {
3171
3329
  this.cacheStore = new CacheStore(this.options.cache, this.cacheContext);
3172
3330
  }
3173
3331
  async patch() {
3174
- return applyTailwindPatches({
3332
+ const snapshot = this.createPatchSnapshot();
3333
+ if (this.patchMemo && this.patchMemo.snapshot === snapshot) {
3334
+ return this.patchMemo.result;
3335
+ }
3336
+ const result = applyTailwindPatches({
3175
3337
  packageInfo: this.packageInfo,
3176
3338
  options: this.options,
3177
3339
  majorVersion: this.majorVersion
3178
3340
  });
3341
+ this.patchMemo = {
3342
+ result,
3343
+ snapshot: this.createPatchSnapshot()
3344
+ };
3345
+ return result;
3179
3346
  }
3180
3347
  async getPatchStatus() {
3181
3348
  return getPatchStatusReport({
@@ -3193,6 +3360,9 @@ var TailwindcssPatcher = (_class2 = class {
3193
3360
  }
3194
3361
  async runTailwindBuildIfNeeded() {
3195
3362
  if (this.majorVersion === 2 || this.majorVersion === 3) {
3363
+ if (this.inFlightBuild) {
3364
+ return this.inFlightBuild;
3365
+ }
3196
3366
  const executionOptions = resolveTailwindExecutionOptions(this.options, this.majorVersion);
3197
3367
  const buildOptions = {
3198
3368
  cwd: executionOptions.cwd,
@@ -3200,8 +3370,53 @@ var TailwindcssPatcher = (_class2 = class {
3200
3370
  ...executionOptions.config === void 0 ? {} : { config: executionOptions.config },
3201
3371
  ...executionOptions.postcssPlugin === void 0 ? {} : { postcssPlugin: executionOptions.postcssPlugin }
3202
3372
  };
3203
- await runTailwindBuild(buildOptions);
3373
+ this.inFlightBuild = runTailwindBuild(buildOptions).then(() => void 0);
3374
+ try {
3375
+ await this.inFlightBuild;
3376
+ } finally {
3377
+ this.inFlightBuild = void 0;
3378
+ }
3379
+ }
3380
+ }
3381
+ createPatchSnapshot() {
3382
+ const entries = [];
3383
+ const pushSnapshot = (filePath) => {
3384
+ if (!_fsextra2.default.pathExistsSync(filePath)) {
3385
+ entries.push(`${filePath}:missing`);
3386
+ return;
3387
+ }
3388
+ const stat = _fsextra2.default.statSync(filePath);
3389
+ entries.push(`${filePath}:${stat.size}:${Math.trunc(stat.mtimeMs)}`);
3390
+ };
3391
+ if (this.options.features.exposeContext.enabled && (this.majorVersion === 2 || this.majorVersion === 3)) {
3392
+ if (this.majorVersion === 2) {
3393
+ pushSnapshot(_pathe2.default.resolve(this.packageInfo.rootPath, "lib/jit/processTailwindFeatures.js"));
3394
+ pushSnapshot(_pathe2.default.resolve(this.packageInfo.rootPath, "lib/jit/index.js"));
3395
+ } else {
3396
+ pushSnapshot(_pathe2.default.resolve(this.packageInfo.rootPath, "lib/processTailwindFeatures.js"));
3397
+ const pluginPath = ["lib/plugin.js", "lib/index.js"].map((file) => _pathe2.default.resolve(this.packageInfo.rootPath, file)).find((file) => _fsextra2.default.pathExistsSync(file));
3398
+ if (pluginPath) {
3399
+ pushSnapshot(pluginPath);
3400
+ }
3401
+ }
3402
+ }
3403
+ if (_optionalChain([this, 'access', _151 => _151.options, 'access', _152 => _152.features, 'access', _153 => _153.extendLengthUnits, 'optionalAccess', _154 => _154.enabled])) {
3404
+ if (this.majorVersion === 3) {
3405
+ const target = _nullishCoalesce(this.options.features.extendLengthUnits.lengthUnitsFilePath, () => ( "lib/util/dataTypes.js"));
3406
+ pushSnapshot(_pathe2.default.resolve(this.packageInfo.rootPath, target));
3407
+ } else if (this.majorVersion === 4) {
3408
+ const distDir = _pathe2.default.resolve(this.packageInfo.rootPath, "dist");
3409
+ if (_fsextra2.default.pathExistsSync(distDir)) {
3410
+ const chunkNames = _fsextra2.default.readdirSync(distDir).filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs")).sort();
3411
+ for (const chunkName of chunkNames) {
3412
+ pushSnapshot(_pathe2.default.join(distDir, chunkName));
3413
+ }
3414
+ } else {
3415
+ entries.push(`${distDir}:missing`);
3416
+ }
3417
+ }
3204
3418
  }
3419
+ return entries.join("|");
3205
3420
  }
3206
3421
  async collectClassSet() {
3207
3422
  if (this.majorVersion === 4) {
@@ -3213,12 +3428,12 @@ var TailwindcssPatcher = (_class2 = class {
3213
3428
  debugCacheRead(meta) {
3214
3429
  if (meta.hit) {
3215
3430
  logger_default.debug(
3216
- `[cache] hit fingerprint=${_nullishCoalesce(_optionalChain([meta, 'access', _127 => _127.fingerprint, 'optionalAccess', _128 => _128.slice, 'call', _129 => _129(0, 12)]), () => ( "n/a"))} schema=${_nullishCoalesce(meta.schemaVersion, () => ( "legacy"))} ${meta.details.join("; ")}`
3431
+ `[cache] hit fingerprint=${_nullishCoalesce(_optionalChain([meta, 'access', _155 => _155.fingerprint, 'optionalAccess', _156 => _156.slice, 'call', _157 => _157(0, 12)]), () => ( "n/a"))} schema=${_nullishCoalesce(meta.schemaVersion, () => ( "legacy"))} ${meta.details.join("; ")}`
3217
3432
  );
3218
3433
  return;
3219
3434
  }
3220
3435
  logger_default.debug(
3221
- `[cache] miss reason=${meta.reason} fingerprint=${_nullishCoalesce(_optionalChain([meta, 'access', _130 => _130.fingerprint, 'optionalAccess', _131 => _131.slice, 'call', _132 => _132(0, 12)]), () => ( "n/a"))} schema=${_nullishCoalesce(meta.schemaVersion, () => ( "legacy"))} ${meta.details.join("; ")}`
3436
+ `[cache] miss reason=${meta.reason} fingerprint=${_nullishCoalesce(_optionalChain([meta, 'access', _158 => _158.fingerprint, 'optionalAccess', _159 => _159.slice, 'call', _160 => _160(0, 12)]), () => ( "n/a"))} schema=${_nullishCoalesce(meta.schemaVersion, () => ( "legacy"))} ${meta.details.join("; ")}`
3222
3437
  );
3223
3438
  }
3224
3439
  async mergeWithCache(set) {
@@ -3231,13 +3446,13 @@ var TailwindcssPatcher = (_class2 = class {
3231
3446
  for (const value of existing) {
3232
3447
  set.add(value);
3233
3448
  }
3234
- const writeTarget = await this.cacheStore.write(set);
3449
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : await this.cacheStore.write(set);
3235
3450
  if (writeTarget) {
3236
3451
  logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
3237
3452
  }
3238
3453
  } else {
3239
3454
  if (set.size > 0) {
3240
- const writeTarget = await this.cacheStore.write(set);
3455
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : await this.cacheStore.write(set);
3241
3456
  if (writeTarget) {
3242
3457
  logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
3243
3458
  }
@@ -3257,13 +3472,13 @@ var TailwindcssPatcher = (_class2 = class {
3257
3472
  for (const value of existing) {
3258
3473
  set.add(value);
3259
3474
  }
3260
- const writeTarget = this.cacheStore.writeSync(set);
3475
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : this.cacheStore.writeSync(set);
3261
3476
  if (writeTarget) {
3262
3477
  logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
3263
3478
  }
3264
3479
  } else {
3265
3480
  if (set.size > 0) {
3266
- const writeTarget = this.cacheStore.writeSync(set);
3481
+ const writeTarget = this.areSetsEqual(existing, set) ? void 0 : this.cacheStore.writeSync(set);
3267
3482
  if (writeTarget) {
3268
3483
  logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
3269
3484
  }
@@ -3273,6 +3488,17 @@ var TailwindcssPatcher = (_class2 = class {
3273
3488
  }
3274
3489
  return set;
3275
3490
  }
3491
+ areSetsEqual(a, b) {
3492
+ if (a.size !== b.size) {
3493
+ return false;
3494
+ }
3495
+ for (const value of a) {
3496
+ if (!b.has(value)) {
3497
+ return false;
3498
+ }
3499
+ }
3500
+ return true;
3501
+ }
3276
3502
  async getClassSet() {
3277
3503
  await this.runTailwindBuildIfNeeded();
3278
3504
  const set = await this.collectClassSet();
@@ -3291,7 +3517,7 @@ var TailwindcssPatcher = (_class2 = class {
3291
3517
  return merged;
3292
3518
  }
3293
3519
  async extract(options) {
3294
- const shouldWrite = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _133 => _133.write]), () => ( this.options.output.enabled));
3520
+ const shouldWrite = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _161 => _161.write]), () => ( this.options.output.enabled));
3295
3521
  const classSet = await this.getClassSet();
3296
3522
  const classList = Array.from(classSet);
3297
3523
  const result = {
@@ -3327,55 +3553,112 @@ var TailwindcssPatcher = (_class2 = class {
3327
3553
  __init4() {this.extractValidCandidates = exports.extractValidCandidates = extractValidCandidates}
3328
3554
  async collectContentTokens(options) {
3329
3555
  return extractProjectCandidatesWithPositions({
3330
- cwd: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _134 => _134.cwd]), () => ( this.options.projectRoot)),
3331
- sources: _nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _135 => _135.sources]), () => ( _optionalChain([this, 'access', _136 => _136.options, 'access', _137 => _137.tailwind, 'access', _138 => _138.v4, 'optionalAccess', _139 => _139.sources]))), () => ( []))
3556
+ cwd: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _162 => _162.cwd]), () => ( this.options.projectRoot)),
3557
+ sources: _nullishCoalesce(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _163 => _163.sources]), () => ( _optionalChain([this, 'access', _164 => _164.options, 'access', _165 => _165.tailwind, 'access', _166 => _166.v4, 'optionalAccess', _167 => _167.sources]))), () => ( []))
3332
3558
  });
3333
3559
  }
3334
3560
  async collectContentTokensByFile(options) {
3335
3561
  const collectContentOptions = {
3336
- ..._optionalChain([options, 'optionalAccess', _140 => _140.cwd]) === void 0 ? {} : { cwd: options.cwd },
3337
- ..._optionalChain([options, 'optionalAccess', _141 => _141.sources]) === void 0 ? {} : { sources: options.sources }
3562
+ ..._optionalChain([options, 'optionalAccess', _168 => _168.cwd]) === void 0 ? {} : { cwd: options.cwd },
3563
+ ..._optionalChain([options, 'optionalAccess', _169 => _169.sources]) === void 0 ? {} : { sources: options.sources }
3338
3564
  };
3339
3565
  const report = await this.collectContentTokens(collectContentOptions);
3340
3566
  const groupOptions = {
3341
- ..._optionalChain([options, 'optionalAccess', _142 => _142.key]) === void 0 ? {} : { key: options.key },
3342
- ..._optionalChain([options, 'optionalAccess', _143 => _143.stripAbsolutePaths]) === void 0 ? {} : { stripAbsolutePaths: options.stripAbsolutePaths }
3567
+ ..._optionalChain([options, 'optionalAccess', _170 => _170.key]) === void 0 ? {} : { key: options.key },
3568
+ ..._optionalChain([options, 'optionalAccess', _171 => _171.stripAbsolutePaths]) === void 0 ? {} : { stripAbsolutePaths: options.stripAbsolutePaths }
3343
3569
  };
3344
3570
  return groupTokensByFile(report, groupOptions);
3345
3571
  }
3346
3572
  }, _class2);
3347
3573
 
3348
- // src/cli/migrate-config.ts
3349
-
3350
-
3574
+ // src/commands/migration-report.ts
3575
+ var MIGRATION_REPORT_KIND = "tw-patch-migrate-report";
3576
+ var MIGRATION_REPORT_SCHEMA_VERSION = 1;
3577
+ function assertMigrationReportCompatibility(report, reportFile) {
3578
+ if (report.reportKind !== void 0 && report.reportKind !== MIGRATION_REPORT_KIND) {
3579
+ throw new Error(`Unsupported report kind "${report.reportKind}" in ${reportFile}.`);
3580
+ }
3581
+ if (report.schemaVersion !== void 0 && (!Number.isInteger(report.schemaVersion) || report.schemaVersion > MIGRATION_REPORT_SCHEMA_VERSION)) {
3582
+ throw new Error(
3583
+ `Unsupported report schema version "${String(report.schemaVersion)}" in ${reportFile}. Current supported version is ${MIGRATION_REPORT_SCHEMA_VERSION}.`
3584
+ );
3585
+ }
3586
+ }
3587
+
3588
+ // src/commands/migrate-config.ts
3589
+
3590
+
3591
+ // src/commands/migration-aggregation.ts
3592
+ function createMigrationAggregationState() {
3593
+ return {
3594
+ scannedFiles: 0,
3595
+ changedFiles: 0,
3596
+ writtenFiles: 0,
3597
+ backupsWritten: 0,
3598
+ unchangedFiles: 0,
3599
+ missingFiles: 0,
3600
+ entries: []
3601
+ };
3602
+ }
3603
+ function collectMigrationExecutionResult(state, result) {
3604
+ if (result.missing) {
3605
+ state.missingFiles += 1;
3606
+ return;
3607
+ }
3608
+ state.scannedFiles += 1;
3609
+ state.entries.push(result.entry);
3610
+ if (result.changed) {
3611
+ state.changedFiles += 1;
3612
+ if (result.wrote) {
3613
+ state.writtenFiles += 1;
3614
+ }
3615
+ if (result.backupWritten) {
3616
+ state.backupsWritten += 1;
3617
+ }
3618
+ } else {
3619
+ state.unchangedFiles += 1;
3620
+ }
3621
+ }
3622
+ function buildMigrationReport(state, context) {
3623
+ const {
3624
+ cwd,
3625
+ dryRun,
3626
+ rollbackOnError,
3627
+ backupDirectory,
3628
+ toolName,
3629
+ toolVersion,
3630
+ generatedAt = (/* @__PURE__ */ new Date()).toISOString()
3631
+ } = context;
3632
+ return {
3633
+ reportKind: MIGRATION_REPORT_KIND,
3634
+ schemaVersion: MIGRATION_REPORT_SCHEMA_VERSION,
3635
+ generatedAt,
3636
+ tool: {
3637
+ name: toolName,
3638
+ version: toolVersion
3639
+ },
3640
+ cwd,
3641
+ dryRun,
3642
+ rollbackOnError,
3643
+ ...backupDirectory ? { backupDirectory } : {},
3644
+ scannedFiles: state.scannedFiles,
3645
+ changedFiles: state.changedFiles,
3646
+ writtenFiles: state.writtenFiles,
3647
+ backupsWritten: state.backupsWritten,
3648
+ unchangedFiles: state.unchangedFiles,
3649
+ missingFiles: state.missingFiles,
3650
+ entries: state.entries
3651
+ };
3652
+ }
3653
+
3654
+ // src/commands/migration-file-executor.ts
3655
+
3656
+
3657
+
3658
+ // src/commands/migration-source.ts
3351
3659
 
3352
3660
 
3353
3661
 
3354
- var DEFAULT_CONFIG_FILENAMES = [
3355
- "tailwindcss-patch.config.ts",
3356
- "tailwindcss-patch.config.js",
3357
- "tailwindcss-patch.config.mjs",
3358
- "tailwindcss-patch.config.cjs",
3359
- "tailwindcss-mangle.config.ts",
3360
- "tailwindcss-mangle.config.js",
3361
- "tailwindcss-mangle.config.mjs",
3362
- "tailwindcss-mangle.config.cjs"
3363
- ];
3364
- var DEFAULT_CONFIG_FILENAME_SET = new Set(DEFAULT_CONFIG_FILENAMES);
3365
- var DEFAULT_WORKSPACE_IGNORED_DIRS = /* @__PURE__ */ new Set([
3366
- ".git",
3367
- ".idea",
3368
- ".turbo",
3369
- ".vscode",
3370
- ".yarn",
3371
- "coverage",
3372
- "dist",
3373
- "node_modules",
3374
- "tmp"
3375
- ]);
3376
- var DEFAULT_WORKSPACE_MAX_DEPTH = 6;
3377
- var MIGRATION_REPORT_KIND = "tw-patch-migrate-report";
3378
- var MIGRATION_REPORT_SCHEMA_VERSION = 1;
3379
3662
  var ROOT_LEGACY_KEYS = ["cwd", "overwrite", "tailwind", "features", "output", "applyPatches"];
3380
3663
  function getPropertyKeyName(property) {
3381
3664
  if (!property.computed && t5.isIdentifier(property.key)) {
@@ -3636,6 +3919,33 @@ function migrateConfigSource(source) {
3636
3919
  changes: [...changes]
3637
3920
  };
3638
3921
  }
3922
+
3923
+ // src/commands/migration-target-files.ts
3924
+
3925
+
3926
+ var DEFAULT_CONFIG_FILENAMES = [
3927
+ "tailwindcss-patch.config.ts",
3928
+ "tailwindcss-patch.config.js",
3929
+ "tailwindcss-patch.config.mjs",
3930
+ "tailwindcss-patch.config.cjs",
3931
+ "tailwindcss-mangle.config.ts",
3932
+ "tailwindcss-mangle.config.js",
3933
+ "tailwindcss-mangle.config.mjs",
3934
+ "tailwindcss-mangle.config.cjs"
3935
+ ];
3936
+ var DEFAULT_CONFIG_FILENAME_SET = new Set(DEFAULT_CONFIG_FILENAMES);
3937
+ var DEFAULT_WORKSPACE_IGNORED_DIRS = /* @__PURE__ */ new Set([
3938
+ ".git",
3939
+ ".idea",
3940
+ ".turbo",
3941
+ ".vscode",
3942
+ ".yarn",
3943
+ "coverage",
3944
+ "dist",
3945
+ "node_modules",
3946
+ "tmp"
3947
+ ]);
3948
+ var DEFAULT_WORKSPACE_MAX_DEPTH = 6;
3639
3949
  function resolveTargetFiles(cwd, files) {
3640
3950
  const candidates = files && files.length > 0 ? files : [...DEFAULT_CONFIG_FILENAMES];
3641
3951
  const resolved = /* @__PURE__ */ new Set();
@@ -3656,7 +3966,7 @@ async function collectWorkspaceConfigFiles(cwd, maxDepth) {
3656
3966
  let entries;
3657
3967
  try {
3658
3968
  entries = await _fsextra2.default.readdir(dir, { withFileTypes: true });
3659
- } catch (e10) {
3969
+ } catch (e11) {
3660
3970
  continue;
3661
3971
  }
3662
3972
  for (const entry of entries) {
@@ -3746,114 +4056,85 @@ function filterTargetFiles(targetFiles, cwd, include, exclude) {
3746
4056
  return !inExclude;
3747
4057
  });
3748
4058
  }
3749
- async function migrateConfigFiles(options) {
3750
- const cwd = _pathe2.default.resolve(options.cwd);
3751
- const dryRun = _nullishCoalesce(options.dryRun, () => ( false));
3752
- const rollbackOnError = _nullishCoalesce(options.rollbackOnError, () => ( true));
3753
- const backupDirectory = options.backupDir ? _pathe2.default.resolve(cwd, options.backupDir) : void 0;
3754
- const maxDepth = _nullishCoalesce(options.maxDepth, () => ( DEFAULT_WORKSPACE_MAX_DEPTH));
3755
- const discoveredTargetFiles = options.files && options.files.length > 0 ? resolveTargetFiles(cwd, options.files) : options.workspace ? await collectWorkspaceConfigFiles(cwd, maxDepth) : resolveTargetFiles(cwd);
3756
- const targetFiles = filterTargetFiles(discoveredTargetFiles, cwd, options.include, options.exclude);
3757
- const entries = [];
3758
- let scannedFiles = 0;
3759
- let changedFiles = 0;
3760
- let writtenFiles = 0;
3761
- let backupsWritten = 0;
3762
- let unchangedFiles = 0;
3763
- let missingFiles = 0;
3764
- const wroteEntries = [];
3765
- for (const file of targetFiles) {
3766
- const exists = await _fsextra2.default.pathExists(file);
3767
- if (!exists) {
3768
- missingFiles += 1;
3769
- continue;
3770
- }
3771
- scannedFiles += 1;
3772
- const source = await _fsextra2.default.readFile(file, "utf8");
3773
- const migrated = migrateConfigSource(source);
3774
- const entry = {
3775
- file,
3776
- changed: migrated.changed,
3777
- written: false,
3778
- rolledBack: false,
3779
- changes: migrated.changes
3780
- };
3781
- entries.push(entry);
3782
- if (migrated.changed) {
3783
- changedFiles += 1;
3784
- if (!dryRun) {
3785
- try {
3786
- if (backupDirectory) {
3787
- const backupRelativePath = resolveBackupRelativePath(cwd, file);
3788
- const backupFile = _pathe2.default.resolve(backupDirectory, backupRelativePath);
3789
- await _fsextra2.default.ensureDir(_pathe2.default.dirname(backupFile));
3790
- await _fsextra2.default.writeFile(backupFile, source, "utf8");
3791
- entry.backupFile = backupFile;
3792
- backupsWritten += 1;
3793
- }
3794
- await _fsextra2.default.writeFile(file, migrated.code, "utf8");
3795
- entry.written = true;
3796
- wroteEntries.push({ file, source, entry });
3797
- writtenFiles += 1;
3798
- } catch (error) {
3799
- let rollbackCount = 0;
3800
- if (rollbackOnError && wroteEntries.length > 0) {
3801
- for (const written of [...wroteEntries].reverse()) {
3802
- try {
3803
- await _fsextra2.default.writeFile(written.file, written.source, "utf8");
3804
- written.entry.written = false;
3805
- written.entry.rolledBack = true;
3806
- rollbackCount += 1;
3807
- } catch (e11) {
3808
- }
3809
- }
3810
- writtenFiles = Math.max(0, writtenFiles - rollbackCount);
3811
- }
3812
- const reason = error instanceof Error ? error.message : String(error);
3813
- const rollbackHint = rollbackOnError && rollbackCount > 0 ? ` Rolled back ${rollbackCount} previously written file(s).` : "";
3814
- throw new Error(`Failed to write migrated config "${file}": ${reason}.${rollbackHint}`);
3815
- }
3816
- }
3817
- } else {
3818
- unchangedFiles += 1;
4059
+
4060
+ // src/commands/migration-file-executor.ts
4061
+ async function rollbackWrittenEntries(wroteEntries) {
4062
+ let rollbackCount = 0;
4063
+ for (const written of [...wroteEntries].reverse()) {
4064
+ try {
4065
+ await _fsextra2.default.writeFile(written.file, written.source, "utf8");
4066
+ written.entry.written = false;
4067
+ written.entry.rolledBack = true;
4068
+ rollbackCount += 1;
4069
+ } catch (e12) {
3819
4070
  }
3820
4071
  }
3821
- return {
3822
- reportKind: MIGRATION_REPORT_KIND,
3823
- schemaVersion: MIGRATION_REPORT_SCHEMA_VERSION,
3824
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3825
- tool: {
3826
- name: pkgName,
3827
- version: pkgVersion
3828
- },
4072
+ return rollbackCount;
4073
+ }
4074
+ async function executeMigrationFile(options) {
4075
+ const {
3829
4076
  cwd,
4077
+ file,
3830
4078
  dryRun,
3831
4079
  rollbackOnError,
3832
- ...backupDirectory ? { backupDirectory } : {},
3833
- scannedFiles,
3834
- changedFiles,
3835
- writtenFiles,
3836
- backupsWritten,
3837
- unchangedFiles,
3838
- missingFiles,
3839
- entries
4080
+ backupDirectory,
4081
+ wroteEntries
4082
+ } = options;
4083
+ const exists = await _fsextra2.default.pathExists(file);
4084
+ if (!exists) {
4085
+ return {
4086
+ missing: true,
4087
+ changed: false,
4088
+ wrote: false,
4089
+ backupWritten: false
4090
+ };
4091
+ }
4092
+ const source = await _fsextra2.default.readFile(file, "utf8");
4093
+ const migrated = migrateConfigSource(source);
4094
+ const entry = {
4095
+ file,
4096
+ changed: migrated.changed,
4097
+ written: false,
4098
+ rolledBack: false,
4099
+ changes: migrated.changes
3840
4100
  };
3841
- }
3842
- async function restoreConfigFiles(options) {
3843
- const cwd = _pathe2.default.resolve(options.cwd);
3844
- const dryRun = _nullishCoalesce(options.dryRun, () => ( false));
3845
- const strict = _nullishCoalesce(options.strict, () => ( false));
3846
- const reportFile = _pathe2.default.resolve(cwd, options.reportFile);
3847
- const report = await _fsextra2.default.readJSON(reportFile);
3848
- if (report.reportKind !== void 0 && report.reportKind !== MIGRATION_REPORT_KIND) {
3849
- throw new Error(`Unsupported report kind "${report.reportKind}" in ${reportFile}.`);
4101
+ if (!migrated.changed || dryRun) {
4102
+ return {
4103
+ missing: false,
4104
+ changed: migrated.changed,
4105
+ wrote: false,
4106
+ backupWritten: false,
4107
+ entry
4108
+ };
3850
4109
  }
3851
- if (report.schemaVersion !== void 0 && (!Number.isInteger(report.schemaVersion) || report.schemaVersion > MIGRATION_REPORT_SCHEMA_VERSION)) {
3852
- throw new Error(
3853
- `Unsupported report schema version "${String(report.schemaVersion)}" in ${reportFile}. Current supported version is ${MIGRATION_REPORT_SCHEMA_VERSION}.`
3854
- );
4110
+ let backupWritten = false;
4111
+ try {
4112
+ if (backupDirectory) {
4113
+ const backupRelativePath = resolveBackupRelativePath(cwd, file);
4114
+ const backupFile = _pathe2.default.resolve(backupDirectory, backupRelativePath);
4115
+ await _fsextra2.default.ensureDir(_pathe2.default.dirname(backupFile));
4116
+ await _fsextra2.default.writeFile(backupFile, source, "utf8");
4117
+ entry.backupFile = backupFile;
4118
+ backupWritten = true;
4119
+ }
4120
+ await _fsextra2.default.writeFile(file, migrated.code, "utf8");
4121
+ entry.written = true;
4122
+ wroteEntries.push({ file, source, entry });
4123
+ return {
4124
+ missing: false,
4125
+ changed: true,
4126
+ wrote: true,
4127
+ backupWritten,
4128
+ entry
4129
+ };
4130
+ } catch (error) {
4131
+ const rollbackCount = rollbackOnError && wroteEntries.length > 0 ? await rollbackWrittenEntries(wroteEntries) : 0;
4132
+ const reason = error instanceof Error ? error.message : String(error);
4133
+ const rollbackHint = rollbackOnError && rollbackCount > 0 ? ` Rolled back ${rollbackCount} previously written file(s).` : "";
4134
+ throw new Error(`Failed to write migrated config "${file}": ${reason}.${rollbackHint}`);
3855
4135
  }
3856
- const entries = Array.isArray(report.entries) ? report.entries : [];
4136
+ }
4137
+ async function restoreConfigEntries(entries, dryRun) {
3857
4138
  let scannedEntries = 0;
3858
4139
  let restorableEntries = 0;
3859
4140
  let restoredFiles = 0;
@@ -3882,6 +4163,93 @@ async function restoreConfigFiles(options) {
3882
4163
  restoredFiles += 1;
3883
4164
  restored.push(targetFile);
3884
4165
  }
4166
+ return {
4167
+ scannedEntries,
4168
+ restorableEntries,
4169
+ restoredFiles,
4170
+ missingBackups,
4171
+ skippedEntries,
4172
+ restored
4173
+ };
4174
+ }
4175
+
4176
+ // src/commands/migration-report-loader.ts
4177
+
4178
+ async function loadMigrationReportForRestore(reportFile) {
4179
+ const report = await _fsextra2.default.readJSON(reportFile);
4180
+ assertMigrationReportCompatibility(report, reportFile);
4181
+ return {
4182
+ ...report.reportKind === void 0 ? {} : { reportKind: report.reportKind },
4183
+ ...report.schemaVersion === void 0 ? {} : { schemaVersion: report.schemaVersion },
4184
+ entries: Array.isArray(report.entries) ? report.entries : []
4185
+ };
4186
+ }
4187
+
4188
+ // src/commands/migration-target-resolver.ts
4189
+ async function resolveMigrationTargetFiles(options) {
4190
+ const {
4191
+ cwd,
4192
+ files,
4193
+ workspace,
4194
+ maxDepth,
4195
+ include,
4196
+ exclude
4197
+ } = options;
4198
+ const resolvedMaxDepth = _nullishCoalesce(maxDepth, () => ( DEFAULT_WORKSPACE_MAX_DEPTH));
4199
+ const discoveredTargetFiles = files && files.length > 0 ? resolveTargetFiles(cwd, files) : workspace ? await collectWorkspaceConfigFiles(cwd, resolvedMaxDepth) : resolveTargetFiles(cwd);
4200
+ return filterTargetFiles(discoveredTargetFiles, cwd, include, exclude);
4201
+ }
4202
+
4203
+ // src/commands/migrate-config.ts
4204
+ async function migrateConfigFiles(options) {
4205
+ const cwd = _pathe2.default.resolve(options.cwd);
4206
+ const dryRun = _nullishCoalesce(options.dryRun, () => ( false));
4207
+ const rollbackOnError = _nullishCoalesce(options.rollbackOnError, () => ( true));
4208
+ const backupDirectory = options.backupDir ? _pathe2.default.resolve(cwd, options.backupDir) : void 0;
4209
+ const targetFiles = await resolveMigrationTargetFiles({
4210
+ cwd,
4211
+ files: options.files,
4212
+ workspace: options.workspace,
4213
+ maxDepth: options.maxDepth,
4214
+ include: options.include,
4215
+ exclude: options.exclude
4216
+ });
4217
+ const aggregation = createMigrationAggregationState();
4218
+ const wroteEntries = [];
4219
+ for (const file of targetFiles) {
4220
+ const result = await executeMigrationFile({
4221
+ cwd,
4222
+ file,
4223
+ dryRun,
4224
+ rollbackOnError,
4225
+ wroteEntries,
4226
+ ...backupDirectory ? { backupDirectory } : {}
4227
+ });
4228
+ collectMigrationExecutionResult(aggregation, result);
4229
+ }
4230
+ return buildMigrationReport(aggregation, {
4231
+ cwd,
4232
+ dryRun,
4233
+ rollbackOnError,
4234
+ ...backupDirectory ? { backupDirectory } : {},
4235
+ toolName: pkgName,
4236
+ toolVersion: pkgVersion
4237
+ });
4238
+ }
4239
+ async function restoreConfigFiles(options) {
4240
+ const cwd = _pathe2.default.resolve(options.cwd);
4241
+ const dryRun = _nullishCoalesce(options.dryRun, () => ( false));
4242
+ const strict = _nullishCoalesce(options.strict, () => ( false));
4243
+ const reportFile = _pathe2.default.resolve(cwd, options.reportFile);
4244
+ const report = await loadMigrationReportForRestore(reportFile);
4245
+ const {
4246
+ scannedEntries,
4247
+ restorableEntries,
4248
+ restoredFiles,
4249
+ missingBackups,
4250
+ skippedEntries,
4251
+ restored
4252
+ } = await restoreConfigEntries(report.entries, dryRun);
3885
4253
  if (strict && missingBackups > 0) {
3886
4254
  throw new Error(`Restore failed: ${missingBackups} backup file(s) missing in report ${reportFile}.`);
3887
4255
  }
@@ -3901,105 +4269,7 @@ async function restoreConfigFiles(options) {
3901
4269
  };
3902
4270
  }
3903
4271
 
3904
- // src/cli/commands.ts
3905
-
3906
- var _config = require('@tailwindcss-mangle/config');
3907
-
3908
- // ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
3909
- function isPlainObject(value) {
3910
- if (value === null || typeof value !== "object") {
3911
- return false;
3912
- }
3913
- const prototype = Object.getPrototypeOf(value);
3914
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
3915
- return false;
3916
- }
3917
- if (Symbol.iterator in value) {
3918
- return false;
3919
- }
3920
- if (Symbol.toStringTag in value) {
3921
- return Object.prototype.toString.call(value) === "[object Module]";
3922
- }
3923
- return true;
3924
- }
3925
- function _defu(baseObject, defaults, namespace = ".", merger) {
3926
- if (!isPlainObject(defaults)) {
3927
- return _defu(baseObject, {}, namespace, merger);
3928
- }
3929
- const object = Object.assign({}, defaults);
3930
- for (const key in baseObject) {
3931
- if (key === "__proto__" || key === "constructor") {
3932
- continue;
3933
- }
3934
- const value = baseObject[key];
3935
- if (value === null || value === void 0) {
3936
- continue;
3937
- }
3938
- if (merger && merger(object, key, value, namespace)) {
3939
- continue;
3940
- }
3941
- if (Array.isArray(value) && Array.isArray(object[key])) {
3942
- object[key] = [...value, ...object[key]];
3943
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
3944
- object[key] = _defu(
3945
- value,
3946
- object[key],
3947
- (namespace ? `${namespace}.` : "") + key.toString(),
3948
- merger
3949
- );
3950
- } else {
3951
- object[key] = value;
3952
- }
3953
- }
3954
- return object;
3955
- }
3956
- function createDefu(merger) {
3957
- return (...arguments_) => (
3958
- // eslint-disable-next-line unicorn/no-array-reduce
3959
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
3960
- );
3961
- }
3962
- var defu = createDefu();
3963
- var defuFn = createDefu((object, key, currentValue) => {
3964
- if (object[key] !== void 0 && typeof currentValue === "function") {
3965
- object[key] = currentValue(object[key]);
3966
- return true;
3967
- }
3968
- });
3969
- var defuArrayFn = createDefu((object, key, currentValue) => {
3970
- if (Array.isArray(object[key]) && typeof currentValue === "function") {
3971
- object[key] = currentValue(object[key]);
3972
- return true;
3973
- }
3974
- });
3975
-
3976
- // ../shared/src/utils.ts
3977
- var defuOverrideArray = createDefu((obj, key, value) => {
3978
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
3979
- obj[key] = value;
3980
- return true;
3981
- }
3982
- });
3983
- var preserveClassNames = [
3984
- // https://tailwindcss.com/docs/transition-timing-function start
3985
- // https://github.com/sonofmagic/tailwindcss-mangle/issues/21
3986
- "ease-out",
3987
- "ease-linear",
3988
- "ease-in",
3989
- "ease-in-out"
3990
- // https://tailwindcss.com/docs/transition-timing-function end
3991
- ];
3992
- var preserveClassNamesMap = preserveClassNames.reduce((acc, cur) => {
3993
- acc[cur] = true;
3994
- return acc;
3995
- }, {});
3996
- var acceptChars = [..."abcdefghijklmnopqrstuvwxyz"];
3997
-
3998
- // src/cli/commands.ts
3999
- var _cac = require('cac'); var _cac2 = _interopRequireDefault(_cac);
4000
-
4001
-
4002
- var tailwindcssPatchCommands = ["install", "extract", "tokens", "init", "migrate", "restore", "validate", "status"];
4272
+ // src/commands/validate.ts
4003
4273
  var VALIDATE_EXIT_CODES = {
4004
4274
  OK: 0,
4005
4275
  REPORT_INCOMPATIBLE: 21,
@@ -4014,7 +4284,7 @@ var VALIDATE_FAILURE_REASONS = [
4014
4284
  "unknown-error"
4015
4285
  ];
4016
4286
  var IO_ERROR_CODES = /* @__PURE__ */ new Set(["ENOENT", "EACCES", "EPERM", "EISDIR", "ENOTDIR", "EMFILE", "ENFILE"]);
4017
- function isNodeError(error) {
4287
+ function isNodeError2(error) {
4018
4288
  return !!error && typeof error === "object" && ("code" in error || "message" in error);
4019
4289
  }
4020
4290
  function classifyValidateError(error) {
@@ -4033,7 +4303,7 @@ function classifyValidateError(error) {
4033
4303
  message
4034
4304
  };
4035
4305
  }
4036
- if (isNodeError(error) && typeof error.code === "string" && IO_ERROR_CODES.has(error.code)) {
4306
+ if (isNodeError2(error) && typeof error.code === "string" && IO_ERROR_CODES.has(error.code)) {
4037
4307
  return {
4038
4308
  reason: "io-error",
4039
4309
  exitCode: VALIDATE_EXIT_CODES.IO_ERROR,
@@ -4056,6 +4326,17 @@ var ValidateCommandError = class extends Error {
4056
4326
  this.exitCode = summary.exitCode;
4057
4327
  }
4058
4328
  };
4329
+
4330
+ // src/commands/types.ts
4331
+ var tailwindcssPatchCommands = ["install", "extract", "tokens", "init", "migrate", "restore", "validate", "status"];
4332
+
4333
+ // src/commands/cli.ts
4334
+ var _cac = require('cac'); var _cac2 = _interopRequireDefault(_cac);
4335
+
4336
+ // src/commands/command-definitions.ts
4337
+
4338
+
4339
+ // src/commands/token-output.ts
4059
4340
  var TOKEN_FORMATS = ["json", "lines", "grouped-json"];
4060
4341
  var DEFAULT_TOKEN_REPORT = ".tw-patch/tw-token-report.json";
4061
4342
  function formatTokenLine(entry) {
@@ -4077,68 +4358,8 @@ function formatGroupedPreview(map, limit = 3) {
4077
4358
  moreFiles: Math.max(0, files.length - limit)
4078
4359
  };
4079
4360
  }
4080
- function resolveCwd(rawCwd) {
4081
- if (!rawCwd) {
4082
- return _process2.default.cwd();
4083
- }
4084
- return _pathe2.default.resolve(rawCwd);
4085
- }
4086
- function createDefaultRunner(factory) {
4087
- let promise;
4088
- return () => {
4089
- if (!promise) {
4090
- promise = factory();
4091
- }
4092
- return promise;
4093
- };
4094
- }
4095
- async function loadPatchOptionsForCwd(cwd, overrides) {
4096
- const { config } = await _config.getConfig.call(void 0, cwd);
4097
- const legacyConfig = config;
4098
- const base = _optionalChain([config, 'optionalAccess', _144 => _144.registry]) ? fromUnifiedConfig(config.registry) : _optionalChain([legacyConfig, 'optionalAccess', _145 => _145.patch]) ? fromLegacyOptions({ patch: legacyConfig.patch }) : {};
4099
- const merged = defu(_nullishCoalesce(overrides, () => ( {})), base);
4100
- return merged;
4101
- }
4102
- function createCommandContext(cli, command, commandName, args, cwd) {
4103
- let cachedOptions;
4104
- let cachedPatcher;
4105
- let cachedConfig;
4106
- const loadPatchOptionsForContext = (overrides) => {
4107
- if (overrides) {
4108
- return loadPatchOptionsForCwd(cwd, overrides);
4109
- }
4110
- if (!cachedOptions) {
4111
- cachedOptions = loadPatchOptionsForCwd(cwd);
4112
- }
4113
- return cachedOptions;
4114
- };
4115
- const createPatcherForContext = async (overrides) => {
4116
- if (overrides) {
4117
- const patchOptions = await loadPatchOptionsForCwd(cwd, overrides);
4118
- return new TailwindcssPatcher(patchOptions);
4119
- }
4120
- if (!cachedPatcher) {
4121
- cachedPatcher = loadPatchOptionsForContext().then((options) => new TailwindcssPatcher(options));
4122
- }
4123
- return cachedPatcher;
4124
- };
4125
- return {
4126
- cli,
4127
- command,
4128
- commandName,
4129
- args,
4130
- cwd,
4131
- logger: logger_default,
4132
- loadConfig: () => {
4133
- if (!cachedConfig) {
4134
- cachedConfig = _config.getConfig.call(void 0, cwd);
4135
- }
4136
- return cachedConfig;
4137
- },
4138
- loadPatchOptions: loadPatchOptionsForContext,
4139
- createPatcher: createPatcherForContext
4140
- };
4141
- }
4361
+
4362
+ // src/commands/command-definitions.ts
4142
4363
  function createCwdOptionDefinition(description = "Working directory") {
4143
4364
  return {
4144
4365
  flags: "--cwd <dir>",
@@ -4228,6 +4449,8 @@ function buildDefaultCommandDefinitions() {
4228
4449
  }
4229
4450
  };
4230
4451
  }
4452
+
4453
+ // src/commands/command-metadata.ts
4231
4454
  function addPrefixIfMissing(value, prefix) {
4232
4455
  if (!prefix || value.startsWith(prefix)) {
4233
4456
  return value;
@@ -4235,10 +4458,10 @@ function addPrefixIfMissing(value, prefix) {
4235
4458
  return `${prefix}${value}`;
4236
4459
  }
4237
4460
  function resolveCommandNames(command, mountOptions, prefix) {
4238
- const override = _optionalChain([mountOptions, 'access', _146 => _146.commandOptions, 'optionalAccess', _147 => _147[command]]);
4239
- const baseName = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _148 => _148.name]), () => ( command));
4461
+ const override = _optionalChain([mountOptions, 'access', _172 => _172.commandOptions, 'optionalAccess', _173 => _173[command]]);
4462
+ const baseName = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _174 => _174.name]), () => ( command));
4240
4463
  const name = addPrefixIfMissing(baseName, prefix);
4241
- const aliases = (_nullishCoalesce(_optionalChain([override, 'optionalAccess', _149 => _149.aliases]), () => ( []))).map((alias) => addPrefixIfMissing(alias, prefix));
4464
+ const aliases = (_nullishCoalesce(_optionalChain([override, 'optionalAccess', _175 => _175.aliases]), () => ( []))).map((alias) => addPrefixIfMissing(alias, prefix));
4242
4465
  return { name, aliases };
4243
4466
  }
4244
4467
  function resolveOptionDefinitions(defaults, override) {
@@ -4255,30 +4478,93 @@ function resolveOptionDefinitions(defaults, override) {
4255
4478
  }
4256
4479
  return [...defaults, ...customDefs];
4257
4480
  }
4481
+ function resolveCommandMetadata(command, mountOptions, prefix, defaults) {
4482
+ const names = resolveCommandNames(command, mountOptions, prefix);
4483
+ const definition = defaults[command];
4484
+ const override = _optionalChain([mountOptions, 'access', _176 => _176.commandOptions, 'optionalAccess', _177 => _177[command]]);
4485
+ const description = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _178 => _178.description]), () => ( definition.description));
4486
+ const optionDefs = resolveOptionDefinitions(definition.optionDefs, override);
4487
+ return { ...names, description, optionDefs };
4488
+ }
4258
4489
  function applyCommandOptions(command, optionDefs) {
4259
4490
  for (const option of optionDefs) {
4260
4491
  command.option(option.flags, _nullishCoalesce(option.description, () => ( "")), option.config);
4261
4492
  }
4262
4493
  }
4494
+
4495
+ // src/commands/command-context.ts
4496
+
4497
+
4498
+ function resolveCommandCwd(rawCwd) {
4499
+ if (!rawCwd) {
4500
+ return _process2.default.cwd();
4501
+ }
4502
+ return _pathe2.default.resolve(rawCwd);
4503
+ }
4504
+ function createMemoizedPromiseRunner(factory) {
4505
+ let promise;
4506
+ return () => {
4507
+ if (!promise) {
4508
+ promise = factory();
4509
+ }
4510
+ return promise;
4511
+ };
4512
+ }
4513
+ function createTailwindcssPatchCommandContext(cli, command, commandName, args, cwd) {
4514
+ const loadCachedConfig = createMemoizedPromiseRunner(
4515
+ () => loadWorkspaceConfigModule().then((mod) => mod.getConfig(cwd))
4516
+ );
4517
+ const loadCachedPatchOptions = createMemoizedPromiseRunner(
4518
+ () => loadPatchOptionsForWorkspace(cwd)
4519
+ );
4520
+ const createCachedPatcher = createMemoizedPromiseRunner(async () => {
4521
+ const patchOptions = await loadCachedPatchOptions();
4522
+ return new TailwindcssPatcher(patchOptions);
4523
+ });
4524
+ const loadPatchOptionsForContext = (overrides) => {
4525
+ if (overrides) {
4526
+ return loadPatchOptionsForWorkspace(cwd, overrides);
4527
+ }
4528
+ return loadCachedPatchOptions();
4529
+ };
4530
+ const createPatcherForContext = async (overrides) => {
4531
+ if (overrides) {
4532
+ const patchOptions = await loadPatchOptionsForWorkspace(cwd, overrides);
4533
+ return new TailwindcssPatcher(patchOptions);
4534
+ }
4535
+ return createCachedPatcher();
4536
+ };
4537
+ return {
4538
+ cli,
4539
+ command,
4540
+ commandName,
4541
+ args,
4542
+ cwd,
4543
+ logger: logger_default,
4544
+ loadConfig: loadCachedConfig,
4545
+ loadPatchOptions: loadPatchOptionsForContext,
4546
+ createPatcher: createPatcherForContext
4547
+ };
4548
+ }
4549
+
4550
+ // src/commands/command-runtime.ts
4263
4551
  function runWithCommandHandler(cli, command, commandName, args, handler, defaultHandler) {
4264
- const cwd = resolveCwd(args.cwd);
4265
- const context = createCommandContext(cli, command, commandName, args, cwd);
4266
- const runDefault = createDefaultRunner(() => defaultHandler(context));
4552
+ const cwd = resolveCommandCwd(args.cwd);
4553
+ const context = createTailwindcssPatchCommandContext(cli, command, commandName, args, cwd);
4554
+ const runDefault = createMemoizedPromiseRunner(() => defaultHandler(context));
4267
4555
  if (!handler) {
4268
4556
  return runDefault();
4269
4557
  }
4270
4558
  return handler(context, runDefault);
4271
4559
  }
4272
- function resolveCommandMetadata(command, mountOptions, prefix, defaults) {
4273
- const names = resolveCommandNames(command, mountOptions, prefix);
4274
- const definition = defaults[command];
4275
- const override = _optionalChain([mountOptions, 'access', _150 => _150.commandOptions, 'optionalAccess', _151 => _151[command]]);
4276
- const description = _nullishCoalesce(_optionalChain([override, 'optionalAccess', _152 => _152.description]), () => ( definition.description));
4277
- const optionDefs = resolveOptionDefinitions(definition.optionDefs, override);
4278
- return { ...names, description, optionDefs };
4279
- }
4280
- async function installCommandDefaultHandler(ctx) {
4281
- const patcher = await ctx.createPatcher();
4560
+
4561
+ // src/commands/basic-handlers.ts
4562
+
4563
+
4564
+
4565
+ var DEFAULT_CONFIG_NAME = "tailwindcss-mangle";
4566
+ async function installCommandDefaultHandler(_ctx) {
4567
+ const patcher = new TailwindcssPatcher();
4282
4568
  await patcher.patch();
4283
4569
  logger_default.success("Tailwind CSS runtime patched successfully.");
4284
4570
  }
@@ -4379,60 +4665,94 @@ async function tokensCommandDefaultHandler(ctx) {
4379
4665
  return report;
4380
4666
  }
4381
4667
  async function initCommandDefaultHandler(ctx) {
4382
- await _config.initConfig.call(void 0, ctx.cwd);
4383
- logger_default.success(`\u2728 ${_config.CONFIG_NAME}.config.ts initialized!`);
4668
+ const configModule = await loadWorkspaceConfigModule();
4669
+ await configModule.initConfig(ctx.cwd);
4670
+ const configName = configModule.CONFIG_NAME || DEFAULT_CONFIG_NAME;
4671
+ logger_default.success(`\u2728 ${configName}.config.ts initialized!`);
4384
4672
  }
4385
- async function migrateCommandDefaultHandler(ctx) {
4386
- const { args } = ctx;
4387
- const normalizePatternArgs = (value) => {
4388
- if (!value) {
4389
- return void 0;
4390
- }
4391
- const raw = Array.isArray(value) ? value : [value];
4392
- const values = raw.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
4393
- return values.length > 0 ? values : void 0;
4673
+
4674
+ // src/commands/migration-args.ts
4675
+ function normalizePatternArgs(value) {
4676
+ if (!value) {
4677
+ return void 0;
4678
+ }
4679
+ const raw = Array.isArray(value) ? value : [value];
4680
+ const values = raw.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
4681
+ return values.length > 0 ? values : void 0;
4682
+ }
4683
+ function parseMaxDepth(value) {
4684
+ if (value === void 0) {
4685
+ return {
4686
+ maxDepth: void 0,
4687
+ hasInvalidMaxDepth: false
4688
+ };
4689
+ }
4690
+ const parsed = Number(value);
4691
+ if (!Number.isFinite(parsed) || parsed < 0) {
4692
+ return {
4693
+ maxDepth: void 0,
4694
+ hasInvalidMaxDepth: true
4695
+ };
4696
+ }
4697
+ return {
4698
+ maxDepth: Math.floor(parsed),
4699
+ hasInvalidMaxDepth: false
4394
4700
  };
4701
+ }
4702
+ function resolveMigrateCommandArgs(args) {
4395
4703
  const include = normalizePatternArgs(args.include);
4396
4704
  const exclude = normalizePatternArgs(args.exclude);
4397
- const parsedMaxDepth = args.maxDepth === void 0 ? void 0 : Number(args.maxDepth);
4398
- const maxDepth = parsedMaxDepth !== void 0 && Number.isFinite(parsedMaxDepth) && parsedMaxDepth >= 0 ? Math.floor(parsedMaxDepth) : void 0;
4705
+ const { maxDepth, hasInvalidMaxDepth } = parseMaxDepth(args.maxDepth);
4399
4706
  const checkMode = _nullishCoalesce(args.check, () => ( false));
4400
4707
  const dryRun = _nullishCoalesce(args.dryRun, () => ( checkMode));
4401
- if (args.workspace && args.maxDepth !== void 0 && maxDepth === void 0) {
4402
- logger_default.warn(`Invalid --max-depth value "${String(args.maxDepth)}", fallback to default depth.`);
4403
- }
4404
- const report = await migrateConfigFiles({
4405
- cwd: ctx.cwd,
4708
+ return {
4709
+ include,
4710
+ exclude,
4711
+ maxDepth,
4712
+ checkMode,
4406
4713
  dryRun,
4407
- ...args.config ? { files: [args.config] } : {},
4408
- ...args.workspace ? { workspace: true } : {},
4409
- ...args.workspace && maxDepth !== void 0 ? { maxDepth } : {},
4410
- ...args.backupDir ? { backupDir: args.backupDir } : {},
4411
- ...include ? { include } : {},
4412
- ...exclude ? { exclude } : {}
4413
- });
4414
- if (args.reportFile) {
4415
- const reportPath = _pathe2.default.resolve(ctx.cwd, args.reportFile);
4416
- await _fsextra2.default.ensureDir(_pathe2.default.dirname(reportPath));
4417
- await _fsextra2.default.writeJSON(reportPath, report, { spaces: 2 });
4418
- logger_default.info(`Migration report written: ${reportPath.replace(_process2.default.cwd(), ".")}`);
4419
- }
4420
- if (args.json) {
4421
- logger_default.log(JSON.stringify(report, null, 2));
4422
- if (checkMode && report.changedFiles > 0) {
4423
- throw new Error(`Migration check failed: ${report.changedFiles} file(s) still need migration.`);
4424
- }
4425
- if (report.scannedFiles === 0) {
4426
- logger_default.warn("No config files found for migration.");
4427
- }
4428
- return report;
4429
- }
4430
- if (report.scannedFiles === 0) {
4431
- logger_default.warn("No config files found for migration.");
4432
- return report;
4433
- }
4714
+ hasInvalidMaxDepth
4715
+ };
4716
+ }
4717
+ function resolveRestoreCommandArgs(args) {
4718
+ return {
4719
+ reportFile: _nullishCoalesce(args.reportFile, () => ( ".tw-patch/migrate-report.json")),
4720
+ dryRun: _nullishCoalesce(args.dryRun, () => ( false)),
4721
+ strict: _nullishCoalesce(args.strict, () => ( false))
4722
+ };
4723
+ }
4724
+ function resolveValidateCommandArgs(args) {
4725
+ return {
4726
+ reportFile: _nullishCoalesce(args.reportFile, () => ( ".tw-patch/migrate-report.json")),
4727
+ strict: _nullishCoalesce(args.strict, () => ( false))
4728
+ };
4729
+ }
4730
+
4731
+ // src/commands/migration-output.ts
4732
+
4733
+
4734
+
4735
+ function formatPathForLog(file) {
4736
+ return file.replace(_process2.default.cwd(), ".");
4737
+ }
4738
+ function createMigrationCheckFailureError(changedFiles) {
4739
+ return new Error(`Migration check failed: ${changedFiles} file(s) still need migration.`);
4740
+ }
4741
+ async function writeMigrationReportFile(cwd, reportFile, report) {
4742
+ const reportPath = _pathe2.default.resolve(cwd, reportFile);
4743
+ await _fsextra2.default.ensureDir(_pathe2.default.dirname(reportPath));
4744
+ await _fsextra2.default.writeJSON(reportPath, report, { spaces: 2 });
4745
+ logger_default.info(`Migration report written: ${formatPathForLog(reportPath)}`);
4746
+ }
4747
+ function logMigrationReportAsJson(report) {
4748
+ logger_default.log(JSON.stringify(report, null, 2));
4749
+ }
4750
+ function logNoMigrationConfigFilesWarning() {
4751
+ logger_default.warn("No config files found for migration.");
4752
+ }
4753
+ function logMigrationEntries(report, dryRun) {
4434
4754
  for (const entry of report.entries) {
4435
- const fileLabel = entry.file.replace(_process2.default.cwd(), ".");
4755
+ const fileLabel = formatPathForLog(entry.file);
4436
4756
  if (!entry.changed) {
4437
4757
  logger_default.info(`No changes: ${fileLabel}`);
4438
4758
  continue;
@@ -4446,105 +4766,156 @@ async function migrateCommandDefaultHandler(ctx) {
4446
4766
  logger_default.info(` - ${change}`);
4447
4767
  }
4448
4768
  if (entry.backupFile) {
4449
- logger_default.info(` - backup: ${entry.backupFile.replace(_process2.default.cwd(), ".")}`);
4769
+ logger_default.info(` - backup: ${formatPathForLog(entry.backupFile)}`);
4450
4770
  }
4451
4771
  }
4772
+ }
4773
+ function logMigrationSummary(report) {
4452
4774
  logger_default.info(
4453
4775
  `Migration summary: scanned=${report.scannedFiles}, changed=${report.changedFiles}, written=${report.writtenFiles}, backups=${report.backupsWritten}, missing=${report.missingFiles}, unchanged=${report.unchangedFiles}`
4454
4776
  );
4455
- if (checkMode && report.changedFiles > 0) {
4456
- throw new Error(`Migration check failed: ${report.changedFiles} file(s) still need migration.`);
4457
- }
4458
- return report;
4459
4777
  }
4460
- async function restoreCommandDefaultHandler(ctx) {
4461
- const { args } = ctx;
4462
- const reportFile = _nullishCoalesce(args.reportFile, () => ( ".tw-patch/migrate-report.json"));
4463
- const result = await restoreConfigFiles({
4464
- cwd: ctx.cwd,
4465
- reportFile,
4466
- dryRun: _nullishCoalesce(args.dryRun, () => ( false)),
4467
- strict: _nullishCoalesce(args.strict, () => ( false))
4468
- });
4469
- if (args.json) {
4470
- logger_default.log(JSON.stringify(result, null, 2));
4471
- return result;
4472
- }
4778
+ function logRestoreResultAsJson(result) {
4779
+ logger_default.log(JSON.stringify(result, null, 2));
4780
+ }
4781
+ function logRestoreSummary(result) {
4473
4782
  logger_default.info(
4474
4783
  `Restore summary: scanned=${result.scannedEntries}, restorable=${result.restorableEntries}, restored=${result.restoredFiles}, missingBackups=${result.missingBackups}, skipped=${result.skippedEntries}`
4475
4784
  );
4476
4785
  if (result.restored.length > 0) {
4477
4786
  const preview = result.restored.slice(0, 5);
4478
4787
  for (const file of preview) {
4479
- logger_default.info(` - ${file.replace(_process2.default.cwd(), ".")}`);
4788
+ logger_default.info(` - ${formatPathForLog(file)}`);
4480
4789
  }
4481
4790
  if (result.restored.length > preview.length) {
4482
4791
  logger_default.info(` ...and ${result.restored.length - preview.length} more`);
4483
4792
  }
4484
4793
  }
4485
- return result;
4486
4794
  }
4487
- async function validateCommandDefaultHandler(ctx) {
4795
+ function logValidateSuccessAsJson(result) {
4796
+ const payload = {
4797
+ ok: true,
4798
+ ...result
4799
+ };
4800
+ logger_default.log(JSON.stringify(payload, null, 2));
4801
+ }
4802
+ function logValidateSuccessSummary(result) {
4803
+ logger_default.success(
4804
+ `Migration report validated: scanned=${result.scannedEntries}, restorable=${result.restorableEntries}, missingBackups=${result.missingBackups}, skipped=${result.skippedEntries}`
4805
+ );
4806
+ if (result.reportKind || result.reportSchemaVersion !== void 0) {
4807
+ const kind = _nullishCoalesce(result.reportKind, () => ( "unknown"));
4808
+ const schema = result.reportSchemaVersion === void 0 ? "unknown" : String(result.reportSchemaVersion);
4809
+ logger_default.info(` metadata: kind=${kind}, schema=${schema}`);
4810
+ }
4811
+ }
4812
+ function logValidateFailureAsJson(summary) {
4813
+ const payload = {
4814
+ ok: false,
4815
+ reason: summary.reason,
4816
+ exitCode: summary.exitCode,
4817
+ message: summary.message
4818
+ };
4819
+ logger_default.log(JSON.stringify(payload, null, 2));
4820
+ }
4821
+ function logValidateFailureSummary(summary) {
4822
+ logger_default.error(`Validation failed [${summary.reason}] (exit ${summary.exitCode}): ${summary.message}`);
4823
+ }
4824
+
4825
+ // src/commands/migrate-handler.ts
4826
+ async function migrateCommandDefaultHandler(ctx) {
4488
4827
  const { args } = ctx;
4489
- const reportFile = _nullishCoalesce(args.reportFile, () => ( ".tw-patch/migrate-report.json"));
4490
- try {
4491
- const result = await restoreConfigFiles({
4492
- cwd: ctx.cwd,
4493
- reportFile,
4494
- dryRun: true,
4495
- strict: _nullishCoalesce(args.strict, () => ( false))
4496
- });
4497
- if (args.json) {
4498
- const payload = {
4499
- ok: true,
4500
- ...result
4501
- };
4502
- logger_default.log(JSON.stringify(payload, null, 2));
4503
- return result;
4828
+ const {
4829
+ include,
4830
+ exclude,
4831
+ maxDepth,
4832
+ checkMode,
4833
+ dryRun,
4834
+ hasInvalidMaxDepth
4835
+ } = resolveMigrateCommandArgs(args);
4836
+ if (args.workspace && hasInvalidMaxDepth) {
4837
+ logger_default.warn(`Invalid --max-depth value "${String(args.maxDepth)}", fallback to default depth.`);
4838
+ }
4839
+ const report = await migrateConfigFiles({
4840
+ cwd: ctx.cwd,
4841
+ dryRun,
4842
+ ...args.config ? { files: [args.config] } : {},
4843
+ ...args.workspace ? { workspace: true } : {},
4844
+ ...args.workspace && maxDepth !== void 0 ? { maxDepth } : {},
4845
+ ...args.backupDir ? { backupDir: args.backupDir } : {},
4846
+ ...include ? { include } : {},
4847
+ ...exclude ? { exclude } : {}
4848
+ });
4849
+ if (args.reportFile) {
4850
+ await writeMigrationReportFile(ctx.cwd, args.reportFile, report);
4851
+ }
4852
+ if (args.json) {
4853
+ logMigrationReportAsJson(report);
4854
+ if (checkMode && report.changedFiles > 0) {
4855
+ throw createMigrationCheckFailureError(report.changedFiles);
4504
4856
  }
4505
- logger_default.success(
4506
- `Migration report validated: scanned=${result.scannedEntries}, restorable=${result.restorableEntries}, missingBackups=${result.missingBackups}, skipped=${result.skippedEntries}`
4507
- );
4508
- if (result.reportKind || result.reportSchemaVersion !== void 0) {
4509
- const kind = _nullishCoalesce(result.reportKind, () => ( "unknown"));
4510
- const schema = result.reportSchemaVersion === void 0 ? "unknown" : String(result.reportSchemaVersion);
4511
- logger_default.info(` metadata: kind=${kind}, schema=${schema}`);
4857
+ if (report.scannedFiles === 0) {
4858
+ logNoMigrationConfigFilesWarning();
4512
4859
  }
4860
+ return report;
4861
+ }
4862
+ if (report.scannedFiles === 0) {
4863
+ logNoMigrationConfigFilesWarning();
4864
+ return report;
4865
+ }
4866
+ logMigrationEntries(report, dryRun);
4867
+ logMigrationSummary(report);
4868
+ if (checkMode && report.changedFiles > 0) {
4869
+ throw createMigrationCheckFailureError(report.changedFiles);
4870
+ }
4871
+ return report;
4872
+ }
4873
+
4874
+ // src/commands/restore-handler.ts
4875
+ async function restoreCommandDefaultHandler(ctx) {
4876
+ const { args } = ctx;
4877
+ const restoreArgs = resolveRestoreCommandArgs(args);
4878
+ const result = await restoreConfigFiles({
4879
+ cwd: ctx.cwd,
4880
+ reportFile: restoreArgs.reportFile,
4881
+ dryRun: restoreArgs.dryRun,
4882
+ strict: restoreArgs.strict
4883
+ });
4884
+ if (args.json) {
4885
+ logRestoreResultAsJson(result);
4513
4886
  return result;
4514
- } catch (error) {
4515
- const summary = classifyValidateError(error);
4516
- if (args.json) {
4517
- const payload = {
4518
- ok: false,
4519
- reason: summary.reason,
4520
- exitCode: summary.exitCode,
4521
- message: summary.message
4522
- };
4523
- logger_default.log(JSON.stringify(payload, null, 2));
4524
- } else {
4525
- logger_default.error(`Validation failed [${summary.reason}] (exit ${summary.exitCode}): ${summary.message}`);
4526
- }
4527
- throw new ValidateCommandError(summary, { cause: error });
4528
4887
  }
4888
+ logRestoreSummary(result);
4889
+ return result;
4529
4890
  }
4891
+
4892
+ // src/commands/status-output.ts
4530
4893
  function formatFilesHint(entry) {
4531
4894
  if (!entry.files.length) {
4532
4895
  return "";
4533
4896
  }
4534
4897
  return ` (${entry.files.join(", ")})`;
4535
4898
  }
4536
- async function statusCommandDefaultHandler(ctx) {
4537
- const patcher = await ctx.createPatcher();
4538
- const report = await patcher.getPatchStatus();
4539
- if (ctx.args.json) {
4540
- logger_default.log(JSON.stringify(report, null, 2));
4541
- return report;
4542
- }
4543
- const applied = report.entries.filter((entry) => entry.status === "applied");
4544
- const pending = report.entries.filter((entry) => entry.status === "not-applied");
4545
- const skipped = report.entries.filter((entry) => entry.status === "skipped" || entry.status === "unsupported");
4546
- const packageLabel = `${_nullishCoalesce(report.package.name, () => ( "tailwindcss"))}@${_nullishCoalesce(report.package.version, () => ( "unknown"))}`;
4547
- logger_default.info(`Patch status for ${packageLabel} (v${report.majorVersion})`);
4899
+ function formatPackageLabel(report) {
4900
+ return `${_nullishCoalesce(report.package.name, () => ( "tailwindcss"))}@${_nullishCoalesce(report.package.version, () => ( "unknown"))}`;
4901
+ }
4902
+ function partitionStatusEntries(report) {
4903
+ return {
4904
+ applied: report.entries.filter((entry) => entry.status === "applied"),
4905
+ pending: report.entries.filter((entry) => entry.status === "not-applied"),
4906
+ skipped: report.entries.filter((entry) => entry.status === "skipped" || entry.status === "unsupported")
4907
+ };
4908
+ }
4909
+ function logStatusReportAsJson(report) {
4910
+ logger_default.log(JSON.stringify(report, null, 2));
4911
+ }
4912
+ function logStatusReportSummary(report) {
4913
+ const {
4914
+ applied,
4915
+ pending,
4916
+ skipped
4917
+ } = partitionStatusEntries(report);
4918
+ logger_default.info(`Patch status for ${formatPackageLabel(report)} (v${report.majorVersion})`);
4548
4919
  if (applied.length) {
4549
4920
  logger_default.success("Applied:");
4550
4921
  applied.forEach((entry) => logger_default.success(` \u2022 ${entry.name}${formatFilesHint(entry)}`));
@@ -4552,7 +4923,7 @@ async function statusCommandDefaultHandler(ctx) {
4552
4923
  if (pending.length) {
4553
4924
  logger_default.warn("Needs attention:");
4554
4925
  pending.forEach((entry) => {
4555
- const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
4926
+ const details = entry.reason ? ` - ${entry.reason}` : "";
4556
4927
  logger_default.warn(` \u2022 ${entry.name}${formatFilesHint(entry)}${details}`);
4557
4928
  });
4558
4929
  } else {
@@ -4561,151 +4932,89 @@ async function statusCommandDefaultHandler(ctx) {
4561
4932
  if (skipped.length) {
4562
4933
  logger_default.info("Skipped:");
4563
4934
  skipped.forEach((entry) => {
4564
- const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
4935
+ const details = entry.reason ? ` - ${entry.reason}` : "";
4565
4936
  logger_default.info(` \u2022 ${entry.name}${details}`);
4566
4937
  });
4567
4938
  }
4939
+ }
4940
+
4941
+ // src/commands/status-handler.ts
4942
+ async function statusCommandDefaultHandler(ctx) {
4943
+ const patcher = await ctx.createPatcher();
4944
+ const report = await patcher.getPatchStatus();
4945
+ if (ctx.args.json) {
4946
+ logStatusReportAsJson(report);
4947
+ return report;
4948
+ }
4949
+ logStatusReportSummary(report);
4568
4950
  return report;
4569
4951
  }
4952
+
4953
+ // src/commands/validate-handler.ts
4954
+ async function validateCommandDefaultHandler(ctx) {
4955
+ const { args } = ctx;
4956
+ const validateArgs = resolveValidateCommandArgs(args);
4957
+ try {
4958
+ const result = await restoreConfigFiles({
4959
+ cwd: ctx.cwd,
4960
+ reportFile: validateArgs.reportFile,
4961
+ dryRun: true,
4962
+ strict: validateArgs.strict
4963
+ });
4964
+ if (args.json) {
4965
+ logValidateSuccessAsJson(result);
4966
+ return result;
4967
+ }
4968
+ logValidateSuccessSummary(result);
4969
+ return result;
4970
+ } catch (error) {
4971
+ const summary = classifyValidateError(error);
4972
+ if (args.json) {
4973
+ logValidateFailureAsJson(summary);
4974
+ } else {
4975
+ logValidateFailureSummary(summary);
4976
+ }
4977
+ throw new ValidateCommandError(summary, { cause: error });
4978
+ }
4979
+ }
4980
+
4981
+ // src/commands/default-handler-map.ts
4982
+ var defaultCommandHandlers = {
4983
+ install: installCommandDefaultHandler,
4984
+ extract: extractCommandDefaultHandler,
4985
+ tokens: tokensCommandDefaultHandler,
4986
+ init: initCommandDefaultHandler,
4987
+ migrate: migrateCommandDefaultHandler,
4988
+ restore: restoreCommandDefaultHandler,
4989
+ validate: validateCommandDefaultHandler,
4990
+ status: statusCommandDefaultHandler
4991
+ };
4992
+
4993
+ // src/commands/command-registrar.ts
4994
+ function registerTailwindcssPatchCommand(cli, commandName, options, prefix, defaultDefinitions) {
4995
+ const metadata = resolveCommandMetadata(commandName, options, prefix, defaultDefinitions);
4996
+ const command = cli.command(metadata.name, metadata.description);
4997
+ applyCommandOptions(command, metadata.optionDefs);
4998
+ command.action(async (args) => {
4999
+ return runWithCommandHandler(
5000
+ cli,
5001
+ command,
5002
+ commandName,
5003
+ args,
5004
+ _optionalChain([options, 'access', _179 => _179.commandHandlers, 'optionalAccess', _180 => _180[commandName]]),
5005
+ defaultCommandHandlers[commandName]
5006
+ );
5007
+ });
5008
+ metadata.aliases.forEach((alias) => command.alias(alias));
5009
+ }
5010
+
5011
+ // src/commands/cli.ts
4570
5012
  function mountTailwindcssPatchCommands(cli, options = {}) {
4571
5013
  const prefix = _nullishCoalesce(options.commandPrefix, () => ( ""));
4572
5014
  const selectedCommands = _nullishCoalesce(options.commands, () => ( tailwindcssPatchCommands));
4573
5015
  const defaultDefinitions = buildDefaultCommandDefinitions();
4574
- const registrars = {
4575
- install: () => {
4576
- const metadata = resolveCommandMetadata("install", options, prefix, defaultDefinitions);
4577
- const command = cli.command(metadata.name, metadata.description);
4578
- applyCommandOptions(command, metadata.optionDefs);
4579
- command.action(async (args) => {
4580
- return runWithCommandHandler(
4581
- cli,
4582
- command,
4583
- "install",
4584
- args,
4585
- _optionalChain([options, 'access', _153 => _153.commandHandlers, 'optionalAccess', _154 => _154.install]),
4586
- installCommandDefaultHandler
4587
- );
4588
- });
4589
- metadata.aliases.forEach((alias) => command.alias(alias));
4590
- },
4591
- extract: () => {
4592
- const metadata = resolveCommandMetadata("extract", options, prefix, defaultDefinitions);
4593
- const command = cli.command(metadata.name, metadata.description);
4594
- applyCommandOptions(command, metadata.optionDefs);
4595
- command.action(async (args) => {
4596
- return runWithCommandHandler(
4597
- cli,
4598
- command,
4599
- "extract",
4600
- args,
4601
- _optionalChain([options, 'access', _155 => _155.commandHandlers, 'optionalAccess', _156 => _156.extract]),
4602
- extractCommandDefaultHandler
4603
- );
4604
- });
4605
- metadata.aliases.forEach((alias) => command.alias(alias));
4606
- },
4607
- tokens: () => {
4608
- const metadata = resolveCommandMetadata("tokens", options, prefix, defaultDefinitions);
4609
- const command = cli.command(metadata.name, metadata.description);
4610
- applyCommandOptions(command, metadata.optionDefs);
4611
- command.action(async (args) => {
4612
- return runWithCommandHandler(
4613
- cli,
4614
- command,
4615
- "tokens",
4616
- args,
4617
- _optionalChain([options, 'access', _157 => _157.commandHandlers, 'optionalAccess', _158 => _158.tokens]),
4618
- tokensCommandDefaultHandler
4619
- );
4620
- });
4621
- metadata.aliases.forEach((alias) => command.alias(alias));
4622
- },
4623
- init: () => {
4624
- const metadata = resolveCommandMetadata("init", options, prefix, defaultDefinitions);
4625
- const command = cli.command(metadata.name, metadata.description);
4626
- applyCommandOptions(command, metadata.optionDefs);
4627
- command.action(async (args) => {
4628
- return runWithCommandHandler(
4629
- cli,
4630
- command,
4631
- "init",
4632
- args,
4633
- _optionalChain([options, 'access', _159 => _159.commandHandlers, 'optionalAccess', _160 => _160.init]),
4634
- initCommandDefaultHandler
4635
- );
4636
- });
4637
- metadata.aliases.forEach((alias) => command.alias(alias));
4638
- },
4639
- migrate: () => {
4640
- const metadata = resolveCommandMetadata("migrate", options, prefix, defaultDefinitions);
4641
- const command = cli.command(metadata.name, metadata.description);
4642
- applyCommandOptions(command, metadata.optionDefs);
4643
- command.action(async (args) => {
4644
- return runWithCommandHandler(
4645
- cli,
4646
- command,
4647
- "migrate",
4648
- args,
4649
- _optionalChain([options, 'access', _161 => _161.commandHandlers, 'optionalAccess', _162 => _162.migrate]),
4650
- migrateCommandDefaultHandler
4651
- );
4652
- });
4653
- metadata.aliases.forEach((alias) => command.alias(alias));
4654
- },
4655
- restore: () => {
4656
- const metadata = resolveCommandMetadata("restore", options, prefix, defaultDefinitions);
4657
- const command = cli.command(metadata.name, metadata.description);
4658
- applyCommandOptions(command, metadata.optionDefs);
4659
- command.action(async (args) => {
4660
- return runWithCommandHandler(
4661
- cli,
4662
- command,
4663
- "restore",
4664
- args,
4665
- _optionalChain([options, 'access', _163 => _163.commandHandlers, 'optionalAccess', _164 => _164.restore]),
4666
- restoreCommandDefaultHandler
4667
- );
4668
- });
4669
- metadata.aliases.forEach((alias) => command.alias(alias));
4670
- },
4671
- validate: () => {
4672
- const metadata = resolveCommandMetadata("validate", options, prefix, defaultDefinitions);
4673
- const command = cli.command(metadata.name, metadata.description);
4674
- applyCommandOptions(command, metadata.optionDefs);
4675
- command.action(async (args) => {
4676
- return runWithCommandHandler(
4677
- cli,
4678
- command,
4679
- "validate",
4680
- args,
4681
- _optionalChain([options, 'access', _165 => _165.commandHandlers, 'optionalAccess', _166 => _166.validate]),
4682
- validateCommandDefaultHandler
4683
- );
4684
- });
4685
- metadata.aliases.forEach((alias) => command.alias(alias));
4686
- },
4687
- status: () => {
4688
- const metadata = resolveCommandMetadata("status", options, prefix, defaultDefinitions);
4689
- const command = cli.command(metadata.name, metadata.description);
4690
- applyCommandOptions(command, metadata.optionDefs);
4691
- command.action(async (args) => {
4692
- return runWithCommandHandler(
4693
- cli,
4694
- command,
4695
- "status",
4696
- args,
4697
- _optionalChain([options, 'access', _167 => _167.commandHandlers, 'optionalAccess', _168 => _168.status]),
4698
- statusCommandDefaultHandler
4699
- );
4700
- });
4701
- metadata.aliases.forEach((alias) => command.alias(alias));
4702
- }
4703
- };
4704
5016
  for (const name of selectedCommands) {
4705
- const register = registrars[name];
4706
- if (register) {
4707
- register();
4708
- }
5017
+ registerTailwindcssPatchCommand(cli, name, options, prefix, defaultDefinitions);
4709
5018
  }
4710
5019
  return cli;
4711
5020
  }
@@ -4740,4 +5049,4 @@ function createTailwindcssPatchCli(options = {}) {
4740
5049
 
4741
5050
 
4742
5051
 
4743
- exports.logger_default = logger_default; exports.CacheStore = CacheStore; exports.extractRawCandidatesWithPositions = extractRawCandidatesWithPositions; exports.extractRawCandidates = extractRawCandidates; exports.extractValidCandidates = extractValidCandidates; exports.extractProjectCandidatesWithPositions = extractProjectCandidatesWithPositions; exports.groupTokensByFile = groupTokensByFile; exports.normalizeOptions = normalizeOptions; exports.getPatchStatusReport = getPatchStatusReport; exports.collectClassesFromContexts = collectClassesFromContexts; exports.collectClassesFromTailwindV4 = collectClassesFromTailwindV4; exports.loadRuntimeContexts = loadRuntimeContexts; exports.runTailwindBuild = runTailwindBuild; exports.TailwindcssPatcher = TailwindcssPatcher; exports.MIGRATION_REPORT_KIND = MIGRATION_REPORT_KIND; exports.MIGRATION_REPORT_SCHEMA_VERSION = MIGRATION_REPORT_SCHEMA_VERSION; exports.migrateConfigFiles = migrateConfigFiles; exports.restoreConfigFiles = restoreConfigFiles; exports.tailwindcssPatchCommands = tailwindcssPatchCommands; exports.VALIDATE_EXIT_CODES = VALIDATE_EXIT_CODES; exports.VALIDATE_FAILURE_REASONS = VALIDATE_FAILURE_REASONS; exports.ValidateCommandError = ValidateCommandError; exports.mountTailwindcssPatchCommands = mountTailwindcssPatchCommands; exports.createTailwindcssPatchCli = createTailwindcssPatchCli;
5052
+ exports.logger_default = logger_default; exports.CacheStore = CacheStore; exports.normalizeOptions = normalizeOptions; exports.extractRawCandidatesWithPositions = extractRawCandidatesWithPositions; exports.extractRawCandidates = extractRawCandidates; exports.extractValidCandidates = extractValidCandidates; exports.extractProjectCandidatesWithPositions = extractProjectCandidatesWithPositions; exports.groupTokensByFile = groupTokensByFile; exports.collectClassesFromContexts = collectClassesFromContexts; exports.collectClassesFromTailwindV4 = collectClassesFromTailwindV4; exports.loadRuntimeContexts = loadRuntimeContexts; exports.runTailwindBuild = runTailwindBuild; exports.getPatchStatusReport = getPatchStatusReport; exports.TailwindcssPatcher = TailwindcssPatcher; exports.MIGRATION_REPORT_KIND = MIGRATION_REPORT_KIND; exports.MIGRATION_REPORT_SCHEMA_VERSION = MIGRATION_REPORT_SCHEMA_VERSION; exports.migrateConfigFiles = migrateConfigFiles; exports.restoreConfigFiles = restoreConfigFiles; exports.VALIDATE_EXIT_CODES = VALIDATE_EXIT_CODES; exports.VALIDATE_FAILURE_REASONS = VALIDATE_FAILURE_REASONS; exports.ValidateCommandError = ValidateCommandError; exports.tailwindcssPatchCommands = tailwindcssPatchCommands; exports.mountTailwindcssPatchCommands = mountTailwindcssPatchCommands; exports.createTailwindcssPatchCli = createTailwindcssPatchCli;