@barqjs/ui-cli 0.0.0-stage → 0.2.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,989 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `barq-ui` — copy barq's components into a project, and keep them in
4
+ * sync with the registry they came from.
5
+ *
6
+ * NO DEPENDENCIES. The argument parsing, the prompts, the diff and the schema
7
+ * checks are each smaller than the library that would do them, and a tool
8
+ * someone runs once to write eight files should not download eight of its own
9
+ * first. `create-barq` in this repository makes the same trade for the same
10
+ * reason.
11
+ *
12
+ * ## What `sync` is, and why it is not `add` again
13
+ *
14
+ * shadcn's `diff` shows what upstream changed and leaves the applying to you,
15
+ * because it cannot tell an edited file from an untouched one. `init` and `add`
16
+ * here record a hash per file, so `sync` can: an untouched file is replaced
17
+ * without asking, an edited one is shown as a diff and kept unless you say
18
+ * otherwise. Owning the code means the edit wins by default.
19
+ */
20
+
21
+ import { realpathSync, writeFileSync } from "node:fs";
22
+ import { join, resolve } from "node:path";
23
+ import { stdout } from "node:process";
24
+ import { fileURLToPath } from "node:url";
25
+
26
+ import { applyItems, missingDependencies, type WrittenFile } from "./add.ts";
27
+ import { CONFIG_FILE, findRoot, requireConfig, writeConfig } from "./config.ts";
28
+ import { hashOf, placed, read, rewrite, targetOf, write } from "./files.ts";
29
+ import { install, installCommand, installedPackages, packageManager } from "./project.ts";
30
+ import {
31
+ defaultRegistry,
32
+ REGISTRY_ENV,
33
+ registriesFor,
34
+ resolveItems,
35
+ sourceFor,
36
+ type Registries,
37
+ type Source,
38
+ } from "./registry.ts";
39
+ import {
40
+ DEFAULT_PATHS,
41
+ parseConfig,
42
+ type Config,
43
+ type RegistryIndexEntry,
44
+ type RegistryItem,
45
+ } from "./schema.ts";
46
+ import { resolveTheme, themeModule, withItemCss, type ThemeDefinition } from "./theme.ts";
47
+ import { unified } from "./diff.ts";
48
+ import { ask, bold, cyan, dim, green, paint, red, say, yellow, type Option } from "./tty.ts";
49
+
50
+ const HELP = `\
51
+ Usage: barq-ui <command> [options]
52
+
53
+ init set up ${CONFIG_FILE}, the theme and the base styles
54
+ add <name...> add components and blocks, with whatever they need
55
+ diff [name...] what the registry has that your copy does not
56
+ sync [name...] take the registry's version, keeping your edits
57
+ list what the registry offers
58
+ search <query> find items by name, description or category
59
+ view <name...> print items as the registry serves them
60
+ info what this project is set up with
61
+ theme <name> change the colour theme
62
+ style <name> change the component style
63
+ build <dir> turn a directory of components into a registry
64
+
65
+ A name is an item in the project's registry, or @scope/name for one of the
66
+ registries ${CONFIG_FILE} lists. Without a \`registry\` in ${CONFIG_FILE}, items
67
+ come from the @barqjs/ui release this CLI belongs to; ${REGISTRY_ENV} replaces it.
68
+
69
+ Options:
70
+ -c, --cwd <dir> where the project is. Defaults to here
71
+ --overwrite replace a file you have edited
72
+ --yes take every default without asking
73
+ --no-install print the install command instead of running it
74
+ --all add: every ui component the registry has
75
+ --dry-run add: say what would be written, and write nothing
76
+ --diff[=<file>] add: show what would change, and write nothing
77
+ --view[=<file>] add: show what would be written, and write nothing
78
+ --json search, info: print JSON
79
+ --path <dir> init: where components go
80
+ --registry <url> init: a registry URL containing {name}
81
+ --style <name> init: the component style (vega, nova, lyra, …)
82
+ --theme <name> init: the base colour theme
83
+ --accent <name> init: an accent over it
84
+ --radius <len> init: --radius
85
+ --dark <sel> init: the dark-mode selector, or "media"
86
+ --no-reset init: do not install the CSS reset
87
+ -h, --help show this
88
+ `;
89
+
90
+ interface Args {
91
+ readonly command?: string;
92
+ readonly rest: string[];
93
+ readonly cwd: string;
94
+ readonly overwrite: boolean;
95
+ readonly yes: boolean;
96
+ readonly reset: boolean;
97
+ readonly path?: string;
98
+ readonly registry?: string;
99
+ readonly style?: string;
100
+ readonly theme?: string;
101
+ readonly accent?: string;
102
+ readonly radius?: string;
103
+ readonly dark?: string;
104
+ readonly help: boolean;
105
+ readonly install: boolean;
106
+ readonly all: boolean;
107
+ readonly dryRun: boolean;
108
+ /** `true` is every file; a string is the files whose path ends with it. */
109
+ readonly diff?: string | true;
110
+ readonly view?: string | true;
111
+ readonly json: boolean;
112
+ }
113
+
114
+ function parse(argv: readonly string[]): Args {
115
+ const rest: string[] = [];
116
+ let command: string | undefined;
117
+ let cwd = process.cwd();
118
+ let overwrite = false;
119
+ let yes = false;
120
+ let reset = true;
121
+ let path: string | undefined;
122
+ let registry: string | undefined;
123
+ let style: string | undefined;
124
+ let theme: string | undefined;
125
+ let accent: string | undefined;
126
+ let radius: string | undefined;
127
+ let dark: string | undefined;
128
+ let help = false;
129
+ let install_ = true;
130
+ let all = false;
131
+ let dryRun = false;
132
+ let diff: string | true | undefined;
133
+ let viewing: string | true | undefined;
134
+ let json = false;
135
+
136
+ const value = (index: number, flag: string): string => {
137
+ const next = argv[index];
138
+ if (next === undefined) throw new Error(`${flag} needs a value`);
139
+ return next;
140
+ };
141
+
142
+ for (let index = 0; index < argv.length; index++) {
143
+ const arg = argv[index] ?? "";
144
+ if (arg === "-h" || arg === "--help") help = true;
145
+ else if (arg === "--overwrite") overwrite = true;
146
+ else if (arg === "-y" || arg === "--yes") yes = true;
147
+ else if (arg === "--no-reset") reset = false;
148
+ else if (arg === "--no-install") install_ = false;
149
+ else if (arg === "-a" || arg === "--all") all = true;
150
+ else if (arg === "--dry-run") dryRun = true;
151
+ else if (arg === "--json") json = true;
152
+ else if (arg === "--diff") diff = true;
153
+ else if (arg === "--view") viewing = true;
154
+ // Only with `=`. A bare `--diff button` cannot say whether `button` is the
155
+ // file to show or the component to add.
156
+ else if (arg.startsWith("--diff=")) diff = arg.slice("--diff=".length);
157
+ else if (arg.startsWith("--view=")) viewing = arg.slice("--view=".length);
158
+ else if (arg === "-c" || arg === "--cwd") cwd = value(++index, arg);
159
+ else if (arg === "--path") path = value(++index, arg);
160
+ else if (arg === "--registry") registry = value(++index, arg);
161
+ else if (arg === "--style") style = value(++index, arg);
162
+ else if (arg === "--theme") theme = value(++index, arg);
163
+ else if (arg === "--accent") accent = value(++index, arg);
164
+ else if (arg === "--radius") radius = value(++index, arg);
165
+ else if (arg === "--dark") dark = value(++index, arg);
166
+ else if (arg.startsWith("--")) {
167
+ const split = arg.indexOf("=");
168
+ if (split < 0) throw new Error(`unknown option ${arg}`);
169
+ // `--theme=blue` as well as `--theme blue`, because both are written.
170
+ argv = [
171
+ ...argv.slice(0, index),
172
+ arg.slice(0, split),
173
+ arg.slice(split + 1),
174
+ ...argv.slice(index + 1),
175
+ ];
176
+ index--;
177
+ } else if (command === undefined) command = arg;
178
+ else rest.push(arg);
179
+ }
180
+
181
+ return {
182
+ command,
183
+ rest,
184
+ cwd: resolve(cwd),
185
+ overwrite,
186
+ yes,
187
+ reset,
188
+ path,
189
+ registry,
190
+ style,
191
+ theme,
192
+ accent,
193
+ radius,
194
+ dark,
195
+ help,
196
+ install: install_,
197
+ all,
198
+ dryRun,
199
+ diff,
200
+ view: viewing,
201
+ json,
202
+ };
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Reporting
207
+ // ---------------------------------------------------------------------------
208
+
209
+ const MARK: Record<WrittenFile["outcome"], string> = {
210
+ written: green("+"),
211
+ replaced: cyan("~"),
212
+ unchanged: dim("="),
213
+ kept: yellow("!"),
214
+ };
215
+
216
+ function report(files: readonly WrittenFile[]): void {
217
+ const interesting = files.filter((file) => file.outcome !== "unchanged");
218
+ if (interesting.length === 0) {
219
+ say(dim("Everything was already up to date."));
220
+ return;
221
+ }
222
+ for (const file of interesting) say(` ${MARK[file.outcome]} ${file.path}`);
223
+
224
+ const kept = files.filter((file) => file.outcome === "kept");
225
+ if (kept.length > 0) {
226
+ say();
227
+ say(
228
+ yellow(
229
+ `${String(kept.length)} file${kept.length === 1 ? "" : "s"} you have edited ` +
230
+ `${kept.length === 1 ? "was" : "were"} left alone.`,
231
+ ),
232
+ );
233
+ say(dim("`barq-ui diff` shows what the registry has; `--overwrite` takes it."));
234
+ }
235
+ }
236
+
237
+ /**
238
+ * The packages the items import that the project does not have: installed, or
239
+ * with `--no-install` named so a person can.
240
+ */
241
+ function settle(root: string, items: readonly RegistryItem[], installing: boolean): void {
242
+ const installed = installedPackages(root);
243
+ const runtime = missingDependencies(items, installed);
244
+ const development = missingDependencies(items, installed, "devDependencies");
245
+ if (runtime.length === 0 && development.length === 0) return;
246
+
247
+ say();
248
+ if (!installing) {
249
+ say(bold("Install what they need:"));
250
+ if (runtime.length > 0) say(` ${installCommand(root, runtime)}`);
251
+ if (development.length > 0) say(` ${installCommand(root, development, { dev: true })}`);
252
+ return;
253
+ }
254
+ say(bold("Installing what they need:"));
255
+ if (runtime.length > 0) install(root, runtime);
256
+ if (development.length > 0) install(root, development, { dev: true });
257
+ }
258
+
259
+ // ---------------------------------------------------------------------------
260
+ // The theme data, which lives in the package rather than in the registry
261
+ // ---------------------------------------------------------------------------
262
+
263
+ /**
264
+ * What a list answers with when the answer is "leave it alone".
265
+ *
266
+ * A prompt has to return a string, and the config's `accent` and `radius` are
267
+ * both absent rather than empty when they are not chosen — an empty `--radius`
268
+ * would write `--radius: ;`.
269
+ */
270
+ const NONE = "";
271
+
272
+ const NO_ACCENT: Option = { value: NONE, label: dim("None, the base's own colours") };
273
+
274
+ /** shadcn's own four, plus leaving whatever the base declares. */
275
+ const RADII: readonly Option[] = [
276
+ { value: NONE, label: dim("The theme's own") },
277
+ { value: "0", label: "None" },
278
+ { value: "0.45rem", label: "Small" },
279
+ { value: "0.625rem", label: "Medium" },
280
+ { value: "0.875rem", label: "Large" },
281
+ ];
282
+
283
+ function blank(answer: string): string | undefined {
284
+ return answer === NONE ? undefined : answer;
285
+ }
286
+
287
+ /** The styles the registry serves, read rather than listed. */
288
+ async function styles(source: Source): Promise<Option[]> {
289
+ const names = (await source.data("styles")) as string[];
290
+ return names
291
+ .toSorted()
292
+ .map((name) => ({ value: name, label: name[0]?.toUpperCase() + name.slice(1) }));
293
+ }
294
+
295
+ /**
296
+ * The chosen style, copied into the project beside the theme: what the tool
297
+ * writes is yours, and a style is ordinary CSS you may want to edit.
298
+ */
299
+ async function writeStyle(
300
+ root: string,
301
+ config: Config,
302
+ name: string,
303
+ source: Source,
304
+ ): Promise<string> {
305
+ const { css } = (await source.data(`style-${name}`)) as { css: string };
306
+ const target = targetOf(config, root, {
307
+ path: "theme/style.css",
308
+ type: "registry:theme",
309
+ content: "",
310
+ });
311
+ writeFileSync(target, css);
312
+ return target;
313
+ }
314
+
315
+ async function themes(source: Source): Promise<ThemeDefinition[]> {
316
+ return (await source.data("themes")) as ThemeDefinition[];
317
+ }
318
+
319
+ // ---------------------------------------------------------------------------
320
+ // Commands
321
+ // ---------------------------------------------------------------------------
322
+
323
+ async function init(args: Args): Promise<void> {
324
+ const prompt = ask(!args.yes);
325
+ try {
326
+ const source = sourceFor(
327
+ parseConfig(args.registry === undefined ? {} : { registry: args.registry }),
328
+ args.cwd,
329
+ );
330
+ const table = await themes(source);
331
+ const options = (kind: ThemeDefinition["kind"]): Option[] =>
332
+ table
333
+ .filter((theme) => theme.kind === kind)
334
+ .map((theme) => ({ value: theme.name, label: theme.title }));
335
+
336
+ const path = args.path ?? (await prompt.question("Where do components go?", DEFAULT_PATHS.ui));
337
+ // NONE first, and it is the default. This package's own look is shadcn's
338
+ // classic registry, transcribed; a style is one of eight SECOND opinions
339
+ // over it, 180 KB each. Defaulting to one would install a file nobody asked
340
+ // for and quietly replace the look the rest of the tool promises.
341
+ const available = await styles(source);
342
+ const style =
343
+ args.style ??
344
+ (available.length === 0
345
+ ? undefined
346
+ : blank(
347
+ await prompt.choose(
348
+ "Component style?",
349
+ [{ value: NONE, label: dim("None, the components' own look") }, ...available],
350
+ NONE,
351
+ ),
352
+ ));
353
+ const base = args.theme ?? (await prompt.choose("Colour theme?", options("base"), "neutral"));
354
+ const accent =
355
+ args.accent ??
356
+ blank(await prompt.choose("An accent over it?", [NO_ACCENT, ...options("accent")], NONE));
357
+ const radius = args.radius ?? blank(await prompt.choose("Corner radius?", RADII, NONE));
358
+ const reset = args.reset && (await prompt.confirm("Install the CSS reset?", true));
359
+
360
+ const root = args.cwd;
361
+ const parent = path.replace(/\/ui$/, "");
362
+ const config = parseConfig({
363
+ ...(args.registry === undefined ? {} : { registry: args.registry }),
364
+ paths: {
365
+ ui: path,
366
+ lib: path.endsWith("/ui") ? `${parent}/lib` : `${path}/lib`,
367
+ theme: path.endsWith("/ui") ? `${parent}/theme` : `${path}/theme`,
368
+ },
369
+ theme: {
370
+ ...(style === undefined ? {} : { style }),
371
+ base,
372
+ ...(accent === undefined ? {} : { accent }),
373
+ ...(radius === undefined ? {} : { radius }),
374
+ ...(args.dark === undefined ? {} : { dark: args.dark }),
375
+ },
376
+ reset,
377
+ items: {},
378
+ });
379
+
380
+ // Before a single file is written. `init` writes the base styles first and
381
+ // reaches the theme last, so a mistyped `--theme` used to leave four files
382
+ // on disk and no `components.json` beside them.
383
+ resolveTheme(config.theme, table);
384
+ if (style !== undefined && !available.some((each) => each.value === style)) {
385
+ throw new Error(
386
+ `no style named "${style}". Try one of: ${available.map((each) => each.value).join(", ")}`,
387
+ );
388
+ }
389
+
390
+ const wanted = ["base", "layers", ...(config.reset ? ["reset"] : []), "utils"];
391
+ const items = await resolveItems(registriesFor(config, root), wanted);
392
+ const applied = applyItems(config, root, items);
393
+
394
+ // The chosen theme, as source. Written last so it can name the files above.
395
+ const themeFile = themeTarget(config, root);
396
+ const module_ = themeModule(config.theme, table, {
397
+ reset: config.reset,
398
+ base: "./base.ts",
399
+ resetPath: "./reset.ts",
400
+ });
401
+ write(themeFile, module_);
402
+ const styleFile =
403
+ style === undefined ? undefined : await writeStyle(root, config, style, source);
404
+
405
+ const next: Config = {
406
+ ...applied.config,
407
+ items: {
408
+ ...applied.config.items,
409
+ theme: { [THEME_KEY]: hashOf(module_) },
410
+ },
411
+ };
412
+ writeConfig(root, next);
413
+
414
+ say(`${green("Set up")} ${bold(CONFIG_FILE)} and the theme.`);
415
+ report([
416
+ ...applied.files,
417
+ {
418
+ item: "theme",
419
+ path: themeFile.slice(root.length + 1),
420
+ absolute: themeFile,
421
+ outcome: "written",
422
+ hash: hashOf(module_),
423
+ incoming: module_,
424
+ },
425
+ ]);
426
+ say();
427
+ say(bold("Import the theme once, at your application's entry:"));
428
+ say(` import "./${config.paths.theme.replace(/^(\.\/)?/, "")}/theme.ts";`);
429
+ if (styleFile !== undefined && style !== undefined) {
430
+ say();
431
+ say(bold("And the style, with its class on the element it applies to:"));
432
+ say(` import "./${config.paths.theme.replace(/^(\.\/)?/, "")}/style.css";`);
433
+ say(` <html class="style-${style}">`);
434
+ }
435
+
436
+ settle(root, items, args.install);
437
+ say();
438
+ say(`Then: ${cyan("barq-ui add button card")}`);
439
+ } finally {
440
+ prompt.close();
441
+ }
442
+ }
443
+
444
+ const THEME_KEY = "theme/theme.ts";
445
+
446
+ function themeTarget(config: Config, root: string): string {
447
+ return targetOf(config, root, { path: THEME_KEY, type: "registry:theme", content: "" });
448
+ }
449
+
450
+ /**
451
+ * What the items' `cssVars` and `css` make of the theme, written the way a
452
+ * component is: replaced when the project has not touched `theme.ts`, kept when
453
+ * it has.
454
+ *
455
+ * The choice is recorded either way. A kept file is the project's to merge,
456
+ * and the next `barq-ui theme` writes the tokens with the colours it picks.
457
+ */
458
+ async function extendTheme(
459
+ config: Config,
460
+ root: string,
461
+ items: readonly RegistryItem[],
462
+ options: { overwrite: boolean; dryRun: boolean },
463
+ ): Promise<{ config: Config; file?: WrittenFile }> {
464
+ if (!items.some((item) => item.cssVars !== undefined || item.css !== undefined)) {
465
+ return { config };
466
+ }
467
+ const theme = items.reduce(withItemCss, config.theme);
468
+
469
+ const incoming = themeModule(theme, await themes(sourceFor(config, root)), {
470
+ reset: config.reset,
471
+ base: "./base.ts",
472
+ resetPath: "./reset.ts",
473
+ });
474
+ const absolute = themeTarget(config, root);
475
+ const existing = read(absolute);
476
+ const common = { item: "theme", path: absolute.slice(root.length + 1), absolute, incoming };
477
+ const recorded = config.items["theme"]?.[THEME_KEY];
478
+
479
+ if (existing !== undefined && existing !== incoming) {
480
+ if (!options.overwrite && hashOf(existing) !== recorded) {
481
+ return {
482
+ config: { ...config, theme },
483
+ file: { ...common, outcome: "kept", hash: hashOf(existing), existing },
484
+ };
485
+ }
486
+ }
487
+ if (!options.dryRun && existing !== incoming) write(absolute, incoming);
488
+ return {
489
+ config: {
490
+ ...config,
491
+ theme,
492
+ items: { ...config.items, theme: { [THEME_KEY]: hashOf(incoming) } },
493
+ },
494
+ file: {
495
+ ...common,
496
+ outcome:
497
+ existing === undefined ? "written" : existing === incoming ? "unchanged" : "replaced",
498
+ hash: hashOf(incoming),
499
+ ...(existing === undefined ? {} : { existing }),
500
+ },
501
+ };
502
+ }
503
+
504
+ /** The files a `--diff=` or `--view=` asked about: all of them, or the ones named. */
505
+ function asked(files: readonly WrittenFile[], which: string | true): WrittenFile[] {
506
+ return which === true ? [...files] : files.filter((file) => file.path.endsWith(which));
507
+ }
508
+
509
+ /**
510
+ * What `add` would do, shown rather than done.
511
+ *
512
+ * `--diff` and `--view` are the same preview read two ways: what would change
513
+ * in a file the project has, and what a file would be.
514
+ */
515
+ function preview(
516
+ root: string,
517
+ args: Args,
518
+ items: readonly RegistryItem[],
519
+ files: readonly WrittenFile[],
520
+ ): void {
521
+ if (args.view !== undefined) {
522
+ for (const file of asked(files, args.view)) {
523
+ say();
524
+ say(bold(file.path));
525
+ say(file.incoming);
526
+ }
527
+ return;
528
+ }
529
+
530
+ if (args.diff !== undefined) {
531
+ const changed = asked(files, args.diff).filter((file) => file.outcome !== "unchanged");
532
+ if (changed.length === 0) {
533
+ say(dim("Nothing would change."));
534
+ return;
535
+ }
536
+ for (const file of changed) {
537
+ say();
538
+ say(`${bold(file.path)}${file.existing === undefined ? dim(" (new)") : ""}`);
539
+ say(
540
+ paint(
541
+ file.existing === undefined
542
+ ? file.incoming
543
+ .split("\n")
544
+ .map((line) => `+ ${line}`)
545
+ .join("\n")
546
+ : unified(file.existing, file.incoming),
547
+ ),
548
+ );
549
+ }
550
+ return;
551
+ }
552
+
553
+ say(bold("Dry run. Nothing was written."));
554
+ report(files);
555
+ const installed = installedPackages(root);
556
+ const runtime = missingDependencies(items, installed);
557
+ const development = missingDependencies(items, installed, "devDependencies");
558
+ if (runtime.length > 0 || development.length > 0) {
559
+ say();
560
+ say(bold("Would install:"));
561
+ if (runtime.length > 0) say(` ${installCommand(root, runtime)}`);
562
+ if (development.length > 0) say(` ${installCommand(root, development, { dev: true })}`);
563
+ }
564
+ }
565
+
566
+ async function add(args: Args): Promise<void> {
567
+ const { root, config } = requireConfig(args.cwd);
568
+ const names = args.all
569
+ ? (await sourceFor(config, root).index()).items
570
+ .filter((item) => item.type === "registry:ui")
571
+ .map((item) => item.name)
572
+ : args.rest;
573
+ if (names.length === 0) throw new Error("which component? `barq-ui list` shows them all");
574
+
575
+ const items = await resolveItems(registriesFor(config, root), names);
576
+ const dryRun = args.dryRun || args.diff !== undefined || args.view !== undefined;
577
+
578
+ const applied = applyItems(config, root, items, { overwrite: args.overwrite, dryRun });
579
+ const themed = await extendTheme(applied.config, root, items, {
580
+ overwrite: args.overwrite,
581
+ dryRun,
582
+ });
583
+ const files = [...applied.files, ...(themed.file === undefined ? [] : [themed.file])];
584
+
585
+ if (dryRun) {
586
+ preview(root, args, items, files);
587
+ return;
588
+ }
589
+ writeConfig(root, themed.config);
590
+ report(files);
591
+ settle(root, items, args.install);
592
+ }
593
+
594
+ interface Difference {
595
+ readonly item: string;
596
+ /** The file's path in the registry, which is what its hash is recorded under. */
597
+ readonly key: string;
598
+ readonly path: string;
599
+ readonly absolute: string;
600
+ readonly diff: string;
601
+ readonly theirs: string;
602
+ }
603
+
604
+ /** What each item's files look like now, against what the registry has. */
605
+ async function compare(
606
+ config: Config,
607
+ root: string,
608
+ registries: Registries,
609
+ names: readonly string[],
610
+ ): Promise<Difference[]> {
611
+ const wanted = names.length > 0 ? names : Object.keys(config.items).filter((n) => n !== "theme");
612
+ const items = await resolveItems(registries, wanted);
613
+ const together = placed(items);
614
+ const out: Difference[] = [];
615
+
616
+ for (const item of items) {
617
+ for (const file of item.files) {
618
+ const absolute = targetOf(config, root, file);
619
+ const mine = read(absolute);
620
+ if (mine === undefined) continue;
621
+ const theirs = rewrite(config, root, file, together);
622
+ const diff = unified(mine, theirs);
623
+ if (diff === "") continue;
624
+ out.push({
625
+ item: item.name,
626
+ key: file.path,
627
+ path: absolute.slice(root.length + 1),
628
+ absolute,
629
+ diff,
630
+ theirs,
631
+ });
632
+ }
633
+ }
634
+ return out;
635
+ }
636
+
637
+ async function showDiff(args: Args): Promise<void> {
638
+ const { root, config } = requireConfig(args.cwd);
639
+ const changes = await compare(config, root, registriesFor(config, root), args.rest);
640
+
641
+ if (changes.length === 0) {
642
+ say(dim("Nothing has changed."));
643
+ return;
644
+ }
645
+ for (const change of changes) {
646
+ say();
647
+ say(bold(change.path));
648
+ say(paint(change.diff));
649
+ }
650
+ say();
651
+ say(dim(`${String(changes.length)} file(s). \`barq-ui sync\` takes the registry's version.`));
652
+ }
653
+
654
+ async function sync(args: Args): Promise<void> {
655
+ const { root, config } = requireConfig(args.cwd);
656
+ const changes = await compare(config, root, registriesFor(config, root), args.rest);
657
+
658
+ if (changes.length === 0) {
659
+ say(dim("Nothing to sync."));
660
+ return;
661
+ }
662
+
663
+ const prompt = ask(!args.yes);
664
+ const items = { ...config.items };
665
+ let taken = 0;
666
+
667
+ try {
668
+ for (const change of changes) {
669
+ const mine = read(change.absolute) ?? "";
670
+ const recorded = items[change.item]?.[change.key];
671
+ const untouched = recorded !== undefined && hashOf(mine) === recorded;
672
+
673
+ if (!untouched && !args.overwrite) {
674
+ say();
675
+ say(`${bold(change.path)} ${yellow("(you have edited this)")}`);
676
+ say(paint(change.diff));
677
+ const take = await prompt.confirm("Take the registry's version?", false);
678
+ if (!take) continue;
679
+ }
680
+
681
+ write(change.absolute, change.theirs);
682
+ taken++;
683
+ items[change.item] = { ...items[change.item], [change.key]: hashOf(change.theirs) };
684
+ }
685
+ } finally {
686
+ prompt.close();
687
+ }
688
+
689
+ writeConfig(root, { ...config, items });
690
+ say();
691
+ say(
692
+ taken === 0
693
+ ? dim("Nothing was replaced.")
694
+ : `${green("Synced")} ${String(taken)} file${taken === 1 ? "" : "s"}.`,
695
+ );
696
+ }
697
+
698
+ async function list(args: Args): Promise<void> {
699
+ const root = requireConfigOrCwd(args.cwd);
700
+ const config = root.config;
701
+ const index = await sourceFor(config, root.root).index();
702
+
703
+ const groups = new Map<string, typeof index.items>();
704
+ for (const item of index.items) {
705
+ groups.set(item.type, [...(groups.get(item.type) ?? []), item]);
706
+ }
707
+
708
+ for (const [type, items] of [...groups].toSorted(([a], [b]) => a.localeCompare(b))) {
709
+ say();
710
+ say(bold(type.replace("registry:", "")));
711
+ for (const item of items) {
712
+ const have = config.items[item.name] !== undefined ? green(" (added)") : "";
713
+ say(` ${item.name.padEnd(18)}${dim(item.description?.slice(0, 60) ?? "")}${have}`);
714
+ }
715
+ }
716
+ }
717
+
718
+ /** `list` works before `init`, against the default registry. */
719
+ function requireConfigOrCwd(cwd: string): { root: string; config: Config } {
720
+ try {
721
+ return requireConfig(cwd);
722
+ } catch {
723
+ return { root: cwd, config: parseConfig({ paths: DEFAULT_PATHS, items: {} }) };
724
+ }
725
+ }
726
+
727
+ /** `view` works before `init` too: reading an item needs a registry, not a project. */
728
+ async function view(args: Args): Promise<void> {
729
+ if (args.rest.length === 0) throw new Error("which item? `barq-ui list` shows them all");
730
+ const { root, config } = requireConfigOrCwd(args.cwd);
731
+ const registries = registriesFor(config, root);
732
+
733
+ const items: RegistryItem[] = [];
734
+ for (const address of args.rest) {
735
+ const { source, name } = registries.locate(address);
736
+ items.push({ ...(await source.item(name)), name: address });
737
+ }
738
+ say(JSON.stringify(items, null, 2));
739
+ }
740
+
741
+ interface Found {
742
+ /** What `add` takes: the name, with its scope when it has one. */
743
+ readonly name: string;
744
+ readonly type: string;
745
+ readonly title: string;
746
+ readonly description?: string;
747
+ readonly categories: readonly string[];
748
+ readonly registry: string;
749
+ }
750
+
751
+ /** Every word of the query, somewhere in what the entry says about itself. */
752
+ function matches(entry: RegistryIndexEntry, words: readonly string[]): boolean {
753
+ const haystack = [entry.name, entry.title, entry.description ?? "", ...entry.categories]
754
+ .join(" ")
755
+ .toLowerCase();
756
+ return words.every((word) => haystack.includes(word));
757
+ }
758
+
759
+ async function search(args: Args): Promise<void> {
760
+ const words = args.rest.map((word) => word.toLowerCase());
761
+ if (words.length === 0) throw new Error("search for what? `barq-ui search sidebar`");
762
+ const { root, config } = requireConfigOrCwd(args.cwd);
763
+ const registries = registriesFor(config, root);
764
+
765
+ const found: Found[] = [];
766
+ const unreachable: string[] = [];
767
+ for (const scope of [undefined, ...registries.scopes]) {
768
+ try {
769
+ const source = registries.source(scope);
770
+ for (const entry of (await source.index()).items) {
771
+ if (!matches(entry, words)) continue;
772
+ found.push({
773
+ name: scope === undefined ? entry.name : `${scope}/${entry.name}`,
774
+ type: entry.type,
775
+ title: entry.title,
776
+ ...(entry.description === undefined ? {} : { description: entry.description }),
777
+ categories: entry.categories,
778
+ registry: source.describe,
779
+ });
780
+ }
781
+ } catch (error) {
782
+ // One registry that is down should not hide what the others have.
783
+ unreachable.push(
784
+ `${scope ?? "the registry"}: ${error instanceof Error ? error.message : String(error)}`,
785
+ );
786
+ }
787
+ }
788
+
789
+ if (args.json) {
790
+ say(JSON.stringify({ items: found, errors: unreachable }, null, 2));
791
+ return;
792
+ }
793
+ for (const line of unreachable) say(yellow(line));
794
+ if (found.length === 0) {
795
+ say(dim(`Nothing matches "${args.rest.join(" ")}".`));
796
+ return;
797
+ }
798
+ const width = Math.max(...found.map((item) => item.name.length)) + 2;
799
+ for (const item of found) {
800
+ say(
801
+ ` ${item.name.padEnd(width)}${dim(item.type.replace("registry:", "").padEnd(11))}${dim(item.description?.slice(0, 60) ?? "")}`,
802
+ );
803
+ }
804
+ say();
805
+ say(
806
+ dim(
807
+ `${String(found.length)} item${found.length === 1 ? "" : "s"}. \`barq-ui add <name>\` takes one.`,
808
+ ),
809
+ );
810
+ }
811
+
812
+ async function info(args: Args): Promise<void> {
813
+ const root = findRoot(args.cwd);
814
+ const { config } = requireConfigOrCwd(args.cwd);
815
+ const project = root ?? args.cwd;
816
+ const added = Object.keys(config.items)
817
+ .filter((name) => name !== "theme")
818
+ .toSorted();
819
+ const facts = {
820
+ root: project,
821
+ config: root === undefined ? null : join(root, CONFIG_FILE),
822
+ registry: config.registry ?? defaultRegistry(),
823
+ registries: Object.fromEntries(
824
+ Object.entries(config.registries).map(([scope, endpoint]) => [scope, endpoint.url]),
825
+ ),
826
+ paths: config.paths,
827
+ theme: config.theme,
828
+ packageManager: packageManager(project),
829
+ packages: [...installedPackages(project)]
830
+ .filter((name) => name.startsWith("@barqjs/"))
831
+ .toSorted(),
832
+ items: added,
833
+ };
834
+
835
+ if (args.json) {
836
+ say(JSON.stringify(facts, null, 2));
837
+ return;
838
+ }
839
+
840
+ const row = (label: string, value: string): void => say(` ${label.padEnd(17)}${value}`);
841
+ say(bold("Project"));
842
+ row("root", facts.root);
843
+ row("config", facts.config ?? dim(`none. \`barq-ui init\` writes ${CONFIG_FILE}`));
844
+ row("package manager", facts.packageManager);
845
+ row("barq packages", facts.packages.length === 0 ? dim("none") : facts.packages.join(", "));
846
+ say();
847
+ say(bold("Registries"));
848
+ row("(default)", facts.registry);
849
+ for (const [scope, url] of Object.entries(facts.registries)) row(scope, url);
850
+ say();
851
+ say(bold("Paths"));
852
+ for (const kind of ["ui", "lib", "theme", "components", "hooks"] as const) {
853
+ row(kind, config.paths[kind]);
854
+ }
855
+ say();
856
+ say(bold("Theme"));
857
+ row("base", config.theme.base);
858
+ if (config.theme.accent !== undefined) row("accent", config.theme.accent);
859
+ if (config.theme.style !== undefined) row("style", config.theme.style);
860
+ if (config.theme.radius !== undefined) row("radius", config.theme.radius);
861
+ say();
862
+ say(bold(`Added (${String(added.length)})`));
863
+ say(added.length === 0 ? dim(" nothing yet") : ` ${added.join(", ")}`);
864
+ await Promise.resolve();
865
+ }
866
+
867
+ async function chooseTheme(args: Args): Promise<void> {
868
+ const name = args.rest[0];
869
+ if (name === undefined) throw new Error("which theme? `barq-ui list` shows the components");
870
+ const { root, config } = requireConfig(args.cwd);
871
+ const table = await themes(sourceFor(config, root));
872
+
873
+ const chosen = table.find((entry) => entry.name === name);
874
+ if (chosen === undefined) {
875
+ throw new Error(
876
+ `no theme named "${name}". Try one of: ${table.map((entry) => entry.name).join(", ")}`,
877
+ );
878
+ }
879
+
880
+ const next = {
881
+ ...config.theme,
882
+ ...(chosen.kind === "base" ? { base: name } : { accent: name }),
883
+ ...(args.radius === undefined ? {} : { radius: args.radius }),
884
+ };
885
+ const module_ = themeModule(next, table, {
886
+ reset: config.reset,
887
+ base: "./base.ts",
888
+ resetPath: "./reset.ts",
889
+ });
890
+ const path = themeTarget(config, root);
891
+ write(path, module_);
892
+
893
+ writeConfig(root, {
894
+ ...config,
895
+ theme: next,
896
+ items: { ...config.items, theme: { [THEME_KEY]: hashOf(module_) } },
897
+ });
898
+ say(`${green("Theme")} ${bold(chosen.title)} written to ${path.slice(root.length + 1)}.`);
899
+ }
900
+
901
+ /** `barq-ui style nova`, the shape `barq-ui theme` already has. */
902
+ async function chooseStyle(args: Args): Promise<void> {
903
+ const name = args.rest[0] ?? args.style;
904
+ const { root, config } = requireConfig(args.cwd);
905
+ const source = sourceFor(config, root);
906
+ const available = await styles(source);
907
+ if (name === undefined) {
908
+ throw new Error(`which style? ${available.map((each) => each.value).join(", ")}`);
909
+ }
910
+ if (!available.some((each) => each.value === name)) {
911
+ throw new Error(
912
+ `no style named "${name}". Try one of: ${available.map((each) => each.value).join(", ")}`,
913
+ );
914
+ }
915
+
916
+ const path = await writeStyle(root, config, name, source);
917
+ writeConfig(root, { ...config, theme: { ...config.theme, style: name } });
918
+ say(`${green("Style")} ${bold(name)} written to ${path.slice(root.length + 1)}.`);
919
+ say(dim(`Put class="style-${name}" on the element it applies to.`));
920
+ }
921
+
922
+ async function build(args: Args): Promise<void> {
923
+ const directory = args.rest[0];
924
+ if (directory === undefined) throw new Error("which directory? `barq-ui build ./src/ui`");
925
+ const { buildRegistry } = await import("./build.ts");
926
+ const written = buildRegistry(resolve(args.cwd, directory), resolve(args.cwd, "registry"));
927
+ say(`${green("Built")} ${String(written)} items into registry/`);
928
+ }
929
+
930
+ // ---------------------------------------------------------------------------
931
+
932
+ async function main(): Promise<void> {
933
+ const args = parse(process.argv.slice(2));
934
+ if (args.help || args.command === undefined) {
935
+ stdout.write(HELP);
936
+ return;
937
+ }
938
+
939
+ switch (args.command) {
940
+ case "init":
941
+ return await init(args);
942
+ case "style":
943
+ return await chooseStyle(args);
944
+ case "add":
945
+ return await add(args);
946
+ case "diff":
947
+ return await showDiff(args);
948
+ case "sync":
949
+ return await sync(args);
950
+ case "list":
951
+ return await list(args);
952
+ case "search":
953
+ return await search(args);
954
+ case "view":
955
+ return await view(args);
956
+ case "info":
957
+ return await info(args);
958
+ case "theme":
959
+ return await chooseTheme(args);
960
+ case "build":
961
+ return await build(args);
962
+ default:
963
+ throw new Error(`unknown command "${args.command}". Try \`barq-ui --help\``);
964
+ }
965
+ }
966
+
967
+ /**
968
+ * Exported so the suite can drive the commands, and guarded so importing it
969
+ * does not run one. The guard compares the script node was asked to run with
970
+ * this module rather than reading `import.meta.main`, which node only defines
971
+ * from 24.2 and so is `undefined` for the built `bin` on every older node the
972
+ * engines range admits. `argv[1]` is the `.bin` symlink under a package
973
+ * manager, hence the realpath.
974
+ */
975
+ export async function run(): Promise<void> {
976
+ try {
977
+ await main();
978
+ } catch (error) {
979
+ say(red(error instanceof Error ? error.message : String(error)));
980
+ process.exitCode = 1;
981
+ }
982
+ }
983
+
984
+ function invokedDirectly(): boolean {
985
+ const script = process.argv[1];
986
+ return script !== undefined && realpathSync(script) === fileURLToPath(import.meta.url);
987
+ }
988
+
989
+ if (invokedDirectly()) await run();