stera-ui 0.2.0 → 0.3.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.
@@ -0,0 +1,695 @@
1
+ // src/utils/transform.ts
2
+ function applyTransforms(content, ctx, transforms) {
3
+ return transforms.reduce((acc, fn) => fn(acc, ctx), content);
4
+ }
5
+
6
+ // src/utils/transform-imports.ts
7
+ var DEFAULT_ALIASES = {
8
+ utils: "@/lib/utils",
9
+ ui: "@/components/ui",
10
+ components: "@/components",
11
+ lib: "@/lib",
12
+ hooks: "@/hooks"
13
+ };
14
+ var transformImports = (content, ctx) => {
15
+ if (!ctx.filename.endsWith(".ts") && !ctx.filename.endsWith(".tsx")) {
16
+ return content;
17
+ }
18
+ const { aliases } = ctx.config;
19
+ const rules = [];
20
+ if (aliases.utils !== DEFAULT_ALIASES.utils) {
21
+ rules.push({ type: "exact", from: DEFAULT_ALIASES.utils, to: aliases.utils });
22
+ }
23
+ if (aliases.ui !== DEFAULT_ALIASES.ui) {
24
+ rules.push({ type: "prefix", from: DEFAULT_ALIASES.ui, to: aliases.ui });
25
+ }
26
+ if (aliases.components !== DEFAULT_ALIASES.components) {
27
+ rules.push({ type: "prefix", from: DEFAULT_ALIASES.components, to: aliases.components });
28
+ }
29
+ if (aliases.lib !== DEFAULT_ALIASES.lib) {
30
+ rules.push({ type: "prefix", from: DEFAULT_ALIASES.lib, to: aliases.lib });
31
+ }
32
+ if (aliases.hooks !== DEFAULT_ALIASES.hooks) {
33
+ rules.push({ type: "prefix", from: DEFAULT_ALIASES.hooks, to: aliases.hooks });
34
+ }
35
+ if (rules.length === 0) {
36
+ return content;
37
+ }
38
+ return content.replace(
39
+ /from\s+(["'])([^"']+)\1/g,
40
+ (match, quote, importPath) => {
41
+ for (const rule of rules) {
42
+ if (rule.type === "exact" && importPath === rule.from) {
43
+ return `from ${quote}${rule.to}${quote}`;
44
+ }
45
+ if (rule.type === "prefix" && importPath.startsWith(rule.from + "/")) {
46
+ const rest = importPath.slice(rule.from.length);
47
+ return `from ${quote}${rule.to}${rest}${quote}`;
48
+ }
49
+ if (rule.type === "prefix" && importPath === rule.from) {
50
+ return `from ${quote}${rule.to}${quote}`;
51
+ }
52
+ }
53
+ return match;
54
+ }
55
+ );
56
+ };
57
+
58
+ // src/utils/resolve-paths.ts
59
+ import path from "path";
60
+ import { loadConfig, createMatchPath } from "tsconfig-paths";
61
+ var TYPE_TO_ALIAS = {
62
+ "registry:ui": "ui",
63
+ "registry:lib": "lib",
64
+ "registry:hook": "hooks",
65
+ "registry:component": "components"
66
+ };
67
+ function resolveAlias(alias, projectRoot) {
68
+ const tsConfig = loadConfig(projectRoot);
69
+ if (tsConfig.resultType === "success") {
70
+ const match = createMatchPath(tsConfig.absoluteBaseUrl, tsConfig.paths);
71
+ const resolved = match(alias, void 0, () => true, [".ts", ".tsx"]);
72
+ if (resolved) {
73
+ return path.relative(projectRoot, resolved);
74
+ }
75
+ }
76
+ return alias.replace(/^@\//, "");
77
+ }
78
+ function resolveOutputPath(config, projectRoot, file) {
79
+ const alias = TYPE_TO_ALIAS[file.type];
80
+ if (alias) {
81
+ const dir = resolveAlias(config.aliases[alias], projectRoot);
82
+ const filename = path.basename(file.path);
83
+ return path.join(projectRoot, dir, filename);
84
+ }
85
+ if (file.type === "registry:style") {
86
+ const cssDir = path.dirname(config.css);
87
+ const filename = path.basename(file.path);
88
+ return path.join(projectRoot, cssDir, filename);
89
+ }
90
+ return path.join(projectRoot, file.path);
91
+ }
92
+
93
+ // src/utils/resolve-config.ts
94
+ import fs from "fs";
95
+ import path2 from "path";
96
+ var CONFIG_FILE = "components.json";
97
+ function migrateConfig(raw) {
98
+ if (!("version" in raw) && "tailwind" in raw) {
99
+ const legacy = raw;
100
+ return {
101
+ version: 1,
102
+ css: legacy.tailwind.css || "src/styles/globals.css",
103
+ aliases: legacy.aliases
104
+ };
105
+ }
106
+ return raw;
107
+ }
108
+ function findConfigPath(cwd) {
109
+ let dir = path2.resolve(cwd);
110
+ while (true) {
111
+ const configPath = path2.join(dir, CONFIG_FILE);
112
+ if (fs.existsSync(configPath)) return configPath;
113
+ const parent = path2.dirname(dir);
114
+ if (parent === dir) return null;
115
+ dir = parent;
116
+ }
117
+ }
118
+ function loadConfig2(cwd) {
119
+ const configPath = findConfigPath(cwd);
120
+ if (!configPath) return null;
121
+ try {
122
+ const raw = JSON.parse(fs.readFileSync(configPath, "utf-8"));
123
+ return migrateConfig(raw);
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ // src/utils/detect-project.ts
130
+ import fs2 from "fs";
131
+ import path3 from "path";
132
+ function hasFile(cwd, filenames) {
133
+ return filenames.some((f) => fs2.existsSync(path3.join(cwd, f)));
134
+ }
135
+ function findTailwindCssFile(cwd) {
136
+ const candidates = [
137
+ "src/app/globals.css",
138
+ "src/styles/globals.css",
139
+ "src/index.css",
140
+ "app/globals.css",
141
+ "styles/globals.css",
142
+ "index.css"
143
+ ];
144
+ for (const candidate of candidates) {
145
+ const fullPath = path3.join(cwd, candidate);
146
+ if (!fs2.existsSync(fullPath)) continue;
147
+ const content = fs2.readFileSync(fullPath, "utf-8");
148
+ if (content.includes('@import "tailwindcss"') || content.includes("@import 'tailwindcss'") || content.includes("@tailwind base")) {
149
+ return candidate;
150
+ }
151
+ }
152
+ return null;
153
+ }
154
+ function detectProject(cwd) {
155
+ const hasSrc = fs2.existsSync(path3.join(cwd, "src"));
156
+ let framework = "other";
157
+ if (hasFile(cwd, ["next.config.ts", "next.config.js", "next.config.mjs"])) {
158
+ framework = "next";
159
+ } else if (hasFile(cwd, ["vite.config.ts", "vite.config.js", "vite.config.mjs"])) {
160
+ framework = "vite";
161
+ }
162
+ let rsc = false;
163
+ if (framework === "next") {
164
+ const appDir = hasSrc ? "src/app" : "app";
165
+ rsc = fs2.existsSync(path3.join(cwd, appDir));
166
+ }
167
+ const existingCssFile = findTailwindCssFile(cwd);
168
+ let layoutFile = null;
169
+ if (framework === "next") {
170
+ const appDir = hasSrc ? "src/app" : "app";
171
+ for (const ext of ["tsx", "jsx", "ts", "js"]) {
172
+ const candidate = `${appDir}/layout.${ext}`;
173
+ if (fs2.existsSync(path3.join(cwd, candidate))) {
174
+ layoutFile = candidate;
175
+ break;
176
+ }
177
+ }
178
+ } else if (framework === "vite") {
179
+ if (fs2.existsSync(path3.join(cwd, "index.html"))) {
180
+ layoutFile = "index.html";
181
+ }
182
+ }
183
+ return { hasSrc, framework, rsc, existingCssFile, layoutFile };
184
+ }
185
+
186
+ // src/utils/detect-globals.ts
187
+ import fs3 from "fs";
188
+ import path4 from "path";
189
+ function hasGlobalsCss(config, projectRoot) {
190
+ const cssPath = path4.resolve(projectRoot, config.css);
191
+ if (!fs3.existsSync(cssPath)) {
192
+ return false;
193
+ }
194
+ const steraPath = path4.join(path4.dirname(cssPath), "stera-ui.css");
195
+ return fs3.existsSync(steraPath);
196
+ }
197
+
198
+ // src/utils/install-deps.ts
199
+ import fs4 from "fs";
200
+ import path5 from "path";
201
+ import { detect } from "@antfu/ni";
202
+ import { execa } from "execa";
203
+
204
+ // src/utils/format.ts
205
+ var BRAND = "\x1B[38;2;166;244;48m";
206
+ var DIM = "\x1B[2m";
207
+ var RESET = "\x1B[0m";
208
+ var enabled = process.stdout.isTTY && !process.env.NO_COLOR;
209
+ var wrap = (code, text) => enabled ? `${code}${text}${RESET}` : text;
210
+ var brand = (text) => wrap(BRAND, text);
211
+ var dim = (text) => wrap(DIM, text);
212
+ var LOGO = brand("\u273B");
213
+ var CHECK = brand("\u2713");
214
+ var CROSS = "\u2717";
215
+ var WARN = "!";
216
+
217
+ // src/utils/spinner.ts
218
+ var FRAMES = ["\u2022", "\u2726", "\u2736", "\u273B"].map(brand);
219
+ var INTERVAL_MS = 150;
220
+ function createSpinner(text) {
221
+ const isTTY = process.stdout.isTTY;
222
+ if (!isTTY) {
223
+ process.stdout.write(` ${text}...
224
+ `);
225
+ return {
226
+ succeed(msg) {
227
+ process.stdout.write(` ${CHECK} ${msg}
228
+ `);
229
+ },
230
+ fail(msg) {
231
+ process.stdout.write(` ${CROSS} ${msg}
232
+ `);
233
+ }
234
+ };
235
+ }
236
+ let frameIndex = 0;
237
+ const interval = setInterval(() => {
238
+ process.stdout.write(`\r ${FRAMES[frameIndex % FRAMES.length]} ${text}`);
239
+ frameIndex++;
240
+ }, INTERVAL_MS);
241
+ const clear = () => {
242
+ clearInterval(interval);
243
+ process.stdout.write("\r" + " ".repeat(text.length + 6) + "\r");
244
+ };
245
+ return {
246
+ succeed(msg) {
247
+ clear();
248
+ process.stdout.write(` ${CHECK} ${msg}
249
+ `);
250
+ },
251
+ fail(msg) {
252
+ clear();
253
+ process.stdout.write(` ${CROSS} ${msg}
254
+ `);
255
+ }
256
+ };
257
+ }
258
+
259
+ // src/utils/install-deps.ts
260
+ async function detectPackageManager(cwd) {
261
+ const detected = await detect({ programmatic: true, cwd });
262
+ if (detected === "pnpm@6" || detected === "pnpm") return "pnpm";
263
+ if (detected === "yarn@berry" || detected === "yarn") return "yarn";
264
+ if (detected === "bun") return "bun";
265
+ if (detected === "npm") return "npm";
266
+ const userAgent = process.env.npm_config_user_agent || "";
267
+ if (userAgent.startsWith("pnpm")) return "pnpm";
268
+ if (userAgent.startsWith("yarn")) return "yarn";
269
+ if (userAgent.startsWith("bun")) return "bun";
270
+ return "npm";
271
+ }
272
+ function getInstallArgs(pm, deps) {
273
+ switch (pm) {
274
+ case "pnpm":
275
+ return ["pnpm", ["add", ...deps]];
276
+ case "yarn":
277
+ return ["yarn", ["add", ...deps]];
278
+ case "bun":
279
+ return ["bun", ["add", ...deps]];
280
+ default:
281
+ return ["npm", ["install", ...deps]];
282
+ }
283
+ }
284
+ async function installDependencies(deps, cwd) {
285
+ if (deps.length === 0) return;
286
+ const pkgPath = path5.join(cwd, "package.json");
287
+ let existing = /* @__PURE__ */ new Set();
288
+ if (fs4.existsSync(pkgPath)) {
289
+ try {
290
+ const pkg = JSON.parse(fs4.readFileSync(pkgPath, "utf-8"));
291
+ existing = new Set(Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }));
292
+ } catch {
293
+ }
294
+ }
295
+ const toInstall = deps.filter((dep) => !existing.has(dep));
296
+ if (toInstall.length === 0) return;
297
+ const pm = await detectPackageManager(cwd);
298
+ const [cmd, args] = getInstallArgs(pm, toInstall);
299
+ const spinner = createSpinner(`Installing with ${pm}`);
300
+ try {
301
+ await execa(cmd, args, { cwd });
302
+ spinner.succeed(`Installed with ${pm}`);
303
+ } catch (error) {
304
+ spinner.fail(`Install failed`);
305
+ if (error instanceof Error && "stdout" in error && typeof error.stdout === "string" && error.stdout.includes("ERR_PNPM_ADDING_TO_ROOT")) {
306
+ throw new Error(
307
+ `Cannot install dependencies at a pnpm workspace root.
308
+ Run stera-ui init from within a specific workspace package instead,
309
+ or use "pnpm add -w <package>" manually to install at the root.`
310
+ );
311
+ }
312
+ throw error;
313
+ }
314
+ }
315
+
316
+ // src/utils/write-files.ts
317
+ import fs5 from "fs";
318
+ import path6 from "path";
319
+ import readline from "readline/promises";
320
+ async function confirmOverwrite(relativePath) {
321
+ if (!process.stdin.isTTY) {
322
+ console.log(` Skipping ${relativePath} (already exists, use --overwrite to replace)`);
323
+ return false;
324
+ }
325
+ const rl = readline.createInterface({
326
+ input: process.stdin,
327
+ output: process.stdout
328
+ });
329
+ const answer = await rl.question(` ${relativePath} already exists. Overwrite? (y/N) `);
330
+ rl.close();
331
+ return answer.toLowerCase() === "y";
332
+ }
333
+ async function writeComponentFiles(items, config, projectRoot, options = {}) {
334
+ const written = [];
335
+ const skipped = [];
336
+ for (const item of items) {
337
+ for (const file of item.files ?? []) {
338
+ const outputPath = resolveOutputPath(config, projectRoot, file);
339
+ const relativePath = path6.relative(projectRoot, outputPath);
340
+ if (fs5.existsSync(outputPath)) {
341
+ const existing = fs5.readFileSync(outputPath, "utf-8");
342
+ if (existing === file.content) {
343
+ skipped.push(relativePath);
344
+ continue;
345
+ }
346
+ if (!options.overwrite) {
347
+ const confirmed = await confirmOverwrite(relativePath);
348
+ if (!confirmed) {
349
+ skipped.push(relativePath);
350
+ continue;
351
+ }
352
+ }
353
+ }
354
+ const dir = path6.dirname(outputPath);
355
+ fs5.mkdirSync(dir, { recursive: true });
356
+ fs5.writeFileSync(outputPath, file.content ?? "", "utf-8");
357
+ written.push(relativePath);
358
+ }
359
+ }
360
+ return { written, skipped };
361
+ }
362
+
363
+ // src/utils/update-fonts.ts
364
+ import { existsSync, promises as fs6 } from "fs";
365
+ import path7 from "path";
366
+ import {
367
+ Project,
368
+ ScriptKind,
369
+ SyntaxKind,
370
+ VariableDeclarationKind
371
+ } from "ts-morph";
372
+ var ROOT_FONT_VARIABLES = /* @__PURE__ */ new Set([
373
+ "--font-sans",
374
+ "--font-serif",
375
+ "--font-mono"
376
+ ]);
377
+ function massageTreeForFonts(fonts, project) {
378
+ const result = {
379
+ cssVars: {},
380
+ dependencies: [],
381
+ cssImports: []
382
+ };
383
+ if (fonts.length === 0) return result;
384
+ const isNext = project.framework === "next";
385
+ for (const font of fonts) {
386
+ if (isNext) {
387
+ result.cssVars[font.font.variable] = `var(${font.font.variable})`;
388
+ } else {
389
+ const fontName = font.name.replace(/^font-/, "");
390
+ const fontSourceDep = font.font.dependency ?? `@fontsource-variable/${fontName}`;
391
+ result.dependencies.push(fontSourceDep);
392
+ result.cssImports.push(`@import "${fontSourceDep}";`);
393
+ result.cssVars[font.font.variable] = font.font.family;
394
+ }
395
+ }
396
+ return result;
397
+ }
398
+ async function updateFonts(fonts, project, cwd, options = {}) {
399
+ if (fonts.length === 0) return;
400
+ if (project.framework !== "next") return;
401
+ const layoutPath = findLayoutFile(project, cwd);
402
+ if (!layoutPath) return;
403
+ if (options.silent) {
404
+ try {
405
+ const layoutContent = await fs6.readFile(layoutPath, "utf-8");
406
+ const updatedContent = transformLayoutFonts(layoutContent, fonts);
407
+ if (updatedContent !== layoutContent) {
408
+ await fs6.writeFile(layoutPath, updatedContent, "utf-8");
409
+ }
410
+ } catch {
411
+ }
412
+ return;
413
+ }
414
+ const spinner = createSpinner("Updating fonts");
415
+ try {
416
+ const layoutContent = await fs6.readFile(layoutPath, "utf-8");
417
+ const updatedContent = transformLayoutFonts(layoutContent, fonts);
418
+ if (updatedContent !== layoutContent) {
419
+ await fs6.writeFile(layoutPath, updatedContent, "utf-8");
420
+ }
421
+ spinner.succeed("Updated layout with font imports");
422
+ } catch {
423
+ spinner.fail("Failed to update fonts");
424
+ }
425
+ }
426
+ function findLayoutFile(project, cwd) {
427
+ if (!project.layoutFile) return null;
428
+ const fullPath = path7.join(cwd, project.layoutFile);
429
+ return existsSync(fullPath) ? fullPath : null;
430
+ }
431
+ function transformLayoutFonts(input, fonts) {
432
+ const project = new Project({ compilerOptions: {} });
433
+ const sourceFile = project.createSourceFile("layout.tsx", input, {
434
+ scriptKind: ScriptKind.TSX
435
+ });
436
+ const googleFonts = fonts.filter((f) => f.font.provider === "google");
437
+ const fontVariableNames = [];
438
+ const fontUtilityClasses = [];
439
+ for (const font of googleFonts) {
440
+ const importName = font.font.import;
441
+ if (!importName) continue;
442
+ const existingImport = sourceFile.getImportDeclaration(
443
+ (decl) => decl.getModuleSpecifierValue() === "next/font/google"
444
+ );
445
+ let hasExistingImport = false;
446
+ if (existingImport) {
447
+ const namedImports = existingImport.getNamedImports();
448
+ hasExistingImport = namedImports.some(
449
+ (imp) => imp.getName() === importName
450
+ );
451
+ if (!hasExistingImport) {
452
+ existingImport.addNamedImport(importName);
453
+ }
454
+ } else {
455
+ sourceFile.addImportDeclaration({
456
+ moduleSpecifier: "next/font/google",
457
+ namedImports: [importName]
458
+ });
459
+ }
460
+ const varName = getFontVariableName(importName, font.font.variable);
461
+ const fontOptions = buildFontOptions(font);
462
+ const existingVarDecl = findFontVariableDeclaration(
463
+ sourceFile,
464
+ font.font.variable
465
+ );
466
+ if (hasExistingImport && !existingVarDecl && isRootFontVariable(font.font.variable)) {
467
+ continue;
468
+ }
469
+ if (existingVarDecl) {
470
+ existingVarDecl.setInitializer(`${importName}(${fontOptions})`);
471
+ if (existingVarDecl.getName() !== varName) {
472
+ existingVarDecl.rename(varName);
473
+ }
474
+ } else {
475
+ const insertPosition = findInsertPosition(sourceFile);
476
+ const statement = sourceFile.insertVariableStatement(insertPosition, {
477
+ declarationKind: VariableDeclarationKind.Const,
478
+ declarations: [
479
+ {
480
+ name: varName,
481
+ initializer: `${importName}(${fontOptions})`
482
+ }
483
+ ]
484
+ });
485
+ statement.appendWhitespace("\n");
486
+ }
487
+ fontVariableNames.push(varName);
488
+ if (shouldApplyFontUtilityToHtml(font)) {
489
+ fontUtilityClasses.push(font.font.variable.replace("--", ""));
490
+ }
491
+ }
492
+ const fontFamilyClasses = /* @__PURE__ */ new Set(["font-sans", "font-serif", "font-mono"]);
493
+ const lastFontFamilyClass = [...fontUtilityClasses].reverse().find((cls) => fontFamilyClasses.has(cls));
494
+ const filteredUtilityClasses = fontUtilityClasses.filter(
495
+ (cls) => !fontFamilyClasses.has(cls)
496
+ );
497
+ if (lastFontFamilyClass) {
498
+ filteredUtilityClasses.unshift(lastFontFamilyClass);
499
+ }
500
+ if (fontVariableNames.length > 0) {
501
+ updateHtmlClassName(sourceFile, fontVariableNames, filteredUtilityClasses);
502
+ }
503
+ return sourceFile.getFullText();
504
+ }
505
+ function buildFontOptions(font) {
506
+ const options = {};
507
+ if (font.font.subsets?.length) options.subsets = font.font.subsets;
508
+ if (font.font.weight?.length) options.weight = font.font.weight;
509
+ options.variable = font.font.variable;
510
+ return JSON.stringify(options).replace(/"([^"]+)":/g, "$1:").replace(/"/g, "'");
511
+ }
512
+ function isRootFontVariable(variable) {
513
+ return ROOT_FONT_VARIABLES.has(variable);
514
+ }
515
+ function shouldApplyFontUtilityToHtml(font) {
516
+ return !font.font.selector && isRootFontVariable(font.font.variable);
517
+ }
518
+ function getFontVariableName(importName, variable) {
519
+ const baseName = toCamelCase(importName);
520
+ if (isRootFontVariable(variable)) return baseName;
521
+ return `${baseName}${toPascalCase(variable.replace(/^--font-/, ""))}`;
522
+ }
523
+ function toCamelCase(str) {
524
+ return str.split("_").map(
525
+ (part, index) => index === 0 ? part.toLowerCase() : part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
526
+ ).join("");
527
+ }
528
+ function toPascalCase(str) {
529
+ return str.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
530
+ }
531
+ function findFontVariableDeclaration(sourceFile, variable) {
532
+ for (const statement of sourceFile.getVariableStatements()) {
533
+ for (const declaration of statement.getDeclarations()) {
534
+ const initializer = declaration.getInitializer();
535
+ if (!initializer || initializer.getKind() !== SyntaxKind.CallExpression)
536
+ continue;
537
+ const args = initializer.getArguments();
538
+ if (args.length === 0) continue;
539
+ const argText = args[0].getText();
540
+ if (argText.includes("variable:") && argText.includes(variable)) {
541
+ return declaration;
542
+ }
543
+ }
544
+ }
545
+ return null;
546
+ }
547
+ function findInsertPosition(sourceFile) {
548
+ const imports = sourceFile.getImportDeclarations();
549
+ if (imports.length > 0) {
550
+ return imports[imports.length - 1].getChildIndex() + 1;
551
+ }
552
+ return 0;
553
+ }
554
+ function updateHtmlClassName(sourceFile, fontVariableNames, fontUtilityClasses) {
555
+ const jsxElements = sourceFile.getDescendantsOfKind(
556
+ SyntaxKind.JsxOpeningElement
557
+ );
558
+ for (const element of jsxElements) {
559
+ if (element.getTagNameNode().getText() !== "html") continue;
560
+ const newUtilityClasses = fontUtilityClasses.map((cls) => `"${cls}"`);
561
+ const newVarExpressions = fontVariableNames.map(
562
+ (name) => `${name}.variable`
563
+ );
564
+ const allNewArgs = [...newUtilityClasses, ...newVarExpressions];
565
+ const classNameAttr = element.getAttribute("className");
566
+ if (!classNameAttr) {
567
+ element.addAttribute({
568
+ name: "className",
569
+ initializer: `{cn(${allNewArgs.join(", ")})}`
570
+ });
571
+ ensureCnImport(sourceFile);
572
+ return;
573
+ }
574
+ if (classNameAttr.getKind() !== SyntaxKind.JsxAttribute) return;
575
+ const jsxAttr = classNameAttr.asKindOrThrow(SyntaxKind.JsxAttribute);
576
+ const initializer = jsxAttr.getInitializer();
577
+ if (!initializer) return;
578
+ if (initializer.getKind() === SyntaxKind.StringLiteral) {
579
+ const currentValue = initializer.getText().slice(1, -1);
580
+ ensureCnImport(sourceFile);
581
+ jsxAttr.setInitializer(
582
+ `{cn("${currentValue}", ${allNewArgs.join(", ")})}`
583
+ );
584
+ } else if (initializer.getKind() === SyntaxKind.JsxExpression) {
585
+ const jsxExpr = initializer.asKindOrThrow(SyntaxKind.JsxExpression);
586
+ const expr = jsxExpr.getExpression();
587
+ if (!expr) return;
588
+ const exprText = expr.getText();
589
+ if (exprText.startsWith("cn(")) {
590
+ const hasAllFontVars = newVarExpressions.every(
591
+ (v) => exprText.includes(v)
592
+ );
593
+ const hasAllUtilityClasses = fontUtilityClasses.every(
594
+ (cls) => exprText.includes(`"${cls}"`)
595
+ );
596
+ if (hasAllFontVars && hasAllUtilityClasses) continue;
597
+ let cleanedExpr = exprText;
598
+ for (const varExpr of newVarExpressions) {
599
+ cleanedExpr = cleanedExpr.replace(
600
+ new RegExp(`,?\\s*${varExpr.replace(".", "\\.")}`, "g"),
601
+ ""
602
+ );
603
+ }
604
+ cleanedExpr = cleanedExpr.replace(/cn\(\s*,/, "cn(");
605
+ const newExpr = cleanedExpr.replace(
606
+ /\)$/,
607
+ `, ${allNewArgs.join(", ")})`
608
+ );
609
+ jsxExpr.replaceWithText(`{${newExpr}}`);
610
+ } else if (/^\w+\.variable$/.test(exprText)) {
611
+ ensureCnImport(sourceFile);
612
+ jsxExpr.replaceWithText(`{cn(${allNewArgs.join(", ")})}`);
613
+ } else if (exprText.startsWith("`") && exprText.endsWith("`")) {
614
+ const cnArgs = parseTemplateLiteralToCnArgs(exprText);
615
+ ensureCnImport(sourceFile);
616
+ const allNewArgsSet = new Set(allNewArgs);
617
+ const fontFamilyLiterals = new Set(
618
+ ["font-sans", "font-serif", "font-mono"].map((c) => `"${c}"`)
619
+ );
620
+ const cleanedCnArgs = cnArgs.filter(
621
+ (arg) => !allNewArgsSet.has(arg) && !fontFamilyLiterals.has(arg)
622
+ );
623
+ jsxExpr.replaceWithText(
624
+ `{cn(${[...cleanedCnArgs, ...allNewArgs].join(", ")})}`
625
+ );
626
+ } else {
627
+ ensureCnImport(sourceFile);
628
+ jsxExpr.replaceWithText(`{cn(${exprText}, ${allNewArgs.join(", ")})}`);
629
+ }
630
+ }
631
+ }
632
+ }
633
+ function ensureCnImport(sourceFile) {
634
+ const existingImport = sourceFile.getImportDeclaration(
635
+ (decl) => decl.getNamedImports().some((imp) => imp.getName() === "cn")
636
+ );
637
+ if (!existingImport) {
638
+ const utilsImport = sourceFile.getImportDeclaration(
639
+ (decl) => decl.getModuleSpecifierValue().includes("/lib/utils")
640
+ );
641
+ if (utilsImport) {
642
+ const namedImports = utilsImport.getNamedImports();
643
+ if (!namedImports.some((imp) => imp.getName() === "cn")) {
644
+ utilsImport.addNamedImport("cn");
645
+ }
646
+ } else {
647
+ sourceFile.addImportDeclaration({
648
+ moduleSpecifier: "@/lib/utils",
649
+ namedImports: ["cn"]
650
+ });
651
+ }
652
+ }
653
+ }
654
+ function parseTemplateLiteralToCnArgs(templateLiteral) {
655
+ const staticArgs = [];
656
+ const variableArgs = [];
657
+ const content = templateLiteral.slice(1, -1);
658
+ const parts = content.split(/(\$\{[^}]+\})/);
659
+ for (const part of parts) {
660
+ if (!part) continue;
661
+ if (part.startsWith("${") && part.endsWith("}")) {
662
+ const expr = part.slice(2, -1).trim();
663
+ if (expr) variableArgs.push(expr);
664
+ } else {
665
+ const staticParts = part.trim().split(/\s+/).filter(Boolean);
666
+ for (const staticPart of staticParts) {
667
+ staticArgs.push(`"${staticPart}"`);
668
+ }
669
+ }
670
+ }
671
+ return [...staticArgs, ...variableArgs];
672
+ }
673
+
674
+ export {
675
+ applyTransforms,
676
+ transformImports,
677
+ resolveOutputPath,
678
+ CONFIG_FILE,
679
+ findConfigPath,
680
+ loadConfig2 as loadConfig,
681
+ detectProject,
682
+ hasGlobalsCss,
683
+ brand,
684
+ dim,
685
+ LOGO,
686
+ CHECK,
687
+ CROSS,
688
+ WARN,
689
+ createSpinner,
690
+ detectPackageManager,
691
+ installDependencies,
692
+ writeComponentFiles,
693
+ massageTreeForFonts,
694
+ updateFonts
695
+ };