tailwindcss-patch 8.6.1 → 8.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +193 -11
- package/dist/chunk-2YHCFHVA.mjs +4739 -0
- package/dist/chunk-ATKR3J24.js +4743 -0
- package/dist/cli.js +20 -5
- package/dist/cli.mjs +20 -5
- package/dist/index.d.mts +282 -23
- package/dist/index.d.ts +282 -23
- package/dist/index.js +16 -2
- package/dist/index.mjs +15 -1
- package/package.json +14 -10
- package/schema/migration-report.schema.json +144 -0
- package/schema/restore-result.schema.json +68 -0
- package/schema/validate-result.schema.json +122 -0
- package/dist/chunk-DRPYVUDA.js +0 -2462
- package/dist/chunk-LOJHMBK5.mjs +0 -2458
|
@@ -0,0 +1,4739 @@
|
|
|
1
|
+
// src/logger.ts
|
|
2
|
+
import { createConsola } from "consola";
|
|
3
|
+
var logger = createConsola();
|
|
4
|
+
var logger_default = logger;
|
|
5
|
+
|
|
6
|
+
// src/cache/store.ts
|
|
7
|
+
import process2 from "process";
|
|
8
|
+
import fs2 from "fs-extra";
|
|
9
|
+
|
|
10
|
+
// src/cache/context.ts
|
|
11
|
+
import { createHash } from "crypto";
|
|
12
|
+
import process from "process";
|
|
13
|
+
import fs from "fs-extra";
|
|
14
|
+
import path from "pathe";
|
|
15
|
+
|
|
16
|
+
// package.json
|
|
17
|
+
var package_default = {
|
|
18
|
+
name: "tailwindcss-patch",
|
|
19
|
+
version: "8.7.0",
|
|
20
|
+
description: "patch tailwindcss for exposing context and extract classes",
|
|
21
|
+
author: "ice breaker <1324318532@qq.com>",
|
|
22
|
+
license: "MIT",
|
|
23
|
+
homepage: "https://mangle.icebreaker.top/",
|
|
24
|
+
repository: {
|
|
25
|
+
type: "git",
|
|
26
|
+
url: "git+https://github.com/sonofmagic/tailwindcss-mangle.git",
|
|
27
|
+
directory: "packages/tailwindcss-patch"
|
|
28
|
+
},
|
|
29
|
+
bugs: {
|
|
30
|
+
url: "https://github.com/sonofmagic/tailwindcss-mangle/issues"
|
|
31
|
+
},
|
|
32
|
+
keywords: [
|
|
33
|
+
"tailwindcss",
|
|
34
|
+
"patch",
|
|
35
|
+
"extract",
|
|
36
|
+
"class"
|
|
37
|
+
],
|
|
38
|
+
exports: {
|
|
39
|
+
".": {
|
|
40
|
+
types: "./src/index.ts",
|
|
41
|
+
import: "./src/index.ts",
|
|
42
|
+
require: "./src/index.ts"
|
|
43
|
+
},
|
|
44
|
+
"./migration-report.schema.json": "./schema/migration-report.schema.json",
|
|
45
|
+
"./restore-result.schema.json": "./schema/restore-result.schema.json",
|
|
46
|
+
"./validate-result.schema.json": "./schema/validate-result.schema.json"
|
|
47
|
+
},
|
|
48
|
+
main: "./src/index.ts",
|
|
49
|
+
module: "./src/index.ts",
|
|
50
|
+
types: "./src/index.ts",
|
|
51
|
+
bin: {
|
|
52
|
+
"tw-patch": "dev/bin.ts",
|
|
53
|
+
"tailwindcss-patch": "dev/bin.ts"
|
|
54
|
+
},
|
|
55
|
+
files: [
|
|
56
|
+
"bin",
|
|
57
|
+
"dist",
|
|
58
|
+
"schema"
|
|
59
|
+
],
|
|
60
|
+
scripts: {
|
|
61
|
+
dev: "tsup --watch --sourcemap",
|
|
62
|
+
build: "tsup",
|
|
63
|
+
test: "vitest run",
|
|
64
|
+
"test:dev": "vitest",
|
|
65
|
+
patch: "tsx dev/bin.ts install",
|
|
66
|
+
r0: "tsx dev/bin.ts extract",
|
|
67
|
+
r1: "tsx dev/bin.ts extract --css index.css"
|
|
68
|
+
},
|
|
69
|
+
publishConfig: {
|
|
70
|
+
access: "public",
|
|
71
|
+
registry: "https://registry.npmjs.org/",
|
|
72
|
+
bin: {
|
|
73
|
+
"tw-patch": "bin/tw-patch.js",
|
|
74
|
+
"tailwindcss-patch": "bin/tw-patch.js"
|
|
75
|
+
},
|
|
76
|
+
exports: {
|
|
77
|
+
".": {
|
|
78
|
+
types: "./dist/index.d.ts",
|
|
79
|
+
import: "./dist/index.mjs",
|
|
80
|
+
require: "./dist/index.js"
|
|
81
|
+
},
|
|
82
|
+
"./migration-report.schema.json": "./schema/migration-report.schema.json",
|
|
83
|
+
"./restore-result.schema.json": "./schema/restore-result.schema.json",
|
|
84
|
+
"./validate-result.schema.json": "./schema/validate-result.schema.json"
|
|
85
|
+
},
|
|
86
|
+
main: "./dist/index.js",
|
|
87
|
+
module: "./dist/index.mjs",
|
|
88
|
+
types: "./dist/index.d.ts"
|
|
89
|
+
},
|
|
90
|
+
peerDependencies: {
|
|
91
|
+
tailwindcss: ">=2.0.0"
|
|
92
|
+
},
|
|
93
|
+
peerDependenciesMeta: {
|
|
94
|
+
tailwindcss: {
|
|
95
|
+
optional: true
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
dependencies: {
|
|
99
|
+
"@babel/generator": "^7.29.1",
|
|
100
|
+
"@babel/parser": "^7.29.0",
|
|
101
|
+
"@babel/traverse": "^7.29.0",
|
|
102
|
+
"@babel/types": "^7.29.0",
|
|
103
|
+
"@tailwindcss-mangle/config": "workspace:*",
|
|
104
|
+
"@tailwindcss/node": "^4.1.18",
|
|
105
|
+
cac: "^6.7.14",
|
|
106
|
+
consola: "^3.4.2",
|
|
107
|
+
"fs-extra": "^11.3.3",
|
|
108
|
+
"local-pkg": "^1.1.2",
|
|
109
|
+
pathe: "^2.0.3",
|
|
110
|
+
postcss: "^8.5.6",
|
|
111
|
+
semver: "^7.7.4",
|
|
112
|
+
"tailwindcss-config": "^1.1.4"
|
|
113
|
+
},
|
|
114
|
+
devDependencies: {
|
|
115
|
+
"@tailwindcss/oxide": "^4.1.18",
|
|
116
|
+
"@tailwindcss/postcss": "^4.1.18",
|
|
117
|
+
"@tailwindcss/vite": "^4.1.18",
|
|
118
|
+
tailwindcss: "catalog:tailwindcss4",
|
|
119
|
+
"tailwindcss-3": "catalog:tailwindcss3",
|
|
120
|
+
"tailwindcss-4": "catalog:tailwindcss4"
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// src/constants.ts
|
|
125
|
+
var pkgName = "tailwindcss-patch";
|
|
126
|
+
var pkgVersion = package_default.version;
|
|
127
|
+
|
|
128
|
+
// src/cache/types.ts
|
|
129
|
+
var CACHE_SCHEMA_VERSION = 2;
|
|
130
|
+
var CACHE_FINGERPRINT_VERSION = 1;
|
|
131
|
+
|
|
132
|
+
// src/cache/context.ts
|
|
133
|
+
var DEFAULT_TAILWIND_CONFIG_FILES = [
|
|
134
|
+
"tailwind.config.js",
|
|
135
|
+
"tailwind.config.cjs",
|
|
136
|
+
"tailwind.config.mjs",
|
|
137
|
+
"tailwind.config.ts",
|
|
138
|
+
"tailwind.config.cts",
|
|
139
|
+
"tailwind.config.mts"
|
|
140
|
+
];
|
|
141
|
+
function normalizePathname(value) {
|
|
142
|
+
return path.normalize(value).replaceAll("\\", "/");
|
|
143
|
+
}
|
|
144
|
+
function resolveRealpathSyncSafe(value) {
|
|
145
|
+
const resolved = path.resolve(value);
|
|
146
|
+
try {
|
|
147
|
+
return normalizePathname(fs.realpathSync(resolved));
|
|
148
|
+
} catch {
|
|
149
|
+
return normalizePathname(resolved);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function resolveFileMtimeMsSync(value) {
|
|
153
|
+
if (!value) {
|
|
154
|
+
return void 0;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
const stat = fs.statSync(value);
|
|
158
|
+
if (!stat.isFile()) {
|
|
159
|
+
return void 0;
|
|
160
|
+
}
|
|
161
|
+
return stat.mtimeMs;
|
|
162
|
+
} catch {
|
|
163
|
+
return void 0;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function resolveTailwindConfigPath(options, majorVersion) {
|
|
167
|
+
const tailwind = options.tailwind;
|
|
168
|
+
const baseDir = tailwind.cwd ?? options.projectRoot;
|
|
169
|
+
const configured = (() => {
|
|
170
|
+
if (majorVersion === 2 && tailwind.v2?.config) {
|
|
171
|
+
return tailwind.v2.config;
|
|
172
|
+
}
|
|
173
|
+
if (majorVersion === 3 && tailwind.v3?.config) {
|
|
174
|
+
return tailwind.v3.config;
|
|
175
|
+
}
|
|
176
|
+
return tailwind.config;
|
|
177
|
+
})();
|
|
178
|
+
if (configured) {
|
|
179
|
+
const absolute = path.isAbsolute(configured) ? configured : path.resolve(baseDir, configured);
|
|
180
|
+
if (fs.pathExistsSync(absolute)) {
|
|
181
|
+
return resolveRealpathSyncSafe(absolute);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
for (const candidate of DEFAULT_TAILWIND_CONFIG_FILES) {
|
|
185
|
+
const absolute = path.resolve(baseDir, candidate);
|
|
186
|
+
if (fs.pathExistsSync(absolute)) {
|
|
187
|
+
return resolveRealpathSyncSafe(absolute);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return void 0;
|
|
191
|
+
}
|
|
192
|
+
function stableSerialize(input) {
|
|
193
|
+
if (input === null) {
|
|
194
|
+
return "null";
|
|
195
|
+
}
|
|
196
|
+
if (typeof input === "string") {
|
|
197
|
+
return JSON.stringify(input);
|
|
198
|
+
}
|
|
199
|
+
if (typeof input === "number" || typeof input === "boolean") {
|
|
200
|
+
return JSON.stringify(input);
|
|
201
|
+
}
|
|
202
|
+
if (Array.isArray(input)) {
|
|
203
|
+
return `[${input.map((item) => stableSerialize(item)).join(",")}]`;
|
|
204
|
+
}
|
|
205
|
+
if (typeof input === "object") {
|
|
206
|
+
const entries = Object.entries(input).filter(([, value]) => value !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${JSON.stringify(key)}:${stableSerialize(value)}`);
|
|
207
|
+
return `{${entries.join(",")}}`;
|
|
208
|
+
}
|
|
209
|
+
return JSON.stringify(String(input));
|
|
210
|
+
}
|
|
211
|
+
function hash(input) {
|
|
212
|
+
return createHash("sha256").update(input).digest("hex");
|
|
213
|
+
}
|
|
214
|
+
function toFingerprintOptions(normalized) {
|
|
215
|
+
return {
|
|
216
|
+
overwrite: normalized.overwrite,
|
|
217
|
+
output: {
|
|
218
|
+
removeUniversalSelector: normalized.output.removeUniversalSelector,
|
|
219
|
+
format: normalized.output.format
|
|
220
|
+
},
|
|
221
|
+
features: normalized.features,
|
|
222
|
+
tailwind: {
|
|
223
|
+
packageName: normalized.tailwind.packageName,
|
|
224
|
+
cwd: normalized.tailwind.cwd,
|
|
225
|
+
config: normalized.tailwind.config,
|
|
226
|
+
postcssPlugin: normalized.tailwind.postcssPlugin,
|
|
227
|
+
versionHint: normalized.tailwind.versionHint,
|
|
228
|
+
v2: normalized.tailwind.v2,
|
|
229
|
+
v3: normalized.tailwind.v3,
|
|
230
|
+
v4: normalized.tailwind.v4
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
function createCacheContextDescriptor(options, packageInfo, majorVersion) {
|
|
235
|
+
const projectRootRealpath = resolveRealpathSyncSafe(options.projectRoot);
|
|
236
|
+
const processCwdRealpath = resolveRealpathSyncSafe(process.cwd());
|
|
237
|
+
const cacheCwdRealpath = resolveRealpathSyncSafe(options.cache.cwd);
|
|
238
|
+
const tailwindPackageRootRealpath = resolveRealpathSyncSafe(packageInfo.rootPath);
|
|
239
|
+
const tailwindConfigPath = resolveTailwindConfigPath(options, majorVersion);
|
|
240
|
+
const tailwindConfigMtimeMs = resolveFileMtimeMsSync(tailwindConfigPath);
|
|
241
|
+
const optionsHash = hash(stableSerialize(toFingerprintOptions(options)));
|
|
242
|
+
const metadata = {
|
|
243
|
+
fingerprintVersion: CACHE_FINGERPRINT_VERSION,
|
|
244
|
+
projectRootRealpath,
|
|
245
|
+
processCwdRealpath,
|
|
246
|
+
cacheCwdRealpath,
|
|
247
|
+
...tailwindConfigPath === void 0 ? {} : { tailwindConfigPath },
|
|
248
|
+
...tailwindConfigMtimeMs === void 0 ? {} : { tailwindConfigMtimeMs },
|
|
249
|
+
tailwindPackageRootRealpath,
|
|
250
|
+
tailwindPackageVersion: packageInfo.version ?? "unknown",
|
|
251
|
+
patcherVersion: pkgVersion,
|
|
252
|
+
majorVersion,
|
|
253
|
+
optionsHash
|
|
254
|
+
};
|
|
255
|
+
const fingerprint = hash(stableSerialize(metadata));
|
|
256
|
+
return {
|
|
257
|
+
fingerprint,
|
|
258
|
+
metadata
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function explainContextMismatch(current, cached) {
|
|
262
|
+
const reasons = [];
|
|
263
|
+
if (current.projectRootRealpath !== cached.projectRootRealpath) {
|
|
264
|
+
reasons.push(`project-root changed: ${cached.projectRootRealpath} -> ${current.projectRootRealpath}`);
|
|
265
|
+
}
|
|
266
|
+
if (current.processCwdRealpath !== cached.processCwdRealpath) {
|
|
267
|
+
reasons.push(`process-cwd changed: ${cached.processCwdRealpath} -> ${current.processCwdRealpath}`);
|
|
268
|
+
}
|
|
269
|
+
if (current.cacheCwdRealpath !== cached.cacheCwdRealpath) {
|
|
270
|
+
reasons.push(`cache-cwd changed: ${cached.cacheCwdRealpath} -> ${current.cacheCwdRealpath}`);
|
|
271
|
+
}
|
|
272
|
+
if ((current.tailwindConfigPath ?? "") !== (cached.tailwindConfigPath ?? "")) {
|
|
273
|
+
reasons.push(`tailwind-config path changed: ${cached.tailwindConfigPath ?? "<none>"} -> ${current.tailwindConfigPath ?? "<none>"}`);
|
|
274
|
+
}
|
|
275
|
+
if ((current.tailwindConfigMtimeMs ?? -1) !== (cached.tailwindConfigMtimeMs ?? -1)) {
|
|
276
|
+
reasons.push("tailwind-config mtime changed");
|
|
277
|
+
}
|
|
278
|
+
if (current.tailwindPackageRootRealpath !== cached.tailwindPackageRootRealpath) {
|
|
279
|
+
reasons.push(`tailwind-package root changed: ${cached.tailwindPackageRootRealpath} -> ${current.tailwindPackageRootRealpath}`);
|
|
280
|
+
}
|
|
281
|
+
if (current.tailwindPackageVersion !== cached.tailwindPackageVersion) {
|
|
282
|
+
reasons.push(`tailwind-package version changed: ${cached.tailwindPackageVersion} -> ${current.tailwindPackageVersion}`);
|
|
283
|
+
}
|
|
284
|
+
if (current.patcherVersion !== cached.patcherVersion) {
|
|
285
|
+
reasons.push(`patcher version changed: ${cached.patcherVersion} -> ${current.patcherVersion}`);
|
|
286
|
+
}
|
|
287
|
+
if (current.majorVersion !== cached.majorVersion) {
|
|
288
|
+
reasons.push(`major version changed: ${cached.majorVersion} -> ${current.majorVersion}`);
|
|
289
|
+
}
|
|
290
|
+
if (current.optionsHash !== cached.optionsHash) {
|
|
291
|
+
reasons.push(`patch options hash changed: ${cached.optionsHash.slice(0, 12)} -> ${current.optionsHash.slice(0, 12)}`);
|
|
292
|
+
}
|
|
293
|
+
return reasons;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// src/cache/store.ts
|
|
297
|
+
function isErrnoException(error) {
|
|
298
|
+
return error instanceof Error && typeof error.code === "string";
|
|
299
|
+
}
|
|
300
|
+
function isAccessDenied(error) {
|
|
301
|
+
return isErrnoException(error) && Boolean(error.code && ["EPERM", "EBUSY", "EACCES"].includes(error.code));
|
|
302
|
+
}
|
|
303
|
+
function toStringArray(value) {
|
|
304
|
+
if (!Array.isArray(value)) {
|
|
305
|
+
return [];
|
|
306
|
+
}
|
|
307
|
+
return value.filter((item) => typeof item === "string");
|
|
308
|
+
}
|
|
309
|
+
function asObject(value) {
|
|
310
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
311
|
+
return void 0;
|
|
312
|
+
}
|
|
313
|
+
return value;
|
|
314
|
+
}
|
|
315
|
+
function toReadMeta(meta) {
|
|
316
|
+
return {
|
|
317
|
+
...meta,
|
|
318
|
+
details: [...meta.details]
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
function cloneEntry(entry) {
|
|
322
|
+
return {
|
|
323
|
+
context: {
|
|
324
|
+
...entry.context
|
|
325
|
+
},
|
|
326
|
+
values: [...entry.values],
|
|
327
|
+
updatedAt: entry.updatedAt
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
var CacheStore = class {
|
|
331
|
+
constructor(options, context) {
|
|
332
|
+
this.options = options;
|
|
333
|
+
this.context = context;
|
|
334
|
+
this.driver = options.driver ?? "file";
|
|
335
|
+
this.lockPath = `${this.options.path}.lock`;
|
|
336
|
+
}
|
|
337
|
+
driver;
|
|
338
|
+
lockPath;
|
|
339
|
+
memoryCache = null;
|
|
340
|
+
memoryIndex = null;
|
|
341
|
+
lastReadMeta = {
|
|
342
|
+
hit: false,
|
|
343
|
+
reason: "context-not-found",
|
|
344
|
+
details: []
|
|
345
|
+
};
|
|
346
|
+
isContextAware() {
|
|
347
|
+
return this.context !== void 0;
|
|
348
|
+
}
|
|
349
|
+
createEmptyIndex() {
|
|
350
|
+
return {
|
|
351
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
352
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
353
|
+
contexts: {}
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
async ensureDir() {
|
|
357
|
+
await fs2.ensureDir(this.options.dir);
|
|
358
|
+
}
|
|
359
|
+
ensureDirSync() {
|
|
360
|
+
fs2.ensureDirSync(this.options.dir);
|
|
361
|
+
}
|
|
362
|
+
createTempPath() {
|
|
363
|
+
const uniqueSuffix = `${process2.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
364
|
+
return `${this.options.path}.${uniqueSuffix}.tmp`;
|
|
365
|
+
}
|
|
366
|
+
async replaceCacheFile(tempPath) {
|
|
367
|
+
try {
|
|
368
|
+
await fs2.rename(tempPath, this.options.path);
|
|
369
|
+
return true;
|
|
370
|
+
} catch (error) {
|
|
371
|
+
if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
|
|
372
|
+
try {
|
|
373
|
+
await fs2.remove(this.options.path);
|
|
374
|
+
} catch (removeError) {
|
|
375
|
+
if (isAccessDenied(removeError)) {
|
|
376
|
+
logger_default.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
if (!isErrnoException(removeError) || removeError.code !== "ENOENT") {
|
|
380
|
+
throw removeError;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
await fs2.rename(tempPath, this.options.path);
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
replaceCacheFileSync(tempPath) {
|
|
390
|
+
try {
|
|
391
|
+
fs2.renameSync(tempPath, this.options.path);
|
|
392
|
+
return true;
|
|
393
|
+
} catch (error) {
|
|
394
|
+
if (isErrnoException(error) && (error.code === "EEXIST" || error.code === "EPERM")) {
|
|
395
|
+
try {
|
|
396
|
+
fs2.removeSync(this.options.path);
|
|
397
|
+
} catch (removeError) {
|
|
398
|
+
if (isAccessDenied(removeError)) {
|
|
399
|
+
logger_default.debug("Tailwind class cache locked or read-only, skipping update.", removeError);
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
if (!isErrnoException(removeError) || removeError.code !== "ENOENT") {
|
|
403
|
+
throw removeError;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
fs2.renameSync(tempPath, this.options.path);
|
|
407
|
+
return true;
|
|
408
|
+
}
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
async cleanupTempFile(tempPath) {
|
|
413
|
+
try {
|
|
414
|
+
await fs2.remove(tempPath);
|
|
415
|
+
} catch {
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
cleanupTempFileSync(tempPath) {
|
|
419
|
+
try {
|
|
420
|
+
fs2.removeSync(tempPath);
|
|
421
|
+
} catch {
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
async delay(ms) {
|
|
425
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
426
|
+
}
|
|
427
|
+
async acquireLock() {
|
|
428
|
+
await fs2.ensureDir(this.options.dir);
|
|
429
|
+
const maxAttempts = 40;
|
|
430
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
431
|
+
try {
|
|
432
|
+
await fs2.writeFile(this.lockPath, `${process2.pid}
|
|
433
|
+
${Date.now()}`, { flag: "wx" });
|
|
434
|
+
return true;
|
|
435
|
+
} catch (error) {
|
|
436
|
+
if (!isErrnoException(error) || error.code !== "EEXIST") {
|
|
437
|
+
logger_default.debug("Unable to acquire cache lock.", error);
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
try {
|
|
441
|
+
const stat = await fs2.stat(this.lockPath);
|
|
442
|
+
if (Date.now() - stat.mtimeMs > 3e4) {
|
|
443
|
+
await fs2.remove(this.lockPath);
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
} catch {
|
|
447
|
+
}
|
|
448
|
+
await this.delay(25);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
logger_default.debug("Timed out while waiting for cache lock; skipping cache mutation.");
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
releaseLockSyncOrAsync(sync) {
|
|
455
|
+
if (sync) {
|
|
456
|
+
try {
|
|
457
|
+
fs2.removeSync(this.lockPath);
|
|
458
|
+
} catch {
|
|
459
|
+
}
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
return fs2.remove(this.lockPath).catch(() => void 0);
|
|
463
|
+
}
|
|
464
|
+
acquireLockSync() {
|
|
465
|
+
fs2.ensureDirSync(this.options.dir);
|
|
466
|
+
const maxAttempts = 40;
|
|
467
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
468
|
+
try {
|
|
469
|
+
fs2.writeFileSync(this.lockPath, `${process2.pid}
|
|
470
|
+
${Date.now()}`, { flag: "wx" });
|
|
471
|
+
return true;
|
|
472
|
+
} catch (error) {
|
|
473
|
+
if (!isErrnoException(error) || error.code !== "EEXIST") {
|
|
474
|
+
logger_default.debug("Unable to acquire cache lock.", error);
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
try {
|
|
478
|
+
const stat = fs2.statSync(this.lockPath);
|
|
479
|
+
if (Date.now() - stat.mtimeMs > 3e4) {
|
|
480
|
+
fs2.removeSync(this.lockPath);
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
} catch {
|
|
484
|
+
}
|
|
485
|
+
const start = Date.now();
|
|
486
|
+
while (Date.now() - start < 25) {
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
logger_default.debug("Timed out while waiting for cache lock; skipping cache mutation.");
|
|
491
|
+
return false;
|
|
492
|
+
}
|
|
493
|
+
async withFileLock(fn) {
|
|
494
|
+
const locked = await this.acquireLock();
|
|
495
|
+
if (!locked) {
|
|
496
|
+
return void 0;
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
return await fn();
|
|
500
|
+
} finally {
|
|
501
|
+
await this.releaseLockSyncOrAsync(false);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
withFileLockSync(fn) {
|
|
505
|
+
const locked = this.acquireLockSync();
|
|
506
|
+
if (!locked) {
|
|
507
|
+
return void 0;
|
|
508
|
+
}
|
|
509
|
+
try {
|
|
510
|
+
return fn();
|
|
511
|
+
} finally {
|
|
512
|
+
this.releaseLockSyncOrAsync(true);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
normalizeContextEntry(value) {
|
|
516
|
+
const record = asObject(value);
|
|
517
|
+
if (!record) {
|
|
518
|
+
return void 0;
|
|
519
|
+
}
|
|
520
|
+
const values = toStringArray(record["values"]);
|
|
521
|
+
if (values.length === 0) {
|
|
522
|
+
return void 0;
|
|
523
|
+
}
|
|
524
|
+
const contextRecord = asObject(record["context"]);
|
|
525
|
+
if (!contextRecord) {
|
|
526
|
+
return void 0;
|
|
527
|
+
}
|
|
528
|
+
const {
|
|
529
|
+
fingerprintVersion,
|
|
530
|
+
projectRootRealpath,
|
|
531
|
+
processCwdRealpath,
|
|
532
|
+
cacheCwdRealpath,
|
|
533
|
+
tailwindConfigPath,
|
|
534
|
+
tailwindConfigMtimeMs,
|
|
535
|
+
tailwindPackageRootRealpath,
|
|
536
|
+
tailwindPackageVersion,
|
|
537
|
+
patcherVersion,
|
|
538
|
+
majorVersion,
|
|
539
|
+
optionsHash
|
|
540
|
+
} = contextRecord;
|
|
541
|
+
if (fingerprintVersion !== 1 || typeof projectRootRealpath !== "string" || typeof processCwdRealpath !== "string" || typeof cacheCwdRealpath !== "string" || typeof tailwindPackageRootRealpath !== "string" || typeof tailwindPackageVersion !== "string" || typeof patcherVersion !== "string" || majorVersion !== 2 && majorVersion !== 3 && majorVersion !== 4 || typeof optionsHash !== "string") {
|
|
542
|
+
return void 0;
|
|
543
|
+
}
|
|
544
|
+
const normalized = {
|
|
545
|
+
context: {
|
|
546
|
+
fingerprintVersion,
|
|
547
|
+
projectRootRealpath,
|
|
548
|
+
processCwdRealpath,
|
|
549
|
+
cacheCwdRealpath,
|
|
550
|
+
...typeof tailwindConfigPath === "string" ? { tailwindConfigPath } : {},
|
|
551
|
+
...typeof tailwindConfigMtimeMs === "number" ? { tailwindConfigMtimeMs } : {},
|
|
552
|
+
tailwindPackageRootRealpath,
|
|
553
|
+
tailwindPackageVersion,
|
|
554
|
+
patcherVersion,
|
|
555
|
+
majorVersion,
|
|
556
|
+
optionsHash
|
|
557
|
+
},
|
|
558
|
+
values,
|
|
559
|
+
updatedAt: typeof record["updatedAt"] === "string" ? record["updatedAt"] : (/* @__PURE__ */ new Date(0)).toISOString()
|
|
560
|
+
};
|
|
561
|
+
return normalized;
|
|
562
|
+
}
|
|
563
|
+
normalizeIndexFile(payload) {
|
|
564
|
+
if (Array.isArray(payload)) {
|
|
565
|
+
return {
|
|
566
|
+
kind: "legacy",
|
|
567
|
+
data: toStringArray(payload)
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
const record = asObject(payload);
|
|
571
|
+
if (!record) {
|
|
572
|
+
return { kind: "invalid" };
|
|
573
|
+
}
|
|
574
|
+
if (record["schemaVersion"] !== CACHE_SCHEMA_VERSION) {
|
|
575
|
+
return { kind: "invalid" };
|
|
576
|
+
}
|
|
577
|
+
const contextsRecord = asObject(record["contexts"]);
|
|
578
|
+
if (!contextsRecord) {
|
|
579
|
+
return { kind: "invalid" };
|
|
580
|
+
}
|
|
581
|
+
const contexts = {};
|
|
582
|
+
for (const [fingerprint, value] of Object.entries(contextsRecord)) {
|
|
583
|
+
if (typeof fingerprint !== "string" || !fingerprint) {
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
const entry = this.normalizeContextEntry(value);
|
|
587
|
+
if (!entry) {
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
contexts[fingerprint] = entry;
|
|
591
|
+
}
|
|
592
|
+
return {
|
|
593
|
+
kind: "v2",
|
|
594
|
+
data: {
|
|
595
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
596
|
+
updatedAt: typeof record["updatedAt"] === "string" ? record["updatedAt"] : (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
597
|
+
contexts
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
async readParsedCacheFile(cleanupInvalid) {
|
|
602
|
+
try {
|
|
603
|
+
if (!await fs2.pathExists(this.options.path)) {
|
|
604
|
+
return { kind: "empty" };
|
|
605
|
+
}
|
|
606
|
+
const payload = await fs2.readJSON(this.options.path);
|
|
607
|
+
const normalized = this.normalizeIndexFile(payload);
|
|
608
|
+
if (normalized.kind !== "invalid") {
|
|
609
|
+
return normalized;
|
|
610
|
+
}
|
|
611
|
+
if (cleanupInvalid) {
|
|
612
|
+
logger_default.warn("Unable to read Tailwind class cache index, removing invalid file.");
|
|
613
|
+
await fs2.remove(this.options.path);
|
|
614
|
+
}
|
|
615
|
+
return { kind: "invalid" };
|
|
616
|
+
} catch (error) {
|
|
617
|
+
if (isErrnoException(error) && error.code === "ENOENT") {
|
|
618
|
+
return { kind: "empty" };
|
|
619
|
+
}
|
|
620
|
+
logger_default.warn("Unable to read Tailwind class cache index, removing invalid file.", error);
|
|
621
|
+
if (cleanupInvalid) {
|
|
622
|
+
try {
|
|
623
|
+
await fs2.remove(this.options.path);
|
|
624
|
+
} catch (cleanupError) {
|
|
625
|
+
logger_default.error("Failed to clean up invalid cache file", cleanupError);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return { kind: "invalid" };
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
readParsedCacheFileSync(cleanupInvalid) {
|
|
632
|
+
try {
|
|
633
|
+
if (!fs2.pathExistsSync(this.options.path)) {
|
|
634
|
+
return { kind: "empty" };
|
|
635
|
+
}
|
|
636
|
+
const payload = fs2.readJSONSync(this.options.path);
|
|
637
|
+
const normalized = this.normalizeIndexFile(payload);
|
|
638
|
+
if (normalized.kind !== "invalid") {
|
|
639
|
+
return normalized;
|
|
640
|
+
}
|
|
641
|
+
if (cleanupInvalid) {
|
|
642
|
+
logger_default.warn("Unable to read Tailwind class cache index, removing invalid file.");
|
|
643
|
+
fs2.removeSync(this.options.path);
|
|
644
|
+
}
|
|
645
|
+
return { kind: "invalid" };
|
|
646
|
+
} catch (error) {
|
|
647
|
+
if (isErrnoException(error) && error.code === "ENOENT") {
|
|
648
|
+
return { kind: "empty" };
|
|
649
|
+
}
|
|
650
|
+
logger_default.warn("Unable to read Tailwind class cache index, removing invalid file.", error);
|
|
651
|
+
if (cleanupInvalid) {
|
|
652
|
+
try {
|
|
653
|
+
fs2.removeSync(this.options.path);
|
|
654
|
+
} catch (cleanupError) {
|
|
655
|
+
logger_default.error("Failed to clean up invalid cache file", cleanupError);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return { kind: "invalid" };
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
findProjectMatch(index) {
|
|
662
|
+
if (!this.context) {
|
|
663
|
+
return void 0;
|
|
664
|
+
}
|
|
665
|
+
const current = this.context.metadata.projectRootRealpath;
|
|
666
|
+
return Object.entries(index.contexts).find(([, entry]) => entry.context.projectRootRealpath === current);
|
|
667
|
+
}
|
|
668
|
+
async writeIndexFile(index) {
|
|
669
|
+
const tempPath = this.createTempPath();
|
|
670
|
+
try {
|
|
671
|
+
await this.ensureDir();
|
|
672
|
+
await fs2.writeJSON(tempPath, index);
|
|
673
|
+
const replaced = await this.replaceCacheFile(tempPath);
|
|
674
|
+
if (replaced) {
|
|
675
|
+
return this.options.path;
|
|
676
|
+
}
|
|
677
|
+
await this.cleanupTempFile(tempPath);
|
|
678
|
+
return void 0;
|
|
679
|
+
} catch (error) {
|
|
680
|
+
await this.cleanupTempFile(tempPath);
|
|
681
|
+
logger_default.error("Unable to persist Tailwind class cache", error);
|
|
682
|
+
return void 0;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
writeIndexFileSync(index) {
|
|
686
|
+
const tempPath = this.createTempPath();
|
|
687
|
+
try {
|
|
688
|
+
this.ensureDirSync();
|
|
689
|
+
fs2.writeJSONSync(tempPath, index);
|
|
690
|
+
const replaced = this.replaceCacheFileSync(tempPath);
|
|
691
|
+
if (replaced) {
|
|
692
|
+
return this.options.path;
|
|
693
|
+
}
|
|
694
|
+
this.cleanupTempFileSync(tempPath);
|
|
695
|
+
return void 0;
|
|
696
|
+
} catch (error) {
|
|
697
|
+
this.cleanupTempFileSync(tempPath);
|
|
698
|
+
logger_default.error("Unable to persist Tailwind class cache", error);
|
|
699
|
+
return void 0;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
async write(data) {
|
|
703
|
+
if (!this.options.enabled) {
|
|
704
|
+
return void 0;
|
|
705
|
+
}
|
|
706
|
+
if (this.driver === "noop") {
|
|
707
|
+
return void 0;
|
|
708
|
+
}
|
|
709
|
+
if (this.driver === "memory") {
|
|
710
|
+
if (!this.isContextAware()) {
|
|
711
|
+
this.memoryCache = new Set(data);
|
|
712
|
+
return "memory";
|
|
713
|
+
}
|
|
714
|
+
const index = this.memoryIndex ?? this.createEmptyIndex();
|
|
715
|
+
if (!this.context) {
|
|
716
|
+
return "memory";
|
|
717
|
+
}
|
|
718
|
+
index.contexts[this.context.fingerprint] = {
|
|
719
|
+
context: {
|
|
720
|
+
...this.context.metadata
|
|
721
|
+
},
|
|
722
|
+
values: Array.from(data),
|
|
723
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
724
|
+
};
|
|
725
|
+
index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
726
|
+
this.memoryIndex = index;
|
|
727
|
+
return "memory";
|
|
728
|
+
}
|
|
729
|
+
if (!this.isContextAware()) {
|
|
730
|
+
const tempPath = this.createTempPath();
|
|
731
|
+
try {
|
|
732
|
+
await this.ensureDir();
|
|
733
|
+
await fs2.writeJSON(tempPath, Array.from(data));
|
|
734
|
+
const replaced = await this.replaceCacheFile(tempPath);
|
|
735
|
+
if (replaced) {
|
|
736
|
+
return this.options.path;
|
|
737
|
+
}
|
|
738
|
+
await this.cleanupTempFile(tempPath);
|
|
739
|
+
return void 0;
|
|
740
|
+
} catch (error) {
|
|
741
|
+
await this.cleanupTempFile(tempPath);
|
|
742
|
+
logger_default.error("Unable to persist Tailwind class cache", error);
|
|
743
|
+
return void 0;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
const result = await this.withFileLock(async () => {
|
|
747
|
+
const parsed = await this.readParsedCacheFile(false);
|
|
748
|
+
const index = parsed.kind === "v2" ? parsed.data : this.createEmptyIndex();
|
|
749
|
+
if (this.context) {
|
|
750
|
+
index.contexts[this.context.fingerprint] = {
|
|
751
|
+
context: {
|
|
752
|
+
...this.context.metadata
|
|
753
|
+
},
|
|
754
|
+
values: Array.from(data),
|
|
755
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
759
|
+
return this.writeIndexFile(index);
|
|
760
|
+
});
|
|
761
|
+
return result;
|
|
762
|
+
}
|
|
763
|
+
writeSync(data) {
|
|
764
|
+
if (!this.options.enabled) {
|
|
765
|
+
return void 0;
|
|
766
|
+
}
|
|
767
|
+
if (this.driver === "noop") {
|
|
768
|
+
return void 0;
|
|
769
|
+
}
|
|
770
|
+
if (this.driver === "memory") {
|
|
771
|
+
if (!this.isContextAware()) {
|
|
772
|
+
this.memoryCache = new Set(data);
|
|
773
|
+
return "memory";
|
|
774
|
+
}
|
|
775
|
+
const index = this.memoryIndex ?? this.createEmptyIndex();
|
|
776
|
+
if (!this.context) {
|
|
777
|
+
return "memory";
|
|
778
|
+
}
|
|
779
|
+
index.contexts[this.context.fingerprint] = {
|
|
780
|
+
context: {
|
|
781
|
+
...this.context.metadata
|
|
782
|
+
},
|
|
783
|
+
values: Array.from(data),
|
|
784
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
785
|
+
};
|
|
786
|
+
index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
787
|
+
this.memoryIndex = index;
|
|
788
|
+
return "memory";
|
|
789
|
+
}
|
|
790
|
+
if (!this.isContextAware()) {
|
|
791
|
+
const tempPath = this.createTempPath();
|
|
792
|
+
try {
|
|
793
|
+
this.ensureDirSync();
|
|
794
|
+
fs2.writeJSONSync(tempPath, Array.from(data));
|
|
795
|
+
const replaced = this.replaceCacheFileSync(tempPath);
|
|
796
|
+
if (replaced) {
|
|
797
|
+
return this.options.path;
|
|
798
|
+
}
|
|
799
|
+
this.cleanupTempFileSync(tempPath);
|
|
800
|
+
return void 0;
|
|
801
|
+
} catch (error) {
|
|
802
|
+
this.cleanupTempFileSync(tempPath);
|
|
803
|
+
logger_default.error("Unable to persist Tailwind class cache", error);
|
|
804
|
+
return void 0;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const result = this.withFileLockSync(() => {
|
|
808
|
+
const parsed = this.readParsedCacheFileSync(false);
|
|
809
|
+
const index = parsed.kind === "v2" ? parsed.data : this.createEmptyIndex();
|
|
810
|
+
if (this.context) {
|
|
811
|
+
index.contexts[this.context.fingerprint] = {
|
|
812
|
+
context: {
|
|
813
|
+
...this.context.metadata
|
|
814
|
+
},
|
|
815
|
+
values: Array.from(data),
|
|
816
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
index.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
820
|
+
return this.writeIndexFileSync(index);
|
|
821
|
+
});
|
|
822
|
+
return result;
|
|
823
|
+
}
|
|
824
|
+
async readWithMeta() {
|
|
825
|
+
if (!this.options.enabled) {
|
|
826
|
+
return {
|
|
827
|
+
data: /* @__PURE__ */ new Set(),
|
|
828
|
+
meta: {
|
|
829
|
+
hit: false,
|
|
830
|
+
reason: "cache-disabled",
|
|
831
|
+
details: ["cache disabled"]
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
if (this.driver === "noop") {
|
|
836
|
+
return {
|
|
837
|
+
data: /* @__PURE__ */ new Set(),
|
|
838
|
+
meta: {
|
|
839
|
+
hit: false,
|
|
840
|
+
reason: "noop-driver",
|
|
841
|
+
details: ["cache driver is noop"]
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
if (this.driver === "memory") {
|
|
846
|
+
if (!this.isContextAware()) {
|
|
847
|
+
const cache = new Set(this.memoryCache ?? []);
|
|
848
|
+
return {
|
|
849
|
+
data: cache,
|
|
850
|
+
meta: {
|
|
851
|
+
hit: cache.size > 0,
|
|
852
|
+
reason: cache.size > 0 ? "hit" : "context-not-found",
|
|
853
|
+
details: cache.size > 0 ? ["memory cache hit"] : ["memory cache miss"]
|
|
854
|
+
}
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
const index = this.memoryIndex;
|
|
858
|
+
if (!index || !this.context) {
|
|
859
|
+
return {
|
|
860
|
+
data: /* @__PURE__ */ new Set(),
|
|
861
|
+
meta: {
|
|
862
|
+
hit: false,
|
|
863
|
+
reason: "context-not-found",
|
|
864
|
+
...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
|
|
865
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
866
|
+
details: ["no in-memory cache index for current context"]
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
const entry2 = index.contexts[this.context.fingerprint];
|
|
871
|
+
if (entry2) {
|
|
872
|
+
return {
|
|
873
|
+
data: new Set(entry2.values),
|
|
874
|
+
meta: {
|
|
875
|
+
hit: true,
|
|
876
|
+
reason: "hit",
|
|
877
|
+
fingerprint: this.context.fingerprint,
|
|
878
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
879
|
+
details: ["memory cache hit"]
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
const projectMatch2 = this.findProjectMatch(index);
|
|
884
|
+
if (projectMatch2 && this.context) {
|
|
885
|
+
const [, matchedEntry] = projectMatch2;
|
|
886
|
+
return {
|
|
887
|
+
data: /* @__PURE__ */ new Set(),
|
|
888
|
+
meta: {
|
|
889
|
+
hit: false,
|
|
890
|
+
reason: "context-mismatch",
|
|
891
|
+
fingerprint: this.context.fingerprint,
|
|
892
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
893
|
+
details: explainContextMismatch(this.context.metadata, matchedEntry.context)
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
return {
|
|
898
|
+
data: /* @__PURE__ */ new Set(),
|
|
899
|
+
meta: {
|
|
900
|
+
hit: false,
|
|
901
|
+
reason: "context-not-found",
|
|
902
|
+
fingerprint: this.context.fingerprint,
|
|
903
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
904
|
+
details: ["context fingerprint not found in memory cache index"]
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
const parsed = await this.readParsedCacheFile(true);
|
|
909
|
+
if (parsed.kind === "empty") {
|
|
910
|
+
return {
|
|
911
|
+
data: /* @__PURE__ */ new Set(),
|
|
912
|
+
meta: {
|
|
913
|
+
hit: false,
|
|
914
|
+
reason: "file-missing",
|
|
915
|
+
details: ["cache file not found"]
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
if (parsed.kind === "invalid") {
|
|
920
|
+
return {
|
|
921
|
+
data: /* @__PURE__ */ new Set(),
|
|
922
|
+
meta: {
|
|
923
|
+
hit: false,
|
|
924
|
+
reason: "invalid-schema",
|
|
925
|
+
details: ["cache schema invalid and has been reset"]
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
if (!this.isContextAware()) {
|
|
930
|
+
if (parsed.kind === "legacy") {
|
|
931
|
+
return {
|
|
932
|
+
data: new Set(parsed.data),
|
|
933
|
+
meta: {
|
|
934
|
+
hit: parsed.data.length > 0,
|
|
935
|
+
reason: parsed.data.length > 0 ? "hit" : "context-not-found",
|
|
936
|
+
details: ["legacy cache format"]
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
const union = Object.values(parsed.data.contexts).flatMap((entry2) => entry2.values);
|
|
941
|
+
return {
|
|
942
|
+
data: new Set(union),
|
|
943
|
+
meta: {
|
|
944
|
+
hit: union.length > 0,
|
|
945
|
+
reason: union.length > 0 ? "hit" : "context-not-found",
|
|
946
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
947
|
+
details: ["context-less read merged all cache entries"]
|
|
948
|
+
}
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
if (parsed.kind === "legacy") {
|
|
952
|
+
return {
|
|
953
|
+
data: /* @__PURE__ */ new Set(),
|
|
954
|
+
meta: {
|
|
955
|
+
hit: false,
|
|
956
|
+
reason: "legacy-schema",
|
|
957
|
+
...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
|
|
958
|
+
details: ["legacy cache schema detected; rebuilding cache with context fingerprint"]
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
if (!this.context) {
|
|
963
|
+
return {
|
|
964
|
+
data: /* @__PURE__ */ new Set(),
|
|
965
|
+
meta: {
|
|
966
|
+
hit: false,
|
|
967
|
+
reason: "context-not-found",
|
|
968
|
+
details: ["cache context missing"]
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
const entry = parsed.data.contexts[this.context.fingerprint];
|
|
973
|
+
if (entry) {
|
|
974
|
+
const mismatchReasons = explainContextMismatch(this.context.metadata, entry.context);
|
|
975
|
+
if (mismatchReasons.length === 0) {
|
|
976
|
+
return {
|
|
977
|
+
data: new Set(entry.values),
|
|
978
|
+
meta: {
|
|
979
|
+
hit: true,
|
|
980
|
+
reason: "hit",
|
|
981
|
+
fingerprint: this.context.fingerprint,
|
|
982
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
983
|
+
details: [`context fingerprint ${this.context.fingerprint.slice(0, 12)} matched`]
|
|
984
|
+
}
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
return {
|
|
988
|
+
data: /* @__PURE__ */ new Set(),
|
|
989
|
+
meta: {
|
|
990
|
+
hit: false,
|
|
991
|
+
reason: "context-mismatch",
|
|
992
|
+
fingerprint: this.context.fingerprint,
|
|
993
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
994
|
+
details: mismatchReasons
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
const projectMatch = this.findProjectMatch(parsed.data);
|
|
999
|
+
if (projectMatch) {
|
|
1000
|
+
const [matchedFingerprint, matchedEntry] = projectMatch;
|
|
1001
|
+
return {
|
|
1002
|
+
data: /* @__PURE__ */ new Set(),
|
|
1003
|
+
meta: {
|
|
1004
|
+
hit: false,
|
|
1005
|
+
reason: "context-mismatch",
|
|
1006
|
+
fingerprint: this.context.fingerprint,
|
|
1007
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1008
|
+
details: [
|
|
1009
|
+
`nearest context fingerprint: ${matchedFingerprint.slice(0, 12)}`,
|
|
1010
|
+
...explainContextMismatch(this.context.metadata, matchedEntry.context)
|
|
1011
|
+
]
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
return {
|
|
1016
|
+
data: /* @__PURE__ */ new Set(),
|
|
1017
|
+
meta: {
|
|
1018
|
+
hit: false,
|
|
1019
|
+
reason: "context-not-found",
|
|
1020
|
+
fingerprint: this.context.fingerprint,
|
|
1021
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1022
|
+
details: ["context fingerprint not found in cache index"]
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
readWithMetaSync() {
|
|
1027
|
+
if (!this.options.enabled) {
|
|
1028
|
+
return {
|
|
1029
|
+
data: /* @__PURE__ */ new Set(),
|
|
1030
|
+
meta: {
|
|
1031
|
+
hit: false,
|
|
1032
|
+
reason: "cache-disabled",
|
|
1033
|
+
details: ["cache disabled"]
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
if (this.driver === "noop") {
|
|
1038
|
+
return {
|
|
1039
|
+
data: /* @__PURE__ */ new Set(),
|
|
1040
|
+
meta: {
|
|
1041
|
+
hit: false,
|
|
1042
|
+
reason: "noop-driver",
|
|
1043
|
+
details: ["cache driver is noop"]
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
if (this.driver === "memory") {
|
|
1048
|
+
if (!this.isContextAware()) {
|
|
1049
|
+
const cache = new Set(this.memoryCache ?? []);
|
|
1050
|
+
return {
|
|
1051
|
+
data: cache,
|
|
1052
|
+
meta: {
|
|
1053
|
+
hit: cache.size > 0,
|
|
1054
|
+
reason: cache.size > 0 ? "hit" : "context-not-found",
|
|
1055
|
+
details: cache.size > 0 ? ["memory cache hit"] : ["memory cache miss"]
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
const index = this.memoryIndex;
|
|
1060
|
+
if (!index || !this.context) {
|
|
1061
|
+
return {
|
|
1062
|
+
data: /* @__PURE__ */ new Set(),
|
|
1063
|
+
meta: {
|
|
1064
|
+
hit: false,
|
|
1065
|
+
reason: "context-not-found",
|
|
1066
|
+
...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
|
|
1067
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
1068
|
+
details: ["no in-memory cache index for current context"]
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
const entry2 = index.contexts[this.context.fingerprint];
|
|
1073
|
+
if (entry2) {
|
|
1074
|
+
return {
|
|
1075
|
+
data: new Set(entry2.values),
|
|
1076
|
+
meta: {
|
|
1077
|
+
hit: true,
|
|
1078
|
+
reason: "hit",
|
|
1079
|
+
fingerprint: this.context.fingerprint,
|
|
1080
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
1081
|
+
details: ["memory cache hit"]
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
const projectMatch2 = this.findProjectMatch(index);
|
|
1086
|
+
if (projectMatch2 && this.context) {
|
|
1087
|
+
const [, matchedEntry] = projectMatch2;
|
|
1088
|
+
return {
|
|
1089
|
+
data: /* @__PURE__ */ new Set(),
|
|
1090
|
+
meta: {
|
|
1091
|
+
hit: false,
|
|
1092
|
+
reason: "context-mismatch",
|
|
1093
|
+
fingerprint: this.context.fingerprint,
|
|
1094
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
1095
|
+
details: explainContextMismatch(this.context.metadata, matchedEntry.context)
|
|
1096
|
+
}
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
return {
|
|
1100
|
+
data: /* @__PURE__ */ new Set(),
|
|
1101
|
+
meta: {
|
|
1102
|
+
hit: false,
|
|
1103
|
+
reason: "context-not-found",
|
|
1104
|
+
fingerprint: this.context.fingerprint,
|
|
1105
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
1106
|
+
details: ["context fingerprint not found in memory cache index"]
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
const parsed = this.readParsedCacheFileSync(true);
|
|
1111
|
+
if (parsed.kind === "empty") {
|
|
1112
|
+
return {
|
|
1113
|
+
data: /* @__PURE__ */ new Set(),
|
|
1114
|
+
meta: {
|
|
1115
|
+
hit: false,
|
|
1116
|
+
reason: "file-missing",
|
|
1117
|
+
details: ["cache file not found"]
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
if (parsed.kind === "invalid") {
|
|
1122
|
+
return {
|
|
1123
|
+
data: /* @__PURE__ */ new Set(),
|
|
1124
|
+
meta: {
|
|
1125
|
+
hit: false,
|
|
1126
|
+
reason: "invalid-schema",
|
|
1127
|
+
details: ["cache schema invalid and has been reset"]
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
if (!this.isContextAware()) {
|
|
1132
|
+
if (parsed.kind === "legacy") {
|
|
1133
|
+
return {
|
|
1134
|
+
data: new Set(parsed.data),
|
|
1135
|
+
meta: {
|
|
1136
|
+
hit: parsed.data.length > 0,
|
|
1137
|
+
reason: parsed.data.length > 0 ? "hit" : "context-not-found",
|
|
1138
|
+
details: ["legacy cache format"]
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
const union = Object.values(parsed.data.contexts).flatMap((entry2) => entry2.values);
|
|
1143
|
+
return {
|
|
1144
|
+
data: new Set(union),
|
|
1145
|
+
meta: {
|
|
1146
|
+
hit: union.length > 0,
|
|
1147
|
+
reason: union.length > 0 ? "hit" : "context-not-found",
|
|
1148
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1149
|
+
details: ["context-less read merged all cache entries"]
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
if (parsed.kind === "legacy") {
|
|
1154
|
+
return {
|
|
1155
|
+
data: /* @__PURE__ */ new Set(),
|
|
1156
|
+
meta: {
|
|
1157
|
+
hit: false,
|
|
1158
|
+
reason: "legacy-schema",
|
|
1159
|
+
...this.context?.fingerprint === void 0 ? {} : { fingerprint: this.context.fingerprint },
|
|
1160
|
+
details: ["legacy cache schema detected; rebuilding cache with context fingerprint"]
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
if (!this.context) {
|
|
1165
|
+
return {
|
|
1166
|
+
data: /* @__PURE__ */ new Set(),
|
|
1167
|
+
meta: {
|
|
1168
|
+
hit: false,
|
|
1169
|
+
reason: "context-not-found",
|
|
1170
|
+
details: ["cache context missing"]
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
const entry = parsed.data.contexts[this.context.fingerprint];
|
|
1175
|
+
if (entry) {
|
|
1176
|
+
const mismatchReasons = explainContextMismatch(this.context.metadata, entry.context);
|
|
1177
|
+
if (mismatchReasons.length === 0) {
|
|
1178
|
+
return {
|
|
1179
|
+
data: new Set(entry.values),
|
|
1180
|
+
meta: {
|
|
1181
|
+
hit: true,
|
|
1182
|
+
reason: "hit",
|
|
1183
|
+
fingerprint: this.context.fingerprint,
|
|
1184
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1185
|
+
details: [`context fingerprint ${this.context.fingerprint.slice(0, 12)} matched`]
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
return {
|
|
1190
|
+
data: /* @__PURE__ */ new Set(),
|
|
1191
|
+
meta: {
|
|
1192
|
+
hit: false,
|
|
1193
|
+
reason: "context-mismatch",
|
|
1194
|
+
fingerprint: this.context.fingerprint,
|
|
1195
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1196
|
+
details: mismatchReasons
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
const projectMatch = this.findProjectMatch(parsed.data);
|
|
1201
|
+
if (projectMatch) {
|
|
1202
|
+
const [matchedFingerprint, matchedEntry] = projectMatch;
|
|
1203
|
+
return {
|
|
1204
|
+
data: /* @__PURE__ */ new Set(),
|
|
1205
|
+
meta: {
|
|
1206
|
+
hit: false,
|
|
1207
|
+
reason: "context-mismatch",
|
|
1208
|
+
fingerprint: this.context.fingerprint,
|
|
1209
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1210
|
+
details: [
|
|
1211
|
+
`nearest context fingerprint: ${matchedFingerprint.slice(0, 12)}`,
|
|
1212
|
+
...explainContextMismatch(this.context.metadata, matchedEntry.context)
|
|
1213
|
+
]
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
return {
|
|
1218
|
+
data: /* @__PURE__ */ new Set(),
|
|
1219
|
+
meta: {
|
|
1220
|
+
hit: false,
|
|
1221
|
+
reason: "context-not-found",
|
|
1222
|
+
fingerprint: this.context.fingerprint,
|
|
1223
|
+
schemaVersion: parsed.data.schemaVersion,
|
|
1224
|
+
details: ["context fingerprint not found in cache index"]
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
async read() {
|
|
1229
|
+
const result = await this.readWithMeta();
|
|
1230
|
+
this.lastReadMeta = toReadMeta(result.meta);
|
|
1231
|
+
return new Set(result.data);
|
|
1232
|
+
}
|
|
1233
|
+
readSync() {
|
|
1234
|
+
const result = this.readWithMetaSync();
|
|
1235
|
+
this.lastReadMeta = toReadMeta(result.meta);
|
|
1236
|
+
return new Set(result.data);
|
|
1237
|
+
}
|
|
1238
|
+
getLastReadMeta() {
|
|
1239
|
+
return toReadMeta(this.lastReadMeta);
|
|
1240
|
+
}
|
|
1241
|
+
countEntriesFromParsed(parsed) {
|
|
1242
|
+
if (parsed.kind === "legacy") {
|
|
1243
|
+
return {
|
|
1244
|
+
contexts: parsed.data.length ? 1 : 0,
|
|
1245
|
+
entries: parsed.data.length
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
if (parsed.kind === "v2") {
|
|
1249
|
+
const values = Object.values(parsed.data.contexts);
|
|
1250
|
+
return {
|
|
1251
|
+
contexts: values.length,
|
|
1252
|
+
entries: values.reduce((acc, item) => acc + item.values.length, 0)
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
return {
|
|
1256
|
+
contexts: 0,
|
|
1257
|
+
entries: 0
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
async clear(options) {
|
|
1261
|
+
const scope = options?.scope ?? "current";
|
|
1262
|
+
if (!this.options.enabled || this.driver === "noop") {
|
|
1263
|
+
return {
|
|
1264
|
+
scope,
|
|
1265
|
+
filesRemoved: 0,
|
|
1266
|
+
entriesRemoved: 0,
|
|
1267
|
+
contextsRemoved: 0
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
if (this.driver === "memory") {
|
|
1271
|
+
if (!this.isContextAware() || scope === "all") {
|
|
1272
|
+
const entriesRemoved2 = this.memoryCache?.size ?? (this.memoryIndex ? this.countEntriesFromParsed({ kind: "v2", data: this.memoryIndex }).entries : 0);
|
|
1273
|
+
const contextsRemoved = this.memoryIndex ? Object.keys(this.memoryIndex.contexts).length : this.memoryCache?.size ? 1 : 0;
|
|
1274
|
+
this.memoryCache = null;
|
|
1275
|
+
this.memoryIndex = null;
|
|
1276
|
+
return {
|
|
1277
|
+
scope,
|
|
1278
|
+
filesRemoved: 0,
|
|
1279
|
+
entriesRemoved: entriesRemoved2,
|
|
1280
|
+
contextsRemoved
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
if (!this.context || !this.memoryIndex) {
|
|
1284
|
+
return {
|
|
1285
|
+
scope,
|
|
1286
|
+
filesRemoved: 0,
|
|
1287
|
+
entriesRemoved: 0,
|
|
1288
|
+
contextsRemoved: 0
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
const entry = this.memoryIndex.contexts[this.context.fingerprint];
|
|
1292
|
+
if (!entry) {
|
|
1293
|
+
return {
|
|
1294
|
+
scope,
|
|
1295
|
+
filesRemoved: 0,
|
|
1296
|
+
entriesRemoved: 0,
|
|
1297
|
+
contextsRemoved: 0
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
const entriesRemoved = entry.values.length;
|
|
1301
|
+
delete this.memoryIndex.contexts[this.context.fingerprint];
|
|
1302
|
+
return {
|
|
1303
|
+
scope,
|
|
1304
|
+
filesRemoved: 0,
|
|
1305
|
+
entriesRemoved,
|
|
1306
|
+
contextsRemoved: 1
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
const result = await this.withFileLock(async () => {
|
|
1310
|
+
const parsed = await this.readParsedCacheFile(false);
|
|
1311
|
+
if (parsed.kind === "empty") {
|
|
1312
|
+
return {
|
|
1313
|
+
scope,
|
|
1314
|
+
filesRemoved: 0,
|
|
1315
|
+
entriesRemoved: 0,
|
|
1316
|
+
contextsRemoved: 0
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
if (!this.isContextAware() || scope === "all") {
|
|
1320
|
+
const counts = this.countEntriesFromParsed(parsed);
|
|
1321
|
+
await fs2.remove(this.options.path);
|
|
1322
|
+
return {
|
|
1323
|
+
scope,
|
|
1324
|
+
filesRemoved: 1,
|
|
1325
|
+
entriesRemoved: counts.entries,
|
|
1326
|
+
contextsRemoved: counts.contexts
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
if (parsed.kind !== "v2" || !this.context) {
|
|
1330
|
+
const counts = this.countEntriesFromParsed(parsed);
|
|
1331
|
+
await fs2.remove(this.options.path);
|
|
1332
|
+
return {
|
|
1333
|
+
scope,
|
|
1334
|
+
filesRemoved: 1,
|
|
1335
|
+
entriesRemoved: counts.entries,
|
|
1336
|
+
contextsRemoved: counts.contexts
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
const entry = parsed.data.contexts[this.context.fingerprint];
|
|
1340
|
+
if (!entry) {
|
|
1341
|
+
return {
|
|
1342
|
+
scope,
|
|
1343
|
+
filesRemoved: 0,
|
|
1344
|
+
entriesRemoved: 0,
|
|
1345
|
+
contextsRemoved: 0
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
const entriesRemoved = entry.values.length;
|
|
1349
|
+
delete parsed.data.contexts[this.context.fingerprint];
|
|
1350
|
+
const remain = Object.keys(parsed.data.contexts).length;
|
|
1351
|
+
if (remain === 0) {
|
|
1352
|
+
await fs2.remove(this.options.path);
|
|
1353
|
+
return {
|
|
1354
|
+
scope,
|
|
1355
|
+
filesRemoved: 1,
|
|
1356
|
+
entriesRemoved,
|
|
1357
|
+
contextsRemoved: 1
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
parsed.data.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1361
|
+
await this.writeIndexFile(parsed.data);
|
|
1362
|
+
return {
|
|
1363
|
+
scope,
|
|
1364
|
+
filesRemoved: 0,
|
|
1365
|
+
entriesRemoved,
|
|
1366
|
+
contextsRemoved: 1
|
|
1367
|
+
};
|
|
1368
|
+
});
|
|
1369
|
+
return result ?? {
|
|
1370
|
+
scope,
|
|
1371
|
+
filesRemoved: 0,
|
|
1372
|
+
entriesRemoved: 0,
|
|
1373
|
+
contextsRemoved: 0
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
clearSync(options) {
|
|
1377
|
+
const scope = options?.scope ?? "current";
|
|
1378
|
+
if (!this.options.enabled || this.driver === "noop") {
|
|
1379
|
+
return {
|
|
1380
|
+
scope,
|
|
1381
|
+
filesRemoved: 0,
|
|
1382
|
+
entriesRemoved: 0,
|
|
1383
|
+
contextsRemoved: 0
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
if (this.driver === "memory") {
|
|
1387
|
+
if (!this.isContextAware() || scope === "all") {
|
|
1388
|
+
const entriesRemoved2 = this.memoryCache?.size ?? (this.memoryIndex ? this.countEntriesFromParsed({ kind: "v2", data: this.memoryIndex }).entries : 0);
|
|
1389
|
+
const contextsRemoved = this.memoryIndex ? Object.keys(this.memoryIndex.contexts).length : this.memoryCache?.size ? 1 : 0;
|
|
1390
|
+
this.memoryCache = null;
|
|
1391
|
+
this.memoryIndex = null;
|
|
1392
|
+
return {
|
|
1393
|
+
scope,
|
|
1394
|
+
filesRemoved: 0,
|
|
1395
|
+
entriesRemoved: entriesRemoved2,
|
|
1396
|
+
contextsRemoved
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
if (!this.context || !this.memoryIndex) {
|
|
1400
|
+
return {
|
|
1401
|
+
scope,
|
|
1402
|
+
filesRemoved: 0,
|
|
1403
|
+
entriesRemoved: 0,
|
|
1404
|
+
contextsRemoved: 0
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
const entry = this.memoryIndex.contexts[this.context.fingerprint];
|
|
1408
|
+
if (!entry) {
|
|
1409
|
+
return {
|
|
1410
|
+
scope,
|
|
1411
|
+
filesRemoved: 0,
|
|
1412
|
+
entriesRemoved: 0,
|
|
1413
|
+
contextsRemoved: 0
|
|
1414
|
+
};
|
|
1415
|
+
}
|
|
1416
|
+
const entriesRemoved = entry.values.length;
|
|
1417
|
+
delete this.memoryIndex.contexts[this.context.fingerprint];
|
|
1418
|
+
return {
|
|
1419
|
+
scope,
|
|
1420
|
+
filesRemoved: 0,
|
|
1421
|
+
entriesRemoved,
|
|
1422
|
+
contextsRemoved: 1
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
const result = this.withFileLockSync(() => {
|
|
1426
|
+
const parsed = this.readParsedCacheFileSync(false);
|
|
1427
|
+
if (parsed.kind === "empty") {
|
|
1428
|
+
return {
|
|
1429
|
+
scope,
|
|
1430
|
+
filesRemoved: 0,
|
|
1431
|
+
entriesRemoved: 0,
|
|
1432
|
+
contextsRemoved: 0
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
if (!this.isContextAware() || scope === "all") {
|
|
1436
|
+
const counts = this.countEntriesFromParsed(parsed);
|
|
1437
|
+
fs2.removeSync(this.options.path);
|
|
1438
|
+
return {
|
|
1439
|
+
scope,
|
|
1440
|
+
filesRemoved: 1,
|
|
1441
|
+
entriesRemoved: counts.entries,
|
|
1442
|
+
contextsRemoved: counts.contexts
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
if (parsed.kind !== "v2" || !this.context) {
|
|
1446
|
+
const counts = this.countEntriesFromParsed(parsed);
|
|
1447
|
+
fs2.removeSync(this.options.path);
|
|
1448
|
+
return {
|
|
1449
|
+
scope,
|
|
1450
|
+
filesRemoved: 1,
|
|
1451
|
+
entriesRemoved: counts.entries,
|
|
1452
|
+
contextsRemoved: counts.contexts
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
const entry = parsed.data.contexts[this.context.fingerprint];
|
|
1456
|
+
if (!entry) {
|
|
1457
|
+
return {
|
|
1458
|
+
scope,
|
|
1459
|
+
filesRemoved: 0,
|
|
1460
|
+
entriesRemoved: 0,
|
|
1461
|
+
contextsRemoved: 0
|
|
1462
|
+
};
|
|
1463
|
+
}
|
|
1464
|
+
const entriesRemoved = entry.values.length;
|
|
1465
|
+
delete parsed.data.contexts[this.context.fingerprint];
|
|
1466
|
+
const remain = Object.keys(parsed.data.contexts).length;
|
|
1467
|
+
if (remain === 0) {
|
|
1468
|
+
fs2.removeSync(this.options.path);
|
|
1469
|
+
return {
|
|
1470
|
+
scope,
|
|
1471
|
+
filesRemoved: 1,
|
|
1472
|
+
entriesRemoved,
|
|
1473
|
+
contextsRemoved: 1
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
parsed.data.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1477
|
+
this.writeIndexFileSync(parsed.data);
|
|
1478
|
+
return {
|
|
1479
|
+
scope,
|
|
1480
|
+
filesRemoved: 0,
|
|
1481
|
+
entriesRemoved,
|
|
1482
|
+
contextsRemoved: 1
|
|
1483
|
+
};
|
|
1484
|
+
});
|
|
1485
|
+
return result ?? {
|
|
1486
|
+
scope,
|
|
1487
|
+
filesRemoved: 0,
|
|
1488
|
+
entriesRemoved: 0,
|
|
1489
|
+
contextsRemoved: 0
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1492
|
+
readIndexSnapshot() {
|
|
1493
|
+
if (this.driver === "memory") {
|
|
1494
|
+
return this.memoryIndex ? {
|
|
1495
|
+
...this.memoryIndex,
|
|
1496
|
+
contexts: Object.fromEntries(Object.entries(this.memoryIndex.contexts).map(([key, value]) => [key, cloneEntry(value)]))
|
|
1497
|
+
} : void 0;
|
|
1498
|
+
}
|
|
1499
|
+
const parsed = this.readParsedCacheFileSync(false);
|
|
1500
|
+
if (parsed.kind !== "v2") {
|
|
1501
|
+
return void 0;
|
|
1502
|
+
}
|
|
1503
|
+
return {
|
|
1504
|
+
...parsed.data,
|
|
1505
|
+
contexts: Object.fromEntries(Object.entries(parsed.data.contexts).map(([key, value]) => [key, cloneEntry(value)]))
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
};
|
|
1509
|
+
|
|
1510
|
+
// src/extraction/candidate-extractor.ts
|
|
1511
|
+
import { promises as fs3 } from "fs";
|
|
1512
|
+
import process3 from "process";
|
|
1513
|
+
import path2 from "pathe";
|
|
1514
|
+
async function importNode() {
|
|
1515
|
+
return import("@tailwindcss/node");
|
|
1516
|
+
}
|
|
1517
|
+
async function importOxide() {
|
|
1518
|
+
return import("@tailwindcss/oxide");
|
|
1519
|
+
}
|
|
1520
|
+
async function loadDesignSystem(css, bases) {
|
|
1521
|
+
const uniqueBases = Array.from(new Set(bases.filter(Boolean)));
|
|
1522
|
+
if (uniqueBases.length === 0) {
|
|
1523
|
+
throw new Error("No base directories provided for Tailwind CSS design system.");
|
|
1524
|
+
}
|
|
1525
|
+
const { __unstable__loadDesignSystem } = await importNode();
|
|
1526
|
+
let lastError;
|
|
1527
|
+
for (const base of uniqueBases) {
|
|
1528
|
+
try {
|
|
1529
|
+
return await __unstable__loadDesignSystem(css, { base });
|
|
1530
|
+
} catch (error) {
|
|
1531
|
+
lastError = error;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
if (lastError instanceof Error) {
|
|
1535
|
+
throw lastError;
|
|
1536
|
+
}
|
|
1537
|
+
throw new Error("Failed to load Tailwind CSS design system.");
|
|
1538
|
+
}
|
|
1539
|
+
async function extractRawCandidatesWithPositions(content, extension = "html") {
|
|
1540
|
+
const { Scanner } = await importOxide();
|
|
1541
|
+
const scanner = new Scanner({});
|
|
1542
|
+
const result = scanner.getCandidatesWithPositions({ content, extension });
|
|
1543
|
+
return result.map(({ candidate, position }) => ({
|
|
1544
|
+
rawCandidate: candidate,
|
|
1545
|
+
start: position,
|
|
1546
|
+
end: position + candidate.length
|
|
1547
|
+
}));
|
|
1548
|
+
}
|
|
1549
|
+
async function extractRawCandidates(sources) {
|
|
1550
|
+
const { Scanner } = await importOxide();
|
|
1551
|
+
const scanner = new Scanner(sources === void 0 ? {} : { sources });
|
|
1552
|
+
return scanner.scan();
|
|
1553
|
+
}
|
|
1554
|
+
async function extractValidCandidates(options) {
|
|
1555
|
+
const providedOptions = options ?? {};
|
|
1556
|
+
const defaultCwd = providedOptions.cwd ?? process3.cwd();
|
|
1557
|
+
const base = providedOptions.base ?? defaultCwd;
|
|
1558
|
+
const baseFallbacks = providedOptions.baseFallbacks ?? [];
|
|
1559
|
+
const css = providedOptions.css ?? '@import "tailwindcss";';
|
|
1560
|
+
const sources = (providedOptions.sources ?? [
|
|
1561
|
+
{
|
|
1562
|
+
base: defaultCwd,
|
|
1563
|
+
pattern: "**/*",
|
|
1564
|
+
negated: false
|
|
1565
|
+
}
|
|
1566
|
+
]).map((source) => ({
|
|
1567
|
+
base: source.base ?? defaultCwd,
|
|
1568
|
+
pattern: source.pattern,
|
|
1569
|
+
negated: source.negated
|
|
1570
|
+
}));
|
|
1571
|
+
const designSystem = await loadDesignSystem(css, [base, ...baseFallbacks]);
|
|
1572
|
+
const candidates = await extractRawCandidates(sources);
|
|
1573
|
+
const parsedCandidates = candidates.filter(
|
|
1574
|
+
(rawCandidate) => designSystem.parseCandidate(rawCandidate).length > 0
|
|
1575
|
+
);
|
|
1576
|
+
if (parsedCandidates.length === 0) {
|
|
1577
|
+
return parsedCandidates;
|
|
1578
|
+
}
|
|
1579
|
+
const cssByCandidate = designSystem.candidatesToCss(parsedCandidates);
|
|
1580
|
+
const validCandidates = [];
|
|
1581
|
+
for (let index = 0; index < parsedCandidates.length; index++) {
|
|
1582
|
+
const candidate = parsedCandidates[index];
|
|
1583
|
+
if (candidate === void 0) {
|
|
1584
|
+
continue;
|
|
1585
|
+
}
|
|
1586
|
+
const css2 = cssByCandidate[index];
|
|
1587
|
+
if (typeof css2 === "string" && css2.trim().length > 0) {
|
|
1588
|
+
validCandidates.push(candidate);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
return validCandidates;
|
|
1592
|
+
}
|
|
1593
|
+
function normalizeSources(sources, cwd) {
|
|
1594
|
+
const baseSources = sources?.length ? sources : [
|
|
1595
|
+
{
|
|
1596
|
+
base: cwd,
|
|
1597
|
+
pattern: "**/*",
|
|
1598
|
+
negated: false
|
|
1599
|
+
}
|
|
1600
|
+
];
|
|
1601
|
+
return baseSources.map((source) => ({
|
|
1602
|
+
base: source.base ?? cwd,
|
|
1603
|
+
pattern: source.pattern,
|
|
1604
|
+
negated: source.negated
|
|
1605
|
+
}));
|
|
1606
|
+
}
|
|
1607
|
+
function buildLineOffsets(content) {
|
|
1608
|
+
const offsets = [0];
|
|
1609
|
+
for (let i = 0; i < content.length; i++) {
|
|
1610
|
+
if (content[i] === "\n") {
|
|
1611
|
+
offsets.push(i + 1);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
if (offsets[offsets.length - 1] !== content.length) {
|
|
1615
|
+
offsets.push(content.length);
|
|
1616
|
+
}
|
|
1617
|
+
return offsets;
|
|
1618
|
+
}
|
|
1619
|
+
function resolveLineMeta(content, offsets, index) {
|
|
1620
|
+
let low = 0;
|
|
1621
|
+
let high = offsets.length - 1;
|
|
1622
|
+
while (low <= high) {
|
|
1623
|
+
const mid = Math.floor((low + high) / 2);
|
|
1624
|
+
const start = offsets[mid];
|
|
1625
|
+
if (start === void 0) {
|
|
1626
|
+
break;
|
|
1627
|
+
}
|
|
1628
|
+
const nextStart = offsets[mid + 1] ?? content.length;
|
|
1629
|
+
if (index < start) {
|
|
1630
|
+
high = mid - 1;
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
if (index >= nextStart) {
|
|
1634
|
+
low = mid + 1;
|
|
1635
|
+
continue;
|
|
1636
|
+
}
|
|
1637
|
+
const line = mid + 1;
|
|
1638
|
+
const column = index - start + 1;
|
|
1639
|
+
const lineEnd = content.indexOf("\n", start);
|
|
1640
|
+
const lineText = content.slice(start, lineEnd === -1 ? content.length : lineEnd);
|
|
1641
|
+
return { line, column, lineText };
|
|
1642
|
+
}
|
|
1643
|
+
const lastStart = offsets[offsets.length - 2] ?? 0;
|
|
1644
|
+
return {
|
|
1645
|
+
line: offsets.length - 1,
|
|
1646
|
+
column: index - lastStart + 1,
|
|
1647
|
+
lineText: content.slice(lastStart)
|
|
1648
|
+
};
|
|
1649
|
+
}
|
|
1650
|
+
function toExtension(filename) {
|
|
1651
|
+
const ext = path2.extname(filename).replace(/^\./, "");
|
|
1652
|
+
return ext || "txt";
|
|
1653
|
+
}
|
|
1654
|
+
function toRelativeFile(cwd, filename) {
|
|
1655
|
+
const relative = path2.relative(cwd, filename);
|
|
1656
|
+
return relative === "" ? path2.basename(filename) : relative;
|
|
1657
|
+
}
|
|
1658
|
+
async function extractProjectCandidatesWithPositions(options) {
|
|
1659
|
+
const cwd = options?.cwd ? path2.resolve(options.cwd) : process3.cwd();
|
|
1660
|
+
const normalizedSources = normalizeSources(options?.sources, cwd);
|
|
1661
|
+
const { Scanner } = await importOxide();
|
|
1662
|
+
const scanner = new Scanner({
|
|
1663
|
+
sources: normalizedSources
|
|
1664
|
+
});
|
|
1665
|
+
const files = scanner.files ?? [];
|
|
1666
|
+
const entries = [];
|
|
1667
|
+
const skipped = [];
|
|
1668
|
+
for (const file of files) {
|
|
1669
|
+
let content;
|
|
1670
|
+
try {
|
|
1671
|
+
content = await fs3.readFile(file, "utf8");
|
|
1672
|
+
} catch (error) {
|
|
1673
|
+
skipped.push({
|
|
1674
|
+
file,
|
|
1675
|
+
reason: error instanceof Error ? error.message : "Unknown error"
|
|
1676
|
+
});
|
|
1677
|
+
continue;
|
|
1678
|
+
}
|
|
1679
|
+
const extension = toExtension(file);
|
|
1680
|
+
const matches = scanner.getCandidatesWithPositions({
|
|
1681
|
+
file,
|
|
1682
|
+
content,
|
|
1683
|
+
extension
|
|
1684
|
+
});
|
|
1685
|
+
if (!matches.length) {
|
|
1686
|
+
continue;
|
|
1687
|
+
}
|
|
1688
|
+
const offsets = buildLineOffsets(content);
|
|
1689
|
+
const relativeFile = toRelativeFile(cwd, file);
|
|
1690
|
+
for (const match of matches) {
|
|
1691
|
+
const info = resolveLineMeta(content, offsets, match.position);
|
|
1692
|
+
entries.push({
|
|
1693
|
+
rawCandidate: match.candidate,
|
|
1694
|
+
file,
|
|
1695
|
+
relativeFile,
|
|
1696
|
+
extension,
|
|
1697
|
+
start: match.position,
|
|
1698
|
+
end: match.position + match.candidate.length,
|
|
1699
|
+
length: match.candidate.length,
|
|
1700
|
+
line: info.line,
|
|
1701
|
+
column: info.column,
|
|
1702
|
+
lineText: info.lineText
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
return {
|
|
1707
|
+
entries,
|
|
1708
|
+
filesScanned: files.length,
|
|
1709
|
+
skippedFiles: skipped,
|
|
1710
|
+
sources: normalizedSources
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
function groupTokensByFile(report, options) {
|
|
1714
|
+
const key = options?.key ?? "relative";
|
|
1715
|
+
const stripAbsolute = options?.stripAbsolutePaths ?? key !== "absolute";
|
|
1716
|
+
return report.entries.reduce((acc, entry) => {
|
|
1717
|
+
const bucketKey = key === "absolute" ? entry.file : entry.relativeFile;
|
|
1718
|
+
if (!acc[bucketKey]) {
|
|
1719
|
+
acc[bucketKey] = [];
|
|
1720
|
+
}
|
|
1721
|
+
const value = stripAbsolute ? {
|
|
1722
|
+
...entry,
|
|
1723
|
+
file: entry.relativeFile
|
|
1724
|
+
} : entry;
|
|
1725
|
+
acc[bucketKey].push(value);
|
|
1726
|
+
return acc;
|
|
1727
|
+
}, {});
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
// src/options/normalize.ts
|
|
1731
|
+
import process4 from "process";
|
|
1732
|
+
import fs4 from "fs-extra";
|
|
1733
|
+
import path3 from "pathe";
|
|
1734
|
+
var hasWarnedDeprecatedOptions = false;
|
|
1735
|
+
var deprecatedOptionMapping = {
|
|
1736
|
+
cwd: "projectRoot",
|
|
1737
|
+
overwrite: "apply.overwrite",
|
|
1738
|
+
tailwind: "tailwindcss",
|
|
1739
|
+
features: "apply",
|
|
1740
|
+
output: "extract"
|
|
1741
|
+
};
|
|
1742
|
+
function resolveRealpathSafe(value) {
|
|
1743
|
+
const resolved = path3.resolve(value);
|
|
1744
|
+
try {
|
|
1745
|
+
return path3.normalize(fs4.realpathSync(resolved));
|
|
1746
|
+
} catch {
|
|
1747
|
+
return path3.normalize(resolved);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
function toPrettyValue(value) {
|
|
1751
|
+
if (typeof value === "number") {
|
|
1752
|
+
return value > 0 ? value : false;
|
|
1753
|
+
}
|
|
1754
|
+
if (value === true) {
|
|
1755
|
+
return 2;
|
|
1756
|
+
}
|
|
1757
|
+
return false;
|
|
1758
|
+
}
|
|
1759
|
+
function normalizeCacheDriver(driver) {
|
|
1760
|
+
if (driver === "memory" || driver === "noop") {
|
|
1761
|
+
return driver;
|
|
1762
|
+
}
|
|
1763
|
+
return "file";
|
|
1764
|
+
}
|
|
1765
|
+
function normalizeCacheOptions(cache, projectRoot) {
|
|
1766
|
+
let enabled = false;
|
|
1767
|
+
let cwd = resolveRealpathSafe(projectRoot);
|
|
1768
|
+
let dir = path3.resolve(cwd, "node_modules/.cache", pkgName);
|
|
1769
|
+
let file = "class-cache.json";
|
|
1770
|
+
let strategy = "merge";
|
|
1771
|
+
let driver = "file";
|
|
1772
|
+
if (typeof cache === "boolean") {
|
|
1773
|
+
enabled = cache;
|
|
1774
|
+
} else if (typeof cache === "object" && cache) {
|
|
1775
|
+
enabled = cache.enabled ?? true;
|
|
1776
|
+
cwd = cache.cwd ? resolveRealpathSafe(cache.cwd) : cwd;
|
|
1777
|
+
dir = cache.dir ? path3.resolve(cache.dir) : path3.resolve(cwd, "node_modules/.cache", pkgName);
|
|
1778
|
+
file = cache.file ?? file;
|
|
1779
|
+
strategy = cache.strategy ?? strategy;
|
|
1780
|
+
driver = normalizeCacheDriver(cache.driver);
|
|
1781
|
+
}
|
|
1782
|
+
const filename = path3.resolve(dir, file);
|
|
1783
|
+
return {
|
|
1784
|
+
enabled,
|
|
1785
|
+
cwd,
|
|
1786
|
+
dir,
|
|
1787
|
+
file,
|
|
1788
|
+
path: filename,
|
|
1789
|
+
strategy,
|
|
1790
|
+
driver
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
function normalizeOutputOptions(output) {
|
|
1794
|
+
const enabled = output?.write ?? true;
|
|
1795
|
+
const file = output?.file ?? ".tw-patch/tw-class-list.json";
|
|
1796
|
+
const format = output?.format ?? "json";
|
|
1797
|
+
const pretty = toPrettyValue(output?.pretty ?? true);
|
|
1798
|
+
const removeUniversalSelector = output?.removeUniversalSelector ?? true;
|
|
1799
|
+
return {
|
|
1800
|
+
enabled,
|
|
1801
|
+
file,
|
|
1802
|
+
format,
|
|
1803
|
+
pretty,
|
|
1804
|
+
removeUniversalSelector
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
function normalizeExposeContextOptions(exposeContext) {
|
|
1808
|
+
if (exposeContext === false) {
|
|
1809
|
+
return {
|
|
1810
|
+
enabled: false,
|
|
1811
|
+
refProperty: "contextRef"
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
if (typeof exposeContext === "object" && exposeContext) {
|
|
1815
|
+
return {
|
|
1816
|
+
enabled: true,
|
|
1817
|
+
refProperty: exposeContext.refProperty ?? "contextRef"
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
return {
|
|
1821
|
+
enabled: true,
|
|
1822
|
+
refProperty: "contextRef"
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
function normalizeExtendLengthUnitsOptions(extend) {
|
|
1826
|
+
if (extend === false || extend === void 0) {
|
|
1827
|
+
return null;
|
|
1828
|
+
}
|
|
1829
|
+
if (extend.enabled === false) {
|
|
1830
|
+
return null;
|
|
1831
|
+
}
|
|
1832
|
+
const base = {
|
|
1833
|
+
units: ["rpx"],
|
|
1834
|
+
overwrite: true
|
|
1835
|
+
};
|
|
1836
|
+
return {
|
|
1837
|
+
...base,
|
|
1838
|
+
...extend,
|
|
1839
|
+
enabled: extend.enabled ?? true,
|
|
1840
|
+
units: extend.units ?? base.units,
|
|
1841
|
+
overwrite: extend.overwrite ?? base.overwrite
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1844
|
+
function normalizeTailwindV4Options(v4, fallbackBase) {
|
|
1845
|
+
const configuredBase = v4?.base ? path3.resolve(v4.base) : void 0;
|
|
1846
|
+
const base = configuredBase ?? fallbackBase;
|
|
1847
|
+
const cssEntries = Array.isArray(v4?.cssEntries) ? v4.cssEntries.filter((entry) => Boolean(entry)).map((entry) => path3.resolve(entry)) : [];
|
|
1848
|
+
const userSources = v4?.sources;
|
|
1849
|
+
const hasUserDefinedSources = Boolean(userSources?.length);
|
|
1850
|
+
const sources = hasUserDefinedSources ? userSources : [
|
|
1851
|
+
{
|
|
1852
|
+
base: fallbackBase,
|
|
1853
|
+
pattern: "**/*",
|
|
1854
|
+
negated: false
|
|
1855
|
+
}
|
|
1856
|
+
];
|
|
1857
|
+
return {
|
|
1858
|
+
base,
|
|
1859
|
+
...configuredBase === void 0 ? {} : { configuredBase },
|
|
1860
|
+
...v4?.css === void 0 ? {} : { css: v4.css },
|
|
1861
|
+
cssEntries,
|
|
1862
|
+
sources,
|
|
1863
|
+
hasUserDefinedSources
|
|
1864
|
+
};
|
|
1865
|
+
}
|
|
1866
|
+
function normalizeTailwindOptions(tailwind, projectRoot) {
|
|
1867
|
+
const packageName = tailwind?.packageName ?? "tailwindcss";
|
|
1868
|
+
const versionHint = tailwind?.version;
|
|
1869
|
+
const resolve = tailwind?.resolve;
|
|
1870
|
+
const cwd = tailwind?.cwd ?? projectRoot;
|
|
1871
|
+
const config = tailwind?.config;
|
|
1872
|
+
const postcssPlugin = tailwind?.postcssPlugin;
|
|
1873
|
+
const v4 = normalizeTailwindV4Options(tailwind?.v4, cwd);
|
|
1874
|
+
return {
|
|
1875
|
+
packageName,
|
|
1876
|
+
cwd,
|
|
1877
|
+
...versionHint === void 0 ? {} : { versionHint },
|
|
1878
|
+
...resolve === void 0 ? {} : { resolve },
|
|
1879
|
+
...config === void 0 ? {} : { config },
|
|
1880
|
+
...postcssPlugin === void 0 ? {} : { postcssPlugin },
|
|
1881
|
+
...tailwind?.v2 === void 0 ? {} : { v2: tailwind.v2 },
|
|
1882
|
+
...tailwind?.v3 === void 0 ? {} : { v3: tailwind.v3 },
|
|
1883
|
+
v4
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
function resolveOptionSlices(options) {
|
|
1887
|
+
const projectRoot = options.projectRoot ?? options.cwd;
|
|
1888
|
+
const overwrite = options.apply?.overwrite ?? options.overwrite;
|
|
1889
|
+
const tailwind = options.tailwindcss ?? options.tailwind;
|
|
1890
|
+
const exposeContext = options.apply?.exposeContext !== void 0 ? options.apply.exposeContext : options.features?.exposeContext;
|
|
1891
|
+
const extendLengthUnits = options.apply?.extendLengthUnits !== void 0 ? options.apply.extendLengthUnits : options.features?.extendLengthUnits;
|
|
1892
|
+
const write = options.extract?.write ?? options.output?.enabled;
|
|
1893
|
+
const file = options.extract?.file ?? options.output?.file;
|
|
1894
|
+
const format = options.extract?.format ?? options.output?.format;
|
|
1895
|
+
const pretty = options.extract?.pretty ?? options.output?.pretty;
|
|
1896
|
+
const removeUniversalSelector = options.extract?.removeUniversalSelector ?? options.output?.removeUniversalSelector;
|
|
1897
|
+
const extract = {
|
|
1898
|
+
...write === void 0 ? {} : { write },
|
|
1899
|
+
...file === void 0 ? {} : { file },
|
|
1900
|
+
...format === void 0 ? {} : { format },
|
|
1901
|
+
...pretty === void 0 ? {} : { pretty },
|
|
1902
|
+
...removeUniversalSelector === void 0 ? {} : { removeUniversalSelector }
|
|
1903
|
+
};
|
|
1904
|
+
return {
|
|
1905
|
+
...projectRoot === void 0 ? {} : { projectRoot },
|
|
1906
|
+
...overwrite === void 0 ? {} : { overwrite },
|
|
1907
|
+
...tailwind === void 0 ? {} : { tailwind },
|
|
1908
|
+
...Object.keys(extract).length === 0 ? {} : { extract },
|
|
1909
|
+
...exposeContext === void 0 ? {} : { exposeContext },
|
|
1910
|
+
...extendLengthUnits === void 0 ? {} : { extendLengthUnits }
|
|
1911
|
+
};
|
|
1912
|
+
}
|
|
1913
|
+
function findUsedDeprecatedOptions(options) {
|
|
1914
|
+
const result = [];
|
|
1915
|
+
for (const key of Object.keys(deprecatedOptionMapping)) {
|
|
1916
|
+
if (options[key] !== void 0) {
|
|
1917
|
+
result.push(key);
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
return result;
|
|
1921
|
+
}
|
|
1922
|
+
function warnDeprecatedOptionsIfNeeded(options) {
|
|
1923
|
+
if (hasWarnedDeprecatedOptions) {
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
const used = findUsedDeprecatedOptions(options);
|
|
1927
|
+
if (used.length === 0) {
|
|
1928
|
+
return;
|
|
1929
|
+
}
|
|
1930
|
+
hasWarnedDeprecatedOptions = true;
|
|
1931
|
+
const mapping = used.map((key) => `${key} -> ${deprecatedOptionMapping[key]}`).join(", ");
|
|
1932
|
+
logger_default.warn(
|
|
1933
|
+
`[deprecated] TailwindcssPatcher options (${used.join(", ")}) are deprecated and will be removed in the next major version. Please migrate to: ${mapping}.`
|
|
1934
|
+
);
|
|
1935
|
+
}
|
|
1936
|
+
function normalizeOptions(options = {}) {
|
|
1937
|
+
warnDeprecatedOptionsIfNeeded(options);
|
|
1938
|
+
const resolved = resolveOptionSlices(options);
|
|
1939
|
+
const projectRoot = resolveRealpathSafe(resolved.projectRoot ? path3.resolve(resolved.projectRoot) : process4.cwd());
|
|
1940
|
+
const overwrite = resolved.overwrite ?? true;
|
|
1941
|
+
const output = normalizeOutputOptions(resolved.extract);
|
|
1942
|
+
const cache = normalizeCacheOptions(options.cache, projectRoot);
|
|
1943
|
+
const tailwind = normalizeTailwindOptions(resolved.tailwind, projectRoot);
|
|
1944
|
+
const exposeContext = normalizeExposeContextOptions(resolved.exposeContext);
|
|
1945
|
+
const extendLengthUnits = normalizeExtendLengthUnitsOptions(resolved.extendLengthUnits);
|
|
1946
|
+
const filter = (className) => {
|
|
1947
|
+
if (output.removeUniversalSelector && className === "*") {
|
|
1948
|
+
return false;
|
|
1949
|
+
}
|
|
1950
|
+
if (typeof options.filter === "function") {
|
|
1951
|
+
return options.filter(className) !== false;
|
|
1952
|
+
}
|
|
1953
|
+
return true;
|
|
1954
|
+
};
|
|
1955
|
+
return {
|
|
1956
|
+
projectRoot,
|
|
1957
|
+
overwrite,
|
|
1958
|
+
tailwind,
|
|
1959
|
+
features: {
|
|
1960
|
+
exposeContext,
|
|
1961
|
+
extendLengthUnits
|
|
1962
|
+
},
|
|
1963
|
+
output,
|
|
1964
|
+
cache,
|
|
1965
|
+
filter
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
// src/patching/status.ts
|
|
1970
|
+
import * as t4 from "@babel/types";
|
|
1971
|
+
import fs6 from "fs-extra";
|
|
1972
|
+
import path5 from "pathe";
|
|
1973
|
+
|
|
1974
|
+
// src/babel/index.ts
|
|
1975
|
+
import _babelGenerate from "@babel/generator";
|
|
1976
|
+
import _babelTraverse from "@babel/traverse";
|
|
1977
|
+
import { parse, parseExpression } from "@babel/parser";
|
|
1978
|
+
function _interopDefaultCompat(e) {
|
|
1979
|
+
return e && typeof e === "object" && "default" in e ? e.default : e;
|
|
1980
|
+
}
|
|
1981
|
+
var generate = _interopDefaultCompat(_babelGenerate);
|
|
1982
|
+
var traverse = _interopDefaultCompat(_babelTraverse);
|
|
1983
|
+
|
|
1984
|
+
// src/patching/operations/export-context/postcss-v2.ts
|
|
1985
|
+
import * as t from "@babel/types";
|
|
1986
|
+
var IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
|
|
1987
|
+
function toIdentifierName(property) {
|
|
1988
|
+
if (!property) {
|
|
1989
|
+
return "contextRef";
|
|
1990
|
+
}
|
|
1991
|
+
const sanitized = property.replace(/[^\w$]/gu, "_");
|
|
1992
|
+
if (/^\d/.test(sanitized)) {
|
|
1993
|
+
return `_${sanitized}`;
|
|
1994
|
+
}
|
|
1995
|
+
return sanitized || "contextRef";
|
|
1996
|
+
}
|
|
1997
|
+
function createExportsMember(property) {
|
|
1998
|
+
if (IDENTIFIER_RE.test(property)) {
|
|
1999
|
+
return t.memberExpression(t.identifier("exports"), t.identifier(property));
|
|
2000
|
+
}
|
|
2001
|
+
return t.memberExpression(t.identifier("exports"), t.stringLiteral(property), true);
|
|
2002
|
+
}
|
|
2003
|
+
function transformProcessTailwindFeaturesReturnContextV2(content) {
|
|
2004
|
+
const ast = parse(content, {
|
|
2005
|
+
sourceType: "unambiguous"
|
|
2006
|
+
});
|
|
2007
|
+
let hasPatched = false;
|
|
2008
|
+
traverse(ast, {
|
|
2009
|
+
FunctionDeclaration(path13) {
|
|
2010
|
+
const node = path13.node;
|
|
2011
|
+
if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1 || !t.isReturnStatement(node.body.body[0])) {
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
const returnStatement3 = node.body.body[0];
|
|
2015
|
+
if (!t.isFunctionExpression(returnStatement3.argument)) {
|
|
2016
|
+
return;
|
|
2017
|
+
}
|
|
2018
|
+
const body = returnStatement3.argument.body.body;
|
|
2019
|
+
const lastStatement = body[body.length - 1];
|
|
2020
|
+
const alreadyReturnsContext = Boolean(
|
|
2021
|
+
t.isReturnStatement(lastStatement) && t.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context"
|
|
2022
|
+
);
|
|
2023
|
+
hasPatched = alreadyReturnsContext;
|
|
2024
|
+
if (!alreadyReturnsContext) {
|
|
2025
|
+
body.push(t.returnStatement(t.identifier("context")));
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
});
|
|
2029
|
+
return {
|
|
2030
|
+
code: hasPatched ? content : generate(ast).code,
|
|
2031
|
+
hasPatched
|
|
2032
|
+
};
|
|
2033
|
+
}
|
|
2034
|
+
function transformPostcssPluginV2(content, options) {
|
|
2035
|
+
const refIdentifier = t.identifier(toIdentifierName(options.refProperty));
|
|
2036
|
+
const exportMember = createExportsMember(options.refProperty);
|
|
2037
|
+
const valueMember = t.memberExpression(refIdentifier, t.identifier("value"));
|
|
2038
|
+
const ast = parse(content);
|
|
2039
|
+
let hasPatched = false;
|
|
2040
|
+
traverse(ast, {
|
|
2041
|
+
Program(path13) {
|
|
2042
|
+
const program = path13.node;
|
|
2043
|
+
const index = program.body.findIndex((statement) => {
|
|
2044
|
+
return t.isFunctionDeclaration(statement) && statement.id?.name === "_default";
|
|
2045
|
+
});
|
|
2046
|
+
if (index === -1) {
|
|
2047
|
+
return;
|
|
2048
|
+
}
|
|
2049
|
+
const previous = program.body[index - 1];
|
|
2050
|
+
const beforePrevious = program.body[index - 2];
|
|
2051
|
+
const alreadyHasVariable = Boolean(
|
|
2052
|
+
previous && t.isVariableDeclaration(previous) && previous.declarations.length === 1 && t.isIdentifier(previous.declarations[0].id) && previous.declarations[0].id.name === refIdentifier.name
|
|
2053
|
+
);
|
|
2054
|
+
const alreadyAssignsExports = Boolean(
|
|
2055
|
+
beforePrevious && t.isExpressionStatement(beforePrevious) && t.isAssignmentExpression(beforePrevious.expression) && t.isMemberExpression(beforePrevious.expression.left) && t.isIdentifier(beforePrevious.expression.right) && beforePrevious.expression.right.name === refIdentifier.name && generate(beforePrevious.expression.left).code === generate(exportMember).code
|
|
2056
|
+
);
|
|
2057
|
+
hasPatched = alreadyHasVariable && alreadyAssignsExports;
|
|
2058
|
+
if (!alreadyHasVariable) {
|
|
2059
|
+
program.body.splice(
|
|
2060
|
+
index,
|
|
2061
|
+
0,
|
|
2062
|
+
t.variableDeclaration("var", [
|
|
2063
|
+
t.variableDeclarator(
|
|
2064
|
+
refIdentifier,
|
|
2065
|
+
t.objectExpression([
|
|
2066
|
+
t.objectProperty(t.identifier("value"), t.arrayExpression())
|
|
2067
|
+
])
|
|
2068
|
+
)
|
|
2069
|
+
]),
|
|
2070
|
+
t.expressionStatement(
|
|
2071
|
+
t.assignmentExpression("=", exportMember, refIdentifier)
|
|
2072
|
+
)
|
|
2073
|
+
);
|
|
2074
|
+
}
|
|
2075
|
+
},
|
|
2076
|
+
FunctionDeclaration(path13) {
|
|
2077
|
+
if (hasPatched) {
|
|
2078
|
+
return;
|
|
2079
|
+
}
|
|
2080
|
+
const fn = path13.node;
|
|
2081
|
+
if (fn.id?.name !== "_default") {
|
|
2082
|
+
return;
|
|
2083
|
+
}
|
|
2084
|
+
if (fn.body.body.length !== 1 || !t.isReturnStatement(fn.body.body[0])) {
|
|
2085
|
+
return;
|
|
2086
|
+
}
|
|
2087
|
+
const returnStatement3 = fn.body.body[0];
|
|
2088
|
+
if (!t.isCallExpression(returnStatement3.argument) || !t.isMemberExpression(returnStatement3.argument.callee) || !t.isArrayExpression(returnStatement3.argument.callee.object)) {
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
const fnExpression = returnStatement3.argument.callee.object.elements[1];
|
|
2092
|
+
if (!fnExpression || !t.isFunctionExpression(fnExpression)) {
|
|
2093
|
+
return;
|
|
2094
|
+
}
|
|
2095
|
+
const block = fnExpression.body;
|
|
2096
|
+
const statements = block.body;
|
|
2097
|
+
if (t.isExpressionStatement(statements[0]) && t.isAssignmentExpression(statements[0].expression) && t.isNumericLiteral(statements[0].expression.right)) {
|
|
2098
|
+
hasPatched = true;
|
|
2099
|
+
return;
|
|
2100
|
+
}
|
|
2101
|
+
const lastStatement = statements[statements.length - 1];
|
|
2102
|
+
if (lastStatement && t.isExpressionStatement(lastStatement)) {
|
|
2103
|
+
statements[statements.length - 1] = t.expressionStatement(
|
|
2104
|
+
t.callExpression(
|
|
2105
|
+
t.memberExpression(valueMember, t.identifier("push")),
|
|
2106
|
+
[lastStatement.expression]
|
|
2107
|
+
)
|
|
2108
|
+
);
|
|
2109
|
+
}
|
|
2110
|
+
const index = statements.findIndex((statement) => t.isIfStatement(statement));
|
|
2111
|
+
if (index > -1) {
|
|
2112
|
+
const ifStatement = statements[index];
|
|
2113
|
+
if (t.isBlockStatement(ifStatement.consequent) && ifStatement.consequent.body[1] && t.isForOfStatement(ifStatement.consequent.body[1])) {
|
|
2114
|
+
const forOf = ifStatement.consequent.body[1];
|
|
2115
|
+
if (t.isBlockStatement(forOf.body) && forOf.body.body.length === 1) {
|
|
2116
|
+
const nestedIf = forOf.body.body[0];
|
|
2117
|
+
if (nestedIf && t.isIfStatement(nestedIf) && t.isBlockStatement(nestedIf.consequent) && nestedIf.consequent.body.length === 1 && t.isExpressionStatement(nestedIf.consequent.body[0])) {
|
|
2118
|
+
nestedIf.consequent.body[0] = t.expressionStatement(
|
|
2119
|
+
t.callExpression(
|
|
2120
|
+
t.memberExpression(valueMember, t.identifier("push")),
|
|
2121
|
+
[nestedIf.consequent.body[0].expression]
|
|
2122
|
+
)
|
|
2123
|
+
);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
statements.unshift(
|
|
2129
|
+
t.expressionStatement(
|
|
2130
|
+
t.assignmentExpression(
|
|
2131
|
+
"=",
|
|
2132
|
+
t.memberExpression(valueMember, t.identifier("length")),
|
|
2133
|
+
t.numericLiteral(0)
|
|
2134
|
+
)
|
|
2135
|
+
)
|
|
2136
|
+
);
|
|
2137
|
+
}
|
|
2138
|
+
});
|
|
2139
|
+
return {
|
|
2140
|
+
code: hasPatched ? content : generate(ast).code,
|
|
2141
|
+
hasPatched
|
|
2142
|
+
};
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
// src/patching/operations/export-context/postcss-v3.ts
|
|
2146
|
+
import * as t2 from "@babel/types";
|
|
2147
|
+
var IDENTIFIER_RE2 = /^[A-Z_$][\w$]*$/i;
|
|
2148
|
+
function toIdentifierName2(property) {
|
|
2149
|
+
if (!property) {
|
|
2150
|
+
return "contextRef";
|
|
2151
|
+
}
|
|
2152
|
+
const sanitized = property.replace(/[^\w$]/gu, "_");
|
|
2153
|
+
if (/^\d/.test(sanitized)) {
|
|
2154
|
+
return `_${sanitized}`;
|
|
2155
|
+
}
|
|
2156
|
+
return sanitized || "contextRef";
|
|
2157
|
+
}
|
|
2158
|
+
function createModuleExportsMember(property) {
|
|
2159
|
+
const object = t2.memberExpression(t2.identifier("module"), t2.identifier("exports"));
|
|
2160
|
+
if (IDENTIFIER_RE2.test(property)) {
|
|
2161
|
+
return t2.memberExpression(object, t2.identifier(property));
|
|
2162
|
+
}
|
|
2163
|
+
return t2.memberExpression(object, t2.stringLiteral(property), true);
|
|
2164
|
+
}
|
|
2165
|
+
function transformProcessTailwindFeaturesReturnContext(content) {
|
|
2166
|
+
const ast = parse(content);
|
|
2167
|
+
let hasPatched = false;
|
|
2168
|
+
traverse(ast, {
|
|
2169
|
+
FunctionDeclaration(path13) {
|
|
2170
|
+
const node = path13.node;
|
|
2171
|
+
if (node.id?.name !== "processTailwindFeatures" || node.body.body.length !== 1) {
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
const [returnStatement3] = node.body.body;
|
|
2175
|
+
if (!t2.isReturnStatement(returnStatement3) || !t2.isFunctionExpression(returnStatement3.argument)) {
|
|
2176
|
+
return;
|
|
2177
|
+
}
|
|
2178
|
+
const expression = returnStatement3.argument;
|
|
2179
|
+
const body = expression.body.body;
|
|
2180
|
+
const lastStatement = body[body.length - 1];
|
|
2181
|
+
const alreadyReturnsContext = Boolean(
|
|
2182
|
+
t2.isReturnStatement(lastStatement) && t2.isIdentifier(lastStatement.argument) && lastStatement.argument.name === "context"
|
|
2183
|
+
);
|
|
2184
|
+
hasPatched = alreadyReturnsContext;
|
|
2185
|
+
if (!alreadyReturnsContext) {
|
|
2186
|
+
body.push(t2.returnStatement(t2.identifier("context")));
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
});
|
|
2190
|
+
return {
|
|
2191
|
+
code: hasPatched ? content : generate(ast).code,
|
|
2192
|
+
hasPatched
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
function transformPostcssPlugin(content, { refProperty }) {
|
|
2196
|
+
const ast = parse(content);
|
|
2197
|
+
const refIdentifier = t2.identifier(toIdentifierName2(refProperty));
|
|
2198
|
+
const moduleExportsMember = createModuleExportsMember(refProperty);
|
|
2199
|
+
const valueMember = t2.memberExpression(refIdentifier, t2.identifier("value"));
|
|
2200
|
+
let hasPatched = false;
|
|
2201
|
+
traverse(ast, {
|
|
2202
|
+
Program(path13) {
|
|
2203
|
+
const program = path13.node;
|
|
2204
|
+
const index = program.body.findIndex((statement) => {
|
|
2205
|
+
return t2.isExpressionStatement(statement) && t2.isAssignmentExpression(statement.expression) && t2.isMemberExpression(statement.expression.left) && t2.isFunctionExpression(statement.expression.right) && statement.expression.right.id?.name === "tailwindcss";
|
|
2206
|
+
});
|
|
2207
|
+
if (index === -1) {
|
|
2208
|
+
return;
|
|
2209
|
+
}
|
|
2210
|
+
const previousStatement = program.body[index - 1];
|
|
2211
|
+
const lastStatement = program.body[program.body.length - 1];
|
|
2212
|
+
const alreadyHasVariable = Boolean(
|
|
2213
|
+
previousStatement && t2.isVariableDeclaration(previousStatement) && previousStatement.declarations.length === 1 && t2.isIdentifier(previousStatement.declarations[0].id) && previousStatement.declarations[0].id.name === refIdentifier.name
|
|
2214
|
+
);
|
|
2215
|
+
const alreadyAssignsModuleExports = Boolean(
|
|
2216
|
+
t2.isExpressionStatement(lastStatement) && t2.isAssignmentExpression(lastStatement.expression) && t2.isMemberExpression(lastStatement.expression.left) && t2.isIdentifier(lastStatement.expression.right) && lastStatement.expression.right.name === refIdentifier.name && generate(lastStatement.expression.left).code === generate(moduleExportsMember).code
|
|
2217
|
+
);
|
|
2218
|
+
hasPatched = alreadyHasVariable && alreadyAssignsModuleExports;
|
|
2219
|
+
if (!alreadyHasVariable) {
|
|
2220
|
+
program.body.splice(
|
|
2221
|
+
index,
|
|
2222
|
+
0,
|
|
2223
|
+
t2.variableDeclaration("const", [
|
|
2224
|
+
t2.variableDeclarator(
|
|
2225
|
+
refIdentifier,
|
|
2226
|
+
t2.objectExpression([
|
|
2227
|
+
t2.objectProperty(t2.identifier("value"), t2.arrayExpression())
|
|
2228
|
+
])
|
|
2229
|
+
)
|
|
2230
|
+
])
|
|
2231
|
+
);
|
|
2232
|
+
}
|
|
2233
|
+
if (!alreadyAssignsModuleExports) {
|
|
2234
|
+
program.body.push(
|
|
2235
|
+
t2.expressionStatement(
|
|
2236
|
+
t2.assignmentExpression("=", moduleExportsMember, refIdentifier)
|
|
2237
|
+
)
|
|
2238
|
+
);
|
|
2239
|
+
}
|
|
2240
|
+
},
|
|
2241
|
+
FunctionExpression(path13) {
|
|
2242
|
+
if (hasPatched) {
|
|
2243
|
+
return;
|
|
2244
|
+
}
|
|
2245
|
+
const fn = path13.node;
|
|
2246
|
+
if (fn.id?.name !== "tailwindcss" || fn.body.body.length !== 1) {
|
|
2247
|
+
return;
|
|
2248
|
+
}
|
|
2249
|
+
const [returnStatement3] = fn.body.body;
|
|
2250
|
+
if (!returnStatement3 || !t2.isReturnStatement(returnStatement3) || !t2.isObjectExpression(returnStatement3.argument)) {
|
|
2251
|
+
return;
|
|
2252
|
+
}
|
|
2253
|
+
const properties = returnStatement3.argument.properties;
|
|
2254
|
+
if (properties.length !== 2) {
|
|
2255
|
+
return;
|
|
2256
|
+
}
|
|
2257
|
+
const pluginsProperty = properties.find(
|
|
2258
|
+
(prop) => t2.isObjectProperty(prop) && t2.isIdentifier(prop.key) && prop.key.name === "plugins"
|
|
2259
|
+
);
|
|
2260
|
+
if (!pluginsProperty || !t2.isObjectProperty(pluginsProperty) || !t2.isCallExpression(pluginsProperty.value) || !t2.isMemberExpression(pluginsProperty.value.callee) || !t2.isArrayExpression(pluginsProperty.value.callee.object)) {
|
|
2261
|
+
return;
|
|
2262
|
+
}
|
|
2263
|
+
const pluginsArray = pluginsProperty.value.callee.object.elements;
|
|
2264
|
+
const targetPlugin = pluginsArray[1];
|
|
2265
|
+
if (!targetPlugin || !t2.isFunctionExpression(targetPlugin)) {
|
|
2266
|
+
return;
|
|
2267
|
+
}
|
|
2268
|
+
const block = targetPlugin.body;
|
|
2269
|
+
const statements = block.body;
|
|
2270
|
+
const last = statements[statements.length - 1];
|
|
2271
|
+
if (last && t2.isExpressionStatement(last)) {
|
|
2272
|
+
statements[statements.length - 1] = t2.expressionStatement(
|
|
2273
|
+
t2.callExpression(
|
|
2274
|
+
t2.memberExpression(valueMember, t2.identifier("push")),
|
|
2275
|
+
[last.expression]
|
|
2276
|
+
)
|
|
2277
|
+
);
|
|
2278
|
+
}
|
|
2279
|
+
const index = statements.findIndex((s) => t2.isIfStatement(s));
|
|
2280
|
+
if (index > -1) {
|
|
2281
|
+
const ifStatement = statements[index];
|
|
2282
|
+
if (t2.isBlockStatement(ifStatement.consequent)) {
|
|
2283
|
+
const [, second] = ifStatement.consequent.body;
|
|
2284
|
+
if (second && t2.isForOfStatement(second) && t2.isBlockStatement(second.body)) {
|
|
2285
|
+
const bodyStatement = second.body.body[0];
|
|
2286
|
+
if (bodyStatement && t2.isIfStatement(bodyStatement) && t2.isBlockStatement(bodyStatement.consequent) && bodyStatement.consequent.body.length === 1 && t2.isExpressionStatement(bodyStatement.consequent.body[0])) {
|
|
2287
|
+
bodyStatement.consequent.body[0] = t2.expressionStatement(
|
|
2288
|
+
t2.callExpression(
|
|
2289
|
+
t2.memberExpression(valueMember, t2.identifier("push")),
|
|
2290
|
+
[bodyStatement.consequent.body[0].expression]
|
|
2291
|
+
)
|
|
2292
|
+
);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
statements.unshift(
|
|
2298
|
+
t2.expressionStatement(
|
|
2299
|
+
t2.assignmentExpression(
|
|
2300
|
+
"=",
|
|
2301
|
+
t2.memberExpression(valueMember, t2.identifier("length")),
|
|
2302
|
+
t2.numericLiteral(0)
|
|
2303
|
+
)
|
|
2304
|
+
)
|
|
2305
|
+
);
|
|
2306
|
+
}
|
|
2307
|
+
});
|
|
2308
|
+
return {
|
|
2309
|
+
code: hasPatched ? content : generate(ast).code,
|
|
2310
|
+
hasPatched
|
|
2311
|
+
};
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
// src/patching/operations/extend-length-units.ts
|
|
2315
|
+
import * as t3 from "@babel/types";
|
|
2316
|
+
import fs5 from "fs-extra";
|
|
2317
|
+
import path4 from "pathe";
|
|
2318
|
+
|
|
2319
|
+
// src/utils.ts
|
|
2320
|
+
function isObject(val) {
|
|
2321
|
+
return val !== null && typeof val === "object" && Array.isArray(val) === false;
|
|
2322
|
+
}
|
|
2323
|
+
function spliceChangesIntoString(str, changes) {
|
|
2324
|
+
if (!changes[0]) {
|
|
2325
|
+
return str;
|
|
2326
|
+
}
|
|
2327
|
+
changes.sort((a, b) => {
|
|
2328
|
+
return a.end - b.end || a.start - b.start;
|
|
2329
|
+
});
|
|
2330
|
+
let result = "";
|
|
2331
|
+
let previous = changes[0];
|
|
2332
|
+
result += str.slice(0, previous.start);
|
|
2333
|
+
result += previous.replacement;
|
|
2334
|
+
for (let i = 1; i < changes.length; ++i) {
|
|
2335
|
+
const change = changes[i];
|
|
2336
|
+
result += str.slice(previous.end, change.start);
|
|
2337
|
+
result += change.replacement;
|
|
2338
|
+
previous = change;
|
|
2339
|
+
}
|
|
2340
|
+
result += str.slice(previous.end);
|
|
2341
|
+
return result;
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
// src/patching/operations/extend-length-units.ts
|
|
2345
|
+
function updateLengthUnitsArray(content, options) {
|
|
2346
|
+
const { variableName = "lengthUnits", units } = options;
|
|
2347
|
+
const ast = parse(content);
|
|
2348
|
+
let arrayRef;
|
|
2349
|
+
let changed = false;
|
|
2350
|
+
traverse(ast, {
|
|
2351
|
+
Identifier(path13) {
|
|
2352
|
+
if (path13.node.name === variableName && t3.isVariableDeclarator(path13.parent) && t3.isArrayExpression(path13.parent.init)) {
|
|
2353
|
+
arrayRef = path13.parent.init;
|
|
2354
|
+
const existing = new Set(
|
|
2355
|
+
path13.parent.init.elements.map((element) => t3.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
|
|
2356
|
+
);
|
|
2357
|
+
for (const unit of units) {
|
|
2358
|
+
if (!existing.has(unit)) {
|
|
2359
|
+
path13.parent.init.elements = path13.parent.init.elements.map((element) => {
|
|
2360
|
+
if (t3.isStringLiteral(element)) {
|
|
2361
|
+
return t3.stringLiteral(element.value);
|
|
2362
|
+
}
|
|
2363
|
+
return element;
|
|
2364
|
+
});
|
|
2365
|
+
path13.parent.init.elements.push(t3.stringLiteral(unit));
|
|
2366
|
+
changed = true;
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
});
|
|
2372
|
+
return {
|
|
2373
|
+
...arrayRef === void 0 ? {} : { arrayRef },
|
|
2374
|
+
changed
|
|
2375
|
+
};
|
|
2376
|
+
}
|
|
2377
|
+
function applyExtendLengthUnitsPatchV3(rootDir, options) {
|
|
2378
|
+
if (!options.enabled) {
|
|
2379
|
+
return { changed: false, code: void 0 };
|
|
2380
|
+
}
|
|
2381
|
+
const opts = {
|
|
2382
|
+
...options,
|
|
2383
|
+
lengthUnitsFilePath: options.lengthUnitsFilePath ?? "lib/util/dataTypes.js",
|
|
2384
|
+
variableName: options.variableName ?? "lengthUnits"
|
|
2385
|
+
};
|
|
2386
|
+
const dataTypesFilePath = path4.resolve(rootDir, opts.lengthUnitsFilePath);
|
|
2387
|
+
const exists = fs5.existsSync(dataTypesFilePath);
|
|
2388
|
+
if (!exists) {
|
|
2389
|
+
return { changed: false, code: void 0 };
|
|
2390
|
+
}
|
|
2391
|
+
const content = fs5.readFileSync(dataTypesFilePath, "utf8");
|
|
2392
|
+
const { arrayRef, changed } = updateLengthUnitsArray(content, opts);
|
|
2393
|
+
if (!arrayRef || !changed) {
|
|
2394
|
+
return { changed: false, code: void 0 };
|
|
2395
|
+
}
|
|
2396
|
+
const { code } = generate(arrayRef, {
|
|
2397
|
+
jsescOption: { quotes: "single" }
|
|
2398
|
+
});
|
|
2399
|
+
if (arrayRef.start != null && arrayRef.end != null) {
|
|
2400
|
+
const nextCode = `${content.slice(0, arrayRef.start)}${code}${content.slice(arrayRef.end)}`;
|
|
2401
|
+
if (opts.overwrite) {
|
|
2402
|
+
const target = opts.destPath ? path4.resolve(opts.destPath) : dataTypesFilePath;
|
|
2403
|
+
fs5.writeFileSync(target, nextCode, "utf8");
|
|
2404
|
+
logger_default.success("Patched Tailwind CSS length unit list (v3).");
|
|
2405
|
+
}
|
|
2406
|
+
return {
|
|
2407
|
+
changed: true,
|
|
2408
|
+
code: nextCode
|
|
2409
|
+
};
|
|
2410
|
+
}
|
|
2411
|
+
return {
|
|
2412
|
+
changed: false,
|
|
2413
|
+
code: void 0
|
|
2414
|
+
};
|
|
2415
|
+
}
|
|
2416
|
+
function applyExtendLengthUnitsPatchV4(rootDir, options) {
|
|
2417
|
+
if (!options.enabled) {
|
|
2418
|
+
return { files: [], changed: false };
|
|
2419
|
+
}
|
|
2420
|
+
const opts = { ...options };
|
|
2421
|
+
const distDir = path4.resolve(rootDir, "dist");
|
|
2422
|
+
if (!fs5.existsSync(distDir)) {
|
|
2423
|
+
return { files: [], changed: false };
|
|
2424
|
+
}
|
|
2425
|
+
const entries = fs5.readdirSync(distDir);
|
|
2426
|
+
const chunkNames = entries.filter((entry) => entry.endsWith(".js") || entry.endsWith(".mjs"));
|
|
2427
|
+
const pattern = /\[\s*["']cm["'],\s*["']mm["'],[\w,"']+\]/;
|
|
2428
|
+
const candidates = chunkNames.map((chunkName) => {
|
|
2429
|
+
const file = path4.join(distDir, chunkName);
|
|
2430
|
+
const code = fs5.readFileSync(file, "utf8");
|
|
2431
|
+
const match = pattern.exec(code);
|
|
2432
|
+
if (!match) {
|
|
2433
|
+
return null;
|
|
2434
|
+
}
|
|
2435
|
+
return {
|
|
2436
|
+
file,
|
|
2437
|
+
code,
|
|
2438
|
+
match,
|
|
2439
|
+
hasPatched: false
|
|
2440
|
+
};
|
|
2441
|
+
}).filter((candidate) => candidate !== null);
|
|
2442
|
+
for (const item of candidates) {
|
|
2443
|
+
const { code, file, match } = item;
|
|
2444
|
+
const ast = parse(match[0], { sourceType: "unambiguous" });
|
|
2445
|
+
traverse(ast, {
|
|
2446
|
+
ArrayExpression(path13) {
|
|
2447
|
+
for (const unit of opts.units) {
|
|
2448
|
+
if (path13.node.elements.some((element) => t3.isStringLiteral(element) && element.value === unit)) {
|
|
2449
|
+
item.hasPatched = true;
|
|
2450
|
+
return;
|
|
2451
|
+
}
|
|
2452
|
+
path13.node.elements.push(t3.stringLiteral(unit));
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
});
|
|
2456
|
+
if (item.hasPatched) {
|
|
2457
|
+
continue;
|
|
2458
|
+
}
|
|
2459
|
+
const { code: replacement } = generate(ast, { minified: true });
|
|
2460
|
+
const start = match.index ?? 0;
|
|
2461
|
+
const end = start + match[0].length;
|
|
2462
|
+
item.code = spliceChangesIntoString(code, [
|
|
2463
|
+
{
|
|
2464
|
+
start,
|
|
2465
|
+
end,
|
|
2466
|
+
replacement: replacement.endsWith(";") ? replacement.slice(0, -1) : replacement
|
|
2467
|
+
}
|
|
2468
|
+
]);
|
|
2469
|
+
if (opts.overwrite) {
|
|
2470
|
+
fs5.writeFileSync(file, item.code, "utf8");
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
if (candidates.some((file) => !file.hasPatched)) {
|
|
2474
|
+
logger_default.success("Patched Tailwind CSS length unit list (v4).");
|
|
2475
|
+
}
|
|
2476
|
+
return {
|
|
2477
|
+
changed: candidates.some((file) => !file.hasPatched),
|
|
2478
|
+
files: candidates
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
|
|
2482
|
+
// src/patching/status.ts
|
|
2483
|
+
function inspectLengthUnitsArray(content, variableName, units) {
|
|
2484
|
+
const ast = parse(content);
|
|
2485
|
+
let found = false;
|
|
2486
|
+
let missingUnits = [];
|
|
2487
|
+
traverse(ast, {
|
|
2488
|
+
Identifier(path13) {
|
|
2489
|
+
if (path13.node.name === variableName && t4.isVariableDeclarator(path13.parent) && t4.isArrayExpression(path13.parent.init)) {
|
|
2490
|
+
found = true;
|
|
2491
|
+
const existing = new Set(
|
|
2492
|
+
path13.parent.init.elements.map((element) => t4.isStringLiteral(element) ? element.value : void 0).filter(Boolean)
|
|
2493
|
+
);
|
|
2494
|
+
missingUnits = units.filter((unit) => !existing.has(unit));
|
|
2495
|
+
path13.stop();
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
});
|
|
2499
|
+
return {
|
|
2500
|
+
found,
|
|
2501
|
+
missingUnits
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
function checkExposeContextPatch(context) {
|
|
2505
|
+
const { packageInfo, options, majorVersion } = context;
|
|
2506
|
+
const refProperty = options.features.exposeContext.refProperty;
|
|
2507
|
+
if (!options.features.exposeContext.enabled) {
|
|
2508
|
+
return {
|
|
2509
|
+
name: "exposeContext",
|
|
2510
|
+
status: "skipped",
|
|
2511
|
+
reason: "exposeContext feature disabled",
|
|
2512
|
+
files: []
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
if (majorVersion === 4) {
|
|
2516
|
+
return {
|
|
2517
|
+
name: "exposeContext",
|
|
2518
|
+
status: "unsupported",
|
|
2519
|
+
reason: "Context export patch is only required for Tailwind v2/v3",
|
|
2520
|
+
files: []
|
|
2521
|
+
};
|
|
2522
|
+
}
|
|
2523
|
+
const checks = [];
|
|
2524
|
+
function inspectFile(relative, transform) {
|
|
2525
|
+
const filePath = path5.resolve(packageInfo.rootPath, relative);
|
|
2526
|
+
if (!fs6.existsSync(filePath)) {
|
|
2527
|
+
checks.push({ relative, exists: false, patched: false });
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
2530
|
+
const content = fs6.readFileSync(filePath, "utf8");
|
|
2531
|
+
const { hasPatched } = transform(content);
|
|
2532
|
+
checks.push({
|
|
2533
|
+
relative,
|
|
2534
|
+
exists: true,
|
|
2535
|
+
patched: hasPatched
|
|
2536
|
+
});
|
|
2537
|
+
}
|
|
2538
|
+
if (majorVersion === 3) {
|
|
2539
|
+
inspectFile("lib/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContext);
|
|
2540
|
+
const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
|
|
2541
|
+
const pluginRelative = pluginCandidates.find((candidate) => fs6.existsSync(path5.resolve(packageInfo.rootPath, candidate)));
|
|
2542
|
+
if (pluginRelative) {
|
|
2543
|
+
inspectFile(pluginRelative, (content) => transformPostcssPlugin(content, { refProperty }));
|
|
2544
|
+
} else {
|
|
2545
|
+
checks.push({ relative: "lib/plugin.js", exists: false, patched: false });
|
|
2546
|
+
}
|
|
2547
|
+
} else {
|
|
2548
|
+
inspectFile("lib/jit/processTailwindFeatures.js", transformProcessTailwindFeaturesReturnContextV2);
|
|
2549
|
+
inspectFile("lib/jit/index.js", (content) => transformPostcssPluginV2(content, { refProperty }));
|
|
2550
|
+
}
|
|
2551
|
+
const files = checks.filter((check) => check.exists).map((check) => check.relative);
|
|
2552
|
+
const missingFiles = checks.filter((check) => !check.exists);
|
|
2553
|
+
const unpatchedFiles = checks.filter((check) => check.exists && !check.patched);
|
|
2554
|
+
const reasons = [];
|
|
2555
|
+
if (missingFiles.length) {
|
|
2556
|
+
reasons.push(`missing files: ${missingFiles.map((item) => item.relative).join(", ")}`);
|
|
2557
|
+
}
|
|
2558
|
+
if (unpatchedFiles.length) {
|
|
2559
|
+
reasons.push(`unpatched files: ${unpatchedFiles.map((item) => item.relative).join(", ")}`);
|
|
2560
|
+
}
|
|
2561
|
+
return {
|
|
2562
|
+
name: "exposeContext",
|
|
2563
|
+
status: reasons.length ? "not-applied" : "applied",
|
|
2564
|
+
...reasons.length ? { reason: reasons.join("; ") } : {},
|
|
2565
|
+
files
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
function checkExtendLengthUnitsV3(rootDir, options) {
|
|
2569
|
+
const lengthUnitsFilePath = options.lengthUnitsFilePath ?? "lib/util/dataTypes.js";
|
|
2570
|
+
const variableName = options.variableName ?? "lengthUnits";
|
|
2571
|
+
const target = path5.resolve(rootDir, lengthUnitsFilePath);
|
|
2572
|
+
const files = fs6.existsSync(target) ? [path5.relative(rootDir, target)] : [];
|
|
2573
|
+
if (!fs6.existsSync(target)) {
|
|
2574
|
+
return {
|
|
2575
|
+
name: "extendLengthUnits",
|
|
2576
|
+
status: "not-applied",
|
|
2577
|
+
reason: `missing ${lengthUnitsFilePath}`,
|
|
2578
|
+
files
|
|
2579
|
+
};
|
|
2580
|
+
}
|
|
2581
|
+
const content = fs6.readFileSync(target, "utf8");
|
|
2582
|
+
const { found, missingUnits } = inspectLengthUnitsArray(content, variableName, options.units);
|
|
2583
|
+
if (!found) {
|
|
2584
|
+
return {
|
|
2585
|
+
name: "extendLengthUnits",
|
|
2586
|
+
status: "not-applied",
|
|
2587
|
+
reason: `could not locate ${variableName} array in ${lengthUnitsFilePath}`,
|
|
2588
|
+
files
|
|
2589
|
+
};
|
|
2590
|
+
}
|
|
2591
|
+
if (missingUnits.length) {
|
|
2592
|
+
return {
|
|
2593
|
+
name: "extendLengthUnits",
|
|
2594
|
+
status: "not-applied",
|
|
2595
|
+
reason: `missing units: ${missingUnits.join(", ")}`,
|
|
2596
|
+
files
|
|
2597
|
+
};
|
|
2598
|
+
}
|
|
2599
|
+
return {
|
|
2600
|
+
name: "extendLengthUnits",
|
|
2601
|
+
status: "applied",
|
|
2602
|
+
files
|
|
2603
|
+
};
|
|
2604
|
+
}
|
|
2605
|
+
function checkExtendLengthUnitsV4(rootDir, options) {
|
|
2606
|
+
const distDir = path5.resolve(rootDir, "dist");
|
|
2607
|
+
if (!fs6.existsSync(distDir)) {
|
|
2608
|
+
return {
|
|
2609
|
+
name: "extendLengthUnits",
|
|
2610
|
+
status: "not-applied",
|
|
2611
|
+
reason: "dist directory not found for Tailwind v4 package",
|
|
2612
|
+
files: []
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
const result = applyExtendLengthUnitsPatchV4(rootDir, {
|
|
2616
|
+
...options,
|
|
2617
|
+
enabled: true,
|
|
2618
|
+
overwrite: false
|
|
2619
|
+
});
|
|
2620
|
+
if (result.files.length === 0) {
|
|
2621
|
+
return {
|
|
2622
|
+
name: "extendLengthUnits",
|
|
2623
|
+
status: "not-applied",
|
|
2624
|
+
reason: "no bundle chunks matched the length unit pattern",
|
|
2625
|
+
files: []
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
const files = result.files.map((file) => path5.relative(rootDir, file.file));
|
|
2629
|
+
const pending = result.files.filter((file) => !file.hasPatched);
|
|
2630
|
+
if (pending.length) {
|
|
2631
|
+
return {
|
|
2632
|
+
name: "extendLengthUnits",
|
|
2633
|
+
status: "not-applied",
|
|
2634
|
+
reason: `missing units in ${pending.length} bundle${pending.length > 1 ? "s" : ""}`,
|
|
2635
|
+
files: pending.map((file) => path5.relative(rootDir, file.file))
|
|
2636
|
+
};
|
|
2637
|
+
}
|
|
2638
|
+
return {
|
|
2639
|
+
name: "extendLengthUnits",
|
|
2640
|
+
status: "applied",
|
|
2641
|
+
files
|
|
2642
|
+
};
|
|
2643
|
+
}
|
|
2644
|
+
function checkExtendLengthUnitsPatch(context) {
|
|
2645
|
+
const { packageInfo, options, majorVersion } = context;
|
|
2646
|
+
if (!options.features.extendLengthUnits) {
|
|
2647
|
+
return {
|
|
2648
|
+
name: "extendLengthUnits",
|
|
2649
|
+
status: "skipped",
|
|
2650
|
+
reason: "extendLengthUnits feature disabled",
|
|
2651
|
+
files: []
|
|
2652
|
+
};
|
|
2653
|
+
}
|
|
2654
|
+
if (majorVersion === 2) {
|
|
2655
|
+
return {
|
|
2656
|
+
name: "extendLengthUnits",
|
|
2657
|
+
status: "unsupported",
|
|
2658
|
+
reason: "length unit extension is only applied for Tailwind v3/v4",
|
|
2659
|
+
files: []
|
|
2660
|
+
};
|
|
2661
|
+
}
|
|
2662
|
+
if (majorVersion === 3) {
|
|
2663
|
+
return checkExtendLengthUnitsV3(packageInfo.rootPath, options.features.extendLengthUnits);
|
|
2664
|
+
}
|
|
2665
|
+
return checkExtendLengthUnitsV4(packageInfo.rootPath, options.features.extendLengthUnits);
|
|
2666
|
+
}
|
|
2667
|
+
function getPatchStatusReport(context) {
|
|
2668
|
+
return {
|
|
2669
|
+
package: {
|
|
2670
|
+
name: context.packageInfo.name ?? context.packageInfo.packageJson?.name,
|
|
2671
|
+
version: context.packageInfo.version,
|
|
2672
|
+
root: context.packageInfo.rootPath
|
|
2673
|
+
},
|
|
2674
|
+
majorVersion: context.majorVersion,
|
|
2675
|
+
entries: [
|
|
2676
|
+
checkExposeContextPatch(context),
|
|
2677
|
+
checkExtendLengthUnitsPatch(context)
|
|
2678
|
+
]
|
|
2679
|
+
};
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
// src/runtime/class-collector.ts
|
|
2683
|
+
import process5 from "process";
|
|
2684
|
+
import fs7 from "fs-extra";
|
|
2685
|
+
import path6 from "pathe";
|
|
2686
|
+
function collectClassesFromContexts(contexts, filter) {
|
|
2687
|
+
const set = /* @__PURE__ */ new Set();
|
|
2688
|
+
for (const context of contexts) {
|
|
2689
|
+
if (!isObject(context) || !context.classCache) {
|
|
2690
|
+
continue;
|
|
2691
|
+
}
|
|
2692
|
+
for (const key of context.classCache.keys()) {
|
|
2693
|
+
const className = key.toString();
|
|
2694
|
+
if (filter(className)) {
|
|
2695
|
+
set.add(className);
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
return set;
|
|
2700
|
+
}
|
|
2701
|
+
async function collectClassesFromTailwindV4(options) {
|
|
2702
|
+
const set = /* @__PURE__ */ new Set();
|
|
2703
|
+
const v4Options = options.tailwind.v4;
|
|
2704
|
+
if (!v4Options) {
|
|
2705
|
+
return set;
|
|
2706
|
+
}
|
|
2707
|
+
const toAbsolute = (value) => {
|
|
2708
|
+
if (!value) {
|
|
2709
|
+
return void 0;
|
|
2710
|
+
}
|
|
2711
|
+
return path6.isAbsolute(value) ? value : path6.resolve(options.projectRoot, value);
|
|
2712
|
+
};
|
|
2713
|
+
const resolvedConfiguredBase = toAbsolute(v4Options.configuredBase);
|
|
2714
|
+
const resolvedDefaultBase = toAbsolute(v4Options.base) ?? process5.cwd();
|
|
2715
|
+
const resolveSources = (base) => {
|
|
2716
|
+
if (!v4Options.sources?.length) {
|
|
2717
|
+
return void 0;
|
|
2718
|
+
}
|
|
2719
|
+
return v4Options.sources.map((source) => ({
|
|
2720
|
+
base: source.base ?? base,
|
|
2721
|
+
pattern: source.pattern,
|
|
2722
|
+
negated: source.negated
|
|
2723
|
+
}));
|
|
2724
|
+
};
|
|
2725
|
+
if (v4Options.cssEntries.length > 0) {
|
|
2726
|
+
for (const entry of v4Options.cssEntries) {
|
|
2727
|
+
const filePath = path6.isAbsolute(entry) ? entry : path6.resolve(options.projectRoot, entry);
|
|
2728
|
+
if (!await fs7.pathExists(filePath)) {
|
|
2729
|
+
continue;
|
|
2730
|
+
}
|
|
2731
|
+
const css = await fs7.readFile(filePath, "utf8");
|
|
2732
|
+
const entryDir = path6.dirname(filePath);
|
|
2733
|
+
const designSystemBases = resolvedConfiguredBase && resolvedConfiguredBase !== entryDir ? [entryDir, resolvedConfiguredBase] : [entryDir];
|
|
2734
|
+
const sourcesBase = resolvedConfiguredBase ?? entryDir;
|
|
2735
|
+
const sources = resolveSources(sourcesBase);
|
|
2736
|
+
const firstBase = designSystemBases[0] ?? entryDir;
|
|
2737
|
+
const extractOptions = {
|
|
2738
|
+
cwd: options.projectRoot,
|
|
2739
|
+
base: firstBase,
|
|
2740
|
+
baseFallbacks: designSystemBases.slice(1),
|
|
2741
|
+
css,
|
|
2742
|
+
...sources === void 0 ? {} : { sources }
|
|
2743
|
+
};
|
|
2744
|
+
const candidates = await extractValidCandidates(extractOptions);
|
|
2745
|
+
for (const candidate of candidates) {
|
|
2746
|
+
if (options.filter(candidate)) {
|
|
2747
|
+
set.add(candidate);
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
} else {
|
|
2752
|
+
const baseForCss = resolvedConfiguredBase ?? resolvedDefaultBase;
|
|
2753
|
+
const sources = resolveSources(baseForCss);
|
|
2754
|
+
const extractOptions = {
|
|
2755
|
+
cwd: options.projectRoot,
|
|
2756
|
+
base: baseForCss,
|
|
2757
|
+
...v4Options.css === void 0 ? {} : { css: v4Options.css },
|
|
2758
|
+
...sources === void 0 ? {} : { sources }
|
|
2759
|
+
};
|
|
2760
|
+
const candidates = await extractValidCandidates(extractOptions);
|
|
2761
|
+
for (const candidate of candidates) {
|
|
2762
|
+
if (options.filter(candidate)) {
|
|
2763
|
+
set.add(candidate);
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
return set;
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
// src/runtime/context-registry.ts
|
|
2771
|
+
import { createRequire } from "module";
|
|
2772
|
+
import fs8 from "fs-extra";
|
|
2773
|
+
import path7 from "pathe";
|
|
2774
|
+
var require2 = createRequire(import.meta.url);
|
|
2775
|
+
function resolveRuntimeEntry(packageInfo, majorVersion) {
|
|
2776
|
+
const root = packageInfo.rootPath;
|
|
2777
|
+
if (majorVersion === 2) {
|
|
2778
|
+
const jitIndex = path7.join(root, "lib/jit/index.js");
|
|
2779
|
+
if (fs8.existsSync(jitIndex)) {
|
|
2780
|
+
return jitIndex;
|
|
2781
|
+
}
|
|
2782
|
+
} else if (majorVersion === 3) {
|
|
2783
|
+
const plugin = path7.join(root, "lib/plugin.js");
|
|
2784
|
+
const index = path7.join(root, "lib/index.js");
|
|
2785
|
+
if (fs8.existsSync(plugin)) {
|
|
2786
|
+
return plugin;
|
|
2787
|
+
}
|
|
2788
|
+
if (fs8.existsSync(index)) {
|
|
2789
|
+
return index;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
return void 0;
|
|
2793
|
+
}
|
|
2794
|
+
function loadRuntimeContexts(packageInfo, majorVersion, refProperty) {
|
|
2795
|
+
if (majorVersion === 4) {
|
|
2796
|
+
return [];
|
|
2797
|
+
}
|
|
2798
|
+
const entry = resolveRuntimeEntry(packageInfo, majorVersion);
|
|
2799
|
+
if (!entry) {
|
|
2800
|
+
return [];
|
|
2801
|
+
}
|
|
2802
|
+
const moduleExports = require2(entry);
|
|
2803
|
+
if (!moduleExports) {
|
|
2804
|
+
return [];
|
|
2805
|
+
}
|
|
2806
|
+
const ref = moduleExports[refProperty];
|
|
2807
|
+
if (!ref) {
|
|
2808
|
+
return [];
|
|
2809
|
+
}
|
|
2810
|
+
if (Array.isArray(ref)) {
|
|
2811
|
+
return ref;
|
|
2812
|
+
}
|
|
2813
|
+
if (typeof ref === "object" && Array.isArray(ref.value)) {
|
|
2814
|
+
return ref.value;
|
|
2815
|
+
}
|
|
2816
|
+
return [];
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
// src/runtime/process-tailwindcss.ts
|
|
2820
|
+
import { createRequire as createRequire2 } from "module";
|
|
2821
|
+
import path8 from "pathe";
|
|
2822
|
+
import postcss from "postcss";
|
|
2823
|
+
import { loadConfig } from "tailwindcss-config";
|
|
2824
|
+
var require3 = createRequire2(import.meta.url);
|
|
2825
|
+
async function resolveConfigPath(options) {
|
|
2826
|
+
if (options.config && path8.isAbsolute(options.config)) {
|
|
2827
|
+
return options.config;
|
|
2828
|
+
}
|
|
2829
|
+
const result = await loadConfig({ cwd: options.cwd });
|
|
2830
|
+
if (!result) {
|
|
2831
|
+
throw new Error(`Unable to locate Tailwind CSS config from ${options.cwd}`);
|
|
2832
|
+
}
|
|
2833
|
+
return result.filepath;
|
|
2834
|
+
}
|
|
2835
|
+
async function runTailwindBuild(options) {
|
|
2836
|
+
const configPath = await resolveConfigPath(options);
|
|
2837
|
+
const pluginName = options.postcssPlugin ?? (options.majorVersion === 4 ? "@tailwindcss/postcss" : "tailwindcss");
|
|
2838
|
+
if (options.majorVersion === 4) {
|
|
2839
|
+
return postcss([
|
|
2840
|
+
require3(pluginName)({
|
|
2841
|
+
config: configPath
|
|
2842
|
+
})
|
|
2843
|
+
]).process("@import 'tailwindcss';", {
|
|
2844
|
+
from: void 0
|
|
2845
|
+
});
|
|
2846
|
+
}
|
|
2847
|
+
return postcss([
|
|
2848
|
+
require3(pluginName)({
|
|
2849
|
+
config: configPath
|
|
2850
|
+
})
|
|
2851
|
+
]).process("@tailwind base;@tailwind components;@tailwind utilities;", {
|
|
2852
|
+
from: void 0
|
|
2853
|
+
});
|
|
2854
|
+
}
|
|
2855
|
+
|
|
2856
|
+
// src/api/tailwindcss-patcher.ts
|
|
2857
|
+
import process6 from "process";
|
|
2858
|
+
import fs10 from "fs-extra";
|
|
2859
|
+
import { getPackageInfoSync } from "local-pkg";
|
|
2860
|
+
import path10 from "pathe";
|
|
2861
|
+
import { coerce } from "semver";
|
|
2862
|
+
|
|
2863
|
+
// src/options/legacy.ts
|
|
2864
|
+
function normalizeLegacyFeatures(patch) {
|
|
2865
|
+
const apply = patch?.applyPatches;
|
|
2866
|
+
const extend = apply?.extendLengthUnits;
|
|
2867
|
+
let extendOption = false;
|
|
2868
|
+
if (extend && typeof extend === "object") {
|
|
2869
|
+
extendOption = {
|
|
2870
|
+
...extend,
|
|
2871
|
+
enabled: true
|
|
2872
|
+
};
|
|
2873
|
+
} else if (extend === true) {
|
|
2874
|
+
extendOption = {
|
|
2875
|
+
enabled: true,
|
|
2876
|
+
units: ["rpx"],
|
|
2877
|
+
...patch?.overwrite === void 0 ? {} : { overwrite: patch.overwrite }
|
|
2878
|
+
};
|
|
2879
|
+
}
|
|
2880
|
+
return {
|
|
2881
|
+
exposeContext: apply?.exportContext ?? true,
|
|
2882
|
+
extendLengthUnits: extendOption
|
|
2883
|
+
};
|
|
2884
|
+
}
|
|
2885
|
+
function fromLegacyOptions(options) {
|
|
2886
|
+
if (!options) {
|
|
2887
|
+
return {};
|
|
2888
|
+
}
|
|
2889
|
+
const patch = options.patch;
|
|
2890
|
+
const features = normalizeLegacyFeatures(patch);
|
|
2891
|
+
const output = patch?.output;
|
|
2892
|
+
const tailwindConfig = patch?.tailwindcss;
|
|
2893
|
+
const tailwindVersion = tailwindConfig?.version;
|
|
2894
|
+
const tailwindV2 = tailwindConfig?.v2;
|
|
2895
|
+
const tailwindV3 = tailwindConfig?.v3;
|
|
2896
|
+
const tailwindV4 = tailwindConfig?.v4;
|
|
2897
|
+
const tailwindConfigPath = tailwindV3?.config ?? tailwindV2?.config;
|
|
2898
|
+
const tailwindCwd = tailwindV3?.cwd ?? tailwindV2?.cwd ?? patch?.cwd;
|
|
2899
|
+
const normalizedExtract = output ? {
|
|
2900
|
+
...output.filename === void 0 ? {} : { file: output.filename },
|
|
2901
|
+
pretty: output.loose ? 2 : false,
|
|
2902
|
+
...output.removeUniversalSelector === void 0 ? {} : { removeUniversalSelector: output.removeUniversalSelector }
|
|
2903
|
+
} : void 0;
|
|
2904
|
+
const normalizedTailwindcss = {
|
|
2905
|
+
...patch?.packageName === void 0 ? {} : { packageName: patch.packageName },
|
|
2906
|
+
...tailwindVersion === void 0 ? {} : { version: tailwindVersion },
|
|
2907
|
+
...patch?.resolve === void 0 ? {} : { resolve: patch.resolve },
|
|
2908
|
+
...tailwindConfigPath === void 0 ? {} : { config: tailwindConfigPath },
|
|
2909
|
+
...tailwindCwd === void 0 ? {} : { cwd: tailwindCwd },
|
|
2910
|
+
...tailwindV2 === void 0 ? {} : { v2: tailwindV2 },
|
|
2911
|
+
...tailwindV3 === void 0 ? {} : { v3: tailwindV3 },
|
|
2912
|
+
...tailwindV4 === void 0 ? {} : { v4: tailwindV4 }
|
|
2913
|
+
};
|
|
2914
|
+
const normalizedCache = typeof options.cache === "boolean" ? options.cache : options.cache ? {
|
|
2915
|
+
...options.cache,
|
|
2916
|
+
enabled: options.cache.enabled ?? true
|
|
2917
|
+
} : void 0;
|
|
2918
|
+
const normalizedApply = {
|
|
2919
|
+
...patch?.overwrite === void 0 ? {} : { overwrite: patch.overwrite },
|
|
2920
|
+
exposeContext: features.exposeContext,
|
|
2921
|
+
extendLengthUnits: features.extendLengthUnits
|
|
2922
|
+
};
|
|
2923
|
+
return {
|
|
2924
|
+
...patch?.cwd === void 0 ? {} : { projectRoot: patch.cwd },
|
|
2925
|
+
...patch?.filter === void 0 ? {} : { filter: patch.filter },
|
|
2926
|
+
...normalizedCache === void 0 ? {} : { cache: normalizedCache },
|
|
2927
|
+
...normalizedExtract === void 0 ? {} : { extract: normalizedExtract },
|
|
2928
|
+
...Object.keys(normalizedTailwindcss).length === 0 ? {} : { tailwindcss: normalizedTailwindcss },
|
|
2929
|
+
apply: normalizedApply
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
function fromUnifiedConfig(registry) {
|
|
2933
|
+
if (!registry) {
|
|
2934
|
+
return {};
|
|
2935
|
+
}
|
|
2936
|
+
const tailwind = registry.tailwindcss ?? registry.tailwind;
|
|
2937
|
+
const modernExtract = registry.extract;
|
|
2938
|
+
const legacyOutput = registry.output;
|
|
2939
|
+
const pretty = (() => {
|
|
2940
|
+
const value = modernExtract?.pretty ?? legacyOutput?.pretty;
|
|
2941
|
+
if (value === void 0) {
|
|
2942
|
+
return void 0;
|
|
2943
|
+
}
|
|
2944
|
+
if (typeof value === "boolean") {
|
|
2945
|
+
return value ? 2 : false;
|
|
2946
|
+
}
|
|
2947
|
+
return value;
|
|
2948
|
+
})();
|
|
2949
|
+
const removeUniversalSelector = modernExtract?.removeUniversalSelector ?? legacyOutput?.stripUniversalSelector;
|
|
2950
|
+
const outputFile = modernExtract?.file ?? legacyOutput?.file;
|
|
2951
|
+
const normalizedExtract = modernExtract || legacyOutput ? {
|
|
2952
|
+
...modernExtract?.write === void 0 ? {} : { write: modernExtract.write },
|
|
2953
|
+
...outputFile === void 0 ? {} : { file: outputFile },
|
|
2954
|
+
...pretty === void 0 ? {} : { pretty },
|
|
2955
|
+
...removeUniversalSelector === void 0 ? {} : { removeUniversalSelector },
|
|
2956
|
+
...modernExtract?.format === void 0 ? {} : { format: modernExtract.format }
|
|
2957
|
+
} : void 0;
|
|
2958
|
+
const normalizedTailwindcss = tailwind ? {
|
|
2959
|
+
...tailwind.version === void 0 ? {} : { version: tailwind.version },
|
|
2960
|
+
...tailwind.packageName === void 0 ? tailwind.package === void 0 ? {} : { packageName: tailwind.package } : { packageName: tailwind.packageName },
|
|
2961
|
+
...tailwind.resolve === void 0 ? {} : { resolve: tailwind.resolve },
|
|
2962
|
+
...tailwind.config === void 0 ? {} : { config: tailwind.config },
|
|
2963
|
+
...tailwind.cwd === void 0 ? {} : { cwd: tailwind.cwd },
|
|
2964
|
+
...tailwind.v2 === void 0 ? tailwind.legacy === void 0 ? {} : { v2: tailwind.legacy } : { v2: tailwind.v2 },
|
|
2965
|
+
...tailwind.v3 === void 0 ? tailwind.classic === void 0 ? {} : { v3: tailwind.classic } : { v3: tailwind.v3 },
|
|
2966
|
+
...tailwind.v4 === void 0 ? tailwind.next === void 0 ? {} : { v4: tailwind.next } : { v4: tailwind.v4 }
|
|
2967
|
+
} : void 0;
|
|
2968
|
+
const normalizedApply = registry.apply ? {
|
|
2969
|
+
...registry.apply.overwrite === void 0 ? {} : { overwrite: registry.apply.overwrite },
|
|
2970
|
+
...registry.apply.exposeContext === void 0 ? {} : { exposeContext: registry.apply.exposeContext },
|
|
2971
|
+
...registry.apply.extendLengthUnits === void 0 ? {} : { extendLengthUnits: registry.apply.extendLengthUnits }
|
|
2972
|
+
} : void 0;
|
|
2973
|
+
return {
|
|
2974
|
+
...registry.projectRoot === void 0 ? {} : { projectRoot: registry.projectRoot },
|
|
2975
|
+
...normalizedApply === void 0 ? {} : { apply: normalizedApply },
|
|
2976
|
+
...registry.cache === void 0 ? {} : { cache: registry.cache },
|
|
2977
|
+
...registry.filter === void 0 ? {} : { filter: registry.filter },
|
|
2978
|
+
...normalizedExtract === void 0 ? {} : { extract: normalizedExtract },
|
|
2979
|
+
...normalizedTailwindcss === void 0 ? {} : { tailwindcss: normalizedTailwindcss }
|
|
2980
|
+
};
|
|
2981
|
+
}
|
|
2982
|
+
|
|
2983
|
+
// src/patching/operations/export-context/index.ts
|
|
2984
|
+
import fs9 from "fs-extra";
|
|
2985
|
+
import path9 from "pathe";
|
|
2986
|
+
function writeFileIfRequired(filePath, code, overwrite, successMessage) {
|
|
2987
|
+
if (!overwrite) {
|
|
2988
|
+
return;
|
|
2989
|
+
}
|
|
2990
|
+
fs9.writeFileSync(filePath, code, {
|
|
2991
|
+
encoding: "utf8"
|
|
2992
|
+
});
|
|
2993
|
+
logger_default.success(successMessage);
|
|
2994
|
+
}
|
|
2995
|
+
function applyExposeContextPatch(params) {
|
|
2996
|
+
const { rootDir, refProperty, overwrite, majorVersion } = params;
|
|
2997
|
+
const result = {
|
|
2998
|
+
applied: false,
|
|
2999
|
+
files: {}
|
|
3000
|
+
};
|
|
3001
|
+
if (majorVersion === 3) {
|
|
3002
|
+
const processFileRelative = "lib/processTailwindFeatures.js";
|
|
3003
|
+
const processFilePath = path9.resolve(rootDir, processFileRelative);
|
|
3004
|
+
if (fs9.existsSync(processFilePath)) {
|
|
3005
|
+
const content = fs9.readFileSync(processFilePath, "utf8");
|
|
3006
|
+
const { code, hasPatched } = transformProcessTailwindFeaturesReturnContext(content);
|
|
3007
|
+
result.files[processFileRelative] = code;
|
|
3008
|
+
if (!hasPatched) {
|
|
3009
|
+
writeFileIfRequired(
|
|
3010
|
+
processFilePath,
|
|
3011
|
+
code,
|
|
3012
|
+
overwrite,
|
|
3013
|
+
"Patched Tailwind CSS processTailwindFeatures to expose runtime context."
|
|
3014
|
+
);
|
|
3015
|
+
result.applied = true;
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
const pluginCandidates = ["lib/plugin.js", "lib/index.js"];
|
|
3019
|
+
const pluginRelative = pluginCandidates.find((candidate) => fs9.existsSync(path9.resolve(rootDir, candidate)));
|
|
3020
|
+
if (pluginRelative) {
|
|
3021
|
+
const pluginPath = path9.resolve(rootDir, pluginRelative);
|
|
3022
|
+
const content = fs9.readFileSync(pluginPath, "utf8");
|
|
3023
|
+
const { code, hasPatched } = transformPostcssPlugin(content, { refProperty });
|
|
3024
|
+
result.files[pluginRelative] = code;
|
|
3025
|
+
if (!hasPatched) {
|
|
3026
|
+
writeFileIfRequired(
|
|
3027
|
+
pluginPath,
|
|
3028
|
+
code,
|
|
3029
|
+
overwrite,
|
|
3030
|
+
"Patched Tailwind CSS plugin entry to collect runtime contexts."
|
|
3031
|
+
);
|
|
3032
|
+
result.applied = true;
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
} else if (majorVersion === 2) {
|
|
3036
|
+
const processFileRelative = "lib/jit/processTailwindFeatures.js";
|
|
3037
|
+
const processFilePath = path9.resolve(rootDir, processFileRelative);
|
|
3038
|
+
if (fs9.existsSync(processFilePath)) {
|
|
3039
|
+
const content = fs9.readFileSync(processFilePath, "utf8");
|
|
3040
|
+
const { code, hasPatched } = transformProcessTailwindFeaturesReturnContextV2(content);
|
|
3041
|
+
result.files[processFileRelative] = code;
|
|
3042
|
+
if (!hasPatched) {
|
|
3043
|
+
writeFileIfRequired(
|
|
3044
|
+
processFilePath,
|
|
3045
|
+
code,
|
|
3046
|
+
overwrite,
|
|
3047
|
+
"Patched Tailwind CSS JIT processTailwindFeatures to expose runtime context."
|
|
3048
|
+
);
|
|
3049
|
+
result.applied = true;
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
const pluginRelative = "lib/jit/index.js";
|
|
3053
|
+
const pluginPath = path9.resolve(rootDir, pluginRelative);
|
|
3054
|
+
if (fs9.existsSync(pluginPath)) {
|
|
3055
|
+
const content = fs9.readFileSync(pluginPath, "utf8");
|
|
3056
|
+
const { code, hasPatched } = transformPostcssPluginV2(content, { refProperty });
|
|
3057
|
+
result.files[pluginRelative] = code;
|
|
3058
|
+
if (!hasPatched) {
|
|
3059
|
+
writeFileIfRequired(
|
|
3060
|
+
pluginPath,
|
|
3061
|
+
code,
|
|
3062
|
+
overwrite,
|
|
3063
|
+
"Patched Tailwind CSS JIT entry to collect runtime contexts."
|
|
3064
|
+
);
|
|
3065
|
+
result.applied = true;
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
3069
|
+
return result;
|
|
3070
|
+
}
|
|
3071
|
+
|
|
3072
|
+
// src/patching/patch-runner.ts
|
|
3073
|
+
function applyTailwindPatches(context) {
|
|
3074
|
+
const { packageInfo, options, majorVersion } = context;
|
|
3075
|
+
const results = {};
|
|
3076
|
+
if (options.features.exposeContext.enabled && (majorVersion === 2 || majorVersion === 3)) {
|
|
3077
|
+
results.exposeContext = applyExposeContextPatch({
|
|
3078
|
+
rootDir: packageInfo.rootPath,
|
|
3079
|
+
refProperty: options.features.exposeContext.refProperty,
|
|
3080
|
+
overwrite: options.overwrite,
|
|
3081
|
+
majorVersion
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
if (options.features.extendLengthUnits?.enabled) {
|
|
3085
|
+
if (majorVersion === 3) {
|
|
3086
|
+
results.extendLengthUnits = applyExtendLengthUnitsPatchV3(
|
|
3087
|
+
packageInfo.rootPath,
|
|
3088
|
+
options.features.extendLengthUnits
|
|
3089
|
+
);
|
|
3090
|
+
} else if (majorVersion === 4) {
|
|
3091
|
+
results.extendLengthUnits = applyExtendLengthUnitsPatchV4(
|
|
3092
|
+
packageInfo.rootPath,
|
|
3093
|
+
options.features.extendLengthUnits
|
|
3094
|
+
);
|
|
3095
|
+
}
|
|
3096
|
+
}
|
|
3097
|
+
return results;
|
|
3098
|
+
}
|
|
3099
|
+
|
|
3100
|
+
// src/api/tailwindcss-patcher.ts
|
|
3101
|
+
function resolveMajorVersion(version, hint) {
|
|
3102
|
+
if (hint && [2, 3, 4].includes(hint)) {
|
|
3103
|
+
return hint;
|
|
3104
|
+
}
|
|
3105
|
+
if (version) {
|
|
3106
|
+
const coerced = coerce(version);
|
|
3107
|
+
if (coerced) {
|
|
3108
|
+
const major = coerced.major;
|
|
3109
|
+
if (major === 2 || major === 3 || major === 4) {
|
|
3110
|
+
return major;
|
|
3111
|
+
}
|
|
3112
|
+
if (major >= 4) {
|
|
3113
|
+
return 4;
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
return 3;
|
|
3118
|
+
}
|
|
3119
|
+
function resolveTailwindExecutionOptions(normalized, majorVersion) {
|
|
3120
|
+
const base = normalized.tailwind;
|
|
3121
|
+
if (majorVersion === 2 && base.v2) {
|
|
3122
|
+
return {
|
|
3123
|
+
cwd: base.v2.cwd ?? base.cwd ?? normalized.projectRoot,
|
|
3124
|
+
config: base.v2.config ?? base.config,
|
|
3125
|
+
postcssPlugin: base.v2.postcssPlugin ?? base.postcssPlugin
|
|
3126
|
+
};
|
|
3127
|
+
}
|
|
3128
|
+
if (majorVersion === 3 && base.v3) {
|
|
3129
|
+
return {
|
|
3130
|
+
cwd: base.v3.cwd ?? base.cwd ?? normalized.projectRoot,
|
|
3131
|
+
config: base.v3.config ?? base.config,
|
|
3132
|
+
postcssPlugin: base.v3.postcssPlugin ?? base.postcssPlugin
|
|
3133
|
+
};
|
|
3134
|
+
}
|
|
3135
|
+
return {
|
|
3136
|
+
cwd: base.cwd ?? normalized.projectRoot,
|
|
3137
|
+
config: base.config,
|
|
3138
|
+
postcssPlugin: base.postcssPlugin
|
|
3139
|
+
};
|
|
3140
|
+
}
|
|
3141
|
+
var TailwindcssPatcher = class {
|
|
3142
|
+
options;
|
|
3143
|
+
packageInfo;
|
|
3144
|
+
majorVersion;
|
|
3145
|
+
cacheContext;
|
|
3146
|
+
cacheStore;
|
|
3147
|
+
constructor(options = {}) {
|
|
3148
|
+
const resolvedOptions = options && typeof options === "object" && "patch" in options ? fromLegacyOptions(options) : options;
|
|
3149
|
+
this.options = normalizeOptions(resolvedOptions);
|
|
3150
|
+
const packageInfo = getPackageInfoSync(
|
|
3151
|
+
this.options.tailwind.packageName,
|
|
3152
|
+
this.options.tailwind.resolve
|
|
3153
|
+
);
|
|
3154
|
+
if (!packageInfo) {
|
|
3155
|
+
throw new Error(`Unable to locate Tailwind CSS package "${this.options.tailwind.packageName}".`);
|
|
3156
|
+
}
|
|
3157
|
+
this.packageInfo = packageInfo;
|
|
3158
|
+
this.majorVersion = resolveMajorVersion(
|
|
3159
|
+
this.packageInfo.version,
|
|
3160
|
+
this.options.tailwind.versionHint
|
|
3161
|
+
);
|
|
3162
|
+
this.cacheContext = createCacheContextDescriptor(
|
|
3163
|
+
this.options,
|
|
3164
|
+
this.packageInfo,
|
|
3165
|
+
this.majorVersion
|
|
3166
|
+
);
|
|
3167
|
+
this.cacheStore = new CacheStore(this.options.cache, this.cacheContext);
|
|
3168
|
+
}
|
|
3169
|
+
async patch() {
|
|
3170
|
+
return applyTailwindPatches({
|
|
3171
|
+
packageInfo: this.packageInfo,
|
|
3172
|
+
options: this.options,
|
|
3173
|
+
majorVersion: this.majorVersion
|
|
3174
|
+
});
|
|
3175
|
+
}
|
|
3176
|
+
async getPatchStatus() {
|
|
3177
|
+
return getPatchStatusReport({
|
|
3178
|
+
packageInfo: this.packageInfo,
|
|
3179
|
+
options: this.options,
|
|
3180
|
+
majorVersion: this.majorVersion
|
|
3181
|
+
});
|
|
3182
|
+
}
|
|
3183
|
+
getContexts() {
|
|
3184
|
+
return loadRuntimeContexts(
|
|
3185
|
+
this.packageInfo,
|
|
3186
|
+
this.majorVersion,
|
|
3187
|
+
this.options.features.exposeContext.refProperty
|
|
3188
|
+
);
|
|
3189
|
+
}
|
|
3190
|
+
async runTailwindBuildIfNeeded() {
|
|
3191
|
+
if (this.majorVersion === 2 || this.majorVersion === 3) {
|
|
3192
|
+
const executionOptions = resolveTailwindExecutionOptions(this.options, this.majorVersion);
|
|
3193
|
+
const buildOptions = {
|
|
3194
|
+
cwd: executionOptions.cwd,
|
|
3195
|
+
majorVersion: this.majorVersion,
|
|
3196
|
+
...executionOptions.config === void 0 ? {} : { config: executionOptions.config },
|
|
3197
|
+
...executionOptions.postcssPlugin === void 0 ? {} : { postcssPlugin: executionOptions.postcssPlugin }
|
|
3198
|
+
};
|
|
3199
|
+
await runTailwindBuild(buildOptions);
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
async collectClassSet() {
|
|
3203
|
+
if (this.majorVersion === 4) {
|
|
3204
|
+
return collectClassesFromTailwindV4(this.options);
|
|
3205
|
+
}
|
|
3206
|
+
const contexts = this.getContexts();
|
|
3207
|
+
return collectClassesFromContexts(contexts, this.options.filter);
|
|
3208
|
+
}
|
|
3209
|
+
debugCacheRead(meta) {
|
|
3210
|
+
if (meta.hit) {
|
|
3211
|
+
logger_default.debug(
|
|
3212
|
+
`[cache] hit fingerprint=${meta.fingerprint?.slice(0, 12) ?? "n/a"} schema=${meta.schemaVersion ?? "legacy"} ${meta.details.join("; ")}`
|
|
3213
|
+
);
|
|
3214
|
+
return;
|
|
3215
|
+
}
|
|
3216
|
+
logger_default.debug(
|
|
3217
|
+
`[cache] miss reason=${meta.reason} fingerprint=${meta.fingerprint?.slice(0, 12) ?? "n/a"} schema=${meta.schemaVersion ?? "legacy"} ${meta.details.join("; ")}`
|
|
3218
|
+
);
|
|
3219
|
+
}
|
|
3220
|
+
async mergeWithCache(set) {
|
|
3221
|
+
if (!this.options.cache.enabled) {
|
|
3222
|
+
return set;
|
|
3223
|
+
}
|
|
3224
|
+
const { data: existing, meta } = await this.cacheStore.readWithMeta();
|
|
3225
|
+
this.debugCacheRead(meta);
|
|
3226
|
+
if (this.options.cache.strategy === "merge") {
|
|
3227
|
+
for (const value of existing) {
|
|
3228
|
+
set.add(value);
|
|
3229
|
+
}
|
|
3230
|
+
const writeTarget = await this.cacheStore.write(set);
|
|
3231
|
+
if (writeTarget) {
|
|
3232
|
+
logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
|
|
3233
|
+
}
|
|
3234
|
+
} else {
|
|
3235
|
+
if (set.size > 0) {
|
|
3236
|
+
const writeTarget = await this.cacheStore.write(set);
|
|
3237
|
+
if (writeTarget) {
|
|
3238
|
+
logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
|
|
3239
|
+
}
|
|
3240
|
+
} else {
|
|
3241
|
+
return existing;
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
return set;
|
|
3245
|
+
}
|
|
3246
|
+
mergeWithCacheSync(set) {
|
|
3247
|
+
if (!this.options.cache.enabled) {
|
|
3248
|
+
return set;
|
|
3249
|
+
}
|
|
3250
|
+
const { data: existing, meta } = this.cacheStore.readWithMetaSync();
|
|
3251
|
+
this.debugCacheRead(meta);
|
|
3252
|
+
if (this.options.cache.strategy === "merge") {
|
|
3253
|
+
for (const value of existing) {
|
|
3254
|
+
set.add(value);
|
|
3255
|
+
}
|
|
3256
|
+
const writeTarget = this.cacheStore.writeSync(set);
|
|
3257
|
+
if (writeTarget) {
|
|
3258
|
+
logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
|
|
3259
|
+
}
|
|
3260
|
+
} else {
|
|
3261
|
+
if (set.size > 0) {
|
|
3262
|
+
const writeTarget = this.cacheStore.writeSync(set);
|
|
3263
|
+
if (writeTarget) {
|
|
3264
|
+
logger_default.debug(`[cache] stored ${set.size} classes -> ${writeTarget}`);
|
|
3265
|
+
}
|
|
3266
|
+
} else {
|
|
3267
|
+
return existing;
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
return set;
|
|
3271
|
+
}
|
|
3272
|
+
async getClassSet() {
|
|
3273
|
+
await this.runTailwindBuildIfNeeded();
|
|
3274
|
+
const set = await this.collectClassSet();
|
|
3275
|
+
return this.mergeWithCache(set);
|
|
3276
|
+
}
|
|
3277
|
+
getClassSetSync() {
|
|
3278
|
+
if (this.majorVersion === 4) {
|
|
3279
|
+
throw new Error("getClassSetSync is not supported for Tailwind CSS v4 projects. Use getClassSet instead.");
|
|
3280
|
+
}
|
|
3281
|
+
const contexts = this.getContexts();
|
|
3282
|
+
const set = collectClassesFromContexts(contexts, this.options.filter);
|
|
3283
|
+
const merged = this.mergeWithCacheSync(set);
|
|
3284
|
+
if (contexts.length === 0 && merged.size === 0) {
|
|
3285
|
+
return void 0;
|
|
3286
|
+
}
|
|
3287
|
+
return merged;
|
|
3288
|
+
}
|
|
3289
|
+
async extract(options) {
|
|
3290
|
+
const shouldWrite = options?.write ?? this.options.output.enabled;
|
|
3291
|
+
const classSet = await this.getClassSet();
|
|
3292
|
+
const classList = Array.from(classSet);
|
|
3293
|
+
const result = {
|
|
3294
|
+
classList,
|
|
3295
|
+
classSet
|
|
3296
|
+
};
|
|
3297
|
+
if (!shouldWrite || !this.options.output.file) {
|
|
3298
|
+
return result;
|
|
3299
|
+
}
|
|
3300
|
+
const target = path10.resolve(this.options.output.file);
|
|
3301
|
+
await fs10.ensureDir(path10.dirname(target));
|
|
3302
|
+
if (this.options.output.format === "json") {
|
|
3303
|
+
const spaces = typeof this.options.output.pretty === "number" ? this.options.output.pretty : void 0;
|
|
3304
|
+
await fs10.writeJSON(target, classList, { spaces });
|
|
3305
|
+
} else {
|
|
3306
|
+
await fs10.writeFile(target, `${classList.join("\n")}
|
|
3307
|
+
`, "utf8");
|
|
3308
|
+
}
|
|
3309
|
+
logger_default.success(`Tailwind CSS class list saved to ${target.replace(process6.cwd(), ".")}`);
|
|
3310
|
+
return {
|
|
3311
|
+
...result,
|
|
3312
|
+
filename: target
|
|
3313
|
+
};
|
|
3314
|
+
}
|
|
3315
|
+
async clearCache(options) {
|
|
3316
|
+
const result = await this.cacheStore.clear(options);
|
|
3317
|
+
logger_default.debug(
|
|
3318
|
+
`[cache] clear scope=${result.scope} contexts=${result.contextsRemoved} entries=${result.entriesRemoved} files=${result.filesRemoved}`
|
|
3319
|
+
);
|
|
3320
|
+
return result;
|
|
3321
|
+
}
|
|
3322
|
+
// Backwards compatibility helper used by tests and API consumers.
|
|
3323
|
+
extractValidCandidates = extractValidCandidates;
|
|
3324
|
+
async collectContentTokens(options) {
|
|
3325
|
+
return extractProjectCandidatesWithPositions({
|
|
3326
|
+
cwd: options?.cwd ?? this.options.projectRoot,
|
|
3327
|
+
sources: options?.sources ?? this.options.tailwind.v4?.sources ?? []
|
|
3328
|
+
});
|
|
3329
|
+
}
|
|
3330
|
+
async collectContentTokensByFile(options) {
|
|
3331
|
+
const collectContentOptions = {
|
|
3332
|
+
...options?.cwd === void 0 ? {} : { cwd: options.cwd },
|
|
3333
|
+
...options?.sources === void 0 ? {} : { sources: options.sources }
|
|
3334
|
+
};
|
|
3335
|
+
const report = await this.collectContentTokens(collectContentOptions);
|
|
3336
|
+
const groupOptions = {
|
|
3337
|
+
...options?.key === void 0 ? {} : { key: options.key },
|
|
3338
|
+
...options?.stripAbsolutePaths === void 0 ? {} : { stripAbsolutePaths: options.stripAbsolutePaths }
|
|
3339
|
+
};
|
|
3340
|
+
return groupTokensByFile(report, groupOptions);
|
|
3341
|
+
}
|
|
3342
|
+
};
|
|
3343
|
+
|
|
3344
|
+
// src/cli/migrate-config.ts
|
|
3345
|
+
import { parse as parse2 } from "@babel/parser";
|
|
3346
|
+
import generate2 from "@babel/generator";
|
|
3347
|
+
import * as t5 from "@babel/types";
|
|
3348
|
+
import fs11 from "fs-extra";
|
|
3349
|
+
import path11 from "pathe";
|
|
3350
|
+
var DEFAULT_CONFIG_FILENAMES = [
|
|
3351
|
+
"tailwindcss-patch.config.ts",
|
|
3352
|
+
"tailwindcss-patch.config.js",
|
|
3353
|
+
"tailwindcss-patch.config.mjs",
|
|
3354
|
+
"tailwindcss-patch.config.cjs",
|
|
3355
|
+
"tailwindcss-mangle.config.ts",
|
|
3356
|
+
"tailwindcss-mangle.config.js",
|
|
3357
|
+
"tailwindcss-mangle.config.mjs",
|
|
3358
|
+
"tailwindcss-mangle.config.cjs"
|
|
3359
|
+
];
|
|
3360
|
+
var DEFAULT_CONFIG_FILENAME_SET = new Set(DEFAULT_CONFIG_FILENAMES);
|
|
3361
|
+
var DEFAULT_WORKSPACE_IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
3362
|
+
".git",
|
|
3363
|
+
".idea",
|
|
3364
|
+
".turbo",
|
|
3365
|
+
".vscode",
|
|
3366
|
+
".yarn",
|
|
3367
|
+
"coverage",
|
|
3368
|
+
"dist",
|
|
3369
|
+
"node_modules",
|
|
3370
|
+
"tmp"
|
|
3371
|
+
]);
|
|
3372
|
+
var DEFAULT_WORKSPACE_MAX_DEPTH = 6;
|
|
3373
|
+
var MIGRATION_REPORT_KIND = "tw-patch-migrate-report";
|
|
3374
|
+
var MIGRATION_REPORT_SCHEMA_VERSION = 1;
|
|
3375
|
+
var ROOT_LEGACY_KEYS = ["cwd", "overwrite", "tailwind", "features", "output", "applyPatches"];
|
|
3376
|
+
function getPropertyKeyName(property) {
|
|
3377
|
+
if (!property.computed && t5.isIdentifier(property.key)) {
|
|
3378
|
+
return property.key.name;
|
|
3379
|
+
}
|
|
3380
|
+
if (t5.isStringLiteral(property.key)) {
|
|
3381
|
+
return property.key.value;
|
|
3382
|
+
}
|
|
3383
|
+
return void 0;
|
|
3384
|
+
}
|
|
3385
|
+
function findObjectProperty(objectExpression4, name) {
|
|
3386
|
+
for (const property of objectExpression4.properties) {
|
|
3387
|
+
if (!t5.isObjectProperty(property)) {
|
|
3388
|
+
continue;
|
|
3389
|
+
}
|
|
3390
|
+
if (getPropertyKeyName(property) === name) {
|
|
3391
|
+
return property;
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
return void 0;
|
|
3395
|
+
}
|
|
3396
|
+
function findObjectExpressionProperty(objectExpression4, name) {
|
|
3397
|
+
const property = findObjectProperty(objectExpression4, name);
|
|
3398
|
+
if (!property) {
|
|
3399
|
+
return void 0;
|
|
3400
|
+
}
|
|
3401
|
+
if (t5.isObjectExpression(property.value)) {
|
|
3402
|
+
return property.value;
|
|
3403
|
+
}
|
|
3404
|
+
return void 0;
|
|
3405
|
+
}
|
|
3406
|
+
function removeObjectProperty(objectExpression4, property) {
|
|
3407
|
+
const index = objectExpression4.properties.indexOf(property);
|
|
3408
|
+
if (index >= 0) {
|
|
3409
|
+
objectExpression4.properties.splice(index, 1);
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
function hasObjectProperty(objectExpression4, name) {
|
|
3413
|
+
return findObjectProperty(objectExpression4, name) !== void 0;
|
|
3414
|
+
}
|
|
3415
|
+
function keyAsIdentifier(name) {
|
|
3416
|
+
return t5.identifier(name);
|
|
3417
|
+
}
|
|
3418
|
+
function mergeObjectProperties(target, source) {
|
|
3419
|
+
let changed = false;
|
|
3420
|
+
for (const sourceProperty of source.properties) {
|
|
3421
|
+
if (t5.isSpreadElement(sourceProperty)) {
|
|
3422
|
+
target.properties.push(sourceProperty);
|
|
3423
|
+
changed = true;
|
|
3424
|
+
continue;
|
|
3425
|
+
}
|
|
3426
|
+
const sourceKey = getPropertyKeyName(sourceProperty);
|
|
3427
|
+
if (!sourceKey) {
|
|
3428
|
+
target.properties.push(sourceProperty);
|
|
3429
|
+
changed = true;
|
|
3430
|
+
continue;
|
|
3431
|
+
}
|
|
3432
|
+
if (hasObjectProperty(target, sourceKey)) {
|
|
3433
|
+
continue;
|
|
3434
|
+
}
|
|
3435
|
+
target.properties.push(sourceProperty);
|
|
3436
|
+
changed = true;
|
|
3437
|
+
}
|
|
3438
|
+
return changed;
|
|
3439
|
+
}
|
|
3440
|
+
function moveProperty(objectExpression4, from, to, changes, scope) {
|
|
3441
|
+
const source = findObjectProperty(objectExpression4, from);
|
|
3442
|
+
if (!source) {
|
|
3443
|
+
return false;
|
|
3444
|
+
}
|
|
3445
|
+
const target = findObjectProperty(objectExpression4, to);
|
|
3446
|
+
if (!target) {
|
|
3447
|
+
source.key = keyAsIdentifier(to);
|
|
3448
|
+
source.computed = false;
|
|
3449
|
+
source.shorthand = false;
|
|
3450
|
+
changes.add(`${scope}.${from} -> ${scope}.${to}`);
|
|
3451
|
+
return true;
|
|
3452
|
+
}
|
|
3453
|
+
if (t5.isObjectExpression(source.value) && t5.isObjectExpression(target.value)) {
|
|
3454
|
+
const merged = mergeObjectProperties(target.value, source.value);
|
|
3455
|
+
if (merged) {
|
|
3456
|
+
changes.add(`${scope}.${from} merged into ${scope}.${to}`);
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
removeObjectProperty(objectExpression4, source);
|
|
3460
|
+
changes.add(`${scope}.${from} removed (preferred ${scope}.${to})`);
|
|
3461
|
+
return true;
|
|
3462
|
+
}
|
|
3463
|
+
function migrateExtractOptions(extract, changes, scope) {
|
|
3464
|
+
let changed = false;
|
|
3465
|
+
changed = moveProperty(extract, "enabled", "write", changes, scope) || changed;
|
|
3466
|
+
changed = moveProperty(extract, "stripUniversalSelector", "removeUniversalSelector", changes, scope) || changed;
|
|
3467
|
+
return changed;
|
|
3468
|
+
}
|
|
3469
|
+
function migrateTailwindOptions(tailwindcss, changes, scope) {
|
|
3470
|
+
let changed = false;
|
|
3471
|
+
changed = moveProperty(tailwindcss, "package", "packageName", changes, scope) || changed;
|
|
3472
|
+
changed = moveProperty(tailwindcss, "legacy", "v2", changes, scope) || changed;
|
|
3473
|
+
changed = moveProperty(tailwindcss, "classic", "v3", changes, scope) || changed;
|
|
3474
|
+
changed = moveProperty(tailwindcss, "next", "v4", changes, scope) || changed;
|
|
3475
|
+
return changed;
|
|
3476
|
+
}
|
|
3477
|
+
function migrateApplyOptions(apply, changes, scope) {
|
|
3478
|
+
return moveProperty(apply, "exportContext", "exposeContext", changes, scope);
|
|
3479
|
+
}
|
|
3480
|
+
function ensureObjectExpressionProperty(objectExpression4, name, changes, scope) {
|
|
3481
|
+
const existing = findObjectProperty(objectExpression4, name);
|
|
3482
|
+
if (existing) {
|
|
3483
|
+
return t5.isObjectExpression(existing.value) ? existing.value : void 0;
|
|
3484
|
+
}
|
|
3485
|
+
const value = t5.objectExpression([]);
|
|
3486
|
+
objectExpression4.properties.push(t5.objectProperty(keyAsIdentifier(name), value));
|
|
3487
|
+
changes.add(`${scope}.${name} created`);
|
|
3488
|
+
return value;
|
|
3489
|
+
}
|
|
3490
|
+
function moveOverwriteToApply(objectExpression4, changes, scope) {
|
|
3491
|
+
const overwrite = findObjectProperty(objectExpression4, "overwrite");
|
|
3492
|
+
if (!overwrite) {
|
|
3493
|
+
return false;
|
|
3494
|
+
}
|
|
3495
|
+
const apply = ensureObjectExpressionProperty(objectExpression4, "apply", changes, scope);
|
|
3496
|
+
if (!apply) {
|
|
3497
|
+
return false;
|
|
3498
|
+
}
|
|
3499
|
+
const hasApplyOverwrite = hasObjectProperty(apply, "overwrite");
|
|
3500
|
+
if (!hasApplyOverwrite) {
|
|
3501
|
+
apply.properties.push(
|
|
3502
|
+
t5.objectProperty(keyAsIdentifier("overwrite"), overwrite.value)
|
|
3503
|
+
);
|
|
3504
|
+
changes.add(`${scope}.overwrite -> ${scope}.apply.overwrite`);
|
|
3505
|
+
}
|
|
3506
|
+
removeObjectProperty(objectExpression4, overwrite);
|
|
3507
|
+
return true;
|
|
3508
|
+
}
|
|
3509
|
+
function hasAnyRootLegacyKeys(objectExpression4) {
|
|
3510
|
+
return ROOT_LEGACY_KEYS.some((key) => hasObjectProperty(objectExpression4, key));
|
|
3511
|
+
}
|
|
3512
|
+
function migrateOptionObject(objectExpression4, scope, changes) {
|
|
3513
|
+
let changed = false;
|
|
3514
|
+
changed = moveProperty(objectExpression4, "cwd", "projectRoot", changes, scope) || changed;
|
|
3515
|
+
changed = moveProperty(objectExpression4, "tailwind", "tailwindcss", changes, scope) || changed;
|
|
3516
|
+
changed = moveProperty(objectExpression4, "features", "apply", changes, scope) || changed;
|
|
3517
|
+
changed = moveProperty(objectExpression4, "applyPatches", "apply", changes, scope) || changed;
|
|
3518
|
+
changed = moveProperty(objectExpression4, "output", "extract", changes, scope) || changed;
|
|
3519
|
+
changed = moveOverwriteToApply(objectExpression4, changes, scope) || changed;
|
|
3520
|
+
const extract = findObjectExpressionProperty(objectExpression4, "extract");
|
|
3521
|
+
if (extract) {
|
|
3522
|
+
changed = migrateExtractOptions(extract, changes, scope) || changed;
|
|
3523
|
+
}
|
|
3524
|
+
const tailwindcss = findObjectExpressionProperty(objectExpression4, "tailwindcss");
|
|
3525
|
+
if (tailwindcss) {
|
|
3526
|
+
changed = migrateTailwindOptions(tailwindcss, changes, scope) || changed;
|
|
3527
|
+
}
|
|
3528
|
+
const apply = findObjectExpressionProperty(objectExpression4, "apply");
|
|
3529
|
+
if (apply) {
|
|
3530
|
+
changed = migrateApplyOptions(apply, changes, scope) || changed;
|
|
3531
|
+
}
|
|
3532
|
+
return changed;
|
|
3533
|
+
}
|
|
3534
|
+
function unwrapExpression(node) {
|
|
3535
|
+
let current = node;
|
|
3536
|
+
while (t5.isTSAsExpression(current) || t5.isTSSatisfiesExpression(current) || t5.isTSTypeAssertion(current) || t5.isParenthesizedExpression(current)) {
|
|
3537
|
+
current = current.expression;
|
|
3538
|
+
}
|
|
3539
|
+
return current;
|
|
3540
|
+
}
|
|
3541
|
+
function resolveObjectExpressionFromExpression(expression) {
|
|
3542
|
+
const unwrapped = unwrapExpression(expression);
|
|
3543
|
+
if (t5.isObjectExpression(unwrapped)) {
|
|
3544
|
+
return unwrapped;
|
|
3545
|
+
}
|
|
3546
|
+
if (t5.isCallExpression(unwrapped)) {
|
|
3547
|
+
const [firstArg] = unwrapped.arguments;
|
|
3548
|
+
if (!firstArg || !t5.isExpression(firstArg)) {
|
|
3549
|
+
return void 0;
|
|
3550
|
+
}
|
|
3551
|
+
const firstArgUnwrapped = unwrapExpression(firstArg);
|
|
3552
|
+
if (t5.isObjectExpression(firstArgUnwrapped)) {
|
|
3553
|
+
return firstArgUnwrapped;
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
return void 0;
|
|
3557
|
+
}
|
|
3558
|
+
function resolveObjectExpressionFromProgram(program, name) {
|
|
3559
|
+
for (const statement of program.body) {
|
|
3560
|
+
if (!t5.isVariableDeclaration(statement)) {
|
|
3561
|
+
continue;
|
|
3562
|
+
}
|
|
3563
|
+
for (const declaration of statement.declarations) {
|
|
3564
|
+
if (!t5.isIdentifier(declaration.id) || declaration.id.name !== name || !declaration.init) {
|
|
3565
|
+
continue;
|
|
3566
|
+
}
|
|
3567
|
+
const objectExpression4 = resolveObjectExpressionFromExpression(declaration.init);
|
|
3568
|
+
if (objectExpression4) {
|
|
3569
|
+
return objectExpression4;
|
|
3570
|
+
}
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
return void 0;
|
|
3574
|
+
}
|
|
3575
|
+
function resolveRootConfigObjectExpression(program) {
|
|
3576
|
+
for (const statement of program.body) {
|
|
3577
|
+
if (!t5.isExportDefaultDeclaration(statement)) {
|
|
3578
|
+
continue;
|
|
3579
|
+
}
|
|
3580
|
+
const declaration = statement.declaration;
|
|
3581
|
+
if (t5.isIdentifier(declaration)) {
|
|
3582
|
+
return resolveObjectExpressionFromProgram(program, declaration.name);
|
|
3583
|
+
}
|
|
3584
|
+
const objectExpression4 = resolveObjectExpressionFromExpression(declaration);
|
|
3585
|
+
if (objectExpression4) {
|
|
3586
|
+
return objectExpression4;
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
return void 0;
|
|
3590
|
+
}
|
|
3591
|
+
function migrateConfigSource(source) {
|
|
3592
|
+
const ast = parse2(source, {
|
|
3593
|
+
sourceType: "module",
|
|
3594
|
+
plugins: ["typescript", "jsx"]
|
|
3595
|
+
});
|
|
3596
|
+
const root = resolveRootConfigObjectExpression(ast.program);
|
|
3597
|
+
if (!root) {
|
|
3598
|
+
return {
|
|
3599
|
+
changed: false,
|
|
3600
|
+
code: source,
|
|
3601
|
+
changes: []
|
|
3602
|
+
};
|
|
3603
|
+
}
|
|
3604
|
+
const changes = /* @__PURE__ */ new Set();
|
|
3605
|
+
let changed = false;
|
|
3606
|
+
const registry = findObjectExpressionProperty(root, "registry");
|
|
3607
|
+
if (registry) {
|
|
3608
|
+
changed = migrateOptionObject(registry, "registry", changes) || changed;
|
|
3609
|
+
}
|
|
3610
|
+
const patch = findObjectExpressionProperty(root, "patch");
|
|
3611
|
+
if (patch) {
|
|
3612
|
+
changed = migrateOptionObject(patch, "patch", changes) || changed;
|
|
3613
|
+
}
|
|
3614
|
+
if (hasAnyRootLegacyKeys(root)) {
|
|
3615
|
+
changed = migrateOptionObject(root, "root", changes) || changed;
|
|
3616
|
+
}
|
|
3617
|
+
if (!changed) {
|
|
3618
|
+
return {
|
|
3619
|
+
changed: false,
|
|
3620
|
+
code: source,
|
|
3621
|
+
changes: []
|
|
3622
|
+
};
|
|
3623
|
+
}
|
|
3624
|
+
const generated = generate2(ast, {
|
|
3625
|
+
comments: true
|
|
3626
|
+
}).code;
|
|
3627
|
+
const code = source.endsWith("\n") ? `${generated}
|
|
3628
|
+
` : generated;
|
|
3629
|
+
return {
|
|
3630
|
+
changed: true,
|
|
3631
|
+
code,
|
|
3632
|
+
changes: [...changes]
|
|
3633
|
+
};
|
|
3634
|
+
}
|
|
3635
|
+
function resolveTargetFiles(cwd, files) {
|
|
3636
|
+
const candidates = files && files.length > 0 ? files : [...DEFAULT_CONFIG_FILENAMES];
|
|
3637
|
+
const resolved = /* @__PURE__ */ new Set();
|
|
3638
|
+
for (const file of candidates) {
|
|
3639
|
+
resolved.add(path11.resolve(cwd, file));
|
|
3640
|
+
}
|
|
3641
|
+
return [...resolved];
|
|
3642
|
+
}
|
|
3643
|
+
async function collectWorkspaceConfigFiles(cwd, maxDepth) {
|
|
3644
|
+
const files = /* @__PURE__ */ new Set();
|
|
3645
|
+
const queue = [{ dir: cwd, depth: 0 }];
|
|
3646
|
+
while (queue.length > 0) {
|
|
3647
|
+
const current = queue.shift();
|
|
3648
|
+
if (!current) {
|
|
3649
|
+
continue;
|
|
3650
|
+
}
|
|
3651
|
+
const { dir, depth } = current;
|
|
3652
|
+
let entries;
|
|
3653
|
+
try {
|
|
3654
|
+
entries = await fs11.readdir(dir, { withFileTypes: true });
|
|
3655
|
+
} catch {
|
|
3656
|
+
continue;
|
|
3657
|
+
}
|
|
3658
|
+
for (const entry of entries) {
|
|
3659
|
+
const absolutePath = path11.resolve(dir, entry.name);
|
|
3660
|
+
if (entry.isFile() && DEFAULT_CONFIG_FILENAME_SET.has(entry.name)) {
|
|
3661
|
+
files.add(absolutePath);
|
|
3662
|
+
continue;
|
|
3663
|
+
}
|
|
3664
|
+
if (!entry.isDirectory()) {
|
|
3665
|
+
continue;
|
|
3666
|
+
}
|
|
3667
|
+
if (DEFAULT_WORKSPACE_IGNORED_DIRS.has(entry.name)) {
|
|
3668
|
+
continue;
|
|
3669
|
+
}
|
|
3670
|
+
if (depth >= maxDepth) {
|
|
3671
|
+
continue;
|
|
3672
|
+
}
|
|
3673
|
+
queue.push({ dir: absolutePath, depth: depth + 1 });
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
return [...files].sort((a, b) => a.localeCompare(b));
|
|
3677
|
+
}
|
|
3678
|
+
function resolveBackupRelativePath(cwd, file) {
|
|
3679
|
+
const relative = path11.relative(cwd, file);
|
|
3680
|
+
const isExternal = relative.startsWith("..") || path11.isAbsolute(relative);
|
|
3681
|
+
if (isExternal) {
|
|
3682
|
+
const sanitized = file.replace(/[:/\\]+/g, "_");
|
|
3683
|
+
return path11.join("__external__", `${sanitized}.bak`);
|
|
3684
|
+
}
|
|
3685
|
+
return `${relative}.bak`;
|
|
3686
|
+
}
|
|
3687
|
+
function normalizePattern(pattern) {
|
|
3688
|
+
return pattern.replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "");
|
|
3689
|
+
}
|
|
3690
|
+
function globToRegExp(globPattern) {
|
|
3691
|
+
const normalized = normalizePattern(globPattern);
|
|
3692
|
+
let pattern = "";
|
|
3693
|
+
for (let i = 0; i < normalized.length; i += 1) {
|
|
3694
|
+
const char = normalized[i];
|
|
3695
|
+
if (char === "*") {
|
|
3696
|
+
if (normalized[i + 1] === "*") {
|
|
3697
|
+
pattern += ".*";
|
|
3698
|
+
i += 1;
|
|
3699
|
+
} else {
|
|
3700
|
+
pattern += "[^/]*";
|
|
3701
|
+
}
|
|
3702
|
+
continue;
|
|
3703
|
+
}
|
|
3704
|
+
if (char === "?") {
|
|
3705
|
+
pattern += "[^/]";
|
|
3706
|
+
continue;
|
|
3707
|
+
}
|
|
3708
|
+
if ("\\^$+?.()|{}[]".includes(char)) {
|
|
3709
|
+
pattern += `\\${char}`;
|
|
3710
|
+
continue;
|
|
3711
|
+
}
|
|
3712
|
+
pattern += char;
|
|
3713
|
+
}
|
|
3714
|
+
return new RegExp(`^${pattern}$`);
|
|
3715
|
+
}
|
|
3716
|
+
function toPatternList(patterns) {
|
|
3717
|
+
if (!patterns || patterns.length === 0) {
|
|
3718
|
+
return [];
|
|
3719
|
+
}
|
|
3720
|
+
return patterns.map((pattern) => pattern.trim()).filter(Boolean).map(globToRegExp);
|
|
3721
|
+
}
|
|
3722
|
+
function normalizeFileForPattern(file, cwd) {
|
|
3723
|
+
const relative = path11.relative(cwd, file);
|
|
3724
|
+
if (!relative.startsWith("..") && !path11.isAbsolute(relative)) {
|
|
3725
|
+
return relative.replace(/\\/g, "/");
|
|
3726
|
+
}
|
|
3727
|
+
return file.replace(/\\/g, "/");
|
|
3728
|
+
}
|
|
3729
|
+
function filterTargetFiles(targetFiles, cwd, include, exclude) {
|
|
3730
|
+
const includePatterns = toPatternList(include);
|
|
3731
|
+
const excludePatterns = toPatternList(exclude);
|
|
3732
|
+
if (includePatterns.length === 0 && excludePatterns.length === 0) {
|
|
3733
|
+
return targetFiles;
|
|
3734
|
+
}
|
|
3735
|
+
return targetFiles.filter((file) => {
|
|
3736
|
+
const normalized = normalizeFileForPattern(file, cwd);
|
|
3737
|
+
const inInclude = includePatterns.length === 0 || includePatterns.some((pattern) => pattern.test(normalized));
|
|
3738
|
+
if (!inInclude) {
|
|
3739
|
+
return false;
|
|
3740
|
+
}
|
|
3741
|
+
const inExclude = excludePatterns.some((pattern) => pattern.test(normalized));
|
|
3742
|
+
return !inExclude;
|
|
3743
|
+
});
|
|
3744
|
+
}
|
|
3745
|
+
async function migrateConfigFiles(options) {
|
|
3746
|
+
const cwd = path11.resolve(options.cwd);
|
|
3747
|
+
const dryRun = options.dryRun ?? false;
|
|
3748
|
+
const rollbackOnError = options.rollbackOnError ?? true;
|
|
3749
|
+
const backupDirectory = options.backupDir ? path11.resolve(cwd, options.backupDir) : void 0;
|
|
3750
|
+
const maxDepth = options.maxDepth ?? DEFAULT_WORKSPACE_MAX_DEPTH;
|
|
3751
|
+
const discoveredTargetFiles = options.files && options.files.length > 0 ? resolveTargetFiles(cwd, options.files) : options.workspace ? await collectWorkspaceConfigFiles(cwd, maxDepth) : resolveTargetFiles(cwd);
|
|
3752
|
+
const targetFiles = filterTargetFiles(discoveredTargetFiles, cwd, options.include, options.exclude);
|
|
3753
|
+
const entries = [];
|
|
3754
|
+
let scannedFiles = 0;
|
|
3755
|
+
let changedFiles = 0;
|
|
3756
|
+
let writtenFiles = 0;
|
|
3757
|
+
let backupsWritten = 0;
|
|
3758
|
+
let unchangedFiles = 0;
|
|
3759
|
+
let missingFiles = 0;
|
|
3760
|
+
const wroteEntries = [];
|
|
3761
|
+
for (const file of targetFiles) {
|
|
3762
|
+
const exists = await fs11.pathExists(file);
|
|
3763
|
+
if (!exists) {
|
|
3764
|
+
missingFiles += 1;
|
|
3765
|
+
continue;
|
|
3766
|
+
}
|
|
3767
|
+
scannedFiles += 1;
|
|
3768
|
+
const source = await fs11.readFile(file, "utf8");
|
|
3769
|
+
const migrated = migrateConfigSource(source);
|
|
3770
|
+
const entry = {
|
|
3771
|
+
file,
|
|
3772
|
+
changed: migrated.changed,
|
|
3773
|
+
written: false,
|
|
3774
|
+
rolledBack: false,
|
|
3775
|
+
changes: migrated.changes
|
|
3776
|
+
};
|
|
3777
|
+
entries.push(entry);
|
|
3778
|
+
if (migrated.changed) {
|
|
3779
|
+
changedFiles += 1;
|
|
3780
|
+
if (!dryRun) {
|
|
3781
|
+
try {
|
|
3782
|
+
if (backupDirectory) {
|
|
3783
|
+
const backupRelativePath = resolveBackupRelativePath(cwd, file);
|
|
3784
|
+
const backupFile = path11.resolve(backupDirectory, backupRelativePath);
|
|
3785
|
+
await fs11.ensureDir(path11.dirname(backupFile));
|
|
3786
|
+
await fs11.writeFile(backupFile, source, "utf8");
|
|
3787
|
+
entry.backupFile = backupFile;
|
|
3788
|
+
backupsWritten += 1;
|
|
3789
|
+
}
|
|
3790
|
+
await fs11.writeFile(file, migrated.code, "utf8");
|
|
3791
|
+
entry.written = true;
|
|
3792
|
+
wroteEntries.push({ file, source, entry });
|
|
3793
|
+
writtenFiles += 1;
|
|
3794
|
+
} catch (error) {
|
|
3795
|
+
let rollbackCount = 0;
|
|
3796
|
+
if (rollbackOnError && wroteEntries.length > 0) {
|
|
3797
|
+
for (const written of [...wroteEntries].reverse()) {
|
|
3798
|
+
try {
|
|
3799
|
+
await fs11.writeFile(written.file, written.source, "utf8");
|
|
3800
|
+
written.entry.written = false;
|
|
3801
|
+
written.entry.rolledBack = true;
|
|
3802
|
+
rollbackCount += 1;
|
|
3803
|
+
} catch {
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
writtenFiles = Math.max(0, writtenFiles - rollbackCount);
|
|
3807
|
+
}
|
|
3808
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
3809
|
+
const rollbackHint = rollbackOnError && rollbackCount > 0 ? ` Rolled back ${rollbackCount} previously written file(s).` : "";
|
|
3810
|
+
throw new Error(`Failed to write migrated config "${file}": ${reason}.${rollbackHint}`);
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
} else {
|
|
3814
|
+
unchangedFiles += 1;
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
return {
|
|
3818
|
+
reportKind: MIGRATION_REPORT_KIND,
|
|
3819
|
+
schemaVersion: MIGRATION_REPORT_SCHEMA_VERSION,
|
|
3820
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3821
|
+
tool: {
|
|
3822
|
+
name: pkgName,
|
|
3823
|
+
version: pkgVersion
|
|
3824
|
+
},
|
|
3825
|
+
cwd,
|
|
3826
|
+
dryRun,
|
|
3827
|
+
rollbackOnError,
|
|
3828
|
+
...backupDirectory ? { backupDirectory } : {},
|
|
3829
|
+
scannedFiles,
|
|
3830
|
+
changedFiles,
|
|
3831
|
+
writtenFiles,
|
|
3832
|
+
backupsWritten,
|
|
3833
|
+
unchangedFiles,
|
|
3834
|
+
missingFiles,
|
|
3835
|
+
entries
|
|
3836
|
+
};
|
|
3837
|
+
}
|
|
3838
|
+
async function restoreConfigFiles(options) {
|
|
3839
|
+
const cwd = path11.resolve(options.cwd);
|
|
3840
|
+
const dryRun = options.dryRun ?? false;
|
|
3841
|
+
const strict = options.strict ?? false;
|
|
3842
|
+
const reportFile = path11.resolve(cwd, options.reportFile);
|
|
3843
|
+
const report = await fs11.readJSON(reportFile);
|
|
3844
|
+
if (report.reportKind !== void 0 && report.reportKind !== MIGRATION_REPORT_KIND) {
|
|
3845
|
+
throw new Error(`Unsupported report kind "${report.reportKind}" in ${reportFile}.`);
|
|
3846
|
+
}
|
|
3847
|
+
if (report.schemaVersion !== void 0 && (!Number.isInteger(report.schemaVersion) || report.schemaVersion > MIGRATION_REPORT_SCHEMA_VERSION)) {
|
|
3848
|
+
throw new Error(
|
|
3849
|
+
`Unsupported report schema version "${String(report.schemaVersion)}" in ${reportFile}. Current supported version is ${MIGRATION_REPORT_SCHEMA_VERSION}.`
|
|
3850
|
+
);
|
|
3851
|
+
}
|
|
3852
|
+
const entries = Array.isArray(report.entries) ? report.entries : [];
|
|
3853
|
+
let scannedEntries = 0;
|
|
3854
|
+
let restorableEntries = 0;
|
|
3855
|
+
let restoredFiles = 0;
|
|
3856
|
+
let missingBackups = 0;
|
|
3857
|
+
let skippedEntries = 0;
|
|
3858
|
+
const restored = [];
|
|
3859
|
+
for (const entry of entries) {
|
|
3860
|
+
scannedEntries += 1;
|
|
3861
|
+
const targetFile = entry.file ? path11.resolve(entry.file) : void 0;
|
|
3862
|
+
const backupFile = entry.backupFile ? path11.resolve(entry.backupFile) : void 0;
|
|
3863
|
+
if (!targetFile || !backupFile) {
|
|
3864
|
+
skippedEntries += 1;
|
|
3865
|
+
continue;
|
|
3866
|
+
}
|
|
3867
|
+
restorableEntries += 1;
|
|
3868
|
+
const backupExists = await fs11.pathExists(backupFile);
|
|
3869
|
+
if (!backupExists) {
|
|
3870
|
+
missingBackups += 1;
|
|
3871
|
+
continue;
|
|
3872
|
+
}
|
|
3873
|
+
if (!dryRun) {
|
|
3874
|
+
const backupContent = await fs11.readFile(backupFile, "utf8");
|
|
3875
|
+
await fs11.ensureDir(path11.dirname(targetFile));
|
|
3876
|
+
await fs11.writeFile(targetFile, backupContent, "utf8");
|
|
3877
|
+
}
|
|
3878
|
+
restoredFiles += 1;
|
|
3879
|
+
restored.push(targetFile);
|
|
3880
|
+
}
|
|
3881
|
+
if (strict && missingBackups > 0) {
|
|
3882
|
+
throw new Error(`Restore failed: ${missingBackups} backup file(s) missing in report ${reportFile}.`);
|
|
3883
|
+
}
|
|
3884
|
+
return {
|
|
3885
|
+
cwd,
|
|
3886
|
+
reportFile,
|
|
3887
|
+
...report.reportKind === void 0 ? {} : { reportKind: report.reportKind },
|
|
3888
|
+
...report.schemaVersion === void 0 ? {} : { reportSchemaVersion: report.schemaVersion },
|
|
3889
|
+
dryRun,
|
|
3890
|
+
strict,
|
|
3891
|
+
scannedEntries,
|
|
3892
|
+
restorableEntries,
|
|
3893
|
+
restoredFiles,
|
|
3894
|
+
missingBackups,
|
|
3895
|
+
skippedEntries,
|
|
3896
|
+
restored
|
|
3897
|
+
};
|
|
3898
|
+
}
|
|
3899
|
+
|
|
3900
|
+
// src/cli/commands.ts
|
|
3901
|
+
import process7 from "process";
|
|
3902
|
+
import { CONFIG_NAME, getConfig, initConfig } from "@tailwindcss-mangle/config";
|
|
3903
|
+
|
|
3904
|
+
// ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
|
|
3905
|
+
function isPlainObject(value) {
|
|
3906
|
+
if (value === null || typeof value !== "object") {
|
|
3907
|
+
return false;
|
|
3908
|
+
}
|
|
3909
|
+
const prototype = Object.getPrototypeOf(value);
|
|
3910
|
+
if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
|
|
3911
|
+
return false;
|
|
3912
|
+
}
|
|
3913
|
+
if (Symbol.iterator in value) {
|
|
3914
|
+
return false;
|
|
3915
|
+
}
|
|
3916
|
+
if (Symbol.toStringTag in value) {
|
|
3917
|
+
return Object.prototype.toString.call(value) === "[object Module]";
|
|
3918
|
+
}
|
|
3919
|
+
return true;
|
|
3920
|
+
}
|
|
3921
|
+
function _defu(baseObject, defaults, namespace = ".", merger) {
|
|
3922
|
+
if (!isPlainObject(defaults)) {
|
|
3923
|
+
return _defu(baseObject, {}, namespace, merger);
|
|
3924
|
+
}
|
|
3925
|
+
const object = Object.assign({}, defaults);
|
|
3926
|
+
for (const key in baseObject) {
|
|
3927
|
+
if (key === "__proto__" || key === "constructor") {
|
|
3928
|
+
continue;
|
|
3929
|
+
}
|
|
3930
|
+
const value = baseObject[key];
|
|
3931
|
+
if (value === null || value === void 0) {
|
|
3932
|
+
continue;
|
|
3933
|
+
}
|
|
3934
|
+
if (merger && merger(object, key, value, namespace)) {
|
|
3935
|
+
continue;
|
|
3936
|
+
}
|
|
3937
|
+
if (Array.isArray(value) && Array.isArray(object[key])) {
|
|
3938
|
+
object[key] = [...value, ...object[key]];
|
|
3939
|
+
} else if (isPlainObject(value) && isPlainObject(object[key])) {
|
|
3940
|
+
object[key] = _defu(
|
|
3941
|
+
value,
|
|
3942
|
+
object[key],
|
|
3943
|
+
(namespace ? `${namespace}.` : "") + key.toString(),
|
|
3944
|
+
merger
|
|
3945
|
+
);
|
|
3946
|
+
} else {
|
|
3947
|
+
object[key] = value;
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
return object;
|
|
3951
|
+
}
|
|
3952
|
+
function createDefu(merger) {
|
|
3953
|
+
return (...arguments_) => (
|
|
3954
|
+
// eslint-disable-next-line unicorn/no-array-reduce
|
|
3955
|
+
arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
|
|
3956
|
+
);
|
|
3957
|
+
}
|
|
3958
|
+
var defu = createDefu();
|
|
3959
|
+
var defuFn = createDefu((object, key, currentValue) => {
|
|
3960
|
+
if (object[key] !== void 0 && typeof currentValue === "function") {
|
|
3961
|
+
object[key] = currentValue(object[key]);
|
|
3962
|
+
return true;
|
|
3963
|
+
}
|
|
3964
|
+
});
|
|
3965
|
+
var defuArrayFn = createDefu((object, key, currentValue) => {
|
|
3966
|
+
if (Array.isArray(object[key]) && typeof currentValue === "function") {
|
|
3967
|
+
object[key] = currentValue(object[key]);
|
|
3968
|
+
return true;
|
|
3969
|
+
}
|
|
3970
|
+
});
|
|
3971
|
+
|
|
3972
|
+
// ../shared/src/utils.ts
|
|
3973
|
+
var defuOverrideArray = createDefu((obj, key, value) => {
|
|
3974
|
+
if (Array.isArray(obj[key]) && Array.isArray(value)) {
|
|
3975
|
+
obj[key] = value;
|
|
3976
|
+
return true;
|
|
3977
|
+
}
|
|
3978
|
+
});
|
|
3979
|
+
var preserveClassNames = [
|
|
3980
|
+
// https://tailwindcss.com/docs/transition-timing-function start
|
|
3981
|
+
// https://github.com/sonofmagic/tailwindcss-mangle/issues/21
|
|
3982
|
+
"ease-out",
|
|
3983
|
+
"ease-linear",
|
|
3984
|
+
"ease-in",
|
|
3985
|
+
"ease-in-out"
|
|
3986
|
+
// https://tailwindcss.com/docs/transition-timing-function end
|
|
3987
|
+
];
|
|
3988
|
+
var preserveClassNamesMap = preserveClassNames.reduce((acc, cur) => {
|
|
3989
|
+
acc[cur] = true;
|
|
3990
|
+
return acc;
|
|
3991
|
+
}, {});
|
|
3992
|
+
var acceptChars = [..."abcdefghijklmnopqrstuvwxyz"];
|
|
3993
|
+
|
|
3994
|
+
// src/cli/commands.ts
|
|
3995
|
+
import cac from "cac";
|
|
3996
|
+
import fs12 from "fs-extra";
|
|
3997
|
+
import path12 from "pathe";
|
|
3998
|
+
var tailwindcssPatchCommands = ["install", "extract", "tokens", "init", "migrate", "restore", "validate", "status"];
|
|
3999
|
+
var VALIDATE_EXIT_CODES = {
|
|
4000
|
+
OK: 0,
|
|
4001
|
+
REPORT_INCOMPATIBLE: 21,
|
|
4002
|
+
MISSING_BACKUPS: 22,
|
|
4003
|
+
IO_ERROR: 23,
|
|
4004
|
+
UNKNOWN_ERROR: 24
|
|
4005
|
+
};
|
|
4006
|
+
var VALIDATE_FAILURE_REASONS = [
|
|
4007
|
+
"report-incompatible",
|
|
4008
|
+
"missing-backups",
|
|
4009
|
+
"io-error",
|
|
4010
|
+
"unknown-error"
|
|
4011
|
+
];
|
|
4012
|
+
var IO_ERROR_CODES = /* @__PURE__ */ new Set(["ENOENT", "EACCES", "EPERM", "EISDIR", "ENOTDIR", "EMFILE", "ENFILE"]);
|
|
4013
|
+
function isNodeError(error) {
|
|
4014
|
+
return !!error && typeof error === "object" && ("code" in error || "message" in error);
|
|
4015
|
+
}
|
|
4016
|
+
function classifyValidateError(error) {
|
|
4017
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4018
|
+
if (message.startsWith("Unsupported report kind") || message.startsWith("Unsupported report schema version")) {
|
|
4019
|
+
return {
|
|
4020
|
+
reason: "report-incompatible",
|
|
4021
|
+
exitCode: VALIDATE_EXIT_CODES.REPORT_INCOMPATIBLE,
|
|
4022
|
+
message
|
|
4023
|
+
};
|
|
4024
|
+
}
|
|
4025
|
+
if (message.startsWith("Restore failed:")) {
|
|
4026
|
+
return {
|
|
4027
|
+
reason: "missing-backups",
|
|
4028
|
+
exitCode: VALIDATE_EXIT_CODES.MISSING_BACKUPS,
|
|
4029
|
+
message
|
|
4030
|
+
};
|
|
4031
|
+
}
|
|
4032
|
+
if (isNodeError(error) && typeof error.code === "string" && IO_ERROR_CODES.has(error.code)) {
|
|
4033
|
+
return {
|
|
4034
|
+
reason: "io-error",
|
|
4035
|
+
exitCode: VALIDATE_EXIT_CODES.IO_ERROR,
|
|
4036
|
+
message
|
|
4037
|
+
};
|
|
4038
|
+
}
|
|
4039
|
+
return {
|
|
4040
|
+
reason: "unknown-error",
|
|
4041
|
+
exitCode: VALIDATE_EXIT_CODES.UNKNOWN_ERROR,
|
|
4042
|
+
message
|
|
4043
|
+
};
|
|
4044
|
+
}
|
|
4045
|
+
var ValidateCommandError = class extends Error {
|
|
4046
|
+
reason;
|
|
4047
|
+
exitCode;
|
|
4048
|
+
constructor(summary, options) {
|
|
4049
|
+
super(summary.message, options);
|
|
4050
|
+
this.name = "ValidateCommandError";
|
|
4051
|
+
this.reason = summary.reason;
|
|
4052
|
+
this.exitCode = summary.exitCode;
|
|
4053
|
+
}
|
|
4054
|
+
};
|
|
4055
|
+
var TOKEN_FORMATS = ["json", "lines", "grouped-json"];
|
|
4056
|
+
var DEFAULT_TOKEN_REPORT = ".tw-patch/tw-token-report.json";
|
|
4057
|
+
function formatTokenLine(entry) {
|
|
4058
|
+
return `${entry.relativeFile}:${entry.line}:${entry.column} ${entry.rawCandidate} (${entry.start}-${entry.end})`;
|
|
4059
|
+
}
|
|
4060
|
+
function formatGroupedPreview(map, limit = 3) {
|
|
4061
|
+
const files = Object.keys(map);
|
|
4062
|
+
if (!files.length) {
|
|
4063
|
+
return { preview: "", moreFiles: 0 };
|
|
4064
|
+
}
|
|
4065
|
+
const lines = files.slice(0, limit).map((file) => {
|
|
4066
|
+
const tokens = map[file] ?? [];
|
|
4067
|
+
const sample = tokens.slice(0, 3).map((token) => token.rawCandidate).join(", ");
|
|
4068
|
+
const suffix = tokens.length > 3 ? ", \u2026" : "";
|
|
4069
|
+
return `${file}: ${tokens.length} tokens (${sample}${suffix})`;
|
|
4070
|
+
});
|
|
4071
|
+
return {
|
|
4072
|
+
preview: lines.join("\n"),
|
|
4073
|
+
moreFiles: Math.max(0, files.length - limit)
|
|
4074
|
+
};
|
|
4075
|
+
}
|
|
4076
|
+
function resolveCwd(rawCwd) {
|
|
4077
|
+
if (!rawCwd) {
|
|
4078
|
+
return process7.cwd();
|
|
4079
|
+
}
|
|
4080
|
+
return path12.resolve(rawCwd);
|
|
4081
|
+
}
|
|
4082
|
+
function createDefaultRunner(factory) {
|
|
4083
|
+
let promise;
|
|
4084
|
+
return () => {
|
|
4085
|
+
if (!promise) {
|
|
4086
|
+
promise = factory();
|
|
4087
|
+
}
|
|
4088
|
+
return promise;
|
|
4089
|
+
};
|
|
4090
|
+
}
|
|
4091
|
+
async function loadPatchOptionsForCwd(cwd, overrides) {
|
|
4092
|
+
const { config } = await getConfig(cwd);
|
|
4093
|
+
const legacyConfig = config;
|
|
4094
|
+
const base = config?.registry ? fromUnifiedConfig(config.registry) : legacyConfig?.patch ? fromLegacyOptions({ patch: legacyConfig.patch }) : {};
|
|
4095
|
+
const merged = defu(overrides ?? {}, base);
|
|
4096
|
+
return merged;
|
|
4097
|
+
}
|
|
4098
|
+
function createCommandContext(cli, command, commandName, args, cwd) {
|
|
4099
|
+
let cachedOptions;
|
|
4100
|
+
let cachedPatcher;
|
|
4101
|
+
let cachedConfig;
|
|
4102
|
+
const loadPatchOptionsForContext = (overrides) => {
|
|
4103
|
+
if (overrides) {
|
|
4104
|
+
return loadPatchOptionsForCwd(cwd, overrides);
|
|
4105
|
+
}
|
|
4106
|
+
if (!cachedOptions) {
|
|
4107
|
+
cachedOptions = loadPatchOptionsForCwd(cwd);
|
|
4108
|
+
}
|
|
4109
|
+
return cachedOptions;
|
|
4110
|
+
};
|
|
4111
|
+
const createPatcherForContext = async (overrides) => {
|
|
4112
|
+
if (overrides) {
|
|
4113
|
+
const patchOptions = await loadPatchOptionsForCwd(cwd, overrides);
|
|
4114
|
+
return new TailwindcssPatcher(patchOptions);
|
|
4115
|
+
}
|
|
4116
|
+
if (!cachedPatcher) {
|
|
4117
|
+
cachedPatcher = loadPatchOptionsForContext().then((options) => new TailwindcssPatcher(options));
|
|
4118
|
+
}
|
|
4119
|
+
return cachedPatcher;
|
|
4120
|
+
};
|
|
4121
|
+
return {
|
|
4122
|
+
cli,
|
|
4123
|
+
command,
|
|
4124
|
+
commandName,
|
|
4125
|
+
args,
|
|
4126
|
+
cwd,
|
|
4127
|
+
logger: logger_default,
|
|
4128
|
+
loadConfig: () => {
|
|
4129
|
+
if (!cachedConfig) {
|
|
4130
|
+
cachedConfig = getConfig(cwd);
|
|
4131
|
+
}
|
|
4132
|
+
return cachedConfig;
|
|
4133
|
+
},
|
|
4134
|
+
loadPatchOptions: loadPatchOptionsForContext,
|
|
4135
|
+
createPatcher: createPatcherForContext
|
|
4136
|
+
};
|
|
4137
|
+
}
|
|
4138
|
+
function createCwdOptionDefinition(description = "Working directory") {
|
|
4139
|
+
return {
|
|
4140
|
+
flags: "--cwd <dir>",
|
|
4141
|
+
description,
|
|
4142
|
+
config: { default: process7.cwd() }
|
|
4143
|
+
};
|
|
4144
|
+
}
|
|
4145
|
+
function buildDefaultCommandDefinitions() {
|
|
4146
|
+
return {
|
|
4147
|
+
install: {
|
|
4148
|
+
description: "Apply Tailwind CSS runtime patches",
|
|
4149
|
+
optionDefs: [createCwdOptionDefinition()]
|
|
4150
|
+
},
|
|
4151
|
+
extract: {
|
|
4152
|
+
description: "Collect generated class names into a cache file",
|
|
4153
|
+
optionDefs: [
|
|
4154
|
+
createCwdOptionDefinition(),
|
|
4155
|
+
{ flags: "--output <file>", description: "Override output file path" },
|
|
4156
|
+
{ flags: "--format <format>", description: "Output format (json|lines)" },
|
|
4157
|
+
{ flags: "--css <file>", description: "Tailwind CSS entry CSS when using v4" },
|
|
4158
|
+
{ flags: "--no-write", description: "Skip writing to disk" }
|
|
4159
|
+
]
|
|
4160
|
+
},
|
|
4161
|
+
tokens: {
|
|
4162
|
+
description: "Extract Tailwind tokens with file/position metadata",
|
|
4163
|
+
optionDefs: [
|
|
4164
|
+
createCwdOptionDefinition(),
|
|
4165
|
+
{ flags: "--output <file>", description: "Override output file path", config: { default: DEFAULT_TOKEN_REPORT } },
|
|
4166
|
+
{
|
|
4167
|
+
flags: "--format <format>",
|
|
4168
|
+
description: "Output format (json|lines|grouped-json)",
|
|
4169
|
+
config: { default: "json" }
|
|
4170
|
+
},
|
|
4171
|
+
{
|
|
4172
|
+
flags: "--group-key <key>",
|
|
4173
|
+
description: "Grouping key for grouped-json output (relative|absolute)",
|
|
4174
|
+
config: { default: "relative" }
|
|
4175
|
+
},
|
|
4176
|
+
{ flags: "--no-write", description: "Skip writing to disk" }
|
|
4177
|
+
]
|
|
4178
|
+
},
|
|
4179
|
+
init: {
|
|
4180
|
+
description: "Generate a tailwindcss-patch config file",
|
|
4181
|
+
optionDefs: [createCwdOptionDefinition()]
|
|
4182
|
+
},
|
|
4183
|
+
migrate: {
|
|
4184
|
+
description: "Migrate deprecated config fields to modern options",
|
|
4185
|
+
optionDefs: [
|
|
4186
|
+
createCwdOptionDefinition(),
|
|
4187
|
+
{ flags: "--config <file>", description: "Migrate a specific config file path" },
|
|
4188
|
+
{ flags: "--workspace", description: "Scan workspace recursively for config files" },
|
|
4189
|
+
{ flags: "--max-depth <n>", description: "Maximum recursion depth for --workspace", config: { default: 6 } },
|
|
4190
|
+
{ flags: "--include <glob>", description: "Only migrate files that match this glob (repeatable)" },
|
|
4191
|
+
{ flags: "--exclude <glob>", description: "Skip files that match this glob (repeatable)" },
|
|
4192
|
+
{ flags: "--report-file <file>", description: "Write migration report JSON to a file" },
|
|
4193
|
+
{ flags: "--backup-dir <dir>", description: "Write pre-migration backups into this directory" },
|
|
4194
|
+
{ flags: "--check", description: "Exit with an error when migration changes are required" },
|
|
4195
|
+
{ flags: "--json", description: "Print the migration report as JSON" },
|
|
4196
|
+
{ flags: "--dry-run", description: "Preview changes without writing files" }
|
|
4197
|
+
]
|
|
4198
|
+
},
|
|
4199
|
+
restore: {
|
|
4200
|
+
description: "Restore config files from a previous migration report backup snapshot",
|
|
4201
|
+
optionDefs: [
|
|
4202
|
+
createCwdOptionDefinition(),
|
|
4203
|
+
{ flags: "--report-file <file>", description: "Migration report file generated by migrate" },
|
|
4204
|
+
{ flags: "--dry-run", description: "Preview restore targets without writing files" },
|
|
4205
|
+
{ flags: "--strict", description: "Fail when any backup file is missing" },
|
|
4206
|
+
{ flags: "--json", description: "Print the restore result as JSON" }
|
|
4207
|
+
]
|
|
4208
|
+
},
|
|
4209
|
+
validate: {
|
|
4210
|
+
description: "Validate migration report compatibility without modifying files",
|
|
4211
|
+
optionDefs: [
|
|
4212
|
+
createCwdOptionDefinition(),
|
|
4213
|
+
{ flags: "--report-file <file>", description: "Migration report file to validate" },
|
|
4214
|
+
{ flags: "--strict", description: "Fail when any backup file is missing" },
|
|
4215
|
+
{ flags: "--json", description: "Print validation result as JSON" }
|
|
4216
|
+
]
|
|
4217
|
+
},
|
|
4218
|
+
status: {
|
|
4219
|
+
description: "Check which Tailwind patches are applied",
|
|
4220
|
+
optionDefs: [
|
|
4221
|
+
createCwdOptionDefinition(),
|
|
4222
|
+
{ flags: "--json", description: "Print a JSON report of patch status" }
|
|
4223
|
+
]
|
|
4224
|
+
}
|
|
4225
|
+
};
|
|
4226
|
+
}
|
|
4227
|
+
function addPrefixIfMissing(value, prefix) {
|
|
4228
|
+
if (!prefix || value.startsWith(prefix)) {
|
|
4229
|
+
return value;
|
|
4230
|
+
}
|
|
4231
|
+
return `${prefix}${value}`;
|
|
4232
|
+
}
|
|
4233
|
+
function resolveCommandNames(command, mountOptions, prefix) {
|
|
4234
|
+
const override = mountOptions.commandOptions?.[command];
|
|
4235
|
+
const baseName = override?.name ?? command;
|
|
4236
|
+
const name = addPrefixIfMissing(baseName, prefix);
|
|
4237
|
+
const aliases = (override?.aliases ?? []).map((alias) => addPrefixIfMissing(alias, prefix));
|
|
4238
|
+
return { name, aliases };
|
|
4239
|
+
}
|
|
4240
|
+
function resolveOptionDefinitions(defaults, override) {
|
|
4241
|
+
if (!override) {
|
|
4242
|
+
return defaults;
|
|
4243
|
+
}
|
|
4244
|
+
const appendDefaults = override.appendDefaultOptions ?? true;
|
|
4245
|
+
const customDefs = override.optionDefs ?? [];
|
|
4246
|
+
if (!appendDefaults) {
|
|
4247
|
+
return customDefs;
|
|
4248
|
+
}
|
|
4249
|
+
if (customDefs.length === 0) {
|
|
4250
|
+
return defaults;
|
|
4251
|
+
}
|
|
4252
|
+
return [...defaults, ...customDefs];
|
|
4253
|
+
}
|
|
4254
|
+
function applyCommandOptions(command, optionDefs) {
|
|
4255
|
+
for (const option of optionDefs) {
|
|
4256
|
+
command.option(option.flags, option.description ?? "", option.config);
|
|
4257
|
+
}
|
|
4258
|
+
}
|
|
4259
|
+
function runWithCommandHandler(cli, command, commandName, args, handler, defaultHandler) {
|
|
4260
|
+
const cwd = resolveCwd(args.cwd);
|
|
4261
|
+
const context = createCommandContext(cli, command, commandName, args, cwd);
|
|
4262
|
+
const runDefault = createDefaultRunner(() => defaultHandler(context));
|
|
4263
|
+
if (!handler) {
|
|
4264
|
+
return runDefault();
|
|
4265
|
+
}
|
|
4266
|
+
return handler(context, runDefault);
|
|
4267
|
+
}
|
|
4268
|
+
function resolveCommandMetadata(command, mountOptions, prefix, defaults) {
|
|
4269
|
+
const names = resolveCommandNames(command, mountOptions, prefix);
|
|
4270
|
+
const definition = defaults[command];
|
|
4271
|
+
const override = mountOptions.commandOptions?.[command];
|
|
4272
|
+
const description = override?.description ?? definition.description;
|
|
4273
|
+
const optionDefs = resolveOptionDefinitions(definition.optionDefs, override);
|
|
4274
|
+
return { ...names, description, optionDefs };
|
|
4275
|
+
}
|
|
4276
|
+
async function installCommandDefaultHandler(ctx) {
|
|
4277
|
+
const patcher = await ctx.createPatcher();
|
|
4278
|
+
await patcher.patch();
|
|
4279
|
+
logger_default.success("Tailwind CSS runtime patched successfully.");
|
|
4280
|
+
}
|
|
4281
|
+
async function extractCommandDefaultHandler(ctx) {
|
|
4282
|
+
const { args } = ctx;
|
|
4283
|
+
const overrides = {};
|
|
4284
|
+
let hasOverrides = false;
|
|
4285
|
+
if (args.output || args.format) {
|
|
4286
|
+
overrides.extract = {
|
|
4287
|
+
...args.output === void 0 ? {} : { file: args.output },
|
|
4288
|
+
...args.format === void 0 ? {} : { format: args.format }
|
|
4289
|
+
};
|
|
4290
|
+
hasOverrides = true;
|
|
4291
|
+
}
|
|
4292
|
+
if (args.css) {
|
|
4293
|
+
overrides.tailwindcss = {
|
|
4294
|
+
v4: {
|
|
4295
|
+
cssEntries: [args.css]
|
|
4296
|
+
}
|
|
4297
|
+
};
|
|
4298
|
+
hasOverrides = true;
|
|
4299
|
+
}
|
|
4300
|
+
const patcher = await ctx.createPatcher(hasOverrides ? overrides : void 0);
|
|
4301
|
+
const extractOptions = args.write === void 0 ? {} : { write: args.write };
|
|
4302
|
+
const result = await patcher.extract(extractOptions);
|
|
4303
|
+
if (result.filename) {
|
|
4304
|
+
logger_default.success(`Collected ${result.classList.length} classes \u2192 ${result.filename}`);
|
|
4305
|
+
} else {
|
|
4306
|
+
logger_default.success(`Collected ${result.classList.length} classes.`);
|
|
4307
|
+
}
|
|
4308
|
+
return result;
|
|
4309
|
+
}
|
|
4310
|
+
async function tokensCommandDefaultHandler(ctx) {
|
|
4311
|
+
const { args } = ctx;
|
|
4312
|
+
const patcher = await ctx.createPatcher();
|
|
4313
|
+
const report = await patcher.collectContentTokens();
|
|
4314
|
+
const shouldWrite = args.write ?? true;
|
|
4315
|
+
let format = args.format ?? "json";
|
|
4316
|
+
if (!TOKEN_FORMATS.includes(format)) {
|
|
4317
|
+
format = "json";
|
|
4318
|
+
}
|
|
4319
|
+
const targetFile = args.output ?? DEFAULT_TOKEN_REPORT;
|
|
4320
|
+
const groupKey = args.groupKey === "absolute" ? "absolute" : "relative";
|
|
4321
|
+
const buildGrouped = () => groupTokensByFile(report, {
|
|
4322
|
+
key: groupKey,
|
|
4323
|
+
stripAbsolutePaths: groupKey !== "absolute"
|
|
4324
|
+
});
|
|
4325
|
+
const grouped = format === "grouped-json" ? buildGrouped() : null;
|
|
4326
|
+
const resolveGrouped = () => grouped ?? buildGrouped();
|
|
4327
|
+
if (shouldWrite) {
|
|
4328
|
+
const target = path12.resolve(targetFile);
|
|
4329
|
+
await fs12.ensureDir(path12.dirname(target));
|
|
4330
|
+
if (format === "json") {
|
|
4331
|
+
await fs12.writeJSON(target, report, { spaces: 2 });
|
|
4332
|
+
} else if (format === "grouped-json") {
|
|
4333
|
+
await fs12.writeJSON(target, resolveGrouped(), { spaces: 2 });
|
|
4334
|
+
} else {
|
|
4335
|
+
const lines = report.entries.map(formatTokenLine);
|
|
4336
|
+
await fs12.writeFile(target, `${lines.join("\n")}
|
|
4337
|
+
`, "utf8");
|
|
4338
|
+
}
|
|
4339
|
+
logger_default.success(`Collected ${report.entries.length} tokens (${format}) \u2192 ${target.replace(process7.cwd(), ".")}`);
|
|
4340
|
+
} else {
|
|
4341
|
+
logger_default.success(`Collected ${report.entries.length} tokens from ${report.filesScanned} files.`);
|
|
4342
|
+
if (format === "lines") {
|
|
4343
|
+
const preview = report.entries.slice(0, 5).map(formatTokenLine).join("\n");
|
|
4344
|
+
if (preview) {
|
|
4345
|
+
logger_default.log("");
|
|
4346
|
+
logger_default.info(preview);
|
|
4347
|
+
if (report.entries.length > 5) {
|
|
4348
|
+
logger_default.info(`\u2026and ${report.entries.length - 5} more.`);
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
} else if (format === "grouped-json") {
|
|
4352
|
+
const map = resolveGrouped();
|
|
4353
|
+
const { preview, moreFiles } = formatGroupedPreview(map);
|
|
4354
|
+
if (preview) {
|
|
4355
|
+
logger_default.log("");
|
|
4356
|
+
logger_default.info(preview);
|
|
4357
|
+
if (moreFiles > 0) {
|
|
4358
|
+
logger_default.info(`\u2026and ${moreFiles} more files.`);
|
|
4359
|
+
}
|
|
4360
|
+
}
|
|
4361
|
+
} else {
|
|
4362
|
+
const previewEntries = report.entries.slice(0, 3);
|
|
4363
|
+
if (previewEntries.length) {
|
|
4364
|
+
logger_default.log("");
|
|
4365
|
+
logger_default.info(JSON.stringify(previewEntries, null, 2));
|
|
4366
|
+
}
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
4369
|
+
if (report.skippedFiles.length) {
|
|
4370
|
+
logger_default.warn("Skipped files:");
|
|
4371
|
+
for (const skipped of report.skippedFiles) {
|
|
4372
|
+
logger_default.warn(` \u2022 ${skipped.file} (${skipped.reason})`);
|
|
4373
|
+
}
|
|
4374
|
+
}
|
|
4375
|
+
return report;
|
|
4376
|
+
}
|
|
4377
|
+
async function initCommandDefaultHandler(ctx) {
|
|
4378
|
+
await initConfig(ctx.cwd);
|
|
4379
|
+
logger_default.success(`\u2728 ${CONFIG_NAME}.config.ts initialized!`);
|
|
4380
|
+
}
|
|
4381
|
+
async function migrateCommandDefaultHandler(ctx) {
|
|
4382
|
+
const { args } = ctx;
|
|
4383
|
+
const normalizePatternArgs = (value) => {
|
|
4384
|
+
if (!value) {
|
|
4385
|
+
return void 0;
|
|
4386
|
+
}
|
|
4387
|
+
const raw = Array.isArray(value) ? value : [value];
|
|
4388
|
+
const values = raw.flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
|
|
4389
|
+
return values.length > 0 ? values : void 0;
|
|
4390
|
+
};
|
|
4391
|
+
const include = normalizePatternArgs(args.include);
|
|
4392
|
+
const exclude = normalizePatternArgs(args.exclude);
|
|
4393
|
+
const parsedMaxDepth = args.maxDepth === void 0 ? void 0 : Number(args.maxDepth);
|
|
4394
|
+
const maxDepth = parsedMaxDepth !== void 0 && Number.isFinite(parsedMaxDepth) && parsedMaxDepth >= 0 ? Math.floor(parsedMaxDepth) : void 0;
|
|
4395
|
+
const checkMode = args.check ?? false;
|
|
4396
|
+
const dryRun = args.dryRun ?? checkMode;
|
|
4397
|
+
if (args.workspace && args.maxDepth !== void 0 && maxDepth === void 0) {
|
|
4398
|
+
logger_default.warn(`Invalid --max-depth value "${String(args.maxDepth)}", fallback to default depth.`);
|
|
4399
|
+
}
|
|
4400
|
+
const report = await migrateConfigFiles({
|
|
4401
|
+
cwd: ctx.cwd,
|
|
4402
|
+
dryRun,
|
|
4403
|
+
...args.config ? { files: [args.config] } : {},
|
|
4404
|
+
...args.workspace ? { workspace: true } : {},
|
|
4405
|
+
...args.workspace && maxDepth !== void 0 ? { maxDepth } : {},
|
|
4406
|
+
...args.backupDir ? { backupDir: args.backupDir } : {},
|
|
4407
|
+
...include ? { include } : {},
|
|
4408
|
+
...exclude ? { exclude } : {}
|
|
4409
|
+
});
|
|
4410
|
+
if (args.reportFile) {
|
|
4411
|
+
const reportPath = path12.resolve(ctx.cwd, args.reportFile);
|
|
4412
|
+
await fs12.ensureDir(path12.dirname(reportPath));
|
|
4413
|
+
await fs12.writeJSON(reportPath, report, { spaces: 2 });
|
|
4414
|
+
logger_default.info(`Migration report written: ${reportPath.replace(process7.cwd(), ".")}`);
|
|
4415
|
+
}
|
|
4416
|
+
if (args.json) {
|
|
4417
|
+
logger_default.log(JSON.stringify(report, null, 2));
|
|
4418
|
+
if (checkMode && report.changedFiles > 0) {
|
|
4419
|
+
throw new Error(`Migration check failed: ${report.changedFiles} file(s) still need migration.`);
|
|
4420
|
+
}
|
|
4421
|
+
if (report.scannedFiles === 0) {
|
|
4422
|
+
logger_default.warn("No config files found for migration.");
|
|
4423
|
+
}
|
|
4424
|
+
return report;
|
|
4425
|
+
}
|
|
4426
|
+
if (report.scannedFiles === 0) {
|
|
4427
|
+
logger_default.warn("No config files found for migration.");
|
|
4428
|
+
return report;
|
|
4429
|
+
}
|
|
4430
|
+
for (const entry of report.entries) {
|
|
4431
|
+
const fileLabel = entry.file.replace(process7.cwd(), ".");
|
|
4432
|
+
if (!entry.changed) {
|
|
4433
|
+
logger_default.info(`No changes: ${fileLabel}`);
|
|
4434
|
+
continue;
|
|
4435
|
+
}
|
|
4436
|
+
if (dryRun) {
|
|
4437
|
+
logger_default.info(`[dry-run] ${fileLabel}`);
|
|
4438
|
+
} else {
|
|
4439
|
+
logger_default.success(`Migrated: ${fileLabel}`);
|
|
4440
|
+
}
|
|
4441
|
+
for (const change of entry.changes) {
|
|
4442
|
+
logger_default.info(` - ${change}`);
|
|
4443
|
+
}
|
|
4444
|
+
if (entry.backupFile) {
|
|
4445
|
+
logger_default.info(` - backup: ${entry.backupFile.replace(process7.cwd(), ".")}`);
|
|
4446
|
+
}
|
|
4447
|
+
}
|
|
4448
|
+
logger_default.info(
|
|
4449
|
+
`Migration summary: scanned=${report.scannedFiles}, changed=${report.changedFiles}, written=${report.writtenFiles}, backups=${report.backupsWritten}, missing=${report.missingFiles}, unchanged=${report.unchangedFiles}`
|
|
4450
|
+
);
|
|
4451
|
+
if (checkMode && report.changedFiles > 0) {
|
|
4452
|
+
throw new Error(`Migration check failed: ${report.changedFiles} file(s) still need migration.`);
|
|
4453
|
+
}
|
|
4454
|
+
return report;
|
|
4455
|
+
}
|
|
4456
|
+
async function restoreCommandDefaultHandler(ctx) {
|
|
4457
|
+
const { args } = ctx;
|
|
4458
|
+
const reportFile = args.reportFile ?? ".tw-patch/migrate-report.json";
|
|
4459
|
+
const result = await restoreConfigFiles({
|
|
4460
|
+
cwd: ctx.cwd,
|
|
4461
|
+
reportFile,
|
|
4462
|
+
dryRun: args.dryRun ?? false,
|
|
4463
|
+
strict: args.strict ?? false
|
|
4464
|
+
});
|
|
4465
|
+
if (args.json) {
|
|
4466
|
+
logger_default.log(JSON.stringify(result, null, 2));
|
|
4467
|
+
return result;
|
|
4468
|
+
}
|
|
4469
|
+
logger_default.info(
|
|
4470
|
+
`Restore summary: scanned=${result.scannedEntries}, restorable=${result.restorableEntries}, restored=${result.restoredFiles}, missingBackups=${result.missingBackups}, skipped=${result.skippedEntries}`
|
|
4471
|
+
);
|
|
4472
|
+
if (result.restored.length > 0) {
|
|
4473
|
+
const preview = result.restored.slice(0, 5);
|
|
4474
|
+
for (const file of preview) {
|
|
4475
|
+
logger_default.info(` - ${file.replace(process7.cwd(), ".")}`);
|
|
4476
|
+
}
|
|
4477
|
+
if (result.restored.length > preview.length) {
|
|
4478
|
+
logger_default.info(` ...and ${result.restored.length - preview.length} more`);
|
|
4479
|
+
}
|
|
4480
|
+
}
|
|
4481
|
+
return result;
|
|
4482
|
+
}
|
|
4483
|
+
async function validateCommandDefaultHandler(ctx) {
|
|
4484
|
+
const { args } = ctx;
|
|
4485
|
+
const reportFile = args.reportFile ?? ".tw-patch/migrate-report.json";
|
|
4486
|
+
try {
|
|
4487
|
+
const result = await restoreConfigFiles({
|
|
4488
|
+
cwd: ctx.cwd,
|
|
4489
|
+
reportFile,
|
|
4490
|
+
dryRun: true,
|
|
4491
|
+
strict: args.strict ?? false
|
|
4492
|
+
});
|
|
4493
|
+
if (args.json) {
|
|
4494
|
+
const payload = {
|
|
4495
|
+
ok: true,
|
|
4496
|
+
...result
|
|
4497
|
+
};
|
|
4498
|
+
logger_default.log(JSON.stringify(payload, null, 2));
|
|
4499
|
+
return result;
|
|
4500
|
+
}
|
|
4501
|
+
logger_default.success(
|
|
4502
|
+
`Migration report validated: scanned=${result.scannedEntries}, restorable=${result.restorableEntries}, missingBackups=${result.missingBackups}, skipped=${result.skippedEntries}`
|
|
4503
|
+
);
|
|
4504
|
+
if (result.reportKind || result.reportSchemaVersion !== void 0) {
|
|
4505
|
+
const kind = result.reportKind ?? "unknown";
|
|
4506
|
+
const schema = result.reportSchemaVersion === void 0 ? "unknown" : String(result.reportSchemaVersion);
|
|
4507
|
+
logger_default.info(` metadata: kind=${kind}, schema=${schema}`);
|
|
4508
|
+
}
|
|
4509
|
+
return result;
|
|
4510
|
+
} catch (error) {
|
|
4511
|
+
const summary = classifyValidateError(error);
|
|
4512
|
+
if (args.json) {
|
|
4513
|
+
const payload = {
|
|
4514
|
+
ok: false,
|
|
4515
|
+
reason: summary.reason,
|
|
4516
|
+
exitCode: summary.exitCode,
|
|
4517
|
+
message: summary.message
|
|
4518
|
+
};
|
|
4519
|
+
logger_default.log(JSON.stringify(payload, null, 2));
|
|
4520
|
+
} else {
|
|
4521
|
+
logger_default.error(`Validation failed [${summary.reason}] (exit ${summary.exitCode}): ${summary.message}`);
|
|
4522
|
+
}
|
|
4523
|
+
throw new ValidateCommandError(summary, { cause: error });
|
|
4524
|
+
}
|
|
4525
|
+
}
|
|
4526
|
+
function formatFilesHint(entry) {
|
|
4527
|
+
if (!entry.files.length) {
|
|
4528
|
+
return "";
|
|
4529
|
+
}
|
|
4530
|
+
return ` (${entry.files.join(", ")})`;
|
|
4531
|
+
}
|
|
4532
|
+
async function statusCommandDefaultHandler(ctx) {
|
|
4533
|
+
const patcher = await ctx.createPatcher();
|
|
4534
|
+
const report = await patcher.getPatchStatus();
|
|
4535
|
+
if (ctx.args.json) {
|
|
4536
|
+
logger_default.log(JSON.stringify(report, null, 2));
|
|
4537
|
+
return report;
|
|
4538
|
+
}
|
|
4539
|
+
const applied = report.entries.filter((entry) => entry.status === "applied");
|
|
4540
|
+
const pending = report.entries.filter((entry) => entry.status === "not-applied");
|
|
4541
|
+
const skipped = report.entries.filter((entry) => entry.status === "skipped" || entry.status === "unsupported");
|
|
4542
|
+
const packageLabel = `${report.package.name ?? "tailwindcss"}@${report.package.version ?? "unknown"}`;
|
|
4543
|
+
logger_default.info(`Patch status for ${packageLabel} (v${report.majorVersion})`);
|
|
4544
|
+
if (applied.length) {
|
|
4545
|
+
logger_default.success("Applied:");
|
|
4546
|
+
applied.forEach((entry) => logger_default.success(` \u2022 ${entry.name}${formatFilesHint(entry)}`));
|
|
4547
|
+
}
|
|
4548
|
+
if (pending.length) {
|
|
4549
|
+
logger_default.warn("Needs attention:");
|
|
4550
|
+
pending.forEach((entry) => {
|
|
4551
|
+
const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
|
|
4552
|
+
logger_default.warn(` \u2022 ${entry.name}${formatFilesHint(entry)}${details}`);
|
|
4553
|
+
});
|
|
4554
|
+
} else {
|
|
4555
|
+
logger_default.success("All applicable patches are applied.");
|
|
4556
|
+
}
|
|
4557
|
+
if (skipped.length) {
|
|
4558
|
+
logger_default.info("Skipped:");
|
|
4559
|
+
skipped.forEach((entry) => {
|
|
4560
|
+
const details = entry.reason ? ` \u2013 ${entry.reason}` : "";
|
|
4561
|
+
logger_default.info(` \u2022 ${entry.name}${details}`);
|
|
4562
|
+
});
|
|
4563
|
+
}
|
|
4564
|
+
return report;
|
|
4565
|
+
}
|
|
4566
|
+
function mountTailwindcssPatchCommands(cli, options = {}) {
|
|
4567
|
+
const prefix = options.commandPrefix ?? "";
|
|
4568
|
+
const selectedCommands = options.commands ?? tailwindcssPatchCommands;
|
|
4569
|
+
const defaultDefinitions = buildDefaultCommandDefinitions();
|
|
4570
|
+
const registrars = {
|
|
4571
|
+
install: () => {
|
|
4572
|
+
const metadata = resolveCommandMetadata("install", options, prefix, defaultDefinitions);
|
|
4573
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4574
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4575
|
+
command.action(async (args) => {
|
|
4576
|
+
return runWithCommandHandler(
|
|
4577
|
+
cli,
|
|
4578
|
+
command,
|
|
4579
|
+
"install",
|
|
4580
|
+
args,
|
|
4581
|
+
options.commandHandlers?.install,
|
|
4582
|
+
installCommandDefaultHandler
|
|
4583
|
+
);
|
|
4584
|
+
});
|
|
4585
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4586
|
+
},
|
|
4587
|
+
extract: () => {
|
|
4588
|
+
const metadata = resolveCommandMetadata("extract", options, prefix, defaultDefinitions);
|
|
4589
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4590
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4591
|
+
command.action(async (args) => {
|
|
4592
|
+
return runWithCommandHandler(
|
|
4593
|
+
cli,
|
|
4594
|
+
command,
|
|
4595
|
+
"extract",
|
|
4596
|
+
args,
|
|
4597
|
+
options.commandHandlers?.extract,
|
|
4598
|
+
extractCommandDefaultHandler
|
|
4599
|
+
);
|
|
4600
|
+
});
|
|
4601
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4602
|
+
},
|
|
4603
|
+
tokens: () => {
|
|
4604
|
+
const metadata = resolveCommandMetadata("tokens", options, prefix, defaultDefinitions);
|
|
4605
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4606
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4607
|
+
command.action(async (args) => {
|
|
4608
|
+
return runWithCommandHandler(
|
|
4609
|
+
cli,
|
|
4610
|
+
command,
|
|
4611
|
+
"tokens",
|
|
4612
|
+
args,
|
|
4613
|
+
options.commandHandlers?.tokens,
|
|
4614
|
+
tokensCommandDefaultHandler
|
|
4615
|
+
);
|
|
4616
|
+
});
|
|
4617
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4618
|
+
},
|
|
4619
|
+
init: () => {
|
|
4620
|
+
const metadata = resolveCommandMetadata("init", options, prefix, defaultDefinitions);
|
|
4621
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4622
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4623
|
+
command.action(async (args) => {
|
|
4624
|
+
return runWithCommandHandler(
|
|
4625
|
+
cli,
|
|
4626
|
+
command,
|
|
4627
|
+
"init",
|
|
4628
|
+
args,
|
|
4629
|
+
options.commandHandlers?.init,
|
|
4630
|
+
initCommandDefaultHandler
|
|
4631
|
+
);
|
|
4632
|
+
});
|
|
4633
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4634
|
+
},
|
|
4635
|
+
migrate: () => {
|
|
4636
|
+
const metadata = resolveCommandMetadata("migrate", options, prefix, defaultDefinitions);
|
|
4637
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4638
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4639
|
+
command.action(async (args) => {
|
|
4640
|
+
return runWithCommandHandler(
|
|
4641
|
+
cli,
|
|
4642
|
+
command,
|
|
4643
|
+
"migrate",
|
|
4644
|
+
args,
|
|
4645
|
+
options.commandHandlers?.migrate,
|
|
4646
|
+
migrateCommandDefaultHandler
|
|
4647
|
+
);
|
|
4648
|
+
});
|
|
4649
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4650
|
+
},
|
|
4651
|
+
restore: () => {
|
|
4652
|
+
const metadata = resolveCommandMetadata("restore", options, prefix, defaultDefinitions);
|
|
4653
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4654
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4655
|
+
command.action(async (args) => {
|
|
4656
|
+
return runWithCommandHandler(
|
|
4657
|
+
cli,
|
|
4658
|
+
command,
|
|
4659
|
+
"restore",
|
|
4660
|
+
args,
|
|
4661
|
+
options.commandHandlers?.restore,
|
|
4662
|
+
restoreCommandDefaultHandler
|
|
4663
|
+
);
|
|
4664
|
+
});
|
|
4665
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4666
|
+
},
|
|
4667
|
+
validate: () => {
|
|
4668
|
+
const metadata = resolveCommandMetadata("validate", options, prefix, defaultDefinitions);
|
|
4669
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4670
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4671
|
+
command.action(async (args) => {
|
|
4672
|
+
return runWithCommandHandler(
|
|
4673
|
+
cli,
|
|
4674
|
+
command,
|
|
4675
|
+
"validate",
|
|
4676
|
+
args,
|
|
4677
|
+
options.commandHandlers?.validate,
|
|
4678
|
+
validateCommandDefaultHandler
|
|
4679
|
+
);
|
|
4680
|
+
});
|
|
4681
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4682
|
+
},
|
|
4683
|
+
status: () => {
|
|
4684
|
+
const metadata = resolveCommandMetadata("status", options, prefix, defaultDefinitions);
|
|
4685
|
+
const command = cli.command(metadata.name, metadata.description);
|
|
4686
|
+
applyCommandOptions(command, metadata.optionDefs);
|
|
4687
|
+
command.action(async (args) => {
|
|
4688
|
+
return runWithCommandHandler(
|
|
4689
|
+
cli,
|
|
4690
|
+
command,
|
|
4691
|
+
"status",
|
|
4692
|
+
args,
|
|
4693
|
+
options.commandHandlers?.status,
|
|
4694
|
+
statusCommandDefaultHandler
|
|
4695
|
+
);
|
|
4696
|
+
});
|
|
4697
|
+
metadata.aliases.forEach((alias) => command.alias(alias));
|
|
4698
|
+
}
|
|
4699
|
+
};
|
|
4700
|
+
for (const name of selectedCommands) {
|
|
4701
|
+
const register = registrars[name];
|
|
4702
|
+
if (register) {
|
|
4703
|
+
register();
|
|
4704
|
+
}
|
|
4705
|
+
}
|
|
4706
|
+
return cli;
|
|
4707
|
+
}
|
|
4708
|
+
function createTailwindcssPatchCli(options = {}) {
|
|
4709
|
+
const cli = cac(options.name ?? "tw-patch");
|
|
4710
|
+
mountTailwindcssPatchCommands(cli, options.mountOptions);
|
|
4711
|
+
return cli;
|
|
4712
|
+
}
|
|
4713
|
+
|
|
4714
|
+
export {
|
|
4715
|
+
logger_default,
|
|
4716
|
+
CacheStore,
|
|
4717
|
+
extractRawCandidatesWithPositions,
|
|
4718
|
+
extractRawCandidates,
|
|
4719
|
+
extractValidCandidates,
|
|
4720
|
+
extractProjectCandidatesWithPositions,
|
|
4721
|
+
groupTokensByFile,
|
|
4722
|
+
normalizeOptions,
|
|
4723
|
+
getPatchStatusReport,
|
|
4724
|
+
collectClassesFromContexts,
|
|
4725
|
+
collectClassesFromTailwindV4,
|
|
4726
|
+
loadRuntimeContexts,
|
|
4727
|
+
runTailwindBuild,
|
|
4728
|
+
TailwindcssPatcher,
|
|
4729
|
+
MIGRATION_REPORT_KIND,
|
|
4730
|
+
MIGRATION_REPORT_SCHEMA_VERSION,
|
|
4731
|
+
migrateConfigFiles,
|
|
4732
|
+
restoreConfigFiles,
|
|
4733
|
+
tailwindcssPatchCommands,
|
|
4734
|
+
VALIDATE_EXIT_CODES,
|
|
4735
|
+
VALIDATE_FAILURE_REASONS,
|
|
4736
|
+
ValidateCommandError,
|
|
4737
|
+
mountTailwindcssPatchCommands,
|
|
4738
|
+
createTailwindcssPatchCli
|
|
4739
|
+
};
|