@usalyt/cli 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,218 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { assertWithinRoot } from "./paths";
4
+
5
+ export type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
6
+
7
+ export interface TsconfigPathMapping {
8
+ prefix: string;
9
+ targetDir: string;
10
+ }
11
+
12
+ const CSS_CANDIDATES = [
13
+ "src/index.css",
14
+ "src/app/globals.css",
15
+ "app/globals.css",
16
+ "src/styles/globals.css",
17
+ "src/globals.css",
18
+ ];
19
+
20
+ /** Detect the consumer's package manager from lockfiles (defaults to pnpm). */
21
+ export function detectPackageManager(root: string): PackageManager {
22
+ if (existsSync(path.join(root, "pnpm-lock.yaml"))) return "pnpm";
23
+ if (existsSync(path.join(root, "bun.lock")) || existsSync(path.join(root, "bun.lockb"))) {
24
+ return "bun";
25
+ }
26
+ if (existsSync(path.join(root, "yarn.lock"))) return "yarn";
27
+ if (existsSync(path.join(root, "package-lock.json"))) return "npm";
28
+ return "pnpm";
29
+ }
30
+
31
+ /** Build the shell command to add npm dependencies with the detected package manager. */
32
+ export function formatInstallCommand(pm: PackageManager, dependencies: string[]): string {
33
+ const args = formatInstallArgs(pm, dependencies);
34
+ return `${pm} ${args.join(" ")}`;
35
+ }
36
+
37
+ export function formatInstallArgs(pm: PackageManager, dependencies: string[]): string[] {
38
+ if (pm === "npm") {
39
+ return ["install", ...dependencies];
40
+ }
41
+ return ["add", ...dependencies];
42
+ }
43
+
44
+ /** Read dependency names already declared in the consumer's package.json. */
45
+ export function readInstalledDependencies(root: string): Set<string> {
46
+ const pkgPath = path.join(root, "package.json");
47
+ if (!existsSync(pkgPath)) {
48
+ return new Set();
49
+ }
50
+ try {
51
+ const parsed = JSON.parse(readFileSync(pkgPath, "utf8")) as Record<string, unknown>;
52
+ const installed = new Set<string>();
53
+ for (const field of ["dependencies", "devDependencies", "peerDependencies"]) {
54
+ const group = parsed[field];
55
+ if (group && typeof group === "object" && !Array.isArray(group)) {
56
+ for (const name of Object.keys(group as Record<string, unknown>)) {
57
+ installed.add(name);
58
+ }
59
+ }
60
+ }
61
+ return installed;
62
+ } catch {
63
+ return new Set();
64
+ }
65
+ }
66
+
67
+ function stripJsonCommentsAndTrailingCommas(raw: string): string {
68
+ let out = "";
69
+ let inString = false;
70
+ let escaped = false;
71
+ for (let i = 0; i < raw.length; i += 1) {
72
+ const ch = raw[i];
73
+ const next = raw[i + 1];
74
+ if (inString) {
75
+ out += ch;
76
+ if (escaped) {
77
+ escaped = false;
78
+ } else if (ch === "\\") {
79
+ escaped = true;
80
+ } else if (ch === '"') {
81
+ inString = false;
82
+ }
83
+ continue;
84
+ }
85
+ if (ch === '"') {
86
+ inString = true;
87
+ out += ch;
88
+ continue;
89
+ }
90
+ if (ch === "/" && next === "/") {
91
+ while (i < raw.length && raw[i] !== "\n") i += 1;
92
+ out += "\n";
93
+ continue;
94
+ }
95
+ if (ch === "/" && next === "*") {
96
+ i += 2;
97
+ while (i < raw.length && !(raw[i] === "*" && raw[i + 1] === "/")) i += 1;
98
+ i += 1;
99
+ continue;
100
+ }
101
+ out += ch;
102
+ }
103
+ return out.replace(/,\s*([}\]])/g, "$1");
104
+ }
105
+
106
+ /**
107
+ * Inspect `tsconfig.json` (and `tsconfig.app.json`) for a wildcard path alias
108
+ * such as `"@/*": ["./src/*"]` or `"~/*": ["./src/*"]`.
109
+ */
110
+ export function detectTsconfigPathMapping(root: string): TsconfigPathMapping | null {
111
+ for (const filename of ["tsconfig.json", "tsconfig.app.json"]) {
112
+ const filePath = path.join(root, filename);
113
+ if (!existsSync(filePath)) continue;
114
+ try {
115
+ const parsed = JSON.parse(
116
+ stripJsonCommentsAndTrailingCommas(readFileSync(filePath, "utf8"))
117
+ ) as {
118
+ compilerOptions?: {
119
+ baseUrl?: string;
120
+ paths?: Record<string, string[]>;
121
+ };
122
+ };
123
+ const paths = parsed.compilerOptions?.paths;
124
+ if (!paths || typeof paths !== "object") continue;
125
+
126
+ const baseUrl = parsed.compilerOptions?.baseUrl ?? ".";
127
+ for (const [pattern, targets] of Object.entries(paths)) {
128
+ if (!pattern.endsWith("/*") || !Array.isArray(targets) || targets.length === 0) {
129
+ continue;
130
+ }
131
+ const firstTarget = targets[0];
132
+ if (typeof firstTarget !== "string" || !firstTarget.endsWith("/*")) {
133
+ continue;
134
+ }
135
+ const prefix = pattern.slice(0, -1); // e.g. "@/"
136
+ const rawTarget = firstTarget.slice(0, -2); // e.g. "./src" or "."
137
+ const normalized = path.posix
138
+ .normalize(path.posix.join(baseUrl.replace(/\\/g, "/"), rawTarget.replace(/\\/g, "/")))
139
+ .replace(/^\.\/?/, "")
140
+ .replace(/\/$/, "");
141
+ return { prefix, targetDir: normalized };
142
+ }
143
+ } catch {
144
+ continue;
145
+ }
146
+ }
147
+ return null;
148
+ }
149
+
150
+ /** Detect an existing Tailwind CSS entry point, or return the default path. */
151
+ export function detectCssEntry(root: string): string {
152
+ for (const candidate of CSS_CANDIDATES) {
153
+ if (existsSync(path.join(root, candidate))) {
154
+ return candidate;
155
+ }
156
+ }
157
+ return "src/styles/globals.css";
158
+ }
159
+
160
+ export interface ThemeInjectionResult {
161
+ themeFile: string;
162
+ cssEntry: string;
163
+ cssUpdated: boolean;
164
+ }
165
+
166
+ /**
167
+ * Write `usalyt-theme.css` next to the configured Tailwind CSS entry and ensure
168
+ * that entry imports it so copied components have working design tokens without
169
+ * installing `@usalyt/ui`.
170
+ */
171
+ export function injectThemeStylesheet(options: {
172
+ root: string;
173
+ cssEntryRelative: string;
174
+ themeCss: string;
175
+ overwriteTheme?: boolean;
176
+ }): ThemeInjectionResult {
177
+ const { root, cssEntryRelative, themeCss, overwriteTheme = false } = options;
178
+ const normalizedEntry = cssEntryRelative.replace(/\\/g, "/").replace(/^\.?\//, "");
179
+ const cssEntryAbs = path.resolve(root, normalizedEntry);
180
+ assertWithinRoot(root, cssEntryAbs, "tailwind.css");
181
+
182
+ const themeFileAbs = path.join(path.dirname(cssEntryAbs), "usalyt-theme.css");
183
+ assertWithinRoot(root, themeFileAbs, "theme stylesheet");
184
+
185
+ mkdirSync(path.dirname(themeFileAbs), { recursive: true });
186
+ if (overwriteTheme || !existsSync(themeFileAbs)) {
187
+ writeFileSync(themeFileAbs, themeCss, "utf8");
188
+ }
189
+
190
+ const importStatement = '@import "./usalyt-theme.css";';
191
+ let cssUpdated = false;
192
+
193
+ if (existsSync(cssEntryAbs)) {
194
+ const existing = readFileSync(cssEntryAbs, "utf8");
195
+ if (!existing.includes("usalyt-theme.css")) {
196
+ const tailwindImport = /^@import\s+["']tailwindcss["']\s*;\s*$/m;
197
+ const updated = tailwindImport.test(existing)
198
+ ? existing.replace(tailwindImport, (line) => `${line}\n${importStatement}`)
199
+ : `${importStatement}\n${existing}`;
200
+ writeFileSync(cssEntryAbs, updated, "utf8");
201
+ cssUpdated = true;
202
+ }
203
+ } else {
204
+ mkdirSync(path.dirname(cssEntryAbs), { recursive: true });
205
+ writeFileSync(
206
+ cssEntryAbs,
207
+ `@import "tailwindcss";\n${importStatement}\n`,
208
+ "utf8"
209
+ );
210
+ cssUpdated = true;
211
+ }
212
+
213
+ return {
214
+ themeFile: path.relative(root, themeFileAbs).split(path.sep).join("/"),
215
+ cssEntry: path.relative(root, cssEntryAbs).split(path.sep).join("/"),
216
+ cssUpdated,
217
+ };
218
+ }
@@ -0,0 +1,161 @@
1
+ import {
2
+ applyThemePresetToCss,
3
+ decodeThemePreset,
4
+ DEFAULT_THEME_CONFIG,
5
+ encodeThemePreset,
6
+ isDefaultThemeConfig,
7
+ isValidHexColor,
8
+ NAMED_THEME_PRESETS,
9
+ THEME_ACCENTS,
10
+ THEME_BASES,
11
+ THEME_DENSITIES,
12
+ THEME_FONTS,
13
+ THEME_RADII,
14
+ type ThemeAccentId,
15
+ type ThemeBaseId,
16
+ type ThemeDensityId,
17
+ type ThemeFontId,
18
+ type ThemePolarity,
19
+ type ThemePresetConfig,
20
+ type ThemeRadiusId,
21
+ } from "../../../registry/src/theme-presets";
22
+ import type { UsalytThemeConfig } from "./config";
23
+
24
+ export {
25
+ applyThemePresetToCss,
26
+ DEFAULT_THEME_CONFIG,
27
+ encodeThemePreset,
28
+ isDefaultThemeConfig,
29
+ NAMED_THEME_PRESETS,
30
+ THEME_ACCENTS,
31
+ THEME_BASES,
32
+ THEME_DENSITIES,
33
+ THEME_FONTS,
34
+ THEME_RADII,
35
+ type ThemePresetConfig,
36
+ };
37
+
38
+ export interface ThemeFlagInput {
39
+ preset?: string;
40
+ base?: string;
41
+ accent?: string;
42
+ radius?: string;
43
+ density?: string;
44
+ font?: string;
45
+ mode?: string;
46
+ }
47
+
48
+ export class ThemeOptionError extends Error {
49
+ constructor(message: string) {
50
+ super(message);
51
+ this.name = "ThemeOptionError";
52
+ }
53
+ }
54
+
55
+ export function hasThemeFlags(flags: ThemeFlagInput): boolean {
56
+ return Boolean(
57
+ flags.preset ||
58
+ flags.base ||
59
+ flags.accent ||
60
+ flags.radius ||
61
+ flags.density ||
62
+ flags.font ||
63
+ flags.mode
64
+ );
65
+ }
66
+
67
+ export function resolveThemeFromFlags(
68
+ flags: ThemeFlagInput,
69
+ startingConfig: ThemePresetConfig = DEFAULT_THEME_CONFIG
70
+ ): ThemePresetConfig {
71
+ let resolved: ThemePresetConfig = { ...startingConfig };
72
+
73
+ if (flags.preset) {
74
+ const trimmed = flags.preset.trim();
75
+ const isQueryOrUrl = trimmed.includes("=") || trimmed.includes("?");
76
+ const isKnownNamed = NAMED_THEME_PRESETS.some(
77
+ (p) => p.id.toLowerCase() === trimmed.toLowerCase()
78
+ );
79
+ if (!isQueryOrUrl && !isKnownNamed) {
80
+ const available = NAMED_THEME_PRESETS.map((p) => p.id).join(", ");
81
+ throw new ThemeOptionError(
82
+ `Unknown theme preset "${trimmed}". Available presets: ${available} (or pass a query/URL from the Theme Studio).`
83
+ );
84
+ }
85
+ resolved = decodeThemePreset(trimmed);
86
+ }
87
+
88
+ if (flags.base) {
89
+ if (!(flags.base in THEME_BASES)) {
90
+ throw new ThemeOptionError(
91
+ `Invalid --base "${flags.base}". Choose one of: ${Object.keys(THEME_BASES).join(", ")}.`
92
+ );
93
+ }
94
+ resolved.base = flags.base as ThemeBaseId;
95
+ }
96
+
97
+ if (flags.accent) {
98
+ const raw = flags.accent.trim();
99
+ if (raw in THEME_ACCENTS) {
100
+ resolved.accent = raw as ThemeAccentId;
101
+ } else if (isValidHexColor(raw)) {
102
+ resolved.accent = raw.toLowerCase();
103
+ } else if (isValidHexColor(`#${raw}`)) {
104
+ resolved.accent = `#${raw.toLowerCase()}`;
105
+ } else {
106
+ throw new ThemeOptionError(
107
+ `Invalid --accent "${raw}". Use one of (${Object.keys(THEME_ACCENTS).join(", ")}) or a 6-digit hex color like #5e6ad2.`
108
+ );
109
+ }
110
+ }
111
+
112
+ if (flags.radius) {
113
+ if (!(flags.radius in THEME_RADII)) {
114
+ throw new ThemeOptionError(
115
+ `Invalid --radius "${flags.radius}". Choose one of: ${Object.keys(THEME_RADII).join(", ")}.`
116
+ );
117
+ }
118
+ resolved.radius = flags.radius as ThemeRadiusId;
119
+ }
120
+
121
+ if (flags.density) {
122
+ if (!(flags.density in THEME_DENSITIES)) {
123
+ throw new ThemeOptionError(
124
+ `Invalid --density "${flags.density}". Choose one of: ${Object.keys(THEME_DENSITIES).join(", ")}.`
125
+ );
126
+ }
127
+ resolved.density = flags.density as ThemeDensityId;
128
+ }
129
+
130
+ if (flags.font) {
131
+ if (!(flags.font in THEME_FONTS)) {
132
+ throw new ThemeOptionError(
133
+ `Invalid --font "${flags.font}". Choose one of: ${Object.keys(THEME_FONTS).join(", ")}.`
134
+ );
135
+ }
136
+ resolved.font = flags.font as ThemeFontId;
137
+ }
138
+
139
+ if (flags.mode) {
140
+ if (flags.mode !== "dark" && flags.mode !== "light") {
141
+ throw new ThemeOptionError(
142
+ `Invalid --mode "${flags.mode}". Choose "dark" or "light".`
143
+ );
144
+ }
145
+ resolved.defaultMode = flags.mode as ThemePolarity;
146
+ }
147
+
148
+ return resolved;
149
+ }
150
+
151
+ export function toUsalytThemeConfig(config: ThemePresetConfig): UsalytThemeConfig {
152
+ return {
153
+ preset: encodeThemePreset(config),
154
+ base: config.base,
155
+ accent: config.accent,
156
+ radius: config.radius,
157
+ density: config.density,
158
+ font: config.font,
159
+ defaultMode: config.defaultMode,
160
+ };
161
+ }