@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.
package/dist/index.mjs CHANGED
@@ -7,6 +7,9 @@ import path from "node:path";
7
7
  import { createInterface } from "node:readline/promises";
8
8
  import pc from "picocolors";
9
9
  import { fileURLToPath } from "node:url";
10
+ //#region package.json
11
+ var version = "0.0.2";
12
+ //#endregion
10
13
  //#region src/lib/config.ts
11
14
  const CONFIG_FILE = "usalyt.json";
12
15
  var ConfigError = class extends Error {
@@ -60,6 +63,15 @@ function readConfig(root) {
60
63
  if (!isRecord$1(parsed)) throw new ConfigError(`${configPath} must contain a JSON object.`);
61
64
  if (!isRecord$1(parsed.aliases)) throw new ConfigError(`${configPath} must contain an "aliases" object.`);
62
65
  const defaults = defaultConfig();
66
+ const parsedTheme = isRecord$1(parsed.theme) ? {
67
+ ...typeof parsed.theme.preset === "string" ? { preset: parsed.theme.preset } : {},
68
+ ...typeof parsed.theme.base === "string" ? { base: parsed.theme.base } : {},
69
+ ...typeof parsed.theme.accent === "string" ? { accent: parsed.theme.accent } : {},
70
+ ...typeof parsed.theme.radius === "string" ? { radius: parsed.theme.radius } : {},
71
+ ...typeof parsed.theme.density === "string" ? { density: parsed.theme.density } : {},
72
+ ...typeof parsed.theme.font === "string" ? { font: parsed.theme.font } : {},
73
+ ...typeof parsed.theme.defaultMode === "string" ? { defaultMode: parsed.theme.defaultMode } : {}
74
+ } : void 0;
63
75
  return {
64
76
  style: typeof parsed.style === "string" ? parsed.style : defaults.style,
65
77
  rsc: typeof parsed.rsc === "boolean" ? parsed.rsc : defaults.rsc,
@@ -69,8 +81,10 @@ function readConfig(root) {
69
81
  css: typeof parsed.tailwind.css === "string" ? parsed.tailwind.css : defaults.tailwind.css,
70
82
  baseColor: typeof parsed.tailwind.baseColor === "string" ? parsed.tailwind.baseColor : defaults.tailwind.baseColor
71
83
  } : defaults.tailwind,
84
+ ...parsedTheme && Object.keys(parsedTheme).length > 0 ? { theme: parsedTheme } : {},
72
85
  aliases: {
73
86
  components: requireAlias(parsed.aliases, "components"),
87
+ ...typeof parsed.aliases.blocks === "string" && parsed.aliases.blocks.trim() !== "" ? { blocks: parsed.aliases.blocks } : {},
74
88
  utils: requireAlias(parsed.aliases, "utils")
75
89
  }
76
90
  };
@@ -117,7 +131,15 @@ function pathPosixDirname(value) {
117
131
  const index = value.lastIndexOf("/");
118
132
  return index === -1 ? "" : value.slice(0, index);
119
133
  }
120
- function toImportSpecifier(fromFile, toFile) {
134
+ function toImportSpecifier(fromFile, toFile, root, tsconfigPaths) {
135
+ if (root && tsconfigPaths) {
136
+ const relToRoot = path.relative(root, toFile).split(path.sep).join("/");
137
+ const baseDir = tsconfigPaths.targetDir;
138
+ if (baseDir === "" ? !relToRoot.startsWith("..") : relToRoot.startsWith(`${baseDir}/`)) {
139
+ const stripped = (baseDir === "" ? relToRoot : relToRoot.slice(baseDir.length + 1)).replace(/\.(tsx?|jsx?|mts?|cts?|mjs?|cjs?)$/, "").replace(/\/index$/, "");
140
+ return `${tsconfigPaths.prefix}${stripped}`;
141
+ }
142
+ }
121
143
  let specifier = path.relative(path.dirname(fromFile), toFile).split(path.sep).join("/").replace(/\.(tsx?|jsx?|mts?|cts?|mjs?|cjs?)$/, "");
122
144
  specifier = specifier.replace(/\/index$/, "");
123
145
  if (!specifier.startsWith(".")) specifier = `./${specifier}`;
@@ -125,18 +147,19 @@ function toImportSpecifier(fromFile, toFile) {
125
147
  }
126
148
  /**
127
149
  * Rewrite registry-internal relative imports so references between installed
128
- * files keep resolving at their configured destinations. Bare package imports
129
- * are left untouched.
150
+ * files keep resolving at their configured destinations. Uses the consumer's
151
+ * tsconfig path alias when available, falling back to relative paths. Bare
152
+ * package imports are left untouched.
130
153
  */
131
154
  function rewriteRelativeImports(options) {
132
- const { content, sourcePath, destPath, sourceToDest } = options;
155
+ const { content, sourcePath, destPath, sourceToDest, root, tsconfigPaths } = options;
133
156
  const knownSources = new Set(sourceToDest.keys());
134
157
  return content.replace(IMPORT_PATTERN, (match, prefix, quote, specifier) => {
135
158
  const resolved = resolveSourceFile(sourcePath, specifier, knownSources);
136
159
  if (!resolved) return match;
137
160
  const targetDest = sourceToDest.get(resolved);
138
161
  if (!targetDest || targetDest === destPath) return match;
139
- return `${prefix}${quote}${toImportSpecifier(destPath, targetDest)}${quote}`;
162
+ return `${prefix}${quote}${toImportSpecifier(destPath, targetDest, root, tsconfigPaths)}${quote}`;
140
163
  });
141
164
  }
142
165
  //#endregion
@@ -152,14 +175,22 @@ var UnsafePathError = class extends Error {
152
175
  }
153
176
  };
154
177
  const WINDOWS_ABSOLUTE = /^[A-Za-z]:[\\/]/;
155
- /** Strip the `@/` or `~/` prefix and return the root-relative alias path. */
156
- function aliasToRelativePath(alias, label) {
178
+ /** Strip the configured prefix (or `@/`/`~/`) and return the root-relative alias path. */
179
+ function aliasToRelativePath(alias, label, tsconfigPaths) {
157
180
  if (typeof alias !== "string" || alias.trim() === "") throw new UnsafePathError(alias, "", `The ${label} alias must be a non-empty string.`);
158
181
  const original = alias.trim();
159
182
  let value = original;
160
- if (value.startsWith("@/") || value.startsWith("~/")) value = value.slice(2);
183
+ let matchedPrefix = null;
184
+ if (tsconfigPaths && value.startsWith(tsconfigPaths.prefix)) {
185
+ matchedPrefix = tsconfigPaths.prefix;
186
+ value = value.slice(tsconfigPaths.prefix.length);
187
+ } else if (value.startsWith("@/") || value.startsWith("~/")) {
188
+ matchedPrefix = value.slice(0, 2);
189
+ value = value.slice(2);
190
+ }
161
191
  if (value.includes("\0")) throw new UnsafePathError(original, "", `The ${label} alias contains a null byte and cannot be used.`);
162
192
  if (path.isAbsolute(value) || WINDOWS_ABSOLUTE.test(value)) throw new UnsafePathError(original, value, `The ${label} alias "${original}" is absolute. Aliases must resolve inside the consumer root.`);
193
+ if (matchedPrefix && tsconfigPaths && matchedPrefix === tsconfigPaths.prefix && tsconfigPaths.targetDir !== "" && value !== tsconfigPaths.targetDir && !value.startsWith(`${tsconfigPaths.targetDir}/`)) value = path.posix.join(tsconfigPaths.targetDir, value);
163
194
  return value === "" ? "." : value;
164
195
  }
165
196
  function isWithinRoot(root, destination) {
@@ -188,13 +219,161 @@ function assertWithinRoot(root, destination, label) {
188
219
  if (!isWithinRoot(realpathSync(root), realpathAllowMissing(destination))) throw new UnsafePathError(label, destination, `The ${label} destination "${destination}" resolves outside the consumer root ${root} through a symbolic link.`);
189
220
  }
190
221
  /** Resolve a configured alias against the consumer root and enforce containment. */
191
- function resolveAliasWithinRoot(root, alias, label) {
192
- const relative = aliasToRelativePath(alias, label);
222
+ function resolveAliasWithinRoot(root, alias, label, tsconfigPaths) {
223
+ const relative = aliasToRelativePath(alias, label, tsconfigPaths);
193
224
  const destination = path.resolve(root, relative);
194
225
  assertWithinRoot(root, destination, label);
195
226
  return destination;
196
227
  }
197
228
  //#endregion
229
+ //#region src/lib/project.ts
230
+ const CSS_CANDIDATES = [
231
+ "src/index.css",
232
+ "src/app/globals.css",
233
+ "app/globals.css",
234
+ "src/styles/globals.css",
235
+ "src/globals.css"
236
+ ];
237
+ /** Detect the consumer's package manager from lockfiles (defaults to pnpm). */
238
+ function detectPackageManager(root) {
239
+ if (existsSync(path.join(root, "pnpm-lock.yaml"))) return "pnpm";
240
+ if (existsSync(path.join(root, "bun.lock")) || existsSync(path.join(root, "bun.lockb"))) return "bun";
241
+ if (existsSync(path.join(root, "yarn.lock"))) return "yarn";
242
+ if (existsSync(path.join(root, "package-lock.json"))) return "npm";
243
+ return "pnpm";
244
+ }
245
+ /** Build the shell command to add npm dependencies with the detected package manager. */
246
+ function formatInstallCommand(pm, dependencies) {
247
+ return `${pm} ${formatInstallArgs(pm, dependencies).join(" ")}`;
248
+ }
249
+ function formatInstallArgs(pm, dependencies) {
250
+ if (pm === "npm") return ["install", ...dependencies];
251
+ return ["add", ...dependencies];
252
+ }
253
+ /** Read dependency names already declared in the consumer's package.json. */
254
+ function readInstalledDependencies(root) {
255
+ const pkgPath = path.join(root, "package.json");
256
+ if (!existsSync(pkgPath)) return /* @__PURE__ */ new Set();
257
+ try {
258
+ const parsed = JSON.parse(readFileSync(pkgPath, "utf8"));
259
+ const installed = /* @__PURE__ */ new Set();
260
+ for (const field of [
261
+ "dependencies",
262
+ "devDependencies",
263
+ "peerDependencies"
264
+ ]) {
265
+ const group = parsed[field];
266
+ if (group && typeof group === "object" && !Array.isArray(group)) for (const name of Object.keys(group)) installed.add(name);
267
+ }
268
+ return installed;
269
+ } catch {
270
+ return /* @__PURE__ */ new Set();
271
+ }
272
+ }
273
+ function stripJsonCommentsAndTrailingCommas(raw) {
274
+ let out = "";
275
+ let inString = false;
276
+ let escaped = false;
277
+ for (let i = 0; i < raw.length; i += 1) {
278
+ const ch = raw[i];
279
+ const next = raw[i + 1];
280
+ if (inString) {
281
+ out += ch;
282
+ if (escaped) escaped = false;
283
+ else if (ch === "\\") escaped = true;
284
+ else if (ch === "\"") inString = false;
285
+ continue;
286
+ }
287
+ if (ch === "\"") {
288
+ inString = true;
289
+ out += ch;
290
+ continue;
291
+ }
292
+ if (ch === "/" && next === "/") {
293
+ while (i < raw.length && raw[i] !== "\n") i += 1;
294
+ out += "\n";
295
+ continue;
296
+ }
297
+ if (ch === "/" && next === "*") {
298
+ i += 2;
299
+ while (i < raw.length && !(raw[i] === "*" && raw[i + 1] === "/")) i += 1;
300
+ i += 1;
301
+ continue;
302
+ }
303
+ out += ch;
304
+ }
305
+ return out.replace(/,\s*([}\]])/g, "$1");
306
+ }
307
+ /**
308
+ * Inspect `tsconfig.json` (and `tsconfig.app.json`) for a wildcard path alias
309
+ * such as `"@/*": ["./src/*"]` or `"~/*": ["./src/*"]`.
310
+ */
311
+ function detectTsconfigPathMapping(root) {
312
+ for (const filename of ["tsconfig.json", "tsconfig.app.json"]) {
313
+ const filePath = path.join(root, filename);
314
+ if (!existsSync(filePath)) continue;
315
+ try {
316
+ const parsed = JSON.parse(stripJsonCommentsAndTrailingCommas(readFileSync(filePath, "utf8")));
317
+ const paths = parsed.compilerOptions?.paths;
318
+ if (!paths || typeof paths !== "object") continue;
319
+ const baseUrl = parsed.compilerOptions?.baseUrl ?? ".";
320
+ for (const [pattern, targets] of Object.entries(paths)) {
321
+ if (!pattern.endsWith("/*") || !Array.isArray(targets) || targets.length === 0) continue;
322
+ const firstTarget = targets[0];
323
+ if (typeof firstTarget !== "string" || !firstTarget.endsWith("/*")) continue;
324
+ const prefix = pattern.slice(0, -1);
325
+ const rawTarget = firstTarget.slice(0, -2);
326
+ return {
327
+ prefix,
328
+ targetDir: path.posix.normalize(path.posix.join(baseUrl.replace(/\\/g, "/"), rawTarget.replace(/\\/g, "/"))).replace(/^\.\/?/, "").replace(/\/$/, "")
329
+ };
330
+ }
331
+ } catch {
332
+ continue;
333
+ }
334
+ }
335
+ return null;
336
+ }
337
+ /** Detect an existing Tailwind CSS entry point, or return the default path. */
338
+ function detectCssEntry(root) {
339
+ for (const candidate of CSS_CANDIDATES) if (existsSync(path.join(root, candidate))) return candidate;
340
+ return "src/styles/globals.css";
341
+ }
342
+ /**
343
+ * Write `usalyt-theme.css` next to the configured Tailwind CSS entry and ensure
344
+ * that entry imports it so copied components have working design tokens without
345
+ * installing `@usalyt/ui`.
346
+ */
347
+ function injectThemeStylesheet(options) {
348
+ const { root, cssEntryRelative, themeCss, overwriteTheme = false } = options;
349
+ const normalizedEntry = cssEntryRelative.replace(/\\/g, "/").replace(/^\.?\//, "");
350
+ const cssEntryAbs = path.resolve(root, normalizedEntry);
351
+ assertWithinRoot(root, cssEntryAbs, "tailwind.css");
352
+ const themeFileAbs = path.join(path.dirname(cssEntryAbs), "usalyt-theme.css");
353
+ assertWithinRoot(root, themeFileAbs, "theme stylesheet");
354
+ mkdirSync(path.dirname(themeFileAbs), { recursive: true });
355
+ if (overwriteTheme || !existsSync(themeFileAbs)) writeFileSync(themeFileAbs, themeCss, "utf8");
356
+ const importStatement = "@import \"./usalyt-theme.css\";";
357
+ let cssUpdated = false;
358
+ if (existsSync(cssEntryAbs)) {
359
+ const existing = readFileSync(cssEntryAbs, "utf8");
360
+ if (!existing.includes("usalyt-theme.css")) {
361
+ const tailwindImport = /^@import\s+["']tailwindcss["']\s*;\s*$/m;
362
+ writeFileSync(cssEntryAbs, tailwindImport.test(existing) ? existing.replace(tailwindImport, (line) => `${line}\n${importStatement}`) : `${importStatement}\n${existing}`, "utf8");
363
+ cssUpdated = true;
364
+ }
365
+ } else {
366
+ mkdirSync(path.dirname(cssEntryAbs), { recursive: true });
367
+ writeFileSync(cssEntryAbs, `@import "tailwindcss";\n${importStatement}\n`, "utf8");
368
+ cssUpdated = true;
369
+ }
370
+ return {
371
+ themeFile: path.relative(root, themeFileAbs).split(path.sep).join("/"),
372
+ cssEntry: path.relative(root, cssEntryAbs).split(path.sep).join("/"),
373
+ cssUpdated
374
+ };
375
+ }
376
+ //#endregion
198
377
  //#region src/lib/install.ts
199
378
  var UnknownItemsError = class extends Error {
200
379
  names;
@@ -213,6 +392,7 @@ var UnsupportedItemError = class extends Error {
213
392
  const SAFE_ITEM_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
214
393
  const SAFE_FILE_BASENAME = /^[A-Za-z0-9._-]+$/;
215
394
  const REWRITE_EXTENSIONS = /\.(tsx?|jsx?|mts?|cts?)$/;
395
+ const USE_CLIENT_DIRECTIVE = /^\s*["']use client["'];?\r?\n\r?\n?/;
216
396
  function collectRegistryDependencies(targets, itemsByName) {
217
397
  const planned = /* @__PURE__ */ new Set();
218
398
  const ordered = [];
@@ -233,24 +413,43 @@ function relativeDisplayPath(root, destination) {
233
413
  function extensionOf(alias) {
234
414
  return path.extname(alias);
235
415
  }
416
+ function transformSourceContent(options) {
417
+ let result = rewriteRelativeImports({
418
+ content: options.content,
419
+ sourcePath: options.sourcePath,
420
+ destPath: options.destPath,
421
+ sourceToDest: options.sourceToDest,
422
+ root: options.root,
423
+ tsconfigPaths: options.tsconfigPaths
424
+ });
425
+ if (!options.rsc) result = result.replace(USE_CLIENT_DIRECTIVE, "");
426
+ return result;
427
+ }
236
428
  /**
237
429
  * Build every destination and its rewritten content before touching the
238
430
  * filesystem. Unknown items, unsafe destinations, directory collisions, and
239
- * conflicts are all detected here so a rejected request writes nothing.
431
+ * conflicts on explicitly requested items are detected before any write.
432
+ * Existing transitive registry dependencies are skipped rather than failing
433
+ * subsequent installs.
240
434
  */
241
435
  function buildInstallPlan(options) {
242
436
  const { registry, config, root, targets, overwrite } = options;
437
+ const tsconfigPaths = options.tsconfigPaths !== void 0 ? options.tsconfigPaths : detectTsconfigPathMapping(root);
438
+ const requestedSet = new Set(targets);
243
439
  const itemsByName = new Map(registry.items.map((item) => [item.name, item]));
244
440
  const unknown = targets.filter((target) => !itemsByName.has(target));
245
441
  if (unknown.length > 0) throw new UnknownItemsError(unknown);
246
442
  const plannedNames = collectRegistryDependencies(targets, itemsByName);
247
- const componentsDir = resolveAliasWithinRoot(root, config.aliases.components, "components");
443
+ const componentsDir = resolveAliasWithinRoot(root, config.aliases.components, "components", tsconfigPaths);
444
+ const blocksDir = config.aliases.blocks ? resolveAliasWithinRoot(root, config.aliases.blocks, "blocks", tsconfigPaths) : componentsDir;
248
445
  const utilsAlias = config.aliases.utils;
249
- let utilsDestination = resolveAliasWithinRoot(root, utilsAlias, "utils");
446
+ let utilsDestination = resolveAliasWithinRoot(root, utilsAlias, "utils", tsconfigPaths);
250
447
  if (extensionOf(utilsAlias) === "") {
251
448
  utilsDestination = `${utilsDestination}.ts`;
252
449
  assertWithinRoot(root, utilsDestination, "utils");
253
450
  }
451
+ const cssEntryRelative = (config.tailwind?.css || "src/styles/globals.css").replace(/\\/g, "/").replace(/^\.?\//, "");
452
+ const themeDestination = path.join(path.dirname(path.resolve(root, cssEntryRelative)), "usalyt-theme.css");
254
453
  const sourceToDest = /* @__PURE__ */ new Map();
255
454
  const destinationOwner = /* @__PURE__ */ new Map();
256
455
  for (const name of plannedNames) {
@@ -263,16 +462,22 @@ function buildInstallPlan(options) {
263
462
  if (file.path.startsWith("lib/")) {
264
463
  if (item.name !== "utils") throw new UnsupportedItemError(`Registry item "${item.name}" targets the shared lib directory, which is reserved for the "utils" item.`);
265
464
  destination = utilsDestination;
266
- } else destination = path.join(componentsDir, item.name, baseName);
465
+ } else if (file.path.startsWith("styles/")) destination = themeDestination;
466
+ else if (item.type === "registry:block") destination = path.join(blocksDir, item.name, baseName);
467
+ else destination = path.join(componentsDir, item.name, baseName);
267
468
  assertWithinRoot(root, destination, `"${item.name}"`);
268
469
  const owner = destinationOwner.get(destination);
269
- if (owner !== void 0 && owner !== file.path) throw new UnsupportedItemError(`Registry files "${owner}" and "${file.path}" resolve to the same destination: ${destination}`);
270
- destinationOwner.set(destination, file.path);
470
+ if (owner !== void 0 && owner.sourcePath !== file.path) throw new UnsupportedItemError(`Registry files "${owner.sourcePath}" and "${file.path}" resolve to the same destination: ${destination}`);
471
+ destinationOwner.set(destination, {
472
+ sourcePath: file.path,
473
+ itemName: item.name
474
+ });
271
475
  sourceToDest.set(file.path, destination);
272
476
  }
273
477
  }
274
478
  const conflicts = [];
275
- for (const destination of destinationOwner.keys()) {
479
+ const skippedDestinations = /* @__PURE__ */ new Set();
480
+ for (const [destination, owner] of destinationOwner.entries()) {
276
481
  let entry;
277
482
  try {
278
483
  entry = lstatSync(destination);
@@ -286,28 +491,36 @@ function buildInstallPlan(options) {
286
491
  } catch {
287
492
  throw new UnsupportedItemError(`Cannot write "${destination}" because it is a symbolic link with a missing target.`);
288
493
  }
289
- if (!isWithinRoot(realpathSync(root), realDestination)) throw new UnsafePathError(destinationOwner.get(destination) ?? "destination", destination, `The destination "${destination}" resolves outside the consumer root ${root} through a symbolic link.`);
494
+ if (!isWithinRoot(realpathSync(root), realDestination)) throw new UnsafePathError(owner.sourcePath, destination, `The destination "${destination}" resolves outside the consumer root ${root} through a symbolic link.`);
290
495
  }
291
496
  if (entry.isDirectory()) throw new UnsupportedItemError(`Cannot write "${destination}" because a directory already exists at that path.`);
292
- if (!overwrite) conflicts.push(relativeDisplayPath(root, destination));
497
+ if (!overwrite) if (requestedSet.has(owner.itemName)) conflicts.push(relativeDisplayPath(root, destination));
498
+ else skippedDestinations.add(destination);
293
499
  }
500
+ const rsc = config.rsc !== false;
294
501
  const writes = [];
502
+ const skipped = [];
295
503
  for (const name of plannedNames) {
296
504
  const item = itemsByName.get(name);
297
505
  for (const file of item.files) {
298
506
  const destination = sourceToDest.get(file.path);
299
- const content = REWRITE_EXTENSIONS.test(file.path) ? rewriteRelativeImports({
507
+ const content = REWRITE_EXTENSIONS.test(file.path) ? transformSourceContent({
300
508
  content: file.content,
301
509
  sourcePath: file.path,
302
510
  destPath: destination,
303
- sourceToDest
511
+ sourceToDest,
512
+ root,
513
+ rsc,
514
+ tsconfigPaths
304
515
  }) : file.content;
305
- writes.push({
516
+ const planned = {
306
517
  item: item.name,
307
518
  destination,
308
519
  relativeDestination: relativeDisplayPath(root, destination),
309
520
  content
310
- });
521
+ };
522
+ if (skippedDestinations.has(destination)) skipped.push(planned);
523
+ else writes.push(planned);
311
524
  }
312
525
  }
313
526
  const dependencies = /* @__PURE__ */ new Set();
@@ -317,6 +530,7 @@ function buildInstallPlan(options) {
317
530
  }
318
531
  return {
319
532
  writes,
533
+ skipped,
320
534
  dependencies: [...dependencies].sort(),
321
535
  conflicts: conflicts.sort()
322
536
  };
@@ -404,16 +618,16 @@ async function confirmInstall(command) {
404
618
  rl.close();
405
619
  }
406
620
  }
407
- function runPnpmAdd(root, dependencies) {
408
- const result = spawnSync("pnpm", ["add", ...dependencies], {
621
+ function runPackageInstall(root, pm, dependencies) {
622
+ const result = spawnSync(pm, formatInstallArgs(pm, dependencies), {
409
623
  cwd: root,
410
624
  stdio: "inherit"
411
625
  });
412
626
  if (result.error) {
413
- printError(`could not run pnpm: ${result.error.message}`);
627
+ printError(`could not run ${pm}: ${result.error.message}`);
414
628
  return;
415
629
  }
416
- if (result.status !== 0) printError(`pnpm add exited with status ${String(result.status)}.`);
630
+ if (result.status !== 0) printError(`${pm} exited with status ${String(result.status)}.`);
417
631
  }
418
632
  const addCommand = defineCommand({
419
633
  meta: {
@@ -443,7 +657,7 @@ const addCommand = defineCommand({
443
657
  },
444
658
  install: {
445
659
  type: "boolean",
446
- description: "Run the printed pnpm add command when consent is confirmed"
660
+ description: "Install missing npm dependencies using the detected package manager"
447
661
  }
448
662
  },
449
663
  async run({ args }) {
@@ -503,35 +717,977 @@ const addCommand = defineCommand({
503
717
  return;
504
718
  }
505
719
  const installedItems = new Set(plan.writes.map((write) => write.item)).size;
506
- const dependencyCount = installedItems - targets.length;
507
- console.log(`Installed ${installedItems} item(s) (${targets.length} requested, ${dependencyCount} registry dependencies):`);
720
+ const requestedInstalled = targets.filter((t) => plan.writes.some((write) => write.item === t)).length;
721
+ const dependencyCount = Math.max(0, installedItems - requestedInstalled);
722
+ console.log(`Installed ${installedItems} item(s) (${requestedInstalled} requested, ${dependencyCount} registry dependencies):`);
508
723
  for (const write of plan.writes) console.log(` + ${write.relativeDestination}`);
509
- if (plan.dependencies.length === 0) {
510
- console.log("No npm dependencies required.");
724
+ if (plan.skipped.length > 0) {
725
+ console.log(`Skipped ${plan.skipped.length} existing dependency file(s):`);
726
+ for (const skipped of plan.skipped) console.log(` = ${skipped.relativeDestination}`);
727
+ }
728
+ const installedPackages = readInstalledDependencies(root);
729
+ const missingDependencies = plan.dependencies.filter((dep) => !installedPackages.has(dep));
730
+ if (missingDependencies.length === 0) {
731
+ console.log(plan.dependencies.length === 0 ? "No npm dependencies required." : "All required npm dependencies are already installed.");
511
732
  return;
512
733
  }
513
- const installCommand = `pnpm add ${plan.dependencies.join(" ")}`;
734
+ const pm = detectPackageManager(root);
735
+ const installCommand = formatInstallCommand(pm, missingDependencies);
514
736
  console.log(`Dependencies: ${installCommand}`);
515
737
  if (!args.install) {
516
738
  console.log("Dependencies were not installed. Run the command above, or pass --install --yes to execute it.");
517
739
  return;
518
740
  }
519
741
  if (!args.yes) {
520
- if (process.stdin.isTTY && process.stdout.isTTY) if (await confirmInstall(installCommand)) runPnpmAdd(root, plan.dependencies);
742
+ if (process.stdin.isTTY && process.stdout.isTTY) if (await confirmInstall(installCommand)) runPackageInstall(root, pm, missingDependencies);
521
743
  else console.log("Dependencies were not installed.");
522
744
  else console.log("Dependencies were not installed because consent was not confirmed. Pass --yes to execute the printed command.");
523
745
  return;
524
746
  }
525
- runPnpmAdd(root, plan.dependencies);
747
+ runPackageInstall(root, pm, missingDependencies);
748
+ }
749
+ });
750
+ //#endregion
751
+ //#region src/commands/diff.ts
752
+ function renderLineDiff(localText, registryText) {
753
+ const localLines = localText.split(/\r?\n/);
754
+ const registryLines = registryText.split(/\r?\n/);
755
+ const max = Math.max(localLines.length, registryLines.length);
756
+ const diff = [];
757
+ for (let i = 0; i < max; i += 1) {
758
+ const localLine = localLines[i];
759
+ const registryLine = registryLines[i];
760
+ if (localLine === registryLine) continue;
761
+ if (localLine !== void 0) diff.push(pc.red(`- L${i + 1}: ${localLine}`));
762
+ if (registryLine !== void 0) diff.push(pc.green(`+ L${i + 1}: ${registryLine}`));
763
+ }
764
+ return diff;
765
+ }
766
+ const diffCommand = defineCommand({
767
+ meta: {
768
+ name: "diff",
769
+ description: "Compare local installed components against the packaged registry"
770
+ },
771
+ args: { components: {
772
+ type: "positional",
773
+ description: "Component name(s) to compare (defaults to all installed items)",
774
+ required: false
775
+ } },
776
+ run({ args }) {
777
+ const root = process.cwd();
778
+ let registry;
779
+ try {
780
+ ({registry} = loadRegistry());
781
+ } catch (error) {
782
+ printError(error instanceof RegistryLoadError ? error.message : String(error));
783
+ return;
784
+ }
785
+ let config;
786
+ try {
787
+ config = readConfig(root) ?? defaultConfig();
788
+ } catch (error) {
789
+ printError(error.message);
790
+ return;
791
+ }
792
+ const positionals = Array.isArray(args._) ? args._.map((v) => String(v).trim()).filter(Boolean) : [];
793
+ const targets = positionals.length > 0 ? [...new Set(positionals)] : registry.items.map((item) => item.name);
794
+ let plan;
795
+ try {
796
+ plan = buildInstallPlan({
797
+ registry,
798
+ config,
799
+ root,
800
+ targets,
801
+ overwrite: true
802
+ });
803
+ } catch (error) {
804
+ if (error instanceof UnknownItemsError) printError(`${error.message}.`);
805
+ else printError(error.message);
806
+ return;
807
+ }
808
+ const targetSet = new Set(targets);
809
+ const inspected = plan.writes.filter((entry) => targetSet.has(entry.item));
810
+ let checked = 0;
811
+ let changed = 0;
812
+ for (const file of inspected) {
813
+ if (!existsSync(file.destination)) {
814
+ if (positionals.length > 0) {
815
+ console.log(`${pc.yellow("missing")} ${file.relativeDestination}`);
816
+ changed += 1;
817
+ }
818
+ continue;
819
+ }
820
+ checked += 1;
821
+ const localContent = readFileSync(file.destination, "utf8");
822
+ if (localContent === file.content) {
823
+ if (positionals.length > 0) console.log(`${pc.green("up to date")} ${file.relativeDestination}`);
824
+ continue;
825
+ }
826
+ changed += 1;
827
+ console.log(`${pc.yellow("modified")} ${file.relativeDestination}`);
828
+ const lines = renderLineDiff(localContent, file.content);
829
+ for (const line of lines.slice(0, 40)) console.log(` ${line}`);
830
+ if (lines.length > 40) console.log(` ... (${lines.length - 40} more diff lines)`);
831
+ }
832
+ if (checked === 0 && positionals.length === 0) {
833
+ console.log("No installed Usalyt registry files found.");
834
+ return;
835
+ }
836
+ if (changed === 0) console.log(`All ${checked} checked file(s) are up to date.`);
526
837
  }
527
838
  });
528
839
  //#endregion
840
+ //#region ../registry/src/theme-presets.ts
841
+ const DEFAULT_SEMANTIC_COLORS = {
842
+ light: {
843
+ success: "#1e8e3e",
844
+ warning: "#d97706",
845
+ danger: "#b91c1c",
846
+ info: "#027a9e"
847
+ },
848
+ dark: {
849
+ success: "#1e8e3e",
850
+ warning: "#d97706",
851
+ danger: "#dc2626",
852
+ info: "#027a9e"
853
+ }
854
+ };
855
+ const DEFAULT_THEME_CONFIG = {
856
+ base: "graphite",
857
+ accent: "signal-orange",
858
+ radius: "md",
859
+ density: "default",
860
+ font: "inter",
861
+ defaultMode: "light"
862
+ };
863
+ const THEME_BASES = {
864
+ graphite: {
865
+ id: "graphite",
866
+ label: "Graphite",
867
+ dark: {
868
+ canvas: "#0e0e10",
869
+ surface1: "#161618",
870
+ surface2: "#1e1e21",
871
+ surface3: "#26262a",
872
+ surface4: "#2b2b30",
873
+ hairline: "#28282c",
874
+ hairlineStrong: "#3a3a40",
875
+ hairlineTertiary: "#4e4e56",
876
+ ink: "#f2f1ed",
877
+ inkMuted: "#cfcbc2",
878
+ inkSubtle: "#96948e",
879
+ inkTertiary: "#6e6c66",
880
+ field: "rgb(255 255 255 / 0.03)"
881
+ },
882
+ light: {
883
+ canvas: "#f4f3ef",
884
+ surface1: "#ffffff",
885
+ surface2: "#eae8e2",
886
+ surface3: "#e1dfd8",
887
+ surface4: "#ffffff",
888
+ hairline: "#d8d5cd",
889
+ hairlineStrong: "#bfbbb1",
890
+ hairlineTertiary: "#a39f94",
891
+ ink: "#121213",
892
+ inkMuted: "#343330",
893
+ inkSubtle: "#52514e",
894
+ inkTertiary: "#6e6c67",
895
+ field: "rgb(18 18 19 / 0.03)"
896
+ }
897
+ },
898
+ linear: {
899
+ id: "linear",
900
+ label: "Linear",
901
+ dark: {
902
+ canvas: "#010102",
903
+ surface1: "#0f1011",
904
+ surface2: "#141516",
905
+ surface3: "#18191a",
906
+ surface4: "#191a1b",
907
+ hairline: "#23252a",
908
+ hairlineStrong: "#34343a",
909
+ hairlineTertiary: "#3e3e44",
910
+ ink: "#f7f8f8",
911
+ inkMuted: "#d0d6e0",
912
+ inkSubtle: "#8a8f98",
913
+ inkTertiary: "#62666d",
914
+ field: "rgb(255 255 255 / 0.025)"
915
+ },
916
+ light: {
917
+ canvas: "#ffffff",
918
+ surface1: "#ffffff",
919
+ surface2: "#f5f6f6",
920
+ surface3: "#eceef0",
921
+ surface4: "#f6f7f7",
922
+ hairline: "#e4e5e7",
923
+ hairlineStrong: "#d2d4d8",
924
+ hairlineTertiary: "#c2c5cb",
925
+ ink: "#010102",
926
+ inkMuted: "#26282e",
927
+ inkSubtle: "#5c6068",
928
+ inkTertiary: "#62666d",
929
+ field: "rgb(1 1 2 / 0.025)"
930
+ }
931
+ },
932
+ zinc: {
933
+ id: "zinc",
934
+ label: "Zinc",
935
+ dark: {
936
+ canvas: "#09090b",
937
+ surface1: "#111114",
938
+ surface2: "#18181b",
939
+ surface3: "#202024",
940
+ surface4: "#27272a",
941
+ hairline: "#27272a",
942
+ hairlineStrong: "#3f3f46",
943
+ hairlineTertiary: "#52525b",
944
+ ink: "#fafafa",
945
+ inkMuted: "#d4d4d8",
946
+ inkSubtle: "#a1a1aa",
947
+ inkTertiary: "#71717a",
948
+ field: "rgb(255 255 255 / 0.03)"
949
+ },
950
+ light: {
951
+ canvas: "#ffffff",
952
+ surface1: "#ffffff",
953
+ surface2: "#f4f4f5",
954
+ surface3: "#e4e4e7",
955
+ surface4: "#f4f4f5",
956
+ hairline: "#e4e4e7",
957
+ hairlineStrong: "#d4d4d8",
958
+ hairlineTertiary: "#a1a1aa",
959
+ ink: "#09090b",
960
+ inkMuted: "#27272a",
961
+ inkSubtle: "#52525b",
962
+ inkTertiary: "#71717a",
963
+ field: "rgb(9 9 11 / 0.025)"
964
+ }
965
+ },
966
+ slate: {
967
+ id: "slate",
968
+ label: "Slate",
969
+ dark: {
970
+ canvas: "#080d17",
971
+ surface1: "#0f172a",
972
+ surface2: "#152036",
973
+ surface3: "#1e293b",
974
+ surface4: "#253349",
975
+ hairline: "#243247",
976
+ hairlineStrong: "#334155",
977
+ hairlineTertiary: "#475569",
978
+ ink: "#f8fafc",
979
+ inkMuted: "#cbd5e1",
980
+ inkSubtle: "#94a3b8",
981
+ inkTertiary: "#64748b",
982
+ field: "rgb(255 255 255 / 0.03)"
983
+ },
984
+ light: {
985
+ canvas: "#fafbfc",
986
+ surface1: "#ffffff",
987
+ surface2: "#f1f5f9",
988
+ surface3: "#e2e8f0",
989
+ surface4: "#f1f5f9",
990
+ hairline: "#dce3ec",
991
+ hairlineStrong: "#cbd5e1",
992
+ hairlineTertiary: "#94a3b8",
993
+ ink: "#0b1220",
994
+ inkMuted: "#1e293b",
995
+ inkSubtle: "#475569",
996
+ inkTertiary: "#64748b",
997
+ field: "rgb(15 23 42 / 0.025)"
998
+ }
999
+ },
1000
+ stone: {
1001
+ id: "stone",
1002
+ label: "Stone",
1003
+ dark: {
1004
+ canvas: "#0c0a09",
1005
+ surface1: "#161311",
1006
+ surface2: "#1c1917",
1007
+ surface3: "#26221f",
1008
+ surface4: "#2e2925",
1009
+ hairline: "#2e2925",
1010
+ hairlineStrong: "#44403c",
1011
+ hairlineTertiary: "#57534e",
1012
+ ink: "#fafaf9",
1013
+ inkMuted: "#d6d3d1",
1014
+ inkSubtle: "#a8a29e",
1015
+ inkTertiary: "#78716c",
1016
+ field: "rgb(255 255 255 / 0.03)"
1017
+ },
1018
+ light: {
1019
+ canvas: "#fafaf9",
1020
+ surface1: "#ffffff",
1021
+ surface2: "#f5f5f4",
1022
+ surface3: "#e7e5e4",
1023
+ surface4: "#f5f5f4",
1024
+ hairline: "#e7e5e4",
1025
+ hairlineStrong: "#d6d3d1",
1026
+ hairlineTertiary: "#a8a29e",
1027
+ ink: "#0c0a09",
1028
+ inkMuted: "#292524",
1029
+ inkSubtle: "#57534e",
1030
+ inkTertiary: "#78716c",
1031
+ field: "rgb(12 10 9 / 0.025)"
1032
+ }
1033
+ }
1034
+ };
1035
+ const THEME_ACCENTS = {
1036
+ "signal-orange": {
1037
+ id: "signal-orange",
1038
+ label: "Signal Orange",
1039
+ swatch: "#f2541b",
1040
+ dark: {
1041
+ primary: "#f2541b",
1042
+ primaryForeground: "#0e0e10",
1043
+ primaryHover: "#ff6b35",
1044
+ primaryFocus: "#f2541b",
1045
+ ring: "#f2541b"
1046
+ },
1047
+ light: {
1048
+ primary: "#c83e0b",
1049
+ primaryForeground: "#ffffff",
1050
+ primaryHover: "#b03508",
1051
+ primaryFocus: "#ea4b14",
1052
+ ring: "#ea4b14"
1053
+ }
1054
+ },
1055
+ lavender: {
1056
+ id: "lavender",
1057
+ label: "Lavender",
1058
+ swatch: "#5e6ad2",
1059
+ dark: {
1060
+ primary: "#5e6ad2",
1061
+ primaryForeground: "#ffffff",
1062
+ primaryHover: "#828fff",
1063
+ primaryFocus: "#5e69d1",
1064
+ ring: "#5e69d1"
1065
+ },
1066
+ light: {
1067
+ primary: "#5e6ad2",
1068
+ primaryForeground: "#ffffff",
1069
+ primaryHover: "#4f5bc4",
1070
+ primaryFocus: "#5e69d1",
1071
+ ring: "#5e69d1"
1072
+ }
1073
+ },
1074
+ cobalt: {
1075
+ id: "cobalt",
1076
+ label: "Cobalt",
1077
+ swatch: "#2563eb",
1078
+ dark: {
1079
+ primary: "#2563eb",
1080
+ primaryForeground: "#ffffff",
1081
+ primaryHover: "#3b82f6",
1082
+ primaryFocus: "#1d4ed8",
1083
+ ring: "#60a5fa"
1084
+ },
1085
+ light: {
1086
+ primary: "#1d4ed8",
1087
+ primaryForeground: "#ffffff",
1088
+ primaryHover: "#1e40af",
1089
+ primaryFocus: "#1d4ed8",
1090
+ ring: "#1d4ed8"
1091
+ }
1092
+ },
1093
+ emerald: {
1094
+ id: "emerald",
1095
+ label: "Emerald",
1096
+ swatch: "#15803d",
1097
+ dark: {
1098
+ primary: "#15803d",
1099
+ primaryForeground: "#ffffff",
1100
+ primaryHover: "#16a34a",
1101
+ primaryFocus: "#166534",
1102
+ ring: "#4ade80"
1103
+ },
1104
+ light: {
1105
+ primary: "#15803d",
1106
+ primaryForeground: "#ffffff",
1107
+ primaryHover: "#166534",
1108
+ primaryFocus: "#15803d",
1109
+ ring: "#15803d"
1110
+ }
1111
+ },
1112
+ amber: {
1113
+ id: "amber",
1114
+ label: "Amber",
1115
+ swatch: "#f59e0b",
1116
+ dark: {
1117
+ primary: "#f59e0b",
1118
+ primaryForeground: "#010102",
1119
+ primaryHover: "#fbbf24",
1120
+ primaryFocus: "#d97706",
1121
+ ring: "#fbbf24"
1122
+ },
1123
+ light: {
1124
+ primary: "#b45309",
1125
+ primaryForeground: "#ffffff",
1126
+ primaryHover: "#92400e",
1127
+ primaryFocus: "#b45309",
1128
+ ring: "#b45309"
1129
+ }
1130
+ },
1131
+ crimson: {
1132
+ id: "crimson",
1133
+ label: "Crimson",
1134
+ swatch: "#dc2626",
1135
+ dark: {
1136
+ primary: "#dc2626",
1137
+ primaryForeground: "#ffffff",
1138
+ primaryHover: "#ef4444",
1139
+ primaryFocus: "#b91c1c",
1140
+ ring: "#f87171"
1141
+ },
1142
+ light: {
1143
+ primary: "#b91c1c",
1144
+ primaryForeground: "#ffffff",
1145
+ primaryHover: "#991b1b",
1146
+ primaryFocus: "#b91c1c",
1147
+ ring: "#b91c1c"
1148
+ }
1149
+ },
1150
+ monochrome: {
1151
+ id: "monochrome",
1152
+ label: "Monochrome",
1153
+ swatch: "#f7f8f8",
1154
+ dark: {
1155
+ primary: "#f7f8f8",
1156
+ primaryForeground: "#010102",
1157
+ primaryHover: "#d0d6e0",
1158
+ primaryFocus: "#ffffff",
1159
+ ring: "#d0d6e0"
1160
+ },
1161
+ light: {
1162
+ primary: "#111113",
1163
+ primaryForeground: "#ffffff",
1164
+ primaryHover: "#27272a",
1165
+ primaryFocus: "#010102",
1166
+ ring: "#27272a"
1167
+ }
1168
+ }
1169
+ };
1170
+ const THEME_RADII = {
1171
+ none: {
1172
+ id: "none",
1173
+ label: "Sharp (0px)",
1174
+ basePx: 0,
1175
+ scale: {
1176
+ xs: "0px",
1177
+ sm: "0px",
1178
+ md: "0px",
1179
+ lg: "0px",
1180
+ xl: "0px",
1181
+ xxl: "0px"
1182
+ }
1183
+ },
1184
+ sm: {
1185
+ id: "sm",
1186
+ label: "Crisp (4px)",
1187
+ basePx: 4,
1188
+ scale: {
1189
+ xs: "2px",
1190
+ sm: "3px",
1191
+ md: "4px",
1192
+ lg: "6px",
1193
+ xl: "8px",
1194
+ xxl: "12px"
1195
+ }
1196
+ },
1197
+ md: {
1198
+ id: "md",
1199
+ label: "Machined (6px)",
1200
+ basePx: 6,
1201
+ scale: {
1202
+ xs: "3px",
1203
+ sm: "4.5px",
1204
+ md: "6px",
1205
+ lg: "9px",
1206
+ xl: "12px",
1207
+ xxl: "18px"
1208
+ }
1209
+ },
1210
+ lg: {
1211
+ id: "lg",
1212
+ label: "Soft (12px)",
1213
+ basePx: 12,
1214
+ scale: {
1215
+ xs: "6px",
1216
+ sm: "8px",
1217
+ md: "12px",
1218
+ lg: "16px",
1219
+ xl: "20px",
1220
+ xxl: "28px"
1221
+ }
1222
+ },
1223
+ xl: {
1224
+ id: "xl",
1225
+ label: "Rounded (16px)",
1226
+ basePx: 16,
1227
+ scale: {
1228
+ xs: "8px",
1229
+ sm: "10px",
1230
+ md: "16px",
1231
+ lg: "20px",
1232
+ xl: "24px",
1233
+ xxl: "32px"
1234
+ }
1235
+ }
1236
+ };
1237
+ const THEME_DENSITIES = {
1238
+ compact: {
1239
+ id: "compact",
1240
+ label: "Compact (90%)",
1241
+ percent: 90,
1242
+ spacing: "0.225rem"
1243
+ },
1244
+ default: {
1245
+ id: "default",
1246
+ label: "Default (100%)",
1247
+ percent: 100,
1248
+ spacing: "0.25rem"
1249
+ },
1250
+ comfortable: {
1251
+ id: "comfortable",
1252
+ label: "Spacious (110%)",
1253
+ percent: 110,
1254
+ spacing: "0.275rem"
1255
+ }
1256
+ };
1257
+ const THEME_FONTS = {
1258
+ inter: {
1259
+ id: "inter",
1260
+ label: "Inter Variable",
1261
+ stack: "\"Inter Variable\", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif"
1262
+ },
1263
+ system: {
1264
+ id: "system",
1265
+ label: "System UI",
1266
+ stack: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif"
1267
+ },
1268
+ geist: {
1269
+ id: "geist",
1270
+ label: "Geist Sans",
1271
+ stack: "\"Geist\", \"Inter Variable\", ui-sans-serif, system-ui, -apple-system, sans-serif"
1272
+ },
1273
+ jakarta: {
1274
+ id: "jakarta",
1275
+ label: "Plus Jakarta Sans",
1276
+ stack: "\"Plus Jakarta Sans\", \"Inter Variable\", ui-sans-serif, system-ui, -apple-system, sans-serif"
1277
+ }
1278
+ };
1279
+ const NAMED_THEME_PRESETS = [
1280
+ {
1281
+ id: "graphite",
1282
+ label: "Graphite",
1283
+ description: "Dual-polarity anodized chalk light and matte graphite dark with machined 6px corners and Signal Orange.",
1284
+ config: { ...DEFAULT_THEME_CONFIG }
1285
+ },
1286
+ {
1287
+ id: "linear",
1288
+ label: "Linear Craft",
1289
+ description: "Preserved Linear near-black canvas, four-step charcoal ladder, and lavender-blue accent.",
1290
+ config: {
1291
+ base: "linear",
1292
+ accent: "lavender",
1293
+ radius: "lg",
1294
+ density: "default",
1295
+ font: "inter",
1296
+ defaultMode: "dark"
1297
+ }
1298
+ },
1299
+ {
1300
+ id: "minimal-light",
1301
+ label: "Minimal Light",
1302
+ description: "High-contrast monochrome gallery canvas with crisp 4px corners.",
1303
+ config: {
1304
+ base: "zinc",
1305
+ accent: "monochrome",
1306
+ radius: "sm",
1307
+ density: "default",
1308
+ font: "inter",
1309
+ defaultMode: "light"
1310
+ }
1311
+ },
1312
+ {
1313
+ id: "console-dense",
1314
+ label: "Console Dense",
1315
+ description: "Compact 90% spacing for data-heavy dashboards and audit workflows.",
1316
+ config: {
1317
+ base: "slate",
1318
+ accent: "cobalt",
1319
+ radius: "sm",
1320
+ density: "compact",
1321
+ font: "inter",
1322
+ defaultMode: "dark"
1323
+ }
1324
+ },
1325
+ {
1326
+ id: "editorial-stone",
1327
+ label: "Editorial Stone",
1328
+ description: "Warm stone neutrals, emerald accent, and spacious 110% rhythm.",
1329
+ config: {
1330
+ base: "stone",
1331
+ accent: "emerald",
1332
+ radius: "lg",
1333
+ density: "comfortable",
1334
+ font: "jakarta",
1335
+ defaultMode: "dark"
1336
+ }
1337
+ }
1338
+ ];
1339
+ const HEX6_RE = /^#([0-9a-fA-F]{6})$/;
1340
+ function isValidHexColor(value) {
1341
+ return HEX6_RE.test(value.trim());
1342
+ }
1343
+ function hexToRgbTuple(hex) {
1344
+ const clean = hex.trim().replace(/^#/, "");
1345
+ return [
1346
+ parseInt(clean.slice(0, 2), 16),
1347
+ parseInt(clean.slice(2, 4), 16),
1348
+ parseInt(clean.slice(4, 6), 16)
1349
+ ];
1350
+ }
1351
+ function rgbTupleToHex(r, g, b) {
1352
+ const clamp = (n) => Math.min(255, Math.max(0, Math.round(n)));
1353
+ return "#" + [
1354
+ clamp(r),
1355
+ clamp(g),
1356
+ clamp(b)
1357
+ ].map((n) => n.toString(16).padStart(2, "0")).join("");
1358
+ }
1359
+ function relativeLuminance(hex) {
1360
+ const [r, g, b] = hexToRgbTuple(hex).map((channel) => {
1361
+ const s = channel / 255;
1362
+ return s <= .03928 ? s / 12.92 : Math.pow((s + .055) / 1.055, 2.4);
1363
+ });
1364
+ return .2126 * r + .7152 * g + .0722 * b;
1365
+ }
1366
+ function contrastRatioHex(hexA, hexB) {
1367
+ const l1 = relativeLuminance(hexA);
1368
+ const l2 = relativeLuminance(hexB);
1369
+ const lighter = Math.max(l1, l2);
1370
+ const darker = Math.min(l1, l2);
1371
+ return (lighter + .05) / (darker + .05);
1372
+ }
1373
+ function shiftHex(hex, targetHex, amount) {
1374
+ const [r1, g1, b1] = hexToRgbTuple(hex);
1375
+ const [r2, g2, b2] = hexToRgbTuple(targetHex);
1376
+ return rgbTupleToHex(r1 + (r2 - r1) * amount, g1 + (g2 - g1) * amount, b1 + (b2 - b1) * amount);
1377
+ }
1378
+ function resolveAccentTokens(accent, mode) {
1379
+ if (accent in THEME_ACCENTS) {
1380
+ const spec = THEME_ACCENTS[accent][mode];
1381
+ return {
1382
+ ...spec,
1383
+ contrast: contrastRatioHex(spec.primaryForeground, spec.primary)
1384
+ };
1385
+ }
1386
+ const normalized = isValidHexColor(accent) ? accent.trim().toLowerCase() : "#c83e0b";
1387
+ const whiteRatio = contrastRatioHex("#ffffff", normalized);
1388
+ const darkRatio = contrastRatioHex("#0e0e10", normalized);
1389
+ const primaryForeground = whiteRatio >= darkRatio ? "#ffffff" : "#0e0e10";
1390
+ const contrast = Math.max(whiteRatio, darkRatio);
1391
+ return {
1392
+ primary: normalized,
1393
+ primaryForeground,
1394
+ primaryHover: mode === "dark" ? shiftHex(normalized, "#ffffff", .14) : shiftHex(normalized, "#010102", .14),
1395
+ primaryFocus: shiftHex(normalized, "#010102", .08),
1396
+ ring: normalized,
1397
+ contrast
1398
+ };
1399
+ }
1400
+ function calibrateSemanticInk(hueHex, canvasHex, mode) {
1401
+ const target = mode === "dark" ? "#ffffff" : "#0e0e10";
1402
+ let candidate = hueHex;
1403
+ for (let step = 0; step <= 10; step += 1) {
1404
+ candidate = shiftHex(hueHex, target, step * .08);
1405
+ if (contrastRatioHex(candidate, canvasHex) >= 4.7) return candidate;
1406
+ }
1407
+ return target;
1408
+ }
1409
+ function resolveSemanticTokens(overrides, mode, canvasHex) {
1410
+ const defaults = DEFAULT_SEMANTIC_COLORS[mode];
1411
+ const pick = (key) => {
1412
+ const raw = overrides?.[key];
1413
+ return raw && isValidHexColor(raw) ? raw.trim().toLowerCase() : defaults[key];
1414
+ };
1415
+ const success = pick("success");
1416
+ const warning = pick("warning");
1417
+ const danger = pick("danger");
1418
+ const info = pick("info");
1419
+ const whiteOnDanger = contrastRatioHex("#ffffff", danger);
1420
+ const darkOnDanger = contrastRatioHex("#0e0e10", danger);
1421
+ return {
1422
+ success,
1423
+ successForeground: calibrateSemanticInk(success, canvasHex, mode),
1424
+ warning,
1425
+ warningForeground: calibrateSemanticInk(warning, canvasHex, mode),
1426
+ danger,
1427
+ dangerForeground: calibrateSemanticInk(danger, canvasHex, mode),
1428
+ dangerOnSolid: whiteOnDanger >= darkOnDanger ? "#ffffff" : "#0e0e10",
1429
+ info,
1430
+ infoForeground: calibrateSemanticInk(info, canvasHex, mode)
1431
+ };
1432
+ }
1433
+ function hasCustomSemantics(semantic) {
1434
+ if (!semantic) return false;
1435
+ return Boolean(semantic.success && isValidHexColor(semantic.success) || semantic.warning && isValidHexColor(semantic.warning) || semantic.danger && isValidHexColor(semantic.danger) || semantic.info && isValidHexColor(semantic.info));
1436
+ }
1437
+ function buildScopedThemeVars(config, activeMode) {
1438
+ const surface = (THEME_BASES[config.base] ?? THEME_BASES.graphite)[activeMode];
1439
+ const accent = resolveAccentTokens(config.accent, activeMode);
1440
+ const semantic = resolveSemanticTokens(config.semantic, activeMode, surface.canvas);
1441
+ const radius = THEME_RADII[config.radius] ?? THEME_RADII.md;
1442
+ const density = THEME_DENSITIES[config.density] ?? THEME_DENSITIES.default;
1443
+ const font = THEME_FONTS[config.font] ?? THEME_FONTS.inter;
1444
+ return {
1445
+ "--spacing": density.spacing,
1446
+ "--font-sans": font.stack,
1447
+ "--radius": `${radius.basePx}px`,
1448
+ "--radius-xs": radius.scale.xs,
1449
+ "--radius-sm": radius.scale.sm,
1450
+ "--radius-md": radius.scale.md,
1451
+ "--radius-lg": radius.scale.lg,
1452
+ "--radius-xl": radius.scale.xl,
1453
+ "--radius-xxl": radius.scale.xxl,
1454
+ "--color-background": surface.canvas,
1455
+ "--color-foreground": surface.ink,
1456
+ "--color-card": surface.surface1,
1457
+ "--color-card-foreground": surface.ink,
1458
+ "--color-popover": activeMode === "dark" ? surface.surface3 : surface.surface1,
1459
+ "--color-popover-foreground": surface.ink,
1460
+ "--color-secondary": surface.surface2,
1461
+ "--color-secondary-foreground": activeMode === "dark" ? surface.inkMuted : surface.ink,
1462
+ "--color-muted": surface.surface2,
1463
+ "--color-muted-foreground": surface.inkSubtle,
1464
+ "--color-accent": surface.surface3,
1465
+ "--color-accent-foreground": surface.ink,
1466
+ "--color-border": surface.hairline,
1467
+ "--color-input": surface.hairlineStrong,
1468
+ "--color-hairline": surface.hairline,
1469
+ "--color-hairline-strong": surface.hairlineStrong,
1470
+ "--color-hairline-tertiary": surface.hairlineTertiary,
1471
+ "--color-fog": surface.inkSubtle,
1472
+ "--color-field": surface.field,
1473
+ "--color-surface-base": surface.canvas,
1474
+ "--color-surface-raised": surface.surface1,
1475
+ "--color-surface-overlay": activeMode === "dark" ? surface.surface3 : surface.surface1,
1476
+ "--color-surface-inset": surface.surface2,
1477
+ "--color-sidebar": activeMode === "dark" ? surface.surface1 : surface.surface2,
1478
+ "--color-sidebar-foreground": surface.ink,
1479
+ "--color-sidebar-border": surface.hairline,
1480
+ "--color-sidebar-ring": accent.ring,
1481
+ "--color-sidebar-accent": surface.surface3,
1482
+ "--color-sidebar-accent-foreground": surface.ink,
1483
+ "--color-primary": accent.primary,
1484
+ "--color-primary-foreground": accent.primaryForeground,
1485
+ "--color-primary-hover": accent.primaryHover,
1486
+ "--color-primary-focus": accent.primaryFocus,
1487
+ "--color-ring": accent.ring,
1488
+ "--color-pulse-green": semantic.success,
1489
+ "--color-semantic-success": semantic.success,
1490
+ "--color-pulse-green-foreground": semantic.successForeground,
1491
+ "--color-amber-signal": semantic.warning,
1492
+ "--color-amber-signal-foreground": semantic.warningForeground,
1493
+ "--color-coral-red": semantic.danger,
1494
+ "--color-coral-red-foreground": semantic.dangerForeground,
1495
+ "--color-destructive": semantic.danger,
1496
+ "--color-destructive-foreground": semantic.dangerOnSolid,
1497
+ "--color-signal-teal": semantic.info,
1498
+ "--color-signal-teal-foreground": semantic.infoForeground
1499
+ };
1500
+ }
1501
+ function isDefaultThemeConfig(config) {
1502
+ return config.base === DEFAULT_THEME_CONFIG.base && config.accent === DEFAULT_THEME_CONFIG.accent && config.radius === DEFAULT_THEME_CONFIG.radius && config.density === DEFAULT_THEME_CONFIG.density && config.font === DEFAULT_THEME_CONFIG.font && config.defaultMode === DEFAULT_THEME_CONFIG.defaultMode && !hasCustomSemantics(config.semantic);
1503
+ }
1504
+ function encodeThemePreset(config) {
1505
+ if (!hasCustomSemantics(config.semantic)) {
1506
+ const matched = NAMED_THEME_PRESETS.find((preset) => preset.config.base === config.base && preset.config.accent === config.accent && preset.config.radius === config.radius && preset.config.density === config.density && preset.config.font === config.font && preset.config.defaultMode === config.defaultMode);
1507
+ if (matched) return matched.id;
1508
+ }
1509
+ const params = new URLSearchParams();
1510
+ if (config.base !== DEFAULT_THEME_CONFIG.base) params.set("base", config.base);
1511
+ if (config.accent !== DEFAULT_THEME_CONFIG.accent) params.set("accent", config.accent);
1512
+ if (config.radius !== DEFAULT_THEME_CONFIG.radius) params.set("radius", config.radius);
1513
+ if (config.density !== DEFAULT_THEME_CONFIG.density) params.set("density", config.density);
1514
+ if (config.font !== DEFAULT_THEME_CONFIG.font) params.set("font", config.font);
1515
+ if (config.defaultMode !== DEFAULT_THEME_CONFIG.defaultMode) params.set("mode", config.defaultMode);
1516
+ if (config.semantic) for (const key of [
1517
+ "success",
1518
+ "warning",
1519
+ "danger",
1520
+ "info"
1521
+ ]) {
1522
+ const value = config.semantic[key];
1523
+ if (value && isValidHexColor(value)) params.set(key, value.toLowerCase());
1524
+ }
1525
+ return params.toString() || "graphite";
1526
+ }
1527
+ function decodeThemePreset(input) {
1528
+ const trimmed = input.trim();
1529
+ if (!trimmed) return { ...DEFAULT_THEME_CONFIG };
1530
+ const lower = trimmed.toLowerCase();
1531
+ if (lower === "rams") return { ...DEFAULT_THEME_CONFIG };
1532
+ if (lower === "rams-dark") return {
1533
+ ...DEFAULT_THEME_CONFIG,
1534
+ defaultMode: "dark"
1535
+ };
1536
+ const named = NAMED_THEME_PRESETS.find((preset) => preset.id.toLowerCase() === lower);
1537
+ if (named) return { ...named.config };
1538
+ let queryString = trimmed;
1539
+ if (trimmed.includes("?")) queryString = trimmed.slice(trimmed.indexOf("?") + 1);
1540
+ const params = new URLSearchParams(queryString);
1541
+ const presetParam = params.get("preset")?.toLowerCase();
1542
+ const resolved = { ...(presetParam === "rams" ? DEFAULT_THEME_CONFIG : presetParam === "rams-dark" ? {
1543
+ ...DEFAULT_THEME_CONFIG,
1544
+ defaultMode: "dark"
1545
+ } : presetParam ? NAMED_THEME_PRESETS.find((p) => p.id.toLowerCase() === presetParam)?.config : void 0) ?? DEFAULT_THEME_CONFIG };
1546
+ const base = params.get("base")?.toLowerCase();
1547
+ if (base === "rams") resolved.base = "graphite";
1548
+ else if (base && base in THEME_BASES) resolved.base = base;
1549
+ const accent = params.get("accent");
1550
+ if (accent) {
1551
+ if (accent in THEME_ACCENTS) resolved.accent = accent;
1552
+ else if (isValidHexColor(accent)) resolved.accent = accent.toLowerCase();
1553
+ else if (isValidHexColor(`#${accent}`)) resolved.accent = `#${accent.toLowerCase()}`;
1554
+ }
1555
+ const radius = params.get("radius");
1556
+ if (radius && radius in THEME_RADII) resolved.radius = radius;
1557
+ const density = params.get("density");
1558
+ if (density && density in THEME_DENSITIES) resolved.density = density;
1559
+ const font = params.get("font");
1560
+ if (font && font in THEME_FONTS) resolved.font = font;
1561
+ const mode = params.get("mode");
1562
+ if (mode === "dark" || mode === "light") resolved.defaultMode = mode;
1563
+ const semantic = {};
1564
+ for (const key of [
1565
+ "success",
1566
+ "warning",
1567
+ "danger",
1568
+ "info"
1569
+ ]) {
1570
+ const val = params.get(key);
1571
+ if (!val) continue;
1572
+ if (isValidHexColor(val)) semantic[key] = val.toLowerCase();
1573
+ else if (isValidHexColor(`#${val}`)) semantic[key] = `#${val.toLowerCase()}`;
1574
+ }
1575
+ if (Object.keys(semantic).length > 0) resolved.semantic = semantic;
1576
+ return resolved;
1577
+ }
1578
+ const PRESET_MARKER_START = "/* usalyt:theme-preset:start */";
1579
+ const PRESET_MARKER_END = "/* usalyt:theme-preset:end */";
1580
+ function formatCssDecls(vars, indent = " ") {
1581
+ return Object.entries(vars).map(([key, value]) => `${indent}${key}: ${value};`).join("\n");
1582
+ }
1583
+ /**
1584
+ * Render a standalone CSS override block for the selected theme preset.
1585
+ * Safe to paste into a consumer stylesheet or append to `usalyt-theme.css`.
1586
+ */
1587
+ function renderThemeOverrideCss(config) {
1588
+ const darkVars = buildScopedThemeVars(config, "dark");
1589
+ const lightVars = buildScopedThemeVars(config, "light");
1590
+ const defaultIsLight = config.defaultMode === "light";
1591
+ const rootSelector = defaultIsLight ? ":root,\n html[data-theme=\"light\"]:not(.dark)" : ":root,\n .dark,\n html[data-theme=\"dark\"]";
1592
+ const altSelector = defaultIsLight ? ".dark,\n html[data-theme=\"dark\"]" : "html[data-theme=\"light\"]:not(.dark)";
1593
+ const rootVars = defaultIsLight ? lightVars : darkVars;
1594
+ const altVars = defaultIsLight ? darkVars : lightVars;
1595
+ const presetCode = encodeThemePreset(config);
1596
+ return [
1597
+ PRESET_MARKER_START,
1598
+ `/* Usalyt Theme Preset: ${presetCode} */`,
1599
+ "@layer base {",
1600
+ ` ${rootSelector} {`,
1601
+ formatCssDecls(rootVars),
1602
+ " }",
1603
+ "",
1604
+ ` ${altSelector} {`,
1605
+ formatCssDecls(altVars),
1606
+ " }",
1607
+ "}",
1608
+ PRESET_MARKER_END
1609
+ ].join("\n");
1610
+ }
1611
+ /**
1612
+ * Combine the base `theme.css` from the registry with a calibrated preset block.
1613
+ * Idempotent: re-applying replaces any prior `usalyt:theme-preset` block.
1614
+ */
1615
+ function applyThemePresetToCss(baseThemeCss, config) {
1616
+ const stripped = baseThemeCss.replace(/\n*\/\* usalyt:theme-preset:start \*\/[\s\S]*?\/\* usalyt:theme-preset:end \*\/\n*/g, "\n").trimEnd();
1617
+ if (isDefaultThemeConfig(config)) return `${stripped}\n`;
1618
+ return `${stripped}\n\n${renderThemeOverrideCss(config)}\n`;
1619
+ }
1620
+ //#endregion
1621
+ //#region src/lib/theme.ts
1622
+ var ThemeOptionError = class extends Error {
1623
+ constructor(message) {
1624
+ super(message);
1625
+ this.name = "ThemeOptionError";
1626
+ }
1627
+ };
1628
+ function hasThemeFlags(flags) {
1629
+ return Boolean(flags.preset || flags.base || flags.accent || flags.radius || flags.density || flags.font || flags.mode);
1630
+ }
1631
+ function resolveThemeFromFlags(flags, startingConfig = DEFAULT_THEME_CONFIG) {
1632
+ let resolved = { ...startingConfig };
1633
+ if (flags.preset) {
1634
+ const trimmed = flags.preset.trim();
1635
+ const isQueryOrUrl = trimmed.includes("=") || trimmed.includes("?");
1636
+ const isKnownNamed = NAMED_THEME_PRESETS.some((p) => p.id.toLowerCase() === trimmed.toLowerCase());
1637
+ if (!isQueryOrUrl && !isKnownNamed) throw new ThemeOptionError(`Unknown theme preset "${trimmed}". Available presets: ${NAMED_THEME_PRESETS.map((p) => p.id).join(", ")} (or pass a query/URL from the Theme Studio).`);
1638
+ resolved = decodeThemePreset(trimmed);
1639
+ }
1640
+ if (flags.base) {
1641
+ if (!(flags.base in THEME_BASES)) throw new ThemeOptionError(`Invalid --base "${flags.base}". Choose one of: ${Object.keys(THEME_BASES).join(", ")}.`);
1642
+ resolved.base = flags.base;
1643
+ }
1644
+ if (flags.accent) {
1645
+ const raw = flags.accent.trim();
1646
+ if (raw in THEME_ACCENTS) resolved.accent = raw;
1647
+ else if (isValidHexColor(raw)) resolved.accent = raw.toLowerCase();
1648
+ else if (isValidHexColor(`#${raw}`)) resolved.accent = `#${raw.toLowerCase()}`;
1649
+ else throw new ThemeOptionError(`Invalid --accent "${raw}". Use one of (${Object.keys(THEME_ACCENTS).join(", ")}) or a 6-digit hex color like #5e6ad2.`);
1650
+ }
1651
+ if (flags.radius) {
1652
+ if (!(flags.radius in THEME_RADII)) throw new ThemeOptionError(`Invalid --radius "${flags.radius}". Choose one of: ${Object.keys(THEME_RADII).join(", ")}.`);
1653
+ resolved.radius = flags.radius;
1654
+ }
1655
+ if (flags.density) {
1656
+ if (!(flags.density in THEME_DENSITIES)) throw new ThemeOptionError(`Invalid --density "${flags.density}". Choose one of: ${Object.keys(THEME_DENSITIES).join(", ")}.`);
1657
+ resolved.density = flags.density;
1658
+ }
1659
+ if (flags.font) {
1660
+ if (!(flags.font in THEME_FONTS)) throw new ThemeOptionError(`Invalid --font "${flags.font}". Choose one of: ${Object.keys(THEME_FONTS).join(", ")}.`);
1661
+ resolved.font = flags.font;
1662
+ }
1663
+ if (flags.mode) {
1664
+ if (flags.mode !== "dark" && flags.mode !== "light") throw new ThemeOptionError(`Invalid --mode "${flags.mode}". Choose "dark" or "light".`);
1665
+ resolved.defaultMode = flags.mode;
1666
+ }
1667
+ return resolved;
1668
+ }
1669
+ function toUsalytThemeConfig(config) {
1670
+ return {
1671
+ preset: encodeThemePreset(config),
1672
+ base: config.base,
1673
+ accent: config.accent,
1674
+ radius: config.radius,
1675
+ density: config.density,
1676
+ font: config.font,
1677
+ defaultMode: config.defaultMode
1678
+ };
1679
+ }
1680
+ //#endregion
529
1681
  //#region src/commands/init.ts
530
- function aliasFromPath(value, stripExtension = false) {
1682
+ function aliasFromPath(value, stripExtension = false, tsconfigPaths) {
531
1683
  const normalized = value.trim().replace(/\\/g, "/").replace(/^\.?\//, "");
532
- return `@/${stripExtension ? normalized.replace(/\.(tsx?|jsx?)$/, "") : normalized}`;
1684
+ const withoutExtension = stripExtension ? normalized.replace(/\.(tsx?|jsx?)$/, "") : normalized;
1685
+ if (tsconfigPaths && tsconfigPaths.targetDir !== "") {
1686
+ if (withoutExtension.startsWith(`${tsconfigPaths.targetDir}/`)) return `${tsconfigPaths.prefix}${withoutExtension.slice(tsconfigPaths.targetDir.length + 1)}`;
1687
+ }
1688
+ return `${tsconfigPaths?.prefix ?? "@/"}${withoutExtension}`;
533
1689
  }
534
- async function promptForConfig(defaults) {
1690
+ async function promptForConfig(defaults, detectedCss, tsconfigPaths) {
535
1691
  const rl = createInterface({
536
1692
  input: process.stdin,
537
1693
  output: process.stdout
@@ -541,113 +1697,372 @@ async function promptForConfig(defaults) {
541
1697
  const defaultUtils = `${defaults.aliases.utils.replace(/^@\//, "")}.ts`;
542
1698
  const componentsAnswer = await rl.question(`Components directory (relative to the project root) [${defaultComponents}]: `);
543
1699
  const utilsAnswer = await rl.question(`Utils file (relative to the project root) [${defaultUtils}]: `);
1700
+ const cssAnswer = await rl.question(`Global Tailwind CSS file (relative to the project root) [${detectedCss}]: `);
544
1701
  const componentsPath = componentsAnswer.trim() || defaultComponents;
545
1702
  const utilsPath = utilsAnswer.trim() || defaultUtils;
1703
+ const cssPath = cssAnswer.trim() || detectedCss;
546
1704
  return {
547
1705
  ...defaults,
1706
+ tailwind: {
1707
+ ...defaults.tailwind,
1708
+ css: cssPath
1709
+ },
548
1710
  aliases: {
549
- components: aliasFromPath(componentsPath),
550
- utils: aliasFromPath(utilsPath, true)
1711
+ components: aliasFromPath(componentsPath, false, tsconfigPaths),
1712
+ utils: aliasFromPath(utilsPath, true, tsconfigPaths)
551
1713
  }
552
1714
  };
553
1715
  } finally {
554
1716
  rl.close();
555
1717
  }
556
1718
  }
1719
+ const initCommand = defineCommand({
1720
+ meta: {
1721
+ name: "init",
1722
+ description: "Create usalyt.json and set up the Usalyt Tailwind v4 theme tokens"
1723
+ },
1724
+ args: {
1725
+ yes: {
1726
+ type: "boolean",
1727
+ description: "Use detected defaults without prompting",
1728
+ alias: "y"
1729
+ },
1730
+ overwrite: {
1731
+ type: "boolean",
1732
+ description: "Replace an existing usalyt.json and theme stylesheet",
1733
+ alias: "o"
1734
+ },
1735
+ "no-theme": {
1736
+ type: "boolean",
1737
+ description: "Skip writing usalyt-theme.css and updating the Tailwind CSS entry"
1738
+ },
1739
+ preset: {
1740
+ type: "string",
1741
+ description: "Named theme preset (e.g. linear, console-dense, minimal-light) or Theme Studio URL/query"
1742
+ },
1743
+ base: {
1744
+ type: "string",
1745
+ description: "Surface base palette (linear, zinc, slate, stone)"
1746
+ },
1747
+ accent: {
1748
+ type: "string",
1749
+ description: "Primary accent (lavender, cobalt, emerald, amber, crimson, monochrome, or #RRGGBB)"
1750
+ },
1751
+ radius: {
1752
+ type: "string",
1753
+ description: "Border radius scale (none, sm, md, lg, xl)"
1754
+ },
1755
+ density: {
1756
+ type: "string",
1757
+ description: "Spacing density scale (compact, default, comfortable)"
1758
+ },
1759
+ font: {
1760
+ type: "string",
1761
+ description: "Sans font stack (inter, system, geist, jakarta)"
1762
+ },
1763
+ mode: {
1764
+ type: "string",
1765
+ description: "Default theme polarity (dark, light)"
1766
+ }
1767
+ },
1768
+ async run({ args }) {
1769
+ const root = process.cwd();
1770
+ const configPath = configPathFor(root);
1771
+ let resolvedTheme;
1772
+ try {
1773
+ resolvedTheme = resolveThemeFromFlags({
1774
+ preset: args.preset,
1775
+ base: args.base,
1776
+ accent: args.accent,
1777
+ radius: args.radius,
1778
+ density: args.density,
1779
+ font: args.font,
1780
+ mode: args.mode
1781
+ });
1782
+ } catch (error) {
1783
+ if (error instanceof ThemeOptionError) {
1784
+ printError(error.message);
1785
+ return;
1786
+ }
1787
+ throw error;
1788
+ }
1789
+ if (existsSync(configPath) && !args.overwrite) {
1790
+ printError(`${CONFIG_FILE} already exists at ${configPath}. Pass --overwrite to replace it.`);
1791
+ return;
1792
+ }
1793
+ try {
1794
+ if (lstatSync(configPath).isSymbolicLink()) {
1795
+ printError(`${CONFIG_FILE} at ${configPath} is a symbolic link. Remove the link and run init again.`);
1796
+ return;
1797
+ }
1798
+ } catch {}
1799
+ const defaults = defaultConfig();
1800
+ const detectedCss = detectCssEntry(root);
1801
+ const tsconfigPaths = detectTsconfigPathMapping(root);
1802
+ const interactive = !args.yes && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
1803
+ const themeCustomized = hasThemeFlags({
1804
+ preset: args.preset,
1805
+ base: args.base,
1806
+ accent: args.accent,
1807
+ radius: args.radius,
1808
+ density: args.density,
1809
+ font: args.font,
1810
+ mode: args.mode
1811
+ }) || !isDefaultThemeConfig(resolvedTheme);
1812
+ const baseConfig = {
1813
+ ...defaults,
1814
+ tailwind: {
1815
+ ...defaults.tailwind,
1816
+ css: detectedCss,
1817
+ baseColor: themeCustomized ? resolvedTheme.base : defaults.tailwind?.baseColor
1818
+ },
1819
+ ...themeCustomized ? { theme: toUsalytThemeConfig(resolvedTheme) } : {},
1820
+ aliases: tsconfigPaths ? {
1821
+ components: aliasFromPath("src/components/ui", false, tsconfigPaths),
1822
+ utils: aliasFromPath("src/lib/utils", true, tsconfigPaths)
1823
+ } : defaults.aliases
1824
+ };
1825
+ const promptedConfig = interactive ? await promptForConfig(defaults, detectedCss, tsconfigPaths) : baseConfig;
1826
+ const config = themeCustomized ? {
1827
+ ...promptedConfig,
1828
+ tailwind: {
1829
+ ...promptedConfig.tailwind,
1830
+ baseColor: resolvedTheme.base
1831
+ },
1832
+ theme: toUsalytThemeConfig(resolvedTheme)
1833
+ } : promptedConfig;
1834
+ try {
1835
+ writeFileSync(configPath, serializeConfig(config), "utf8");
1836
+ } catch (error) {
1837
+ printError(`could not write ${configPath}: ${error.message}`);
1838
+ return;
1839
+ }
1840
+ console.log(`Created ${CONFIG_FILE} at ${configPath}`);
1841
+ console.log(` components: ${config.aliases.components}`);
1842
+ console.log(` utils: ${config.aliases.utils}`);
1843
+ if (config.tailwind?.css) console.log(` css: ${config.tailwind.css}`);
1844
+ if (themeCustomized) console.log(` preset: ${encodeThemePreset(resolvedTheme)}`);
1845
+ if (args["no-theme"]) return;
1846
+ try {
1847
+ const { registry } = loadRegistry();
1848
+ const themeContent = registry.items.find((item) => item.name === "theme")?.files[0]?.content;
1849
+ if (themeContent && config.tailwind?.css) {
1850
+ const finalThemeCss = applyThemePresetToCss(themeContent, resolvedTheme);
1851
+ const result = injectThemeStylesheet({
1852
+ root,
1853
+ cssEntryRelative: config.tailwind.css,
1854
+ themeCss: finalThemeCss,
1855
+ overwriteTheme: Boolean(args.overwrite)
1856
+ });
1857
+ console.log(` theme: ${result.themeFile}`);
1858
+ if (result.cssUpdated) console.log(` updated: ${result.cssEntry}`);
1859
+ }
1860
+ } catch (error) {
1861
+ if (error instanceof UnsafePathError) {
1862
+ printError(error.message);
1863
+ return;
1864
+ }
1865
+ printError(`could not set up theme stylesheet: ${error.message}`);
1866
+ }
1867
+ }
1868
+ });
557
1869
  //#endregion
558
- //#region src/index.ts
559
- runMain(defineCommand({
1870
+ //#region src/commands/list.ts
1871
+ const listCommand = defineCommand({
560
1872
  meta: {
561
- name: "usalyt",
562
- version: "0.0.1",
563
- description: "Usalyt component distribution CLI"
1873
+ name: "list",
1874
+ description: "List the items in the packaged Usalyt registry"
1875
+ },
1876
+ args: { json: {
1877
+ type: "boolean",
1878
+ description: "Print machine-readable JSON"
1879
+ } },
1880
+ run({ args }) {
1881
+ let registry;
1882
+ try {
1883
+ ({registry} = loadRegistry());
1884
+ } catch (error) {
1885
+ printError(error.message);
1886
+ return;
1887
+ }
1888
+ if (args.json) {
1889
+ const payload = {
1890
+ name: registry.name,
1891
+ version: registry.version,
1892
+ count: registry.items.length,
1893
+ items: registry.items.map((item) => ({
1894
+ name: item.name,
1895
+ type: item.type,
1896
+ title: item.title,
1897
+ description: item.description,
1898
+ license: item.license,
1899
+ dependencies: item.dependencies,
1900
+ registryDependencies: item.registryDependencies
1901
+ }))
1902
+ };
1903
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
1904
+ return;
1905
+ }
1906
+ console.log(`${registry.name} registry ${registry.version}: ${registry.items.length} items`);
1907
+ for (const item of registry.items) console.log(` ${pc.bold(item.name)} (${item.type}) - ${item.description}`);
1908
+ console.log("");
1909
+ console.log("Add components with: usalyt add <component>");
1910
+ }
1911
+ });
1912
+ const themeCommand = defineCommand({
1913
+ meta: {
1914
+ name: "theme",
1915
+ description: "List or apply Usalyt theme presets and design token overrides"
564
1916
  },
565
1917
  subCommands: {
566
- init: defineCommand({
1918
+ apply: defineCommand({
567
1919
  meta: {
568
- name: "init",
569
- description: "Create usalyt.json with the component and utility aliases"
1920
+ name: "apply",
1921
+ description: "Apply a theme preset or token overrides to usalyt-theme.css"
570
1922
  },
571
1923
  args: {
572
- yes: {
573
- type: "boolean",
574
- description: "Use the default aliases without prompting",
575
- alias: "y"
1924
+ preset: {
1925
+ type: "string",
1926
+ description: "Named theme preset (e.g. linear, console-dense, minimal-light) or Theme Studio URL/query"
1927
+ },
1928
+ base: {
1929
+ type: "string",
1930
+ description: "Surface base palette (linear, zinc, slate, stone)"
1931
+ },
1932
+ accent: {
1933
+ type: "string",
1934
+ description: "Primary accent (lavender, cobalt, emerald, amber, crimson, monochrome, or #RRGGBB)"
1935
+ },
1936
+ radius: {
1937
+ type: "string",
1938
+ description: "Border radius scale (none, sm, md, lg, xl)"
576
1939
  },
577
- overwrite: {
578
- type: "boolean",
579
- description: "Replace an existing usalyt.json",
580
- alias: "o"
1940
+ density: {
1941
+ type: "string",
1942
+ description: "Spacing density scale (compact, default, comfortable)"
1943
+ },
1944
+ font: {
1945
+ type: "string",
1946
+ description: "Sans font stack (inter, system, geist, jakarta)"
1947
+ },
1948
+ mode: {
1949
+ type: "string",
1950
+ description: "Default theme polarity (dark, light)"
581
1951
  }
582
1952
  },
583
1953
  async run({ args }) {
584
- const configPath = configPathFor(process.cwd());
585
- if (existsSync(configPath) && !args.overwrite) {
586
- printError(`${CONFIG_FILE} already exists at ${configPath}. Pass --overwrite to replace it.`);
1954
+ const root = process.cwd();
1955
+ let config;
1956
+ try {
1957
+ config = readConfig(root);
1958
+ } catch (error) {
1959
+ if (error instanceof ConfigError) {
1960
+ printError(error.message);
1961
+ return;
1962
+ }
1963
+ throw error;
1964
+ }
1965
+ if (!config) {
1966
+ printError(`No ${CONFIG_FILE} found in ${root}. Run \`usalyt init\` first.`);
587
1967
  return;
588
1968
  }
1969
+ const flags = {
1970
+ preset: args.preset,
1971
+ base: args.base,
1972
+ accent: args.accent,
1973
+ radius: args.radius,
1974
+ density: args.density,
1975
+ font: args.font,
1976
+ mode: args.mode
1977
+ };
1978
+ if (!hasThemeFlags(flags)) {
1979
+ printError("Pass --preset <name|query|url> or at least one token flag (--base, --accent, --radius, --density, --font, --mode).");
1980
+ return;
1981
+ }
1982
+ const currentStart = config.theme?.preset ? resolveThemeFromFlags({ preset: config.theme.preset }, DEFAULT_THEME_CONFIG) : DEFAULT_THEME_CONFIG;
1983
+ let resolvedTheme;
589
1984
  try {
590
- if (lstatSync(configPath).isSymbolicLink()) {
591
- printError(`${CONFIG_FILE} at ${configPath} is a symbolic link. Remove the link and run init again.`);
1985
+ resolvedTheme = resolveThemeFromFlags(flags, currentStart);
1986
+ } catch (error) {
1987
+ if (error instanceof ThemeOptionError) {
1988
+ printError(error.message);
592
1989
  return;
593
1990
  }
594
- } catch {}
595
- const defaults = defaultConfig();
596
- const config = !args.yes && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) ? await promptForConfig(defaults) : defaults;
1991
+ throw error;
1992
+ }
1993
+ const cssEntry = config.tailwind?.css || detectCssEntry(root);
597
1994
  try {
598
- writeFileSync(configPath, serializeConfig(config), "utf8");
1995
+ const { registry } = loadRegistry();
1996
+ const themeContent = registry.items.find((item) => item.name === "theme")?.files[0]?.content;
1997
+ if (!themeContent) {
1998
+ printError("The packaged registry does not contain a theme stylesheet.");
1999
+ return;
2000
+ }
2001
+ const result = injectThemeStylesheet({
2002
+ root,
2003
+ cssEntryRelative: cssEntry,
2004
+ themeCss: applyThemePresetToCss(themeContent, resolvedTheme),
2005
+ overwriteTheme: true
2006
+ });
2007
+ const updatedConfig = {
2008
+ ...config,
2009
+ tailwind: {
2010
+ ...config.tailwind,
2011
+ css: cssEntry,
2012
+ baseColor: resolvedTheme.base
2013
+ },
2014
+ theme: toUsalytThemeConfig(resolvedTheme)
2015
+ };
2016
+ writeFileSync(configPathFor(root), serializeConfig(updatedConfig), "utf8");
2017
+ const presetCode = encodeThemePreset(resolvedTheme);
2018
+ console.log(`Applied theme preset "${presetCode}"`);
2019
+ console.log(` theme: ${result.themeFile}`);
2020
+ console.log(` config: ${CONFIG_FILE}`);
2021
+ if (result.cssUpdated) console.log(` updated: ${result.cssEntry}`);
599
2022
  } catch (error) {
600
- printError(`could not write ${configPath}: ${error.message}`);
601
- return;
2023
+ if (error instanceof UnsafePathError) {
2024
+ printError(error.message);
2025
+ return;
2026
+ }
2027
+ printError(`could not apply theme preset: ${error.message}`);
602
2028
  }
603
- console.log(`Created ${CONFIG_FILE} at ${configPath}`);
604
- console.log(` components: ${config.aliases.components}`);
605
- console.log(` utils: ${config.aliases.utils}`);
606
2029
  }
607
2030
  }),
608
- add: addCommand,
609
2031
  list: defineCommand({
610
2032
  meta: {
611
2033
  name: "list",
612
- description: "List the items in the packaged Usalyt registry"
2034
+ description: "List available curated theme presets"
613
2035
  },
614
2036
  args: { json: {
615
2037
  type: "boolean",
616
- description: "Print machine-readable JSON"
2038
+ description: "Output theme presets as JSON"
617
2039
  } },
618
2040
  run({ args }) {
619
- let registry;
620
- try {
621
- ({registry} = loadRegistry());
622
- } catch (error) {
623
- printError(error.message);
624
- return;
625
- }
626
2041
  if (args.json) {
627
- const payload = {
628
- name: registry.name,
629
- version: registry.version,
630
- count: registry.items.length,
631
- items: registry.items.map((item) => ({
632
- name: item.name,
633
- type: item.type,
634
- title: item.title,
635
- description: item.description,
636
- license: item.license,
637
- dependencies: item.dependencies,
638
- registryDependencies: item.registryDependencies
639
- }))
640
- };
641
- process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
2042
+ console.log(JSON.stringify({ presets: NAMED_THEME_PRESETS }, null, 2));
642
2043
  return;
643
2044
  }
644
- console.log(`${registry.name} registry ${registry.version}: ${registry.items.length} items`);
645
- for (const item of registry.items) console.log(` ${pc.bold(item.name)} (${item.type}) - ${item.description}`);
646
- console.log("");
647
- console.log("Add components with: usalyt add <component>");
2045
+ console.log("Available Usalyt theme presets:");
2046
+ for (const preset of NAMED_THEME_PRESETS) console.log(` ${preset.id.padEnd(18)} ${preset.description}`);
648
2047
  }
649
2048
  })
650
2049
  }
2050
+ });
2051
+ //#endregion
2052
+ //#region src/index.ts
2053
+ runMain(defineCommand({
2054
+ meta: {
2055
+ name: "usalyt",
2056
+ version,
2057
+ description: "Usalyt component distribution CLI"
2058
+ },
2059
+ subCommands: {
2060
+ init: initCommand,
2061
+ add: addCommand,
2062
+ diff: diffCommand,
2063
+ list: listCommand,
2064
+ theme: themeCommand
2065
+ }
651
2066
  }));
652
2067
  //#endregion
653
2068
  export {};