zion 2.3.0 → 2.5.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/dist/cli.js CHANGED
@@ -1,720 +1,2323 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/app.tsx
4
- import { useEffect as useEffect4, useRef as useRef2, useState as useState3 } from "react";
5
- import { Box as Box7, Text as Text11, useApp, useInput as useInput2, useStdout as useStdout2 } from "ink";
6
-
7
- // src/components/BlogDetailView.tsx
8
- import { useEffect } from "react";
9
- import { Box as Box2, Text as Text3, useStdout } from "ink";
10
- import { ScrollView } from "ink-scroll-view";
11
-
12
- // src/components/HintBar.tsx
13
- import { Text } from "ink";
14
-
15
- // src/lib/config.ts
16
- var DOT_CHAR = " \u2022 ";
17
- var BASE_URL = process.env.BASE_URL || "https://zzzzion.com";
18
- var NAV_LINKS = [
19
- { name: "home", path: "/", color: "#264b96" },
20
- { name: "blog", path: "/blog", color: "#006f3c" },
21
- { name: "portfolio", path: "/portfolio", color: "#f9a73e" },
22
- { name: "art", path: "/art", color: "#bf212f" }
3
+ // src/cli.tsx
4
+ import os3 from "os";
5
+ import path14 from "path";
6
+
7
+ // package.json
8
+ var version = "2.5.0";
9
+
10
+ // src/lib/theme.ts
11
+ import chalk, { supportsColor, supportsColorStderr } from "chalk";
12
+ var palette = {
13
+ brand: "#264b96",
14
+ accent: "#5c9fd4",
15
+ success: "#3fb950",
16
+ warning: "#f9a73e",
17
+ error: "#e5534b"
18
+ };
19
+ var symbols = {
20
+ start: "\u250C",
21
+ bar: "\u2502",
22
+ end: "\u2514",
23
+ active: "\u25C6",
24
+ done: "\u25C7",
25
+ warning: "\u25B2",
26
+ error: "\u25A0",
27
+ radioOn: "\u25CF",
28
+ radioOff: "\u25CB",
29
+ checkOn: "\u25FC",
30
+ checkOff: "\u25FB",
31
+ tick: "\u2714",
32
+ cross: "\u2716",
33
+ spinner: ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]
34
+ };
35
+ var paint = {
36
+ accent: chalk.hex(palette.accent),
37
+ success: chalk.hex(palette.success),
38
+ warning: chalk.hex(palette.warning),
39
+ error: chalk.hex(palette.error),
40
+ muted: chalk.gray,
41
+ dim: chalk.dim,
42
+ bold: chalk.bold
43
+ };
44
+ function useColorsFor(stream, allowed = true) {
45
+ const detected = stream === process.stderr ? supportsColorStderr : supportsColor;
46
+ const noColor = Boolean(process.env.NO_COLOR) && !("FORCE_COLOR" in process.env);
47
+ chalk.level = !allowed || noColor || !detected ? 0 : detected.level;
48
+ }
49
+ function badge(text) {
50
+ return chalk.bgHex(palette.brand).hex("#ffffff").bold(` ${text} `);
51
+ }
52
+
53
+ // src/prompts/format.ts
54
+ import chalk2 from "chalk";
55
+ var toneColor = {
56
+ success: paint.success,
57
+ warning: paint.warning,
58
+ error: paint.error,
59
+ info: paint.accent,
60
+ muted: paint.muted
61
+ };
62
+ var stepSymbol = {
63
+ success: symbols.done,
64
+ warning: symbols.warning,
65
+ error: symbols.error,
66
+ info: symbols.done,
67
+ muted: symbols.done
68
+ };
69
+ var finalSymbol = {
70
+ success: symbols.tick,
71
+ warning: symbols.warning,
72
+ error: symbols.cross,
73
+ info: symbols.radioOn,
74
+ muted: symbols.error
75
+ };
76
+ var bar = paint.muted(symbols.bar);
77
+ function join(lines) {
78
+ return lines.filter((line) => typeof line === "string").join("\n");
79
+ }
80
+ function detail(line, tone) {
81
+ return tone === "warning" || tone === "error" ? toneColor[tone](line) : paint.dim(line);
82
+ }
83
+ function formatIntro(title, subtitle) {
84
+ return join([
85
+ "",
86
+ `${paint.muted(symbols.start)} ${badge("zion")} ${paint.bold(title)}`,
87
+ subtitle && `${bar} ${paint.muted(subtitle)}`
88
+ ]);
89
+ }
90
+ function formatStep({ title, lines = [], tone = "success" }) {
91
+ return join([
92
+ bar,
93
+ `${toneColor[tone](stepSymbol[tone])} ${title}`,
94
+ ...lines.map((line) => `${bar} ${detail(line, tone)}`)
95
+ ]);
96
+ }
97
+ function formatHandoff(title, lines = []) {
98
+ return join([bar, `${paint.muted(symbols.end)} ${title}`, ...lines.map((line) => ` ${paint.dim(line)}`), ""]);
99
+ }
100
+ function formatOutro(message, tone, lines, attached) {
101
+ const head = attached ? [bar, `${paint.muted(symbols.end)} ${toneColor[tone](message)}`] : ["", `${toneColor[tone](finalSymbol[tone])} ${toneColor[tone](message)}`];
102
+ return join([...head, ...lines.map((line) => ` ${paint.dim(line)}`), ""]);
103
+ }
104
+ function formatActive({ message, body, footer = "", invalid = false }) {
105
+ const color = invalid ? paint.warning : paint.accent;
106
+ return join([
107
+ bar,
108
+ `${color(symbols.active)} ${paint.bold(message)}`,
109
+ ...body.map((line) => `${color(symbols.bar)} ${line}`),
110
+ `${color(symbols.end)} ${invalid ? paint.warning(footer) : paint.muted(footer)}`
111
+ ]);
112
+ }
113
+ function formatSpinner(frame, title, elapsedSeconds) {
114
+ const spinner = paint.accent(symbols.spinner[frame % symbols.spinner.length]);
115
+ const elapsed = elapsedSeconds >= 2 ? paint.muted(` ${elapsedSeconds}s`) : "";
116
+ return join([bar, `${spinner} ${title}${paint.muted("\u2026")}${elapsed}`]);
117
+ }
118
+ function formatError(message, hint) {
119
+ return join([`${paint.error(symbols.cross)} ${chalk2.bold(message)}`, hint && ` ${paint.muted(hint)}`]);
120
+ }
121
+ function keyHints(hints) {
122
+ return hints.map(([key, action]) => `${chalk2.white(key)} ${action}`).join(paint.muted(" \xB7 "));
123
+ }
124
+
125
+ // src/cli/errors.ts
126
+ var CliError = class extends Error {
127
+ constructor(message, hint, exitCode = 1) {
128
+ super(message);
129
+ this.hint = hint;
130
+ this.exitCode = exitCode;
131
+ this.name = "CliError";
132
+ }
133
+ };
134
+ var UsageError = class extends CliError {
135
+ constructor(message, hint) {
136
+ super(message, hint, 2);
137
+ this.name = "UsageError";
138
+ }
139
+ };
140
+ var CancelledError = class extends Error {
141
+ constructor() {
142
+ super("Cancelled");
143
+ this.name = "CancelledError";
144
+ }
145
+ };
146
+ var reported = /* @__PURE__ */ new WeakSet();
147
+ function markReported(error) {
148
+ if (error instanceof Object) reported.add(error);
149
+ }
150
+ function isReported(error) {
151
+ return error instanceof Object && reported.has(error);
152
+ }
153
+ function exitCodeFor(error) {
154
+ if (error instanceof CancelledError) return 130;
155
+ if (error instanceof CliError) return error.exitCode;
156
+ return 1;
157
+ }
158
+ function errorMessage(error) {
159
+ return error instanceof Error ? error.message : String(error);
160
+ }
161
+
162
+ // src/cli/Cli.ts
163
+ var HELP_FLAGS = /* @__PURE__ */ new Set(["-h", "--help"]);
164
+ var VERSION_FLAGS = /* @__PURE__ */ new Set(["-v", "--version"]);
165
+ var Cli = class {
166
+ constructor(options) {
167
+ this.options = options;
168
+ }
169
+ async run(argv) {
170
+ const { args, noColor, noInput } = extractGlobalFlags(argv);
171
+ const ctx = this.createContext({ noColor, noInput });
172
+ try {
173
+ return await this.dispatch(args, ctx);
174
+ } catch (error) {
175
+ if (!isReported(error)) {
176
+ useColorsFor(ctx.stderr, ctx.color);
177
+ ctx.stderr.write(`${formatError(errorMessage(error), error instanceof CliError ? error.hint : void 0)}
178
+ `);
179
+ }
180
+ return exitCodeFor(error);
181
+ }
182
+ }
183
+ createContext({ noColor, noInput }) {
184
+ const { bin, version: version2, stdin, stdout, stderr, env } = this.options.environment;
185
+ const terminal = Boolean(stdin.isTTY && stderr.isTTY) && env.TERM !== "dumb";
186
+ return { bin, version: version2, stdin, stdout, stderr, color: !noColor, interactive: terminal && !noInput };
187
+ }
188
+ async dispatch(args, ctx) {
189
+ const { registry: registry2, fallback: fallback2, help: help2 } = this.options;
190
+ const [first, ...rest] = args;
191
+ if (first === void 0) return fallback2.run([], ctx);
192
+ if (HELP_FLAGS.has(first)) return this.print(ctx, help2.root(ctx));
193
+ if (VERSION_FLAGS.has(first)) return this.print(ctx, `${ctx.version}
194
+ `);
195
+ if (first.startsWith("-")) throw new UsageError(`unknown option "${first}"`, `run ${ctx.bin} --help for usage`);
196
+ const command = registry2.get(first);
197
+ if (!command) {
198
+ const suggestion = registry2.suggest(first);
199
+ throw new UsageError(
200
+ `unknown command "${first}"`,
201
+ suggestion ? `did you mean ${ctx.bin} ${suggestion}?` : `run ${ctx.bin} --help to see all commands`
202
+ );
203
+ }
204
+ if (optionsOf(rest).some((arg) => HELP_FLAGS.has(arg))) return this.print(ctx, help2.command(command, ctx));
205
+ return command.run(rest, ctx);
206
+ }
207
+ print(ctx, text) {
208
+ useColorsFor(ctx.stdout, ctx.color);
209
+ ctx.stdout.write(text);
210
+ return 0;
211
+ }
212
+ };
213
+ function optionsOf(args) {
214
+ const end = args.indexOf("--");
215
+ return end === -1 ? args : args.slice(0, end);
216
+ }
217
+ function extractGlobalFlags(argv) {
218
+ const end = argv.indexOf("--");
219
+ const head = end === -1 ? argv : argv.slice(0, end);
220
+ const tail = end === -1 ? [] : argv.slice(end);
221
+ return {
222
+ args: [...head.filter((arg) => arg !== "--no-color" && arg !== "--no-input"), ...tail],
223
+ noColor: head.includes("--no-color"),
224
+ noInput: head.includes("--no-input")
225
+ };
226
+ }
227
+
228
+ // src/cli/CommandRegistry.ts
229
+ var CommandRegistry = class {
230
+ commands = /* @__PURE__ */ new Map();
231
+ register(command) {
232
+ if (this.commands.has(command.name)) throw new Error(`command "${command.name}" is already registered`);
233
+ this.commands.set(command.name, command);
234
+ return this;
235
+ }
236
+ get(name) {
237
+ return this.commands.get(name);
238
+ }
239
+ list() {
240
+ return [...this.commands.values()];
241
+ }
242
+ /** The registered name closest to a mistyped one, if any is close enough. */
243
+ suggest(name) {
244
+ let best;
245
+ for (const candidate of this.commands.keys()) {
246
+ const distance = candidate.startsWith(name) ? 0 : levenshtein(name, candidate);
247
+ if (!best || distance < best.distance) best = { name: candidate, distance };
248
+ }
249
+ return best && best.distance <= 2 ? best.name : void 0;
250
+ }
251
+ };
252
+ function levenshtein(a, b) {
253
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
254
+ for (let i = 1; i <= a.length; i++) {
255
+ const current = [i];
256
+ for (let j = 1; j <= b.length; j++) {
257
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
258
+ }
259
+ previous = current;
260
+ }
261
+ return previous[b.length];
262
+ }
263
+
264
+ // src/cli/help.ts
265
+ var HELP_OPTION = ["-h, --help", "show help"];
266
+ var GLOBAL_OPTIONS = [
267
+ HELP_OPTION,
268
+ ["-v, --version", "print the version"],
269
+ ["--no-color", "disable colors (also respects NO_COLOR)"],
270
+ ["--no-input", "never prompt; fail if input is needed"]
23
271
  ];
24
- var COLORS = {
25
- subtle: "gray",
26
- text: "white",
27
- selectedBlog: "#006f3c",
28
- link: "#5c9fd4"
272
+ var HelpPrinter = class {
273
+ constructor(registry2, fallback2) {
274
+ this.registry = registry2;
275
+ this.fallback = fallback2;
276
+ }
277
+ root(ctx) {
278
+ const commands = this.registry.list().map((command) => [command.name, command.summary]);
279
+ return render([
280
+ header(ctx),
281
+ section("Usage", [`${ctx.bin} ${paint.muted("[command] [options]")}`]),
282
+ section("Commands", table(commands)),
283
+ section("Options", table(GLOBAL_OPTIONS)),
284
+ [
285
+ `Run ${paint.accent(ctx.bin)} with no command to ${this.fallback.summary}.`,
286
+ `Run ${paint.accent(`${ctx.bin} help <command>`)} for details on a command.`
287
+ ].map(indent)
288
+ ]);
289
+ }
290
+ command(command, ctx) {
291
+ const help2 = command.help;
292
+ const blocks = [
293
+ header(ctx, command.summary, command.name),
294
+ section("Usage", [`${ctx.bin} ${help2.usage}`]),
295
+ help2.description ? wrap(help2.description, 76).map(indent) : []
296
+ ];
297
+ if (help2.arguments) blocks.push(section(help2.arguments.title, table(help2.arguments.rows)));
298
+ blocks.push(section("Options", table([...help2.options ?? [], HELP_OPTION, ...GLOBAL_OPTIONS.slice(2)])));
299
+ if (help2.environment?.length) blocks.push(section("Environment", table(help2.environment)));
300
+ if (help2.examples?.length) {
301
+ blocks.push(
302
+ section(
303
+ "Examples",
304
+ help2.examples.map((example) => `${paint.muted("$")} ${ctx.bin} ${example}`)
305
+ )
306
+ );
307
+ }
308
+ return render(blocks);
309
+ }
310
+ };
311
+ var HelpCommand = class {
312
+ constructor(printer, registry2) {
313
+ this.printer = printer;
314
+ this.registry = registry2;
315
+ }
316
+ name = "help";
317
+ summary = "show help for a command";
318
+ help = {
319
+ usage: "help [command]",
320
+ arguments: { title: "Arguments", rows: [["command", "the command to describe"]] }
321
+ };
322
+ async run(args, ctx) {
323
+ const [name] = args;
324
+ useColorsFor(ctx.stdout, ctx.color);
325
+ if (!name) {
326
+ ctx.stdout.write(this.printer.root(ctx));
327
+ return 0;
328
+ }
329
+ const command = this.registry.get(name);
330
+ if (!command) throw new UsageError(`unknown command "${name}"`, `run ${ctx.bin} help to see all commands`);
331
+ ctx.stdout.write(this.printer.command(command, ctx));
332
+ return 0;
333
+ }
29
334
  };
335
+ function header(ctx, summary, name) {
336
+ const title = name ? `${badge("zion")} ${paint.bold(name)}` : badge("zion");
337
+ const lines = [indent(`${title} ${paint.muted(`v${ctx.version}`)}`)];
338
+ return summary ? [...lines, indent(paint.muted(summary))] : lines;
339
+ }
340
+ function section(title, lines) {
341
+ return [indent(paint.bold(title.toUpperCase())), ...lines.map((line) => indent(indent(line)))];
342
+ }
343
+ function table(rows) {
344
+ const width = Math.max(...rows.map(([term]) => term.length));
345
+ return rows.map(([term, description]) => `${paint.accent(term.padEnd(width))} ${description}`);
346
+ }
347
+ function indent(line) {
348
+ return ` ${line}`;
349
+ }
350
+ function wrap(text, width) {
351
+ const lines = [];
352
+ let line = "";
353
+ for (const word of text.split(/\s+/)) {
354
+ if (line && line.length + word.length + 1 > width) {
355
+ lines.push(line);
356
+ line = word;
357
+ } else {
358
+ line = line ? `${line} ${word}` : word;
359
+ }
360
+ }
361
+ if (line) lines.push(line);
362
+ return lines;
363
+ }
364
+ function render(blocks) {
365
+ return `
366
+ ${blocks.filter((block) => block.length > 0).map((block) => block.join("\n")).join("\n\n")}
367
+
368
+ `;
369
+ }
30
370
 
31
- // src/components/HintBar.tsx
371
+ // src/commands/TuiCommand.tsx
32
372
  import { jsx } from "react/jsx-runtime";
33
- function HintBar({ text }) {
34
- return /* @__PURE__ */ jsx(Text, { color: COLORS.subtle, children: text });
35
- }
36
-
37
- // src/components/ui/Markdown.tsx
38
- import Table from "cli-table3";
39
- import { marked } from "marked";
40
- import { Box, Text as Text2 } from "ink";
41
- import terminalLink from "terminal-link";
42
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
43
- function Markdown({ children, width }) {
44
- const tokens = marked.lexer(children);
45
- return /* @__PURE__ */ jsx2(Box, { flexDirection: "column", width, children: tokens.map((token, idx) => /* @__PURE__ */ jsx2(TokenRenderer, { token, width }, idx)) });
46
- }
47
- function TokenRenderer({ token, width }) {
48
- switch (token.type) {
49
- case "heading":
50
- return /* @__PURE__ */ jsx2(Box, { marginTop: token.depth === 1 ? 0 : 1, children: /* @__PURE__ */ jsx2(Text2, { bold: true, underline: token.depth === 1, children: renderInline(token.tokens) }) });
51
- case "paragraph":
52
- return /* @__PURE__ */ jsx2(Text2, { wrap: "wrap", children: renderInline(token.tokens) });
53
- case "code": {
54
- const innerWidth = width ? width - 4 : 76;
55
- const horizontalBar = "\u2500".repeat(innerWidth + 2);
56
- const lines = token.text.split("\n").map((line) => {
57
- const truncated = line.length > innerWidth ? line.slice(0, innerWidth) : line;
58
- return `\u2502 ${truncated.padEnd(innerWidth)} \u2502`;
59
- });
60
- const block = [`\u250C${horizontalBar}\u2510`, ...lines, `\u2514${horizontalBar}\u2518`].join("\n");
61
- return /* @__PURE__ */ jsx2(Box, { marginY: 1, children: /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: block }) });
62
- }
63
- case "blockquote":
64
- return /* @__PURE__ */ jsxs(Box, { marginLeft: 2, children: [
65
- /* @__PURE__ */ jsx2(Text2, { color: "gray", children: "\u2502 " }),
66
- /* @__PURE__ */ jsx2(Box, { flexDirection: "column", children: token.tokens?.map((t, idx) => /* @__PURE__ */ jsx2(TokenRenderer, { token: t, width: width ? width - 4 : void 0 }, idx)) })
67
- ] });
68
- case "list":
69
- return /* @__PURE__ */ jsx2(Box, { flexDirection: "column", marginY: 1, children: token.items.map((item, idx) => /* @__PURE__ */ jsxs(Box, { children: [
70
- /* @__PURE__ */ jsx2(Text2, { children: token.ordered ? `${idx + 1}. ` : "\u2022 " }),
71
- /* @__PURE__ */ jsx2(Box, { flexDirection: "column", children: item.tokens.map((t, i) => /* @__PURE__ */ jsx2(TokenRenderer, { token: t, width: width ? width - 2 : void 0 }, i)) })
72
- ] }, idx)) });
73
- case "table":
74
- return /* @__PURE__ */ jsx2(TableRenderer, { token });
75
- case "hr":
76
- return /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "\u2500".repeat(40) });
77
- case "space":
78
- return null;
79
- default:
80
- if ("text" in token && typeof token.text === "string") {
81
- return /* @__PURE__ */ jsx2(Text2, { children: token.text });
82
- }
83
- return null;
373
+ var TuiCommand = class {
374
+ name = "browse";
375
+ summary = "browse zzzzion.com in your terminal";
376
+ help = { usage: "" };
377
+ async run(_args, ctx) {
378
+ if (!ctx.interactive || !ctx.stdout.isTTY) {
379
+ throw new UsageError(
380
+ "browsing zzzzion.com needs an interactive terminal",
381
+ `run ${ctx.bin} --help to see commands`
382
+ );
383
+ }
384
+ const [{ default: App }, { render: render3 }] = await Promise.all([import("./app-YZDBB2BN.js"), import("./render-3OJW5JZI.js")]);
385
+ await render3(/* @__PURE__ */ jsx(App, {})).waitUntilExit();
386
+ return 0;
84
387
  }
388
+ };
389
+
390
+ // src/prompts/InkPrompter.tsx
391
+ import { render as render2 } from "ink";
392
+
393
+ // src/prompts/BasePrompter.ts
394
+ var BasePrompter = class {
395
+ /** True once the terminal was handed to another program, so output is no longer part of the session. */
396
+ handedOff = false;
397
+ intro(title, subtitle) {
398
+ this.emit(formatIntro(title, subtitle));
399
+ }
400
+ step(report) {
401
+ this.emit(formatStep(report));
402
+ }
403
+ outro(message, { tone = "success", lines = [] } = {}) {
404
+ this.emit(formatOutro(message, tone, lines, !this.handedOff));
405
+ }
406
+ async task(title, run, report) {
407
+ const controller = new AbortController();
408
+ const hide = this.showProgress(title, () => controller.abort());
409
+ try {
410
+ const value = await run(controller.signal);
411
+ hide();
412
+ this.step(report(value));
413
+ return value;
414
+ } catch (error) {
415
+ hide();
416
+ const cancelled = controller.signal.aborted;
417
+ this.step({ title, tone: cancelled ? "muted" : "error" });
418
+ throw cancelled ? new CancelledError() : error;
419
+ }
420
+ }
421
+ async handoff(title, lines) {
422
+ this.emit(formatHandoff(title, lines));
423
+ this.handedOff = true;
424
+ await this.release();
425
+ }
426
+ assertCanPrompt() {
427
+ if (this.handedOff) throw new Error("cannot prompt after handing off the terminal");
428
+ }
429
+ };
430
+
431
+ // src/prompts/PromptStore.ts
432
+ var PromptStore = class {
433
+ state = { entries: [], active: null };
434
+ listeners = /* @__PURE__ */ new Set();
435
+ nextId = 0;
436
+ subscribe = (listener) => {
437
+ this.listeners.add(listener);
438
+ return () => this.listeners.delete(listener);
439
+ };
440
+ getSnapshot = () => this.state;
441
+ push(text) {
442
+ this.update({ entries: [...this.state.entries, { id: this.nextId++, text }] });
443
+ }
444
+ setActive(active) {
445
+ this.update({ active });
446
+ }
447
+ cancel() {
448
+ this.state.active?.cancel();
449
+ }
450
+ update(patch) {
451
+ this.state = { ...this.state, ...patch };
452
+ for (const listener of this.listeners) listener();
453
+ }
454
+ };
455
+
456
+ // src/prompts/components/ConfirmPrompt.tsx
457
+ import { useRef, useState } from "react";
458
+ import { Text, useInput } from "ink";
459
+ import { jsx as jsx2 } from "react/jsx-runtime";
460
+ function ConfirmPrompt({ message, defaultValue, onSubmit }) {
461
+ const [value, setValue] = useState(defaultValue);
462
+ const submitted = useRef(false);
463
+ const submit = (answer) => {
464
+ if (submitted.current) return;
465
+ submitted.current = true;
466
+ onSubmit(answer);
467
+ };
468
+ useInput((input, key) => {
469
+ if (input === "y" || input === "Y") submit(true);
470
+ else if (input === "n" || input === "N") submit(false);
471
+ else if (key.leftArrow || key.rightArrow || key.tab || input === "h" || input === "l") setValue((v) => !v);
472
+ else if (key.return) submit(value);
473
+ });
474
+ const choice = (label, selected) => selected ? `${paint.accent(symbols.radioOn)} ${paint.bold(label)}` : paint.muted(`${symbols.radioOff} ${label}`);
475
+ const body = [`${choice("Yes", value)} ${paint.muted("/")} ${choice("No", !value)}`];
476
+ const footer = keyHints([
477
+ ["y/n", "answer"],
478
+ ["\u2190\u2192", "toggle"],
479
+ ["enter", "confirm"]
480
+ ]);
481
+ return /* @__PURE__ */ jsx2(Text, { children: formatActive({ message, body, footer }) });
85
482
  }
86
- function TableRenderer({ token }) {
87
- const table = new Table({
88
- head: token.header.map((cell) => renderInlineToString(cell.tokens)),
89
- style: { head: ["cyan"], border: ["gray"] }
483
+
484
+ // src/prompts/components/MultiSelectPrompt.tsx
485
+ import { useRef as useRef2, useState as useState2 } from "react";
486
+ import { Text as Text2, useInput as useInput2 } from "ink";
487
+ import { jsx as jsx3 } from "react/jsx-runtime";
488
+ function MultiSelectPrompt({ message, options, initialValues, required, onSubmit }) {
489
+ const [index, setIndex] = useState2(0);
490
+ const [chosen, setChosen] = useState2(
491
+ () => new Set(options.flatMap((option, i) => initialValues.includes(option.value) ? [i] : []))
492
+ );
493
+ const [error, setError] = useState2(null);
494
+ const submitted = useRef2(false);
495
+ const count = options.length;
496
+ const toggle = (i) => setChosen((current) => {
497
+ const next = new Set(current);
498
+ if (next.has(i)) next.delete(i);
499
+ else next.add(i);
500
+ return next;
90
501
  });
91
- for (const row of token.rows) {
92
- table.push(row.map((cell) => renderInlineToString(cell.tokens)));
93
- }
94
- return /* @__PURE__ */ jsx2(Text2, { children: table.toString() });
95
- }
96
- function renderInline(tokens) {
97
- if (!tokens) return null;
98
- return tokens.map((token, idx) => {
99
- switch (token.type) {
100
- case "text":
101
- return /* @__PURE__ */ jsx2(Text2, { children: token.text }, idx);
102
- case "strong":
103
- return /* @__PURE__ */ jsx2(Text2, { bold: true, children: renderInline(token.tokens) }, idx);
104
- case "em":
105
- return /* @__PURE__ */ jsx2(Text2, { italic: true, children: renderInline(token.tokens) }, idx);
106
- case "codespan":
107
- return /* @__PURE__ */ jsxs(Text2, { color: "yellow", children: [
108
- "`",
109
- token.text,
110
- "`"
111
- ] }, idx);
112
- case "link": {
113
- const text = renderInlineToString(token.tokens);
114
- return /* @__PURE__ */ jsx2(Text2, { color: "blue", children: terminalLink(text, token.href) }, idx);
502
+ useInput2((input, key) => {
503
+ if (submitted.current) return;
504
+ setError(null);
505
+ if (key.upArrow || input === "k") setIndex((i) => (i - 1 + count) % count);
506
+ else if (key.downArrow || input === "j") setIndex((i) => (i + 1) % count);
507
+ else if (input === " ") toggle(index);
508
+ else if (input === "a") setChosen((current) => new Set(current.size === count ? [] : options.map((_, i) => i)));
509
+ else if (key.return) {
510
+ if (required && chosen.size === 0) {
511
+ setError("Choose at least one with space.");
512
+ return;
115
513
  }
116
- case "image":
117
- return /* @__PURE__ */ jsxs(Text2, { color: "blue", children: [
118
- "[Image: ",
119
- token.text || token.href,
120
- "]"
121
- ] }, idx);
122
- case "br":
123
- return /* @__PURE__ */ jsx2(Text2, { children: "\n" }, idx);
124
- case "del":
125
- return /* @__PURE__ */ jsx2(Text2, { strikethrough: true, children: renderInline(token.tokens) }, idx);
126
- default:
127
- if ("text" in token && typeof token.text === "string") {
128
- return /* @__PURE__ */ jsx2(Text2, { children: token.text }, idx);
129
- }
130
- return null;
514
+ submitted.current = true;
515
+ onSubmit(options.filter((_, i) => chosen.has(i)));
131
516
  }
132
517
  });
518
+ const width = Math.max(...options.map((option) => option.label.length));
519
+ const body = options.map((option, i) => {
520
+ const focused = i === index;
521
+ const on = chosen.has(i);
522
+ const box = on ? paint.accent(symbols.checkOn) : paint.muted(symbols.checkOff);
523
+ const label = option.label.padEnd(width);
524
+ const hint = option.hint ? ` ${focused ? paint.muted(option.hint) : paint.dim(paint.muted(option.hint))}` : "";
525
+ return `${box} ${focused ? paint.bold(label) : on ? label : paint.muted(label)}${hint}`;
526
+ });
527
+ const footer = error ?? keyHints([
528
+ ["\u2191\u2193", "move"],
529
+ ["space", "choose"],
530
+ ["a", "all"],
531
+ ["enter", "confirm"],
532
+ ["ctrl+c", "cancel"]
533
+ ]);
534
+ return /* @__PURE__ */ jsx3(Text2, { children: formatActive({ message, body, footer, invalid: error !== null }) });
133
535
  }
134
- function renderInlineToString(tokens) {
135
- if (!tokens) return "";
136
- return tokens.map((token) => {
137
- if ("text" in token && typeof token.text === "string") {
138
- return token.text;
139
- }
140
- if ("tokens" in token && Array.isArray(token.tokens)) {
141
- return renderInlineToString(token.tokens);
536
+
537
+ // src/prompts/components/PromptHost.tsx
538
+ import { useSyncExternalStore } from "react";
539
+ import { Static, Text as Text3, useInput as useInput3 } from "ink";
540
+ import { Fragment, jsx as jsx4, jsxs } from "react/jsx-runtime";
541
+ function PromptHost({ store }) {
542
+ const { entries, active } = useSyncExternalStore(store.subscribe, store.getSnapshot);
543
+ useInput3((input, key) => {
544
+ if (key.ctrl && input === "c") store.cancel();
545
+ });
546
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
547
+ /* @__PURE__ */ jsx4(Static, { items: [...entries], children: (entry) => /* @__PURE__ */ jsx4(Text3, { children: entry.text }, entry.id) }),
548
+ active?.element
549
+ ] });
550
+ }
551
+
552
+ // src/prompts/components/SelectPrompt.tsx
553
+ import { useRef as useRef3, useState as useState3 } from "react";
554
+ import { Text as Text4, useInput as useInput4 } from "ink";
555
+ import { jsx as jsx5 } from "react/jsx-runtime";
556
+ function SelectPrompt({ message, options, initialIndex, onSubmit }) {
557
+ const [index, setIndex] = useState3(initialIndex);
558
+ const submitted = useRef3(false);
559
+ const count = options.length;
560
+ useInput4((input, key) => {
561
+ if (submitted.current) return;
562
+ if (key.upArrow || input === "k") setIndex((i) => (i - 1 + count) % count);
563
+ else if (key.downArrow || input === "j") setIndex((i) => (i + 1) % count);
564
+ else if (/^[1-9]$/.test(input) && Number(input) <= count) setIndex(Number(input) - 1);
565
+ else if (key.return) {
566
+ submitted.current = true;
567
+ onSubmit(options[index]);
142
568
  }
143
- return "";
144
- }).join("");
569
+ });
570
+ const width = Math.max(...options.map((option) => option.label.length));
571
+ const body = options.map((option, i) => {
572
+ const selected = i === index;
573
+ const marker = selected ? paint.accent(symbols.radioOn) : paint.muted(symbols.radioOff);
574
+ const label = selected ? paint.bold(option.label.padEnd(width)) : option.label.padEnd(width);
575
+ const hint = option.hint ? ` ${selected ? paint.muted(option.hint) : paint.dim(paint.muted(option.hint))}` : "";
576
+ return `${marker} ${label}${hint}`;
577
+ });
578
+ const footer = keyHints([
579
+ ["\u2191\u2193", "move"],
580
+ ["enter", "select"],
581
+ ["ctrl+c", "cancel"]
582
+ ]);
583
+ return /* @__PURE__ */ jsx5(Text4, { children: formatActive({ message, body, footer }) });
145
584
  }
146
585
 
147
- // src/components/BlogDetailView.tsx
148
- import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
149
- function BlogDetailView({ post, scrollRef, viewportHeight, contentWidth }) {
150
- const { stdout } = useStdout();
151
- useEffect(() => {
152
- const handleResize = () => scrollRef.current?.remeasure();
153
- stdout?.on("resize", handleResize);
154
- return () => {
155
- stdout?.off("resize", handleResize);
156
- };
157
- }, [stdout, scrollRef]);
586
+ // src/prompts/components/Spinner.tsx
587
+ import { useEffect, useState as useState4 } from "react";
588
+ import { Text as Text5 } from "ink";
589
+ import { jsx as jsx6 } from "react/jsx-runtime";
590
+ function Spinner({ title }) {
591
+ const [frame, setFrame] = useState4(0);
592
+ const [startedAt] = useState4(() => Date.now());
158
593
  useEffect(() => {
159
- scrollRef.current?.scrollToTop();
160
- }, [post.slug, scrollRef]);
161
- return /* @__PURE__ */ jsxs2(Fragment, { children: [
162
- /* @__PURE__ */ jsx3(Box2, { marginTop: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, color: "white", children: post.title }) }),
163
- /* @__PURE__ */ jsx3(Box2, { marginTop: 1, height: viewportHeight, flexDirection: "column", children: /* @__PURE__ */ jsx3(ScrollView, { ref: scrollRef, children: /* @__PURE__ */ jsx3(Markdown, { width: contentWidth, children: post.content }) }) }),
164
- /* @__PURE__ */ jsx3(Box2, { marginTop: 1, children: /* @__PURE__ */ jsx3(HintBar, { text: "Hint: h: back | j/k: down, up | q: quit" }) })
165
- ] });
594
+ const timer = setInterval(() => setFrame((f) => f + 1), 80);
595
+ return () => clearInterval(timer);
596
+ }, []);
597
+ return /* @__PURE__ */ jsx6(Text5, { children: formatSpinner(frame, title, Math.floor((Date.now() - startedAt) / 1e3)) });
598
+ }
599
+
600
+ // src/prompts/components/TextPrompt.tsx
601
+ import chalk3 from "chalk";
602
+ import { useRef as useRef4, useState as useState5 } from "react";
603
+ import { Text as Text6, useInput as useInput5 } from "ink";
604
+ import { jsx as jsx7 } from "react/jsx-runtime";
605
+ function TextPrompt({ message, defaultValue = "", validate, onSubmit }) {
606
+ const [value, setValue] = useState5("");
607
+ const [error, setError] = useState5();
608
+ const busy = useRef4(false);
609
+ useInput5((input, key) => {
610
+ if (busy.current) return;
611
+ if (key.return) {
612
+ const answer = value.trim() || defaultValue;
613
+ busy.current = true;
614
+ Promise.resolve(validate?.(answer)).then((problem) => {
615
+ if (problem) {
616
+ busy.current = false;
617
+ setError(problem);
618
+ } else {
619
+ onSubmit(answer);
620
+ }
621
+ });
622
+ return;
623
+ }
624
+ if (key.tab && !value && defaultValue) {
625
+ setValue(defaultValue);
626
+ return;
627
+ }
628
+ if (key.backspace || key.delete) {
629
+ setValue((v) => v.slice(0, -1));
630
+ setError(void 0);
631
+ return;
632
+ }
633
+ if (key.ctrl && input === "u") {
634
+ setValue("");
635
+ return;
636
+ }
637
+ if (key.ctrl || key.meta || key.escape || key.tab || key.upArrow || key.downArrow) return;
638
+ if (key.leftArrow || key.rightArrow) return;
639
+ const printable = input.replace(/[\r\n\t]/g, "");
640
+ if (printable) {
641
+ setValue((v) => v + printable);
642
+ setError(void 0);
643
+ }
644
+ });
645
+ const line = value ? `${value}${chalk3.inverse(" ")}` : defaultValue ? `${chalk3.inverse(defaultValue[0])}${paint.muted(defaultValue.slice(1))}` : chalk3.inverse(" ");
646
+ const footer = error ? `${symbols.warning} ${error}` : keyHints([
647
+ ["enter", value || !defaultValue ? "confirm" : "use default"],
648
+ ...defaultValue && !value ? [["tab", "edit default"]] : [],
649
+ ["ctrl+c", "cancel"]
650
+ ]);
651
+ return /* @__PURE__ */ jsx7(Text6, { children: formatActive({ message, body: [line], footer, invalid: Boolean(error) }) });
166
652
  }
167
653
 
168
- // src/components/BlogListView.tsx
169
- import { Box as Box3, Text as Text4 } from "ink";
170
- import { ScrollView as ScrollView2 } from "ink-scroll-view";
654
+ // src/prompts/InkPrompter.tsx
655
+ import { jsx as jsx8 } from "react/jsx-runtime";
656
+ var InkPrompter = class extends BasePrompter {
657
+ constructor(out, stdin) {
658
+ super();
659
+ this.out = out;
660
+ this.instance = render2(/* @__PURE__ */ jsx8(PromptHost, { store: this.store }), {
661
+ stdout: out,
662
+ stdin,
663
+ exitOnCtrlC: false,
664
+ patchConsole: false
665
+ });
666
+ }
667
+ store = new PromptStore();
668
+ instance;
669
+ emit(text) {
670
+ if (this.instance) this.store.push(text);
671
+ else this.out.write(`${text}
672
+ `);
673
+ }
674
+ showProgress(title, cancel) {
675
+ this.store.setActive({ element: /* @__PURE__ */ jsx8(Spinner, { title }), cancel });
676
+ return () => this.store.setActive(null);
677
+ }
678
+ text({ message, defaultValue, validate }) {
679
+ return this.ask(
680
+ (submit) => /* @__PURE__ */ jsx8(TextPrompt, { message, defaultValue, validate, onSubmit: submit }),
681
+ (value) => ({ title: message, lines: [value] })
682
+ );
683
+ }
684
+ select({ message, options, initialValue }) {
685
+ const initialIndex = Math.max(
686
+ 0,
687
+ options.findIndex((option) => option.value === initialValue)
688
+ );
689
+ return this.ask(
690
+ (submit) => /* @__PURE__ */ jsx8(
691
+ SelectPrompt,
692
+ {
693
+ message,
694
+ options,
695
+ initialIndex,
696
+ onSubmit: (option) => submit(option.value)
697
+ }
698
+ ),
699
+ (value) => ({ title: message, lines: [options.find((option) => option.value === value)?.label ?? String(value)] })
700
+ );
701
+ }
702
+ multiselect({ message, options, initialValues = [], required = true }) {
703
+ return this.ask(
704
+ (submit) => /* @__PURE__ */ jsx8(
705
+ MultiSelectPrompt,
706
+ {
707
+ message,
708
+ options,
709
+ initialValues,
710
+ required,
711
+ onSubmit: (chosen) => submit(chosen.map((option) => option.value))
712
+ }
713
+ ),
714
+ (values) => ({
715
+ title: message,
716
+ lines: [
717
+ options.filter((option) => values.includes(option.value)).map((option) => option.label).join(", ") || "None"
718
+ ]
719
+ })
720
+ );
721
+ }
722
+ confirm({ message, defaultValue = false }) {
723
+ return this.ask(
724
+ (submit) => /* @__PURE__ */ jsx8(ConfirmPrompt, { message, defaultValue, onSubmit: submit }),
725
+ (value) => ({ title: message, lines: [value ? "Yes" : "No"] })
726
+ );
727
+ }
728
+ async release() {
729
+ const instance = this.instance;
730
+ if (!instance) return;
731
+ this.instance = null;
732
+ this.store.setActive(null);
733
+ await new Promise((resolve) => setImmediate(resolve));
734
+ instance.unmount();
735
+ await instance.waitUntilExit();
736
+ }
737
+ /** Shows a prompt until it is answered (then logs the answer) or cancelled. */
738
+ ask(build, answered) {
739
+ this.assertCanPrompt();
740
+ return new Promise((resolve, reject) => {
741
+ const element = build((value) => {
742
+ this.store.setActive(null);
743
+ this.step(answered(value));
744
+ resolve(value);
745
+ });
746
+ this.store.setActive({
747
+ element,
748
+ cancel: () => {
749
+ this.store.setActive(null);
750
+ reject(new CancelledError());
751
+ }
752
+ });
753
+ });
754
+ }
755
+ };
171
756
 
172
- // src/lib/content.ts
173
- async function fetchJson(url) {
757
+ // src/prompts/PlainPrompter.ts
758
+ var PlainPrompter = class extends BasePrompter {
759
+ constructor(out) {
760
+ super();
761
+ this.out = out;
762
+ }
763
+ emit(text) {
764
+ this.out.write(`${text}
765
+ `);
766
+ }
767
+ showProgress() {
768
+ return () => {
769
+ };
770
+ }
771
+ async text({ message, defaultValue, validate }) {
772
+ this.assertCanPrompt();
773
+ if (defaultValue === void 0) throw new UsageError(`${message} (no terminal to ask in)`);
774
+ const error = await validate?.(defaultValue);
775
+ if (error) throw new UsageError(error);
776
+ this.step({ title: message, lines: [defaultValue] });
777
+ return defaultValue;
778
+ }
779
+ async select({ message, options, initialValue, nonInteractiveHint }) {
780
+ this.assertCanPrompt();
781
+ const option = options.find((candidate) => candidate.value === initialValue);
782
+ if (!option) throw new UsageError(`${message} (no terminal to ask in)`, nonInteractiveHint);
783
+ this.step({ title: message, lines: [option.label] });
784
+ return option.value;
785
+ }
786
+ async multiselect({
787
+ message,
788
+ options,
789
+ initialValues = [],
790
+ required = true,
791
+ nonInteractiveHint
792
+ }) {
793
+ this.assertCanPrompt();
794
+ const chosen = options.filter((option) => initialValues.includes(option.value));
795
+ if (nonInteractiveHint || required && chosen.length === 0) {
796
+ throw new UsageError(`${message} (no terminal to ask in)`, nonInteractiveHint);
797
+ }
798
+ this.step({ title: message, lines: [chosen.map((option) => option.label).join(", ") || "None"] });
799
+ return chosen.map((option) => option.value);
800
+ }
801
+ async confirm({ message, defaultValue, nonInteractiveHint }) {
802
+ this.assertCanPrompt();
803
+ if (defaultValue === void 0 || nonInteractiveHint) {
804
+ throw new UsageError(`${message} (no terminal to ask in)`, nonInteractiveHint);
805
+ }
806
+ this.step({ title: message, lines: [defaultValue ? "Yes" : "No"] });
807
+ return defaultValue;
808
+ }
809
+ async release() {
810
+ }
811
+ };
812
+
813
+ // src/prompts/index.ts
814
+ var createPrompter = (ctx) => {
815
+ useColorsFor(ctx.stderr, ctx.color);
816
+ return ctx.interactive ? new InkPrompter(ctx.stderr, ctx.stdin) : new PlainPrompter(ctx.stderr);
817
+ };
818
+ async function runSession(ui, flow) {
174
819
  try {
175
- const res = await fetch(url);
176
- if (!res.ok) return { ok: false, error: `${res.status} ${res.statusText} (${url})` };
177
- return { ok: true, data: await res.json() };
178
- } catch (err) {
179
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
820
+ return await flow(ui);
821
+ } catch (error) {
822
+ if (error instanceof CancelledError) {
823
+ ui.outro("Cancelled. Nothing else was changed.", { tone: "muted" });
824
+ } else {
825
+ const hint = error instanceof CliError ? error.hint : void 0;
826
+ ui.outro(errorMessage(error), { tone: "error", lines: hint ? [hint] : [] });
827
+ }
828
+ markReported(error);
829
+ throw error;
830
+ } finally {
831
+ await ui.release();
180
832
  }
181
833
  }
182
- function loadAboutContent() {
183
- return fetchJson(`${BASE_URL}/api/about`);
834
+
835
+ // src/services/paths.ts
836
+ import os from "os";
837
+ import path from "path";
838
+ function expandHome(input) {
839
+ const home = os.homedir();
840
+ if (input === "~") return home;
841
+ if (input.startsWith("~/")) return path.join(home, input.slice(2));
842
+ return path.resolve(input);
184
843
  }
185
- function loadBlogPostList() {
186
- return fetchJson(`${BASE_URL}/api/posts`);
844
+ function tildify(input) {
845
+ const home = os.homedir();
846
+ if (input === home) return "~";
847
+ return input.startsWith(home + path.sep) ? `~${input.slice(home.length)}` : input;
187
848
  }
188
- function loadBlogPost(slug) {
189
- return fetchJson(`${BASE_URL}/api/posts/${slug}`);
849
+
850
+ // src/commands/dotfiles/actions.ts
851
+ var ask = { label: "Ask before each step", hint: "confirm every change", flags: [] };
852
+ var yes = { label: "Yes to everything", hint: "no questions asked", flags: ["-y"], assumeYes: true };
853
+ var dryRun = { label: "Dry run", hint: "preview only, change nothing", flags: ["-n"], dryRun: true };
854
+ var apply = { label: "Create the links", hint: "back up anything in the way", flags: [] };
855
+ var DOT_ACTIONS = [
856
+ {
857
+ id: "install",
858
+ label: "Install",
859
+ hint: "tools, symlinks, shell, git and LazyVim",
860
+ modes: [ask, yes, dryRun],
861
+ done: {
862
+ message: "You're all set.",
863
+ lines: ["Open a new terminal to load the shell config.", "Run dot doctor anytime to check this machine."]
864
+ }
865
+ },
866
+ {
867
+ id: "doctor",
868
+ label: "Doctor",
869
+ hint: "check everything, change nothing",
870
+ modes: [],
871
+ done: { message: "Everything looks good." },
872
+ failed: "dot doctor found problems."
873
+ },
874
+ {
875
+ id: "link",
876
+ label: "Link",
877
+ hint: "(re)create symlinks only",
878
+ modes: [apply, dryRun],
879
+ done: { message: "Links are in place." }
880
+ },
881
+ {
882
+ id: "uninstall",
883
+ label: "Uninstall",
884
+ hint: "remove symlinks and restore backups",
885
+ modes: [],
886
+ confirm: "Remove the dotfile symlinks and restore your backups?",
887
+ done: {
888
+ message: "Dotfiles unlinked and backups restored.",
889
+ lines: ["The source line in ~/.zshrc and ~/.gitconfig.local were left in place."]
890
+ }
891
+ }
892
+ ];
893
+ function findAction(id) {
894
+ return DOT_ACTIONS.find((action) => action.id === id);
190
895
  }
191
- function loadPortfolioList() {
192
- return fetchJson(`${BASE_URL}/api/portfolio`);
896
+ function supportsDryRun(action) {
897
+ return action.modes.some((mode) => mode.dryRun);
193
898
  }
194
- function formatDate(dateStr) {
195
- const date = /* @__PURE__ */ new Date(dateStr + "T00:00:00");
196
- return date.toLocaleDateString("en-US", {
197
- year: "numeric",
198
- month: "long",
199
- day: "numeric"
200
- });
899
+ function modeFromFlags(action, flags) {
900
+ if (flags.dryRun) return action.modes.find((mode) => mode.dryRun);
901
+ if (flags.yes) return action.modes.find((mode) => mode.assumeYes) ?? action.modes[0];
902
+ return void 0;
201
903
  }
202
904
 
203
- // src/components/BlogListView.tsx
204
- import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
205
- function BlogListView({ posts, highlightedIndex, scrollRef, viewportHeight }) {
206
- return /* @__PURE__ */ jsxs3(Fragment2, { children: [
207
- /* @__PURE__ */ jsx4(Box3, { marginTop: 1, height: viewportHeight, flexDirection: "column", children: /* @__PURE__ */ jsx4(ScrollView2, { ref: scrollRef, children: posts.map((post, idx) => {
208
- const isSelected = idx === highlightedIndex;
209
- const prefix = isSelected ? "\u203A " : " ";
210
- const dateStr = formatDate(post.publishedAt);
211
- return /* @__PURE__ */ jsxs3(Box3, { flexDirection: "row", children: [
212
- /* @__PURE__ */ jsx4(Text4, { bold: isSelected, color: isSelected ? COLORS.selectedBlog : void 0, children: prefix }),
213
- /* @__PURE__ */ jsx4(Box3, { width: 20, children: /* @__PURE__ */ jsx4(Text4, { color: COLORS.subtle, children: dateStr }) }),
214
- /* @__PURE__ */ jsx4(Text4, { bold: isSelected, color: isSelected ? COLORS.selectedBlog : COLORS.text, children: post.title })
215
- ] }, post.slug);
216
- }) }) }),
217
- /* @__PURE__ */ jsx4(Box3, { marginTop: 1, children: /* @__PURE__ */ jsx4(HintBar, { text: "Hint: h/l: home, portfolio | j/k: down, up | enter: open | q: quit" }) })
218
- ] });
905
+ // src/commands/dotfiles/options.ts
906
+ import { parseArgs } from "util";
907
+
908
+ // src/cli/parseArgs.ts
909
+ function describeParseError(error) {
910
+ const code = error.code;
911
+ const message = error instanceof Error ? error.message : String(error);
912
+ const option = message.match(/'(-[^']*)'/)?.[1];
913
+ if (code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" && option) return `unknown option "${option}"`;
914
+ if (code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE" && option) return `option "${option}" needs a value`;
915
+ return message;
219
916
  }
220
917
 
221
- // src/components/HomeView.tsx
222
- import { Box as Box4, Text as Text5 } from "ink";
223
- import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
224
- function HomeView({ aboutTitle, aboutContent, contentWidth }) {
225
- return /* @__PURE__ */ jsxs4(Fragment3, { children: [
226
- /* @__PURE__ */ jsx5(Box4, { marginTop: 1, children: /* @__PURE__ */ jsx5(Text5, { bold: true, color: "white", children: aboutTitle }) }),
227
- /* @__PURE__ */ jsx5(Box4, { marginTop: 1, children: /* @__PURE__ */ jsx5(Markdown, { width: contentWidth, children: aboutContent }) }),
228
- /* @__PURE__ */ jsx5(Box4, { marginTop: 1, children: /* @__PURE__ */ jsx5(HintBar, { text: "Hint: l: blog | q, ctrl+c: quit" }) })
229
- ] });
918
+ // src/commands/dotfiles/options.ts
919
+ var ACTION_NAMES = DOT_ACTIONS.map((action) => action.id).join(", ");
920
+ function parseDotfilesOptions(args, bin) {
921
+ const usageHint = `run ${bin} dotfiles --help for usage`;
922
+ let parsed;
923
+ try {
924
+ parsed = parseArgs({
925
+ args: [...args],
926
+ allowPositionals: true,
927
+ strict: true,
928
+ options: {
929
+ dir: { type: "string", short: "d" },
930
+ yes: { type: "boolean", short: "y", default: false },
931
+ "dry-run": { type: "boolean", short: "n", default: false },
932
+ "no-update": { type: "boolean", default: false }
933
+ }
934
+ });
935
+ } catch (error) {
936
+ throw new UsageError(describeParseError(error), usageHint);
937
+ }
938
+ const { values, positionals } = parsed;
939
+ const [name, ...extra] = positionals;
940
+ if (extra.length > 0) throw new UsageError(`unexpected argument "${extra[0]}"`, usageHint);
941
+ const action = name === void 0 ? void 0 : findAction(name);
942
+ if (name !== void 0 && !action) throw new UsageError(`unknown action "${name}"`, `choose one of: ${ACTION_NAMES}`);
943
+ if (values.dir === "") throw new UsageError("--dir needs a path", usageHint);
944
+ if (values["dry-run"] && action && !supportsDryRun(action)) {
945
+ throw new UsageError(`${action.id} has no dry run`, `--dry-run works with: ${dryRunActions()}`);
946
+ }
947
+ return {
948
+ action,
949
+ dir: values.dir,
950
+ yes: values.yes,
951
+ dryRun: values["dry-run"],
952
+ update: !values["no-update"]
953
+ };
954
+ }
955
+ function dryRunActions() {
956
+ return DOT_ACTIONS.filter(supportsDryRun).map((action) => action.id).join(", ");
230
957
  }
231
958
 
232
- // src/components/NavBar.tsx
233
- import { Box as Box5, Text as Text6 } from "ink";
234
- import terminalLink2 from "terminal-link";
235
- import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
236
- function NavBar() {
237
- return /* @__PURE__ */ jsx6(Box5, { flexDirection: "row", children: NAV_LINKS.map((link, idx) => /* @__PURE__ */ jsxs5(Box5, { flexDirection: "row", children: [
238
- idx > 0 && /* @__PURE__ */ jsx6(Text6, { color: COLORS.subtle, children: DOT_CHAR }),
239
- /* @__PURE__ */ jsx6(Box5, { marginRight: 2, children: link.name === "home" || link.name === "blog" ? /* @__PURE__ */ jsx6(Text6, { color: link.color, children: link.name }) : /* @__PURE__ */ jsx6(Text6, { color: link.color, children: terminalLink2(link.name, `${BASE_URL}${link.path}`, { fallback: () => link.name }) }) })
240
- ] }, link.name)) });
241
- }
242
-
243
- // src/components/PortfolioListView.tsx
244
- import { Box as Box6, Text as Text9 } from "ink";
245
- import { ScrollView as ScrollView3 } from "ink-scroll-view";
246
-
247
- // src/components/ui/Badge.tsx
248
- import { Text as Text7 } from "ink";
249
- import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
250
- function Badge({ color, background, children }) {
251
- return /* @__PURE__ */ jsxs6(Fragment4, { children: [
252
- /* @__PURE__ */ jsx7(Text7, { color: background, children: "\uE0B6" }),
253
- /* @__PURE__ */ jsx7(Text7, { color, backgroundColor: background, bold: true, children }),
254
- /* @__PURE__ */ jsx7(Text7, { color: background, children: "\uE0B4" })
255
- ] });
959
+ // src/commands/dotfiles/DotfilesCommand.ts
960
+ var DIR_ENV = "ZION_DOTFILES_DIR";
961
+ var DEFAULT_DIR = "~/.dotfiles";
962
+ var SUPPORTED_PLATFORMS = { darwin: "macOS", linux: "Linux" };
963
+ var DotfilesCommand = class {
964
+ constructor(deps) {
965
+ this.deps = deps;
966
+ const { slug } = deps.repository.source;
967
+ this.help = {
968
+ usage: `dotfiles ${paint.muted("[action] [options]")}`,
969
+ description: `Clones github.com/${slug} (or updates an existing clone) and runs its dot installer. Without an action, you choose one interactively. The clone lives in --dir, $${DIR_ENV}, the clone an earlier install was made from, or ${DEFAULT_DIR}, in that order.`,
970
+ arguments: { title: "Actions", rows: DOT_ACTIONS.map((action) => [action.id, action.hint]) },
971
+ options: [
972
+ ["-d, --dir <path>", `where the dotfiles live (default: ${DEFAULT_DIR})`],
973
+ ["-y, --yes", "answer yes to every prompt, including uninstall"],
974
+ ["-n, --dry-run", "show what would happen, change nothing"],
975
+ ["--no-update", "use an existing clone as is, without pulling"]
976
+ ],
977
+ environment: [[DIR_ENV, "where the dotfiles live, if --dir is not given"]],
978
+ examples: [
979
+ "dotfiles",
980
+ "dotfiles install --yes",
981
+ "dotfiles doctor",
982
+ "dotfiles link --dry-run --dir ~/src/dotfiles"
983
+ ]
984
+ };
985
+ }
986
+ name = "dotfiles";
987
+ summary = "set up zion's dotfiles on this machine";
988
+ help;
989
+ async run(args, ctx) {
990
+ const options = parseDotfilesOptions(args, ctx.bin);
991
+ const ui = this.deps.createPrompter(ctx);
992
+ return runSession(ui, async () => {
993
+ const { repository, runner: runner2 } = this.deps;
994
+ ui.intro("dotfiles", `github.com/${repository.source.slug}`);
995
+ await this.checkSystem(ui);
996
+ const dir = await this.chooseLocation(ui, options);
997
+ const action = options.action ?? await this.chooseAction(ui, ctx);
998
+ const mode = await this.chooseMode(ui, action, options, !options.action);
999
+ if (!await this.confirm(ui, action, options, ctx)) {
1000
+ ui.outro("Left everything as it was.", { tone: "muted" });
1001
+ return 0;
1002
+ }
1003
+ await this.sync(ui, dir, options);
1004
+ const installer = await repository.installerPath(dir);
1005
+ const dotArgs = [action.id, ...mode?.flags ?? []];
1006
+ await ui.handoff(`Handing over to ${paint.bold(`dot ${dotArgs.join(" ")}`)}`, [
1007
+ `$ sh ${tildify(installer)} ${dotArgs.join(" ")}`
1008
+ ]);
1009
+ const code = await runner2.attach("sh", [installer, ...dotArgs], { cwd: dir });
1010
+ this.finish(ui, ctx, action, mode, code);
1011
+ return code;
1012
+ });
1013
+ }
1014
+ async checkSystem(ui) {
1015
+ const { platform, arch, git: git2 } = this.deps;
1016
+ await ui.task(
1017
+ "Checking your system",
1018
+ async (signal) => {
1019
+ const os4 = SUPPORTED_PLATFORMS[platform];
1020
+ if (!os4) throw new CliError(`${platform} isn't supported`, "these dotfiles support macOS and Linux");
1021
+ const version2 = await git2.version(signal);
1022
+ if (!version2) {
1023
+ throw new CliError(
1024
+ "git is not installed",
1025
+ platform === "darwin" ? "run xcode-select --install, then try again" : "install git with your package manager, then try again"
1026
+ );
1027
+ }
1028
+ return `${os4} ${arch} \xB7 git ${version2}`;
1029
+ },
1030
+ (summary) => ({ title: "System", lines: [summary] })
1031
+ );
1032
+ }
1033
+ async chooseLocation(ui, options) {
1034
+ const { repository, env } = this.deps;
1035
+ const given = options.dir ? { dir: options.dir, from: "--dir" } : env[DIR_ENV] ? { dir: env[DIR_ENV], from: `$${DIR_ENV}` } : null;
1036
+ if (given) {
1037
+ const dir = expandHome(given.dir);
1038
+ if (await repository.inspect(dir) === "foreign") throw this.notAClone(dir);
1039
+ ui.step({ title: "Location", lines: [`${tildify(dir)} ${paint.muted(`from ${given.from}`)}`] });
1040
+ return dir;
1041
+ }
1042
+ const found = await repository.locate();
1043
+ if (found) {
1044
+ ui.step({ title: "Location", lines: [`${tildify(found)} ${paint.muted("existing install")}`] });
1045
+ return found;
1046
+ }
1047
+ const answer = await ui.text({
1048
+ message: "Where should your dotfiles live?",
1049
+ defaultValue: DEFAULT_DIR,
1050
+ validate: async (value) => await repository.inspect(expandHome(value)) === "foreign" ? this.notAClone(expandHome(value)).message : void 0
1051
+ });
1052
+ return expandHome(answer);
1053
+ }
1054
+ notAClone(dir) {
1055
+ return new CliError(
1056
+ `${tildify(dir)} already exists and isn't a clone of ${this.deps.repository.source.slug}`,
1057
+ "move it aside, or choose another location with --dir"
1058
+ );
1059
+ }
1060
+ async sync(ui, dir, { update }) {
1061
+ const { repository } = this.deps;
1062
+ const existing = await repository.inspect(dir) === "clone";
1063
+ return ui.task(
1064
+ existing ? "Checking for updates" : `Cloning ${repository.source.slug}`,
1065
+ (signal) => repository.sync(dir, { update, signal }),
1066
+ (result) => describeSync(result, dir)
1067
+ );
1068
+ }
1069
+ chooseAction(ui, ctx) {
1070
+ return ui.select({
1071
+ message: "What would you like to do?",
1072
+ options: DOT_ACTIONS.map((action) => ({ value: action, label: action.label, hint: action.hint })),
1073
+ nonInteractiveHint: `pass an action, e.g. ${ctx.bin} dotfiles install (one of: ${DOT_ACTIONS.map(
1074
+ (a) => a.id
1075
+ ).join(", ")})`
1076
+ });
1077
+ }
1078
+ /** Flags win; otherwise ask only if the action was picked interactively and has a real choice. */
1079
+ async chooseMode(ui, action, options, ask2) {
1080
+ const fromFlags = modeFromFlags(action, options);
1081
+ if (fromFlags || !ask2 || action.modes.length < 2) return fromFlags ?? action.modes[0];
1082
+ return ui.select({
1083
+ message: "How should it run?",
1084
+ options: action.modes.map((mode) => ({ value: mode, label: mode.label, hint: mode.hint })),
1085
+ initialValue: action.modes[0]
1086
+ });
1087
+ }
1088
+ async confirm(ui, action, options, ctx) {
1089
+ if (!action.confirm || options.yes) return true;
1090
+ return ui.confirm({
1091
+ message: action.confirm,
1092
+ defaultValue: false,
1093
+ nonInteractiveHint: `pass --yes to confirm: ${ctx.bin} dotfiles ${action.id} --yes`
1094
+ });
1095
+ }
1096
+ finish(ui, ctx, action, mode, code) {
1097
+ if (code === 0 && mode?.dryRun) ui.outro("Dry run finished. Nothing was changed.");
1098
+ else if (code === 0) ui.outro(action.done.message, { lines: action.done.lines });
1099
+ else if (code === 130) ui.outro("Interrupted.", { tone: "muted" });
1100
+ else {
1101
+ ui.outro(action.failed ?? `dot ${action.id} didn't finish cleanly (exit code ${code})`, {
1102
+ tone: "error",
1103
+ lines: [`Apply the fixes above, then run ${ctx.bin} dotfiles ${action.id} again.`]
1104
+ });
1105
+ }
1106
+ }
1107
+ };
1108
+ function describeSync(result, dir) {
1109
+ const short2 = (commit) => commit.slice(0, 7);
1110
+ switch (result.kind) {
1111
+ case "cloned":
1112
+ return { title: "Repository", lines: [`cloned into ${tildify(dir)} at ${short2(result.commit)}`] };
1113
+ case "current":
1114
+ return { title: "Repository", lines: [`up to date at ${short2(result.commit)}`] };
1115
+ case "updated":
1116
+ return {
1117
+ title: "Repository",
1118
+ lines: [
1119
+ `pulled ${result.count} new commit${result.count === 1 ? "" : "s"} (${short2(result.from)} \u2192 ${short2(
1120
+ result.to
1121
+ )})`
1122
+ ]
1123
+ };
1124
+ case "kept":
1125
+ return {
1126
+ title: "Repository",
1127
+ tone: result.warning ? "warning" : "success",
1128
+ lines: [`${result.reason} at ${short2(result.commit)}`]
1129
+ };
1130
+ }
256
1131
  }
257
1132
 
258
- // src/components/ui/Stars.tsx
259
- import { Text as Text8 } from "ink";
260
- import { jsx as jsx8 } from "react/jsx-runtime";
261
- var formatter = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });
262
- function Stars({ count }) {
263
- return /* @__PURE__ */ jsx8(Text8, { color: COLORS.subtle, children: `\u2605 ${formatter.format(count).toLowerCase()}` });
264
- }
265
-
266
- // src/components/PortfolioListView.tsx
267
- import { Fragment as Fragment5, jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
268
- function PortfolioListView({ projects, highlightedIndex, scrollRef, viewportHeight }) {
269
- return /* @__PURE__ */ jsxs7(Fragment5, { children: [
270
- /* @__PURE__ */ jsx9(Box6, { marginTop: 1, height: viewportHeight, flexDirection: "column", children: /* @__PURE__ */ jsx9(ScrollView3, { ref: scrollRef, children: projects.map((project, idx) => {
271
- const isSelected = idx === highlightedIndex;
272
- const prefix = isSelected ? "\u203A " : " ";
273
- return /* @__PURE__ */ jsxs7(Box6, { flexDirection: "column", marginBottom: 2, children: [
274
- /* @__PURE__ */ jsxs7(Box6, { flexDirection: "row", children: [
275
- /* @__PURE__ */ jsx9(Text9, { bold: isSelected, color: isSelected ? COLORS.selectedBlog : void 0, children: prefix }),
276
- /* @__PURE__ */ jsx9(Text9, { bold: isSelected, color: isSelected ? COLORS.selectedBlog : COLORS.text, children: project.title }),
277
- project.stars !== void 0 && /* @__PURE__ */ jsx9(Box6, { marginLeft: 2, children: /* @__PURE__ */ jsx9(Stars, { count: project.stars }) })
278
- ] }),
279
- /* @__PURE__ */ jsx9(Box6, { marginLeft: 3, paddingBottom: 1, children: /* @__PURE__ */ jsxs7(Text9, { color: COLORS.subtle, children: [
280
- project.description,
281
- " "
282
- ] }) }),
283
- project.links && project.links.length > 0 && /* @__PURE__ */ jsx9(Box6, { marginLeft: 3, flexDirection: "column", paddingBottom: 1, children: project.links.map((link, linkIdx) => /* @__PURE__ */ jsx9(Text9, { color: COLORS.link, children: link.url }, linkIdx)) }),
284
- project.tools && project.tools.length > 0 && /* @__PURE__ */ jsx9(Box6, { marginLeft: 3, flexDirection: "row", gap: 1, paddingBottom: 1, children: project.tools.map((tool, toolIdx) => /* @__PURE__ */ jsx9(Box6, { children: /* @__PURE__ */ jsx9(Badge, { color: "white", background: "gray", children: tool }) }, toolIdx)) })
285
- ] }, idx);
286
- }) }) }),
287
- /* @__PURE__ */ jsx9(Box6, { marginTop: 1, children: /* @__PURE__ */ jsx9(HintBar, { text: "Hint: h: blog | j/k: down, up | q: quit" }) })
288
- ] });
1133
+ // src/commands/dotfiles/DotfilesRepository.ts
1134
+ import { constants } from "fs";
1135
+ import fs from "fs/promises";
1136
+ import path2 from "path";
1137
+ var DotfilesRepository = class {
1138
+ constructor(git2, source) {
1139
+ this.git = git2;
1140
+ this.source = source;
1141
+ }
1142
+ /** The clone this machine was set up from, if the installer's link still points into one. */
1143
+ async locate() {
1144
+ let target;
1145
+ try {
1146
+ target = await fs.realpath(this.source.installerLink);
1147
+ } catch {
1148
+ return null;
1149
+ }
1150
+ const suffix = path2.sep + path2.normalize(this.source.installer);
1151
+ if (!target.endsWith(suffix)) return null;
1152
+ const root = target.slice(0, -suffix.length);
1153
+ return await this.inspect(root) === "clone" ? root : null;
1154
+ }
1155
+ async inspect(dir) {
1156
+ let stat;
1157
+ try {
1158
+ stat = await fs.stat(dir);
1159
+ } catch {
1160
+ return "missing";
1161
+ }
1162
+ if (!stat.isDirectory()) return "foreign";
1163
+ if ((await fs.readdir(dir)).length === 0) return "empty";
1164
+ const [top, real] = await Promise.all([this.git.topLevel(dir), fs.realpath(dir)]);
1165
+ if (!top || await fs.realpath(top) !== real) return "foreign";
1166
+ const remote = await this.git.remoteUrl(dir, "origin");
1167
+ return remote && this.matches(remote) ? "clone" : "foreign";
1168
+ }
1169
+ /** Clones into `dir`, or fast-forwards an existing clone when it's safe to. */
1170
+ async sync(dir, { update, signal }) {
1171
+ const state = await this.inspect(dir);
1172
+ if (state === "foreign") {
1173
+ throw new CliError(
1174
+ `${tildify(dir)} already exists and isn't a clone of ${this.source.slug}`,
1175
+ "move it aside, or choose another location with --dir"
1176
+ );
1177
+ }
1178
+ if (state === "clone") return this.update(dir, update, signal);
1179
+ await fs.mkdir(path2.dirname(dir), { recursive: true });
1180
+ try {
1181
+ await this.git.clone(this.source.url, dir, signal);
1182
+ } catch (error) {
1183
+ if (signal?.aborted) throw error;
1184
+ throw new CliError(
1185
+ `couldn't clone ${this.source.slug}`,
1186
+ `check your connection, then try again (git: ${error.message})`
1187
+ );
1188
+ }
1189
+ return { kind: "cloned", commit: await this.head(dir) };
1190
+ }
1191
+ async installerPath(dir) {
1192
+ const installer = path2.join(dir, this.source.installer);
1193
+ try {
1194
+ await fs.access(installer, constants.R_OK);
1195
+ } catch {
1196
+ throw new CliError(`${tildify(installer)} is missing`, "the repository layout changed; try the latest npx zion");
1197
+ }
1198
+ return installer;
1199
+ }
1200
+ async update(dir, update, signal) {
1201
+ const head = await this.head(dir);
1202
+ const kept = (reason, warning = true) => ({ kind: "kept", commit: head, reason, warning });
1203
+ if (!update) return kept("using the local copy (--no-update)", false);
1204
+ if (await this.git.isDirty(dir)) return kept("local changes found, so the update was skipped");
1205
+ try {
1206
+ await this.git.fetch(dir, signal);
1207
+ } catch (error) {
1208
+ if (signal?.aborted) throw error;
1209
+ return kept("couldn't reach GitHub, using the local copy");
1210
+ }
1211
+ const upstream = await this.git.resolve(dir, "@{upstream}");
1212
+ if (!upstream) return kept("no upstream branch, so the update was skipped");
1213
+ if (upstream === head) return { kind: "current", commit: head };
1214
+ const behind = await this.git.countCommits(dir, "HEAD..@{upstream}");
1215
+ if (behind === 0) return kept("ahead of GitHub, nothing to pull", false);
1216
+ if (!await this.git.fastForward(dir, "@{upstream}"))
1217
+ return kept("diverged from GitHub, so the update was skipped");
1218
+ return { kind: "updated", from: head, to: await this.head(dir), count: behind };
1219
+ }
1220
+ async head(dir) {
1221
+ return await this.git.resolve(dir, "HEAD") ?? "unknown";
1222
+ }
1223
+ matches(remote) {
1224
+ const normalized = remote.trim().toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "");
1225
+ return new RegExp(`github\\.com[:/]${this.source.slug.toLowerCase()}$`).test(normalized);
1226
+ }
1227
+ };
1228
+
1229
+ // src/commands/skills/SkillFiles.ts
1230
+ import fs3 from "fs/promises";
1231
+ import path4 from "path";
1232
+
1233
+ // src/services/Lockfile.ts
1234
+ import { createHash } from "crypto";
1235
+ import fs2 from "fs/promises";
1236
+ import path3 from "path";
1237
+ var VERSION = 1;
1238
+ var JsonLockfile = class {
1239
+ constructor(path15) {
1240
+ this.path = path15;
1241
+ }
1242
+ async read() {
1243
+ let text;
1244
+ try {
1245
+ text = await fs2.readFile(this.path, "utf8");
1246
+ } catch (error) {
1247
+ if (error.code === "ENOENT") return { version: VERSION, skills: {} };
1248
+ throw error;
1249
+ }
1250
+ return this.parse(text);
1251
+ }
1252
+ async update(change) {
1253
+ const data = await this.read();
1254
+ await change(data);
1255
+ await this.write(data);
1256
+ return data;
1257
+ }
1258
+ parse(text) {
1259
+ let data;
1260
+ try {
1261
+ data = JSON.parse(text);
1262
+ } catch {
1263
+ throw this.unreadable("it is not valid JSON");
1264
+ }
1265
+ if (typeof data !== "object" || data === null || Array.isArray(data)) throw this.unreadable("it is not an object");
1266
+ const { version: version2, skills } = data;
1267
+ if (typeof version2 === "number" && version2 > VERSION) {
1268
+ throw new CliError(
1269
+ `${tildify(this.path)} was written by a newer version of zion.`,
1270
+ "Run the latest version instead: npx zion@latest"
1271
+ );
1272
+ }
1273
+ if (version2 !== VERSION) throw this.unreadable(`its version is ${JSON.stringify(version2)}, not ${VERSION}`);
1274
+ if (skills !== void 0 && (typeof skills !== "object" || skills === null || Array.isArray(skills))) {
1275
+ throw this.unreadable('"skills" is not an object');
1276
+ }
1277
+ return { ...data, skills: skills ?? {} };
1278
+ }
1279
+ async write(data) {
1280
+ await fs2.mkdir(path3.dirname(this.path), { recursive: true });
1281
+ const temporary = `${this.path}.${process.pid}.tmp`;
1282
+ try {
1283
+ await fs2.writeFile(temporary, JSON.stringify(data, null, 2) + "\n");
1284
+ await fs2.rename(temporary, this.path);
1285
+ } catch (error) {
1286
+ await fs2.rm(temporary, { force: true });
1287
+ throw error;
1288
+ }
1289
+ }
1290
+ unreadable(reason) {
1291
+ return new CliError(
1292
+ `Couldn't read ${tildify(this.path)}: ${reason}.`,
1293
+ "Fix or delete it. Deleting it only makes zion forget which skills it installed."
1294
+ );
1295
+ }
1296
+ };
1297
+ function gitBlobSha(content) {
1298
+ return createHash("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
289
1299
  }
290
1300
 
291
- // src/components/ui/AnimatedText.tsx
292
- import chalk from "chalk";
293
- import { useEffect as useEffect2, useState } from "react";
294
- import { Text as Text10 } from "ink";
295
- import { jsx as jsx10 } from "react/jsx-runtime";
296
- function hexToRgb(hex) {
297
- const h = hex.replace("#", "");
298
- const n = h.length === 3 ? parseInt(h[0] + h[0] + h[1] + h[1] + h[2] + h[2], 16) : parseInt(h, 16);
299
- return [n >> 16 & 255, n >> 8 & 255, n & 255];
300
- }
301
- var DELAYS = {
302
- pulse: 16,
303
- neon: 500,
304
- radar: 50,
305
- karaoke: 50,
306
- rainbow: 15,
307
- glitch: 55
308
- };
309
- var GLITCH_CHARS = "\u2593\u2592\u2591\u2588\u2580\u2584\u258C\u2590\u2500\u2502\u2524\u2510\u2514\u2518\u251C\u252C\u2534\u253C";
310
- var TOTAL_PULSE_FRAMES = 120;
311
- function lerp(a, b, t) {
312
- return Math.round(a + (b - a) * t);
313
- }
314
- function applyPulse(text, frame, config) {
315
- const [br, bg, bb] = hexToRgb(config?.baseColor ?? "#E6E6E6");
316
- const [pr, pg, pb] = hexToRgb(config?.pulseColor ?? "#FF1010");
317
- const t = (Math.sin(frame / TOTAL_PULSE_FRAMES * Math.PI * 2) + 1) / 2;
318
- const r = lerp(br, pr, t);
319
- const g = lerp(bg, pg, t);
320
- const b = lerp(bb, pb, t);
321
- return chalk.rgb(r, g, b)(text);
322
- }
323
- function applyNeon(text, frame, config) {
324
- const on = frame % 2 === 0;
325
- const onColor = config?.onColor ?? "#00FFFF";
326
- const offColor = config?.offColor ?? "#325050";
327
- return on ? chalk.hex(onColor)(text) : chalk.hex(offColor)(text);
328
- }
329
- function applyRadar(text, frame, config) {
330
- const [br, bg, bb] = hexToRgb(config?.baseColor ?? "#3C3C3C");
331
- const depth = Math.max(1, Math.floor(text.length * 0.2));
332
- const globalPos = frame % (text.length + depth);
333
- const chars = [];
334
- for (let i = 0; i < text.length; i++) {
335
- const pos = -(i - globalPos);
336
- if (pos >= 0 && pos < depth) {
337
- const t = (depth - pos) / depth;
338
- chars.push(chalk.rgb(lerp(br, 255, t), lerp(bg, 255, t), lerp(bb, 255, t))(text[i]));
339
- } else {
340
- chars.push(chalk.rgb(br, bg, bb)(text[i]));
341
- }
342
- }
343
- return chars.join("");
344
- }
345
- function applyKaraoke(text, frame, config) {
346
- const highlightColor = config?.highlightColor ?? "#FFBB00";
347
- const baseColor = config?.baseColor ?? "#FFFFFF";
348
- const pos = frame % (text.length + 20) - 10;
349
- if (pos < 0) {
350
- return chalk.hex(baseColor)(text);
351
- }
352
- return chalk.hex(highlightColor).bold(text.substring(0, pos)) + chalk.hex(baseColor)(text.substring(pos));
353
- }
354
- function hsvToRgb(h, s, v) {
355
- const i = Math.floor(h / 60) % 6;
356
- const f = h / 60 - Math.floor(h / 60);
357
- const p = v * (1 - s);
358
- const q = v * (1 - f * s);
359
- const t = v * (1 - (1 - f) * s);
360
- const map = [
361
- [v, t, p],
362
- [q, v, p],
363
- [p, v, t],
364
- [p, q, v],
365
- [t, p, v],
366
- [v, p, q]
367
- ];
368
- return map[i].map((c) => Math.round(c * 255));
369
- }
370
- function applyRainbow(text, frame, config) {
371
- const sat = config?.saturation ?? 1;
372
- const bri = config?.brightness ?? 1;
373
- const hueStart = 5 * frame % 360;
374
- const chars = [];
375
- for (let i = 0; i < text.length; i++) {
376
- const hue = (hueStart + i * 360 / Math.max(text.length, 1)) % 360;
377
- const [r, g, b] = hsvToRgb(hue, sat, bri);
378
- chars.push(chalk.rgb(r, g, b)(text[i]));
379
- }
380
- return chars.join("");
381
- }
382
- function applyGlitch(text, frame) {
383
- if (frame % 2 + frame % 3 + frame % 11 + frame % 29 + frame % 37 > 52) {
384
- return text.replace(/[^\r\n]/g, " ");
385
- }
386
- const chunkSize = Math.max(3, Math.round(text.length * 0.02));
387
- const chars = [];
388
- for (let i = 0; i < text.length; i++) {
389
- const skip = Math.round(Math.max(0, (Math.random() - 0.8) * chunkSize));
390
- chars.push(text.substring(i, i + skip).replace(/[^\r\n]/g, " "));
391
- i += skip;
392
- if (text[i]) {
393
- if (text[i] !== "\n" && text[i] !== "\r" && Math.random() > 0.995) {
394
- chars.push(GLITCH_CHARS[Math.floor(Math.random() * GLITCH_CHARS.length)]);
395
- } else if (Math.random() > 5e-3) {
396
- chars.push(text[i]);
397
- }
1301
+ // src/commands/skills/SkillFiles.ts
1302
+ var NOISE = /* @__PURE__ */ new Set([".DS_Store"]);
1303
+ var NodeSkillFiles = class {
1304
+ async exists(dir) {
1305
+ return (await fs3.stat(dir).catch(() => null))?.isDirectory() ?? false;
1306
+ }
1307
+ async compare(dir, expected) {
1308
+ if (!await fs3.lstat(dir).catch(() => null)) return { exists: false, changed: [], missing: [], extra: [] };
1309
+ const actual = /* @__PURE__ */ new Map();
1310
+ await walk(dir, async (relative, absolute, isFile) => {
1311
+ actual.set(relative, isFile ? gitBlobSha(await fs3.readFile(absolute)) : null);
1312
+ }).catch(() => {
1313
+ });
1314
+ return {
1315
+ exists: true,
1316
+ changed: Object.keys(expected).filter((file) => actual.has(file) && actual.get(file) !== expected[file]),
1317
+ missing: Object.keys(expected).filter((file) => !actual.has(file)),
1318
+ extra: [...actual.keys()].filter((file) => !(file in expected))
1319
+ };
1320
+ }
1321
+ async write(dir, files, stale) {
1322
+ for (const file of files) {
1323
+ const target = inside(dir, file.path);
1324
+ await fs3.mkdir(path4.dirname(target), { recursive: true });
1325
+ await fs3.rm(target, { force: true });
1326
+ await fs3.writeFile(target, file.content, { mode: file.executable ? 493 : 420 });
398
1327
  }
1328
+ await this.delete(dir, stale);
399
1329
  }
400
- return chars.join("");
401
- }
402
- function applyAnimation(text, name, frame, config) {
403
- switch (name) {
404
- case "pulse":
405
- return applyPulse(text, frame, config);
406
- case "neon":
407
- return applyNeon(text, frame, config);
408
- case "radar":
409
- return applyRadar(text, frame, config);
410
- case "karaoke":
411
- return applyKaraoke(text, frame, config);
412
- case "rainbow":
413
- return applyRainbow(text, frame, config);
414
- case "glitch":
415
- return applyGlitch(text, frame);
416
- }
417
- }
418
- function flattenChildren(children) {
419
- if (typeof children === "string") return children;
420
- if (typeof children === "number") return String(children);
421
- if (children == null || typeof children === "boolean") return "";
422
- if (Array.isArray(children)) return children.map(flattenChildren).join("");
423
- return "";
424
- }
425
- function AnimatedText({
426
- name = "pulse",
427
- speed = 1,
428
- bold,
429
- italic,
430
- underline,
431
- strikethrough,
432
- dimColor,
433
- config,
434
- children
435
- }) {
436
- const [frame, setFrame] = useState(0);
437
- const text = flattenChildren(children);
438
- useEffect2(() => {
439
- const delay = DELAYS[name] / speed;
440
- const interval = setInterval(() => {
441
- setFrame((f) => f + 1);
442
- }, delay);
443
- return () => clearInterval(interval);
444
- }, [name, speed]);
445
- let animated = applyAnimation(text, name, frame, config);
446
- if (bold) animated = chalk.bold(animated);
447
- if (italic) animated = chalk.italic(animated);
448
- if (underline) animated = chalk.underline(animated);
449
- if (strikethrough) animated = chalk.strikethrough(animated);
450
- if (dimColor) animated = chalk.dim(animated);
451
- return /* @__PURE__ */ jsx10(Text10, { children: animated });
452
- }
453
-
454
- // src/hooks/useListNavigation.ts
455
- import { useState as useState2 } from "react";
456
- import { useInput } from "ink";
457
-
458
- // src/hooks/useScrollToIndex.ts
459
- import { useEffect as useEffect3, useRef } from "react";
460
- function useScrollToIndex(index) {
461
- const scrollRef = useRef(null);
462
- useEffect3(() => {
463
- const ref = scrollRef.current;
464
- if (!ref) return;
465
- const pos = ref.getItemPosition(index);
466
- const viewportHeight = ref.getViewportHeight();
467
- const scrollOffset = ref.getScrollOffset();
468
- if (!pos) return;
469
- if (pos.top < scrollOffset) {
470
- ref.scrollTo(pos.top);
471
- } else if (pos.top + pos.height > scrollOffset + viewportHeight) {
472
- ref.scrollTo(pos.top + pos.height - viewportHeight);
473
- }
474
- }, [index]);
475
- return scrollRef;
476
- }
477
-
478
- // src/hooks/useListNavigation.ts
479
- function useListNavigation({ length, onSelect, isActive }) {
480
- const [highlightedIndex, setHighlightedIndex] = useState2(0);
481
- const scrollRef = useScrollToIndex(highlightedIndex);
482
- useInput(
483
- (input, key) => {
484
- if (length === 0) return;
485
- if (key.upArrow || input === "k") {
486
- setHighlightedIndex((i) => Math.max(0, i - 1));
487
- }
488
- if (key.downArrow || input === "j") {
489
- setHighlightedIndex((i) => Math.min(length - 1, i + 1));
490
- }
491
- if (key.return && onSelect) {
492
- onSelect(highlightedIndex);
493
- }
494
- },
495
- { isActive: isActive === true }
496
- );
497
- return {
498
- highlightedIndex,
499
- scrollRef,
500
- reset: () => setHighlightedIndex(0)
501
- };
1330
+ async remove(dir, files) {
1331
+ await this.delete(dir, files);
1332
+ const left = [];
1333
+ await walk(dir, async (relative) => {
1334
+ left.push(relative);
1335
+ }).catch(() => {
1336
+ });
1337
+ if (left.length === 0) await fs3.rm(dir, { recursive: true, force: true });
1338
+ return left;
1339
+ }
1340
+ async delete(dir, files) {
1341
+ for (const file of files) {
1342
+ const target = inside(dir, file);
1343
+ await fs3.rm(target, { force: true });
1344
+ await pruneEmpty(path4.dirname(target), dir);
1345
+ }
1346
+ }
1347
+ };
1348
+ async function walk(dir, visit, prefix = "") {
1349
+ for (const entry of await fs3.readdir(dir, { withFileTypes: true })) {
1350
+ if (NOISE.has(entry.name)) continue;
1351
+ const absolute = path4.join(dir, entry.name);
1352
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
1353
+ if (entry.isDirectory()) await walk(absolute, visit, relative);
1354
+ else await visit(relative, absolute, entry.isFile());
1355
+ }
1356
+ }
1357
+ async function pruneEmpty(dir, root) {
1358
+ for (let current = dir; current.startsWith(root + path4.sep); current = path4.dirname(current)) {
1359
+ const entries = await fs3.readdir(current).catch(() => null);
1360
+ if (!entries || entries.some((name) => !NOISE.has(name))) return;
1361
+ await fs3.rm(current, { recursive: true, force: true });
1362
+ }
1363
+ }
1364
+ function inside(dir, relative) {
1365
+ const target = path4.resolve(dir, relative);
1366
+ if (relative.includes("\0") || path4.isAbsolute(relative) || !target.startsWith(path4.resolve(dir) + path4.sep)) {
1367
+ throw new CliError(`Refusing to write ${relative}`, `it would land outside ${tildify(dir)}`);
1368
+ }
1369
+ return target;
502
1370
  }
503
1371
 
504
- // src/app.tsx
505
- import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
506
- function App() {
507
- const { exit } = useApp();
508
- const { stdout } = useStdout2();
509
- const columns = stdout?.columns ?? 80;
510
- const rows = stdout?.rows ?? 24;
511
- const [currentView, setCurrentView] = useState3("home");
512
- const [errors, setErrors] = useState3({});
513
- const [aboutTitle, setAboutTitle] = useState3("");
514
- const [aboutContent, setAboutContent] = useState3("");
515
- const [blogPosts, setBlogPosts] = useState3([]);
516
- const [currentPost, setCurrentPost] = useState3(null);
517
- const [portfolioProjects, setPortfolioProjects] = useState3([]);
518
- const [loading, setLoading] = useState3("about");
519
- const detailScrollRef = useRef2(null);
520
- const addError = (key, message) => setErrors((prev) => ({ ...prev, [key]: message }));
521
- const clearError = (key) => setErrors((prev) => {
522
- const next = { ...prev };
523
- delete next[key];
524
- return next;
525
- });
526
- const blogList = useListNavigation({
527
- length: blogPosts.length,
528
- isActive: currentView === "blogList",
529
- onSelect: (index) => {
530
- const post = blogPosts[index];
531
- if (!post) return;
532
- setLoading("post");
533
- loadBlogPost(post.slug).then((result) => {
534
- setLoading(null);
535
- if (result.ok) {
536
- clearError("post");
537
- setCurrentPost(result.data);
538
- setCurrentView("blogDetail");
539
- } else {
540
- addError("post", result.error);
541
- }
1372
+ // src/commands/skills/SkillsApi.ts
1373
+ var TIMEOUT_MS = 15e3;
1374
+ var SkillNotFoundError = class extends CliError {
1375
+ constructor(skill, hint) {
1376
+ super(`No skill named ${skill}`, hint);
1377
+ this.skill = skill;
1378
+ this.name = "SkillNotFoundError";
1379
+ }
1380
+ };
1381
+ var HttpSkillsApi = class {
1382
+ constructor(baseUrl, fetchImpl = fetch) {
1383
+ this.fetchImpl = fetchImpl;
1384
+ this.base = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
1385
+ }
1386
+ base;
1387
+ get host() {
1388
+ return this.base.host;
1389
+ }
1390
+ async list(signal) {
1391
+ const body = await this.request("", signal);
1392
+ const skills = body?.skills;
1393
+ if (!Array.isArray(skills)) throw this.malformed();
1394
+ return skills.map((skill) => {
1395
+ if (typeof skill?.name !== "string") throw this.malformed();
1396
+ return skill.name;
1397
+ });
1398
+ }
1399
+ async get(name, signal) {
1400
+ const body = await this.request(encodeURIComponent(name), signal);
1401
+ if (body === void 0) throw new SkillNotFoundError(name);
1402
+ return this.parseSkill(name, body);
1403
+ }
1404
+ /** Resolves to the parsed body, or undefined for a 404. */
1405
+ async request(path15, signal) {
1406
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
1407
+ let body;
1408
+ let status;
1409
+ try {
1410
+ const response = await this.fetchImpl(new URL(path15, this.base), {
1411
+ headers: { accept: "application/json" },
1412
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout
542
1413
  });
1414
+ status = response.status;
1415
+ body = await response.json().catch(() => void 0);
1416
+ } catch (error) {
1417
+ if (signal?.aborted) throw error;
1418
+ if (timeout.aborted) throw new CliError(`${this.host} took too long to answer`, "try again in a moment");
1419
+ throw new CliError(`Couldn't reach ${this.host}`, "check your internet connection, then try again");
1420
+ }
1421
+ if (status === 404) return void 0;
1422
+ if (status < 200 || status >= 300) {
1423
+ const reason = body?.error;
1424
+ throw new CliError(
1425
+ `${this.host} couldn't send the skills (HTTP ${status})`,
1426
+ typeof reason === "string" ? `${reason.replace(/\.$/, "")}; try again in a moment` : "try again in a moment"
1427
+ );
543
1428
  }
1429
+ if (body === void 0) throw this.malformed();
1430
+ return body;
1431
+ }
1432
+ parseSkill(name, body) {
1433
+ const { commit, updatedAt, files } = body;
1434
+ if (typeof commit !== "string" || typeof updatedAt !== "string" || !Array.isArray(files)) throw this.malformed();
1435
+ return {
1436
+ name,
1437
+ commit,
1438
+ updatedAt,
1439
+ files: files.map((file) => {
1440
+ const { path: path15, sha, executable, content } = file ?? {};
1441
+ if (typeof path15 !== "string" || typeof sha !== "string" || typeof content !== "string") throw this.malformed();
1442
+ const bytes = Buffer.from(content, "base64");
1443
+ if (gitBlobSha(bytes) !== sha) {
1444
+ throw new CliError(`${this.host} sent a damaged copy of ${name}/${path15}`, "try again in a moment");
1445
+ }
1446
+ return { path: path15, sha, executable: executable === true, content: bytes };
1447
+ })
1448
+ };
1449
+ }
1450
+ malformed() {
1451
+ return new CliError(
1452
+ `${this.host} sent a response zion doesn't understand`,
1453
+ "run npx zion@latest to get the newest zion"
1454
+ );
1455
+ }
1456
+ };
1457
+
1458
+ // src/commands/skills/InstallFlow.ts
1459
+ import path7 from "path";
1460
+
1461
+ // src/commands/skills/chooseTargets.ts
1462
+ import path5 from "path";
1463
+ async function chooseTargets(ui, { targets, files }, given, lock) {
1464
+ if (given.length > 0) {
1465
+ const chosen = targets.filter((target) => given.includes(target.id));
1466
+ ui.step({ title: "Install into", lines: [chosen.map((target) => tildify(target.dir)).join(", ")] });
1467
+ return chosen;
1468
+ }
1469
+ const used = new Set(Object.values(lock.skills).flatMap((skill) => skill.paths.map((dir) => path5.dirname(dir))));
1470
+ let suggested = targets.filter((target) => used.has(target.dir));
1471
+ if (suggested.length === 0) {
1472
+ const present = await Promise.all(targets.map((target) => files.exists(target.home)));
1473
+ suggested = targets.filter((_, i) => present[i]);
1474
+ }
1475
+ return ui.multiselect({
1476
+ message: "Install into",
1477
+ options: targets.map((target) => ({ value: target, label: tildify(target.dir), hint: target.hint })),
1478
+ initialValues: suggested,
1479
+ nonInteractiveHint: `pass --target (${targets.map((target) => target.id).join(", ")}), e.g. -t ${targets[0].id}`
1480
+ });
1481
+ }
1482
+
1483
+ // src/commands/skills/copies.ts
1484
+ import path6 from "path";
1485
+ function fileHashes(skill) {
1486
+ return Object.fromEntries(skill.files.map((file) => [file.path, file.sha]));
1487
+ }
1488
+ async function planCopies({ files }, skill, locked, chosen) {
1489
+ const remote = fileHashes(skill);
1490
+ const copies = [];
1491
+ for (const dir of /* @__PURE__ */ new Set([...chosen, ...locked?.paths ?? []])) {
1492
+ const ours = locked?.paths.includes(dir) ? locked : void 0;
1493
+ const { exists, changed } = await files.compare(dir, ours?.files ?? remote);
1494
+ if (!exists && !chosen.includes(dir)) continue;
1495
+ copies.push({
1496
+ skill,
1497
+ dir,
1498
+ stale: ours ? Object.keys(ours.files).filter((file) => !(file in remote)) : [],
1499
+ problem: exists && changed.length > 0 ? ours ? "has local edits" : "wasn't installed by zion" : void 0
1500
+ });
1501
+ }
1502
+ return copies;
1503
+ }
1504
+ async function confirmConflicts(ui, copies, { yes: yes2, retry }) {
1505
+ const conflicts = copies.filter((copy) => copy.problem);
1506
+ if (conflicts.length === 0) return true;
1507
+ const width = Math.max(...conflicts.map((copy) => tildify(copy.dir).length));
1508
+ ui.step({
1509
+ title: conflicts.length === 1 ? "Already there" : `${conflicts.length} already there`,
1510
+ tone: "warning",
1511
+ lines: conflicts.map((copy) => `${tildify(copy.dir).padEnd(width)} ${copy.problem}`)
544
1512
  });
545
- const portfolioList = useListNavigation({
546
- length: portfolioProjects.length,
547
- isActive: currentView === "portfolioList"
1513
+ if (yes2) return true;
1514
+ return ui.confirm({
1515
+ message: conflicts.length === 1 ? "Replace it?" : "Replace them?",
1516
+ defaultValue: false,
1517
+ nonInteractiveHint: `pass --yes to replace: ${retry} --yes`
548
1518
  });
549
- useEffect4(() => {
550
- loadAboutContent().then((result) => {
551
- setLoading(null);
552
- if (result.ok) {
553
- clearError("about");
554
- setAboutTitle(result.data.title);
555
- setAboutContent(result.data.content);
556
- } else {
557
- addError("about", result.error);
1519
+ }
1520
+ async function writeCopies(deps, skills, copies) {
1521
+ const { files, lockfile, now } = deps;
1522
+ for (const skill of skills) {
1523
+ const mine = copies.filter((copy) => copy.skill === skill);
1524
+ for (const copy of mine) await files.write(copy.dir, skill.files, copy.stale);
1525
+ await lockfile.update((data) => {
1526
+ const previous = data.skills[skill.name];
1527
+ if (mine.length === 0) {
1528
+ delete data.skills[skill.name];
1529
+ return;
558
1530
  }
1531
+ data.skills[skill.name] = {
1532
+ commit: skill.commit,
1533
+ updatedAt: skill.updatedAt,
1534
+ installedAt: previous?.installedAt ?? now().toISOString(),
1535
+ paths: mine.map((copy) => copy.dir),
1536
+ files: fileHashes(skill)
1537
+ };
559
1538
  });
560
- }, []);
561
- const contentWidth = Math.max(Math.min(Math.floor(columns * 2 / 3), 80), 40);
562
- const blogListVPHeight = Math.min(blogPosts.length, Math.min(Math.floor(rows / 2), 20));
563
- const blogDetailVPHeight = Math.min(Math.floor(rows / 2), 25);
564
- const portfolioListVPHeight = Math.min(Math.floor(rows / 2), 20);
565
- const visibleErrors = [];
566
- if (currentView === "home" && errors.about) visibleErrors.push(errors.about);
567
- if (currentView === "blogList") {
568
- if (errors.posts) visibleErrors.push(errors.posts);
569
- if (errors.post) visibleErrors.push(errors.post);
570
- }
571
- if (currentView === "blogDetail" && errors.post) visibleErrors.push(errors.post);
572
- if (currentView === "portfolioList" && errors.portfolio) visibleErrors.push(errors.portfolio);
573
- const openBlogList = () => {
574
- setCurrentView("blogList");
575
- blogList.reset();
576
- if (blogPosts.length === 0) {
577
- setLoading("posts");
578
- loadBlogPostList().then((result) => {
579
- setLoading(null);
580
- if (result.ok) {
581
- clearError("posts");
582
- setBlogPosts(result.data);
583
- } else {
584
- addError("posts", result.error);
585
- }
1539
+ }
1540
+ }
1541
+ function describeCopies(title, skills, copies) {
1542
+ const width = Math.max(...skills.map((skill) => skill.name.length));
1543
+ return {
1544
+ title,
1545
+ lines: skills.map((skill) => {
1546
+ const dirs = copies.filter((copy) => copy.skill === skill).map((copy) => tildify(path6.dirname(copy.dir)));
1547
+ return `${skill.name.padEnd(width)} ${paint.muted(dirs.length ? dirs.join(", ") : "nowhere")}`;
1548
+ })
1549
+ };
1550
+ }
1551
+ function describeChange(locked, latest) {
1552
+ const before = locked.files;
1553
+ const after = fileHashes(latest);
1554
+ const count = (files2) => files2.length;
1555
+ const changes = [
1556
+ [count(Object.keys(after).filter((file) => file in before && before[file] !== after[file])), "changed"],
1557
+ [count(Object.keys(after).filter((file) => !(file in before))), "added"],
1558
+ [count(Object.keys(before).filter((file) => !(file in after))), "removed"]
1559
+ ];
1560
+ const files = changes.filter(([n]) => n > 0).map(([n, what]) => `${n} ${what}`);
1561
+ return `${short(locked.commit)} \u2192 ${short(latest.commit)}${files.length ? ` \xB7 ${files.join(", ")}` : ""}`;
1562
+ }
1563
+ var short = (commit) => commit.slice(0, 7);
1564
+ function plural(count, noun) {
1565
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
1566
+ }
1567
+
1568
+ // src/commands/skills/InstallFlow.ts
1569
+ var InstallFlow = class {
1570
+ constructor(deps) {
1571
+ this.deps = deps;
1572
+ }
1573
+ async run(ui, options, ctx) {
1574
+ const { api, lockfile } = this.deps;
1575
+ const lock = await lockfile.read();
1576
+ const available = await ui.task(
1577
+ "Fetching the list of skills",
1578
+ (signal) => api.list(signal),
1579
+ (names2) => ({ title: `${plural(names2.length, "skill")} available` })
1580
+ );
1581
+ if (available.length === 0) throw new CliError(`${api.host} has no skills right now`, "try again later");
1582
+ const names = await this.chooseSkills(ui, options, ctx, available, lock);
1583
+ const targets = await chooseTargets(ui, this.deps, options.targets, lock);
1584
+ const skills = await ui.task(
1585
+ `Downloading ${names.join(", ")}`,
1586
+ (signal) => Promise.all(names.map((name) => api.get(name, signal))),
1587
+ (skills2) => {
1588
+ const width = Math.max(...skills2.map((skill) => skill.name.length));
1589
+ return {
1590
+ title: "Downloaded",
1591
+ lines: skills2.map(
1592
+ (skill) => `${skill.name.padEnd(width)} ${paint.muted(
1593
+ `${short(skill.commit)} \xB7 ${plural(skill.files.length, "file")}`
1594
+ )}`
1595
+ )
1596
+ };
1597
+ }
1598
+ );
1599
+ const dirs = targets.map((target) => target.dir);
1600
+ const copies = (await Promise.all(
1601
+ skills.map(
1602
+ (skill) => planCopies(
1603
+ this.deps,
1604
+ skill,
1605
+ lock.skills[skill.name],
1606
+ dirs.map((dir) => path7.join(dir, skill.name))
1607
+ )
1608
+ )
1609
+ )).flat();
1610
+ const retry = `${ctx.bin} skills install ${names.join(" ")} ${targets.map((t) => `-t ${t.id}`).join(" ")}`;
1611
+ if (!await confirmConflicts(ui, copies, { yes: options.yes, retry })) {
1612
+ ui.outro("Left everything as it was.", { tone: "muted" });
1613
+ return 0;
1614
+ }
1615
+ await ui.task(
1616
+ "Installing",
1617
+ () => writeCopies(this.deps, skills, copies),
1618
+ () => describeCopies("Installed", skills, copies)
1619
+ );
1620
+ ui.outro(`Installed ${plural(skills.length, "skill")}.`, {
1621
+ lines: ["Start a new agent session to use them.", `Run ${ctx.bin} skills update to get new versions.`]
1622
+ });
1623
+ return 0;
1624
+ }
1625
+ async chooseSkills(ui, options, ctx, available, lock) {
1626
+ if (options.all) return [...available];
1627
+ if (options.names.length > 0) {
1628
+ const missing = options.names.find((name) => !available.includes(name));
1629
+ if (missing) throw new CliError(`No skill named ${missing}`, `run ${ctx.bin} skills list to see them all`);
1630
+ const names = [...new Set(options.names)];
1631
+ ui.step({ title: "Skills", lines: [names.join(", ")] });
1632
+ return names;
1633
+ }
1634
+ return ui.multiselect({
1635
+ message: "Which skills?",
1636
+ options: available.map((name) => ({
1637
+ value: name,
1638
+ label: name,
1639
+ hint: lock.skills[name] ? `installed ${short(lock.skills[name].commit)}` : void 0
1640
+ })),
1641
+ nonInteractiveHint: `name them, e.g. ${ctx.bin} skills install ${available[0]}, or pass --all`
1642
+ });
1643
+ }
1644
+ };
1645
+
1646
+ // src/commands/skills/ManageFlow.ts
1647
+ import path9 from "path";
1648
+
1649
+ // src/commands/skills/removals.ts
1650
+ import path8 from "path";
1651
+ async function planRemovals({ files }, lock, names, only) {
1652
+ const removals = [];
1653
+ for (const name of names) {
1654
+ const { paths, files: expected } = lock.skills[name];
1655
+ for (const dir of paths.filter((dir2) => !only || only.has(path8.dirname(dir2)))) {
1656
+ const { exists, changed } = await files.compare(dir, expected);
1657
+ removals.push({ name, dir, exists, edited: exists && changed.length > 0 });
1658
+ }
1659
+ }
1660
+ return removals;
1661
+ }
1662
+ async function applyRemovals({ files, lockfile }, lock, removals) {
1663
+ const kept = [];
1664
+ for (const removal of removals) {
1665
+ const owned = Object.keys(lock.skills[removal.name].files);
1666
+ const left = removal.exists ? await files.remove(removal.dir, owned) : [];
1667
+ if (left.length > 0) kept.push(`${tildify(removal.dir)} ${plural(left.length, "file")} zion didn't install`);
1668
+ await lockfile.update((data) => {
1669
+ const entry = data.skills[removal.name];
1670
+ if (!entry) return;
1671
+ entry.paths = entry.paths.filter((dir) => dir !== removal.dir);
1672
+ if (entry.paths.length === 0) delete data.skills[removal.name];
1673
+ });
1674
+ }
1675
+ return kept;
1676
+ }
1677
+ function describeKept(kept, removed) {
1678
+ return kept.length > 0 ? { title: "Removed, but kept", tone: "warning", lines: kept } : { title: "Removed", lines: [removed.join(", ")] };
1679
+ }
1680
+ var KEPT_ADVICE = "Delete what was kept yourself if you no longer need it.";
1681
+
1682
+ // src/commands/skills/ManageFlow.ts
1683
+ var ManageFlow = class {
1684
+ constructor(deps) {
1685
+ this.deps = deps;
1686
+ }
1687
+ async run(ui) {
1688
+ const { api, lockfile } = this.deps;
1689
+ const lock = await lockfile.read();
1690
+ const installed = Object.keys(lock.skills);
1691
+ const { available, latest } = await ui.task(
1692
+ "Fetching skills",
1693
+ (signal) => this.fetchCatalog(lock, signal),
1694
+ ({ available: available2, latest: latest2 }) => {
1695
+ const updates = installed.filter((name) => isOutdated(lock, name, latest2)).length;
1696
+ return {
1697
+ title: [plural(available2.length, "skill"), updates > 0 && plural(updates, "update")].filter(Boolean).join(" \xB7 ")
1698
+ };
1699
+ }
1700
+ );
1701
+ const names = [.../* @__PURE__ */ new Set([...available, ...installed])].sort();
1702
+ const ticked = new Set(
1703
+ await ui.multiselect({
1704
+ message: "Your skills",
1705
+ options: names.map((name) => ({ value: name, label: name, hint: this.hint(lock, name, latest) })),
1706
+ initialValues: installed,
1707
+ required: false
1708
+ })
1709
+ );
1710
+ const adding = names.filter((name) => ticked.has(name) && !lock.skills[name]);
1711
+ const updating = installed.filter((name) => ticked.has(name) && isOutdated(lock, name, latest));
1712
+ const removing = installed.filter((name) => !ticked.has(name));
1713
+ if (adding.length + updating.length + removing.length === 0) {
1714
+ ui.outro("Nothing to change.", { tone: "muted" });
1715
+ return 0;
1716
+ }
1717
+ const targets = adding.length > 0 ? await chooseTargets(ui, this.deps, [], lock) : [];
1718
+ const added = adding.length > 0 ? await ui.task(
1719
+ `Downloading ${adding.join(", ")}`,
1720
+ (signal) => Promise.all(adding.map((name) => api.get(name, signal))),
1721
+ (skills) => ({ title: `Downloaded ${plural(skills.length, "skill")}` })
1722
+ ) : [];
1723
+ const updated = updating.map((name) => latest.get(name));
1724
+ const copies = [
1725
+ ...(await Promise.all(
1726
+ added.map(
1727
+ (skill) => planCopies(
1728
+ this.deps,
1729
+ skill,
1730
+ void 0,
1731
+ targets.map((target) => path9.join(target.dir, skill.name))
1732
+ )
1733
+ )
1734
+ )).flat(),
1735
+ ...(await Promise.all(updated.map((skill) => planCopies(this.deps, skill, lock.skills[skill.name], [])))).flat()
1736
+ ];
1737
+ const removals = await planRemovals(this.deps, lock, removing);
1738
+ this.summarise(ui, lock, added, updated, removing, copies, removals);
1739
+ const risky = copies.some((copy) => copy.problem) || removals.some((removal) => removal.edited);
1740
+ const total = added.length + updated.length + removing.length;
1741
+ if (!await ui.confirm({ message: `Apply ${plural(total, "change")}?`, defaultValue: !risky })) {
1742
+ ui.outro("Left everything as it was.", { tone: "muted" });
1743
+ return 0;
1744
+ }
1745
+ const kept = await ui.task(
1746
+ "Applying",
1747
+ async () => {
1748
+ await writeCopies(this.deps, [...added, ...updated], copies);
1749
+ return applyRemovals(this.deps, lock, removals);
1750
+ },
1751
+ (kept2) => kept2.length > 0 ? { title: "Done, but kept", tone: "warning", lines: kept2 } : { title: "Done" }
1752
+ );
1753
+ const [first, ...rest] = [
1754
+ ["installed", added.length],
1755
+ ["updated", updated.length],
1756
+ ["removed", removing.length]
1757
+ ].filter(([, count]) => count > 0);
1758
+ const message = [`${first[0]} ${plural(first[1], "skill")}`, ...rest.map(([verb, count]) => `${verb} ${count}`)];
1759
+ const sentence = message.join(", ");
1760
+ ui.outro(`${sentence[0].toUpperCase()}${sentence.slice(1)}.`, {
1761
+ lines: [
1762
+ ...added.length + updated.length > 0 ? ["Start a new agent session to use them."] : [],
1763
+ ...kept.length > 0 ? [KEPT_ADVICE] : []
1764
+ ]
1765
+ });
1766
+ return 0;
1767
+ }
1768
+ /** The list of skills, plus the latest version of each installed one to spot updates. */
1769
+ async fetchCatalog(lock, signal) {
1770
+ const { api } = this.deps;
1771
+ const installed = Object.keys(lock.skills);
1772
+ const [available, versions] = await Promise.all([
1773
+ api.list(signal),
1774
+ Promise.all(
1775
+ installed.map(
1776
+ (name) => api.get(name, signal).catch((error) => {
1777
+ if (error instanceof SkillNotFoundError) return null;
1778
+ throw error;
1779
+ })
1780
+ )
1781
+ )
1782
+ ]);
1783
+ return { available, latest: new Map(installed.map((name, i) => [name, versions[i]])) };
1784
+ }
1785
+ hint(lock, name, latest) {
1786
+ const entry = lock.skills[name];
1787
+ if (!entry) return void 0;
1788
+ const where = entry.paths.map((dir) => tildify(path9.dirname(dir))).join(", ");
1789
+ if (latest.get(name) === null) return `${where} \xB7 no longer available`;
1790
+ return isOutdated(lock, name, latest) ? `${where} \xB7 update available` : where;
1791
+ }
1792
+ summarise(ui, lock, added, updated, removing, copies, removals) {
1793
+ const dirsOf = (skill) => copies.filter((copy) => copy.skill === skill).map((copy) => tildify(path9.dirname(copy.dir)));
1794
+ const rows = [
1795
+ ...added.map((skill) => [paint.success("+"), skill.name, dirsOf(skill).join(", ")]),
1796
+ ...updated.map((skill) => [
1797
+ paint.accent("\u2191"),
1798
+ skill.name,
1799
+ describeChange(lock.skills[skill.name], skill)
1800
+ ]),
1801
+ ...removing.map((name) => [
1802
+ paint.error("\u2212"),
1803
+ name,
1804
+ lock.skills[name].paths.map((dir) => tildify(path9.dirname(dir))).join(", ")
1805
+ ])
1806
+ ];
1807
+ const width = Math.max(...rows.map(([, name]) => name.length));
1808
+ ui.step({
1809
+ title: "Changes",
1810
+ lines: rows.map(([mark, name, detail2]) => `${mark} ${name.padEnd(width)} ${paint.muted(detail2)}`)
1811
+ });
1812
+ const warnings = [
1813
+ ...copies.flatMap((copy) => copy.problem ? [[tildify(copy.dir), copy.problem]] : []),
1814
+ ...removals.flatMap((removal) => removal.edited ? [[tildify(removal.dir), "has local edits"]] : [])
1815
+ ];
1816
+ if (warnings.length > 0) {
1817
+ const dirWidth = Math.max(...warnings.map(([dir]) => dir.length));
1818
+ ui.step({
1819
+ title: warnings.length === 1 ? "This would overwrite changes" : "These would overwrite changes",
1820
+ tone: "warning",
1821
+ lines: warnings.map(([dir, problem]) => `${dir.padEnd(dirWidth)} ${problem}`)
586
1822
  });
587
1823
  }
588
- };
589
- const openPortfolioList = () => {
590
- setCurrentView("portfolioList");
591
- portfolioList.reset();
592
- if (portfolioProjects.length === 0) {
593
- setLoading("portfolio");
594
- loadPortfolioList().then((result) => {
595
- setLoading(null);
596
- if (result.ok) {
597
- clearError("portfolio");
598
- setPortfolioProjects(result.data);
599
- } else {
600
- addError("portfolio", result.error);
601
- }
1824
+ }
1825
+ };
1826
+ function isOutdated(lock, name, latest) {
1827
+ const version2 = latest.get(name);
1828
+ return Boolean(version2 && lock.skills[name] && version2.commit !== lock.skills[name].commit);
1829
+ }
1830
+
1831
+ // src/commands/skills/RemoveFlow.ts
1832
+ import path10 from "path";
1833
+ var RemoveFlow = class {
1834
+ constructor(deps) {
1835
+ this.deps = deps;
1836
+ }
1837
+ async run(ui, options, ctx) {
1838
+ const { lockfile, targets } = this.deps;
1839
+ const lock = await lockfile.read();
1840
+ const installed = Object.keys(lock.skills).sort();
1841
+ if (installed.length === 0) {
1842
+ ui.outro("No skills are installed.", { tone: "muted" });
1843
+ return 0;
1844
+ }
1845
+ const names = await this.chooseSkills(ui, options, ctx, installed, lock);
1846
+ const only = options.targets.length ? new Set(targets.filter((target) => options.targets.includes(target.id)).map((target) => target.dir)) : null;
1847
+ const removals = await planRemovals(this.deps, lock, names, only ?? void 0);
1848
+ if (removals.length === 0)
1849
+ throw new CliError("They aren't installed there", `run ${ctx.bin} skills list to see where they are`);
1850
+ const width = Math.max(...removals.map((removal) => tildify(removal.dir).length));
1851
+ const edited = removals.some((removal) => removal.edited);
1852
+ ui.step({
1853
+ title: "To remove",
1854
+ tone: edited ? "warning" : "success",
1855
+ lines: removals.map(
1856
+ (removal) => removal.edited ? `${tildify(removal.dir).padEnd(width)} has local edits` : tildify(removal.dir)
1857
+ )
1858
+ });
1859
+ const confirmed = options.yes || await ui.confirm({
1860
+ message: `Remove ${plural(names.length, "skill")}?`,
1861
+ defaultValue: false,
1862
+ nonInteractiveHint: `pass --yes to confirm: ${ctx.bin} skills remove ${names.join(" ")} --yes`
1863
+ });
1864
+ if (!confirmed) {
1865
+ ui.outro("Left everything as it was.", { tone: "muted" });
1866
+ return 0;
1867
+ }
1868
+ const kept = await ui.task(
1869
+ "Removing",
1870
+ () => applyRemovals(this.deps, lock, removals),
1871
+ (kept2) => describeKept(kept2, names)
1872
+ );
1873
+ ui.outro(`Removed ${plural(names.length, "skill")}.`, {
1874
+ lines: kept.length > 0 ? [KEPT_ADVICE] : []
1875
+ });
1876
+ return 0;
1877
+ }
1878
+ async chooseSkills(ui, options, ctx, installed, lock) {
1879
+ if (options.all) return [...installed];
1880
+ if (options.names.length > 0) {
1881
+ const missing = options.names.find((name) => !lock.skills[name]);
1882
+ if (missing) throw new CliError(`${missing} isn't installed`, `run ${ctx.bin} skills list to see what is`);
1883
+ return [...new Set(options.names)];
1884
+ }
1885
+ return ui.multiselect({
1886
+ message: "Which skills?",
1887
+ options: installed.map((name) => ({
1888
+ value: name,
1889
+ label: name,
1890
+ hint: lock.skills[name].paths.map((dir) => tildify(path10.dirname(dir))).join(", ")
1891
+ })),
1892
+ nonInteractiveHint: `name them, e.g. ${ctx.bin} skills remove ${installed[0]} --yes, or pass --all`
1893
+ });
1894
+ }
1895
+ };
1896
+
1897
+ // src/commands/skills/UpdateFlow.ts
1898
+ var UpdateFlow = class {
1899
+ constructor(deps) {
1900
+ this.deps = deps;
1901
+ }
1902
+ async run(ui, options, ctx) {
1903
+ const { api, lockfile } = this.deps;
1904
+ const lock = await lockfile.read();
1905
+ const installed = Object.keys(lock.skills).sort();
1906
+ if (installed.length === 0) {
1907
+ ui.outro("No skills are installed yet.", {
1908
+ tone: "muted",
1909
+ lines: [`Install some with ${ctx.bin} skills install.`]
602
1910
  });
1911
+ return 0;
603
1912
  }
604
- };
605
- useInput2((input, key) => {
606
- if (input === "q" || key.ctrl && input === "c") {
607
- exit();
608
- return;
1913
+ const missing = options.names.find((name) => !lock.skills[name]);
1914
+ if (missing)
1915
+ throw new CliError(`${missing} isn't installed`, `install it with ${ctx.bin} skills install ${missing}`);
1916
+ const names = options.names.length > 0 ? [...new Set(options.names)] : installed;
1917
+ const pick = ctx.interactive && options.names.length === 0 && !options.yes;
1918
+ const checks = await ui.task(
1919
+ `Checking ${plural(names.length, "skill")} for updates`,
1920
+ (signal) => Promise.all(
1921
+ names.map(async (name) => {
1922
+ const locked = lock.skills[name];
1923
+ try {
1924
+ return { name, locked, latest: await api.get(name, signal) };
1925
+ } catch (error) {
1926
+ if (error instanceof SkillNotFoundError) return { name, locked, latest: null };
1927
+ throw error;
1928
+ }
1929
+ })
1930
+ ),
1931
+ (checks2) => describeChecks(checks2, { listUpdates: !pick })
1932
+ );
1933
+ const outdated = checks.filter(isOutdated2);
1934
+ if (outdated.length === 0) {
1935
+ ui.outro(names.length === 1 ? `${names[0]} is up to date.` : "Everything is up to date.");
1936
+ return 0;
609
1937
  }
610
- const left = input === "h" || key.leftArrow;
611
- const right = input === "l" || key.rightArrow;
612
- switch (currentView) {
613
- case "home":
614
- if (right) openBlogList();
615
- break;
616
- case "blogList":
617
- if (left) setCurrentView("home");
618
- else if (right) openPortfolioList();
619
- break;
620
- case "portfolioList":
621
- if (left) openBlogList();
622
- break;
623
- case "blogDetail":
624
- if (left) {
625
- setCurrentView("blogList");
626
- setCurrentPost(null);
627
- } else if (input === "j" || key.downArrow) {
628
- detailScrollRef.current?.scrollBy(1);
629
- } else if (input === "k" || key.upArrow) {
630
- detailScrollRef.current?.scrollBy(-1);
631
- }
632
- break;
1938
+ const chosen = pick ? await this.chooseUpdates(ui, outdated) : outdated.map((check) => check.latest);
1939
+ const copies = (await Promise.all(chosen.map((skill) => planCopies(this.deps, skill, lock.skills[skill.name], [])))).flat();
1940
+ const retry = `${ctx.bin} skills update ${options.names.join(" ")}`.trimEnd();
1941
+ if (!await confirmConflicts(ui, copies, { yes: options.yes, retry })) {
1942
+ ui.outro("Left everything as it was.", { tone: "muted" });
1943
+ return 0;
633
1944
  }
634
- });
635
- return /* @__PURE__ */ jsx11(Box7, { width: columns, height: rows, justifyContent: "center", alignItems: "center", children: /* @__PURE__ */ jsxs8(Box7, { flexDirection: "column", width: contentWidth, children: [
636
- /* @__PURE__ */ jsx11(NavBar, {}),
637
- visibleErrors.length > 0 && /* @__PURE__ */ jsx11(Box7, { marginTop: 1, flexDirection: "column", children: visibleErrors.map((err, i) => /* @__PURE__ */ jsx11(Text11, { color: "red", children: err }, i)) }),
638
- loading && /* @__PURE__ */ jsx11(Box7, { paddingY: 2, children: /* @__PURE__ */ jsx11(AnimatedText, { name: "radar", speed: 0.6, children: "Loading" }) }),
639
- currentView === "home" && !loading && /* @__PURE__ */ jsx11(HomeView, { aboutTitle, aboutContent, contentWidth }),
640
- currentView === "blogList" && !loading && /* @__PURE__ */ jsx11(
641
- BlogListView,
642
- {
643
- posts: blogPosts,
644
- highlightedIndex: blogList.highlightedIndex,
645
- scrollRef: blogList.scrollRef,
646
- viewportHeight: blogListVPHeight
647
- }
648
- ),
649
- currentView === "blogDetail" && currentPost && /* @__PURE__ */ jsx11(
650
- BlogDetailView,
651
- {
652
- post: currentPost,
653
- scrollRef: detailScrollRef,
654
- viewportHeight: blogDetailVPHeight,
655
- contentWidth
656
- }
657
- ),
658
- currentView === "portfolioList" && !loading && /* @__PURE__ */ jsx11(
659
- PortfolioListView,
660
- {
661
- projects: portfolioProjects,
662
- highlightedIndex: portfolioList.highlightedIndex,
663
- scrollRef: portfolioList.scrollRef,
664
- viewportHeight: portfolioListVPHeight
665
- }
1945
+ await ui.task(
1946
+ "Updating",
1947
+ () => writeCopies(this.deps, chosen, copies),
1948
+ () => describeCopies("Updated", chosen, copies)
1949
+ );
1950
+ ui.outro(`Updated ${plural(chosen.length, "skill")}.`, { lines: ["Start a new agent session to use them."] });
1951
+ return 0;
1952
+ }
1953
+ async chooseUpdates(ui, outdated) {
1954
+ const width = Math.max(...outdated.map((check) => short(check.locked.commit).length));
1955
+ return ui.multiselect({
1956
+ message: "Update which?",
1957
+ options: outdated.map((check) => ({
1958
+ value: check.latest,
1959
+ label: check.name,
1960
+ hint: describeChange(check.locked, check.latest).padStart(width)
1961
+ })),
1962
+ initialValues: outdated.map((check) => check.latest)
1963
+ });
1964
+ }
1965
+ };
1966
+ function isOutdated2(check) {
1967
+ return check.latest !== null && check.latest.commit !== check.locked.commit;
1968
+ }
1969
+ function describeChecks(checks, { listUpdates }) {
1970
+ const updates = checks.filter(isOutdated2);
1971
+ const gone = checks.filter((check) => !check.latest);
1972
+ if (updates.length === 0 && gone.length === 0) return { title: "Up to date" };
1973
+ const shown = [...listUpdates ? updates : [], ...gone];
1974
+ const width = Math.max(0, ...shown.map((check) => check.name.length));
1975
+ return {
1976
+ title: updates.length > 0 ? `${plural(updates.length, "update")} available` : `${plural(gone.length, "skill")} no longer available`,
1977
+ tone: gone.length > 0 ? "warning" : "success",
1978
+ lines: shown.map(
1979
+ (check) => `${check.name.padEnd(width)} ${isOutdated2(check) ? paint.muted(describeChange(check.locked, check.latest)) : "no longer available, left as is"}`
666
1980
  )
667
- ] }) });
668
- }
669
-
670
- // src/lib/render.tsx
671
- import { render as inkRender } from "ink";
672
-
673
- // src/lib/Screen.tsx
674
- import { useCallback, useEffect as useEffect5, useState as useState4 } from "react";
675
- import { Box as Box8, useStdout as useStdout3 } from "ink";
676
- import { jsx as jsx12 } from "react/jsx-runtime";
677
- function Screen({ children }) {
678
- const { stdout } = useStdout3();
679
- const getSize = useCallback(() => ({ height: stdout.rows, width: stdout.columns }), [stdout]);
680
- const [size, setSize] = useState4(getSize);
681
- useEffect5(() => {
682
- const onResize = () => setSize(getSize());
683
- stdout.on("resize", onResize);
684
- return () => {
685
- stdout.off("resize", onResize);
686
- };
687
- }, [stdout, getSize]);
688
- return /* @__PURE__ */ jsx12(Box8, { height: size.height, width: size.width, children });
689
- }
690
-
691
- // src/lib/render.tsx
692
- import { jsx as jsx13 } from "react/jsx-runtime";
693
- var ENTER_ALT_BUFFER = "\x1B[?1049h";
694
- var EXIT_ALT_BUFFER = "\x1B[?1049l";
695
- var CLEAR_SCREEN = "\x1B[2J\x1B[H";
696
- function render(node, options) {
697
- process.stdout.write(ENTER_ALT_BUFFER + CLEAR_SCREEN);
698
- const element = /* @__PURE__ */ jsx13(Screen, { children: node });
699
- const instance = inkRender(element, options);
700
- setImmediate(() => instance.rerender(element));
701
- const cleanup = () => process.stdout.write(EXIT_ALT_BUFFER);
702
- const originalWaitUntilExit = instance.waitUntilExit.bind(instance);
703
- instance.waitUntilExit = async () => {
704
- await originalWaitUntilExit();
705
- cleanup();
706
1981
  };
707
- process.on("exit", cleanup);
708
- const handleSignal = () => {
709
- cleanup();
710
- instance.unmount();
711
- process.exit(0);
1982
+ }
1983
+
1984
+ // src/commands/skills/actions.ts
1985
+ var SKILLS_ACTIONS = [
1986
+ { id: "install", aliases: ["add"], hint: "choose skills and where they go" },
1987
+ { id: "update", aliases: ["upgrade"], hint: "get the latest of what you have" },
1988
+ { id: "remove", aliases: ["rm", "uninstall"], hint: "delete skills zion installed" },
1989
+ { id: "list", aliases: ["ls"], hint: "print every skill and where it is installed" },
1990
+ { id: "show", aliases: [], hint: "print a skill's SKILL.md" }
1991
+ ];
1992
+ function findSkillsAction(name) {
1993
+ return SKILLS_ACTIONS.find((action) => action.id === name || action.aliases.includes(name));
1994
+ }
1995
+
1996
+ // src/commands/skills/options.ts
1997
+ import { parseArgs as parseArgs2 } from "util";
1998
+ var NAME = /^\w[\w.-]*$/;
1999
+ function parseSkillsOptions(args, bin, targetIds) {
2000
+ const usageHint = `run ${bin} skills --help for usage`;
2001
+ let parsed;
2002
+ try {
2003
+ parsed = parseArgs2({
2004
+ args: [...args],
2005
+ allowPositionals: true,
2006
+ strict: true,
2007
+ options: {
2008
+ target: { type: "string", short: "t", multiple: true, default: [] },
2009
+ all: { type: "boolean", short: "a", default: false },
2010
+ yes: { type: "boolean", short: "y", default: false },
2011
+ json: { type: "boolean", default: false }
2012
+ }
2013
+ });
2014
+ } catch (error) {
2015
+ throw new UsageError(describeParseError(error), usageHint);
2016
+ }
2017
+ const { values, positionals } = parsed;
2018
+ const [first, ...names] = positionals;
2019
+ const action = first === void 0 ? void 0 : findSkillsAction(first);
2020
+ if (first !== void 0 && !action) {
2021
+ throw new UsageError(`unknown action "${first}"`, `did you mean ${bin} skills install ${positionals.join(" ")}?`);
2022
+ }
2023
+ const invalid = names.find((name) => !NAME.test(name));
2024
+ if (invalid !== void 0) throw new UsageError(`"${invalid}" isn't a skill name`, usageHint);
2025
+ const targets = [...new Set(values.target)];
2026
+ const unknown = targets.find((target) => !targetIds.includes(target));
2027
+ if (unknown !== void 0) {
2028
+ throw new UsageError(`unknown target "${unknown}"`, `choose one of: ${targetIds.join(", ")}`);
2029
+ }
2030
+ const id = action?.id;
2031
+ const only = (flag, allowed) => {
2032
+ if (!id || !allowed.includes(id)) throw new UsageError(`${flag} works with: ${allowed.join(", ")}`, usageHint);
712
2033
  };
713
- process.on("SIGINT", handleSignal);
714
- process.on("SIGTERM", handleSignal);
715
- return instance;
2034
+ if (targets.length > 0) only("--target", ["install", "remove"]);
2035
+ if (values.all) only("--all", ["install", "remove"]);
2036
+ if (values.yes) only("--yes", ["install", "update", "remove"]);
2037
+ if (values.json) only("--json", ["list"]);
2038
+ if (values.all && names.length > 0) throw new UsageError("pass skill names or --all, not both", usageHint);
2039
+ if (id === "list" && names.length > 0) throw new UsageError(`unexpected argument "${names[0]}"`, usageHint);
2040
+ if (id === "show" && names.length !== 1) {
2041
+ throw new UsageError("show takes exactly one skill name", `e.g. ${bin} skills show commit`);
2042
+ }
2043
+ return { action: id, names, targets, all: values.all, yes: values.yes, json: values.json };
2044
+ }
2045
+
2046
+ // src/commands/skills/output.ts
2047
+ import path11 from "path";
2048
+ async function listSkills({ api, lockfile }, ctx, json) {
2049
+ const [available, lock] = await Promise.all([api.list(), lockfile.read()]);
2050
+ const names = [.../* @__PURE__ */ new Set([...available, ...Object.keys(lock.skills)])].sort();
2051
+ const rows = names.map((name) => {
2052
+ const entry = lock.skills[name];
2053
+ return {
2054
+ name,
2055
+ available: available.includes(name),
2056
+ installed: entry ? { commit: entry.commit, updatedAt: entry.updatedAt, paths: entry.paths } : null
2057
+ };
2058
+ });
2059
+ if (json) {
2060
+ ctx.stdout.write(`${JSON.stringify({ skills: rows }, null, 2)}
2061
+ `);
2062
+ return 0;
2063
+ }
2064
+ useColorsFor(ctx.stdout, ctx.color);
2065
+ const width = Math.max(...names.map((name) => name.length));
2066
+ for (const row of rows) {
2067
+ const status = row.installed ? `${paint.success("installed")} ${paint.muted(short(row.installed.commit))} ${row.installed.paths.map((dir) => tildify(path11.dirname(dir))).join(", ")}` : "";
2068
+ const gone = row.available ? "" : ` ${paint.warning("no longer available")}`;
2069
+ ctx.stdout.write(`${`${row.name.padEnd(width)} ${status}${gone}`.trimEnd()}
2070
+ `);
2071
+ }
2072
+ return 0;
2073
+ }
2074
+ async function showSkill({ api }, ctx, name) {
2075
+ let skill;
2076
+ try {
2077
+ skill = await api.get(name);
2078
+ } catch (error) {
2079
+ if (error instanceof SkillNotFoundError)
2080
+ throw new SkillNotFoundError(name, `run ${ctx.bin} skills list to see them all`);
2081
+ throw error;
2082
+ }
2083
+ const file = skill.files.find((candidate) => candidate.path === "SKILL.md");
2084
+ if (!file) throw new CliError(`${name} has no SKILL.md`);
2085
+ ctx.stdout.write(file.content);
2086
+ return 0;
2087
+ }
2088
+
2089
+ // src/commands/skills/SkillsCommand.ts
2090
+ var SkillsCommand = class {
2091
+ constructor(deps) {
2092
+ this.deps = deps;
2093
+ const { targets, lockfile, api } = deps;
2094
+ this.help = {
2095
+ usage: `skills ${paint.muted("[action] [skill...] [options]")}`,
2096
+ description: `Downloads skills from ${api.host} into the directories your agents load them from. Without an action, it shows every skill as a checklist: tick to install, untick to remove, and installed skills are updated too. When not in a terminal, it prints the list instead. zion remembers what it installed in ${tildify(lockfile.path)}, and never touches files it didn't write without asking. Targets: ${targets.map((t) => `${t.id} is ${tildify(t.dir)}`).join(", ")}.`,
2097
+ arguments: {
2098
+ title: "Actions",
2099
+ rows: SKILLS_ACTIONS.map((action) => [
2100
+ [action.id, ...action.aliases].join(", "),
2101
+ action.id === "show" ? `${action.hint} (takes one skill)` : action.hint
2102
+ ])
2103
+ },
2104
+ options: [
2105
+ ["-t, --target <name>", `${targets.map((t) => t.id).join(" or ")}; repeat to install into both`],
2106
+ ["-a, --all", "every skill, for install and remove"],
2107
+ ["-y, --yes", "answer yes to every prompt, including replacing edited copies"],
2108
+ ["--json", "print list as JSON"]
2109
+ ],
2110
+ examples: [
2111
+ "skills",
2112
+ "skills install commit author -t claude",
2113
+ "skills install --all -t agents -t claude --yes",
2114
+ "skills update",
2115
+ "skills list --json",
2116
+ "skills show commit | less",
2117
+ "skills remove commit --yes"
2118
+ ]
2119
+ };
2120
+ }
2121
+ name = "skills";
2122
+ summary = "install zion's agent skills";
2123
+ help;
2124
+ async run(args, ctx) {
2125
+ const options = parseSkillsOptions(
2126
+ args,
2127
+ ctx.bin,
2128
+ this.deps.targets.map((target) => target.id)
2129
+ );
2130
+ if (options.action === "list") return listSkills(this.deps, ctx, options.json);
2131
+ if (options.action === "show") return showSkill(this.deps, ctx, options.names[0]);
2132
+ const given = options.action;
2133
+ if (!given && !ctx.interactive) return listSkills(this.deps, ctx, false);
2134
+ const ui = this.deps.createPrompter(ctx);
2135
+ return runSession(ui, async () => {
2136
+ ui.intro("skills", this.deps.api.host);
2137
+ const flows = { install: InstallFlow, update: UpdateFlow, remove: RemoveFlow };
2138
+ return given ? new flows[given](this.deps).run(ui, options, ctx) : new ManageFlow(this.deps).run(ui);
2139
+ });
2140
+ }
2141
+ };
2142
+
2143
+ // src/commands/skills/targets.ts
2144
+ import path12 from "path";
2145
+ function skillTargets(homedir) {
2146
+ return [
2147
+ {
2148
+ id: "agents",
2149
+ dir: path12.join(homedir, ".agents", "skills"),
2150
+ home: path12.join(homedir, ".agents"),
2151
+ hint: "Copilot and other agents"
2152
+ },
2153
+ {
2154
+ id: "claude",
2155
+ dir: path12.join(homedir, ".claude", "skills"),
2156
+ home: path12.join(homedir, ".claude"),
2157
+ hint: "Claude Code"
2158
+ }
2159
+ ];
2160
+ }
2161
+
2162
+ // src/services/Git.ts
2163
+ var GitError = class extends Error {
2164
+ constructor(args, stderr) {
2165
+ super(stderr.split("\n").pop() || `git ${args.join(" ")} failed`);
2166
+ this.args = args;
2167
+ this.stderr = stderr;
2168
+ this.name = "GitError";
2169
+ }
2170
+ };
2171
+ var CliGit = class {
2172
+ constructor(runner2) {
2173
+ this.runner = runner2;
2174
+ }
2175
+ // Never block on a credential prompt: a hidden prompt behind a spinner looks like a hang.
2176
+ env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
2177
+ async version(signal) {
2178
+ const { code, stdout } = await this.runner.capture("git", ["--version"], { env: this.env, signal });
2179
+ return code === 0 ? stdout.match(/\d+(\.\d+)+/)?.[0] ?? stdout : null;
2180
+ }
2181
+ topLevel(dir) {
2182
+ return this.query(["-C", dir, "rev-parse", "--show-toplevel"]);
2183
+ }
2184
+ remoteUrl(dir, remote) {
2185
+ return this.query(["-C", dir, "remote", "get-url", remote]);
2186
+ }
2187
+ resolve(dir, ref) {
2188
+ return this.query(["-C", dir, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
2189
+ }
2190
+ async isDirty(dir) {
2191
+ return Boolean(await this.run(["-C", dir, "status", "--porcelain", "--untracked-files=no"]));
2192
+ }
2193
+ async countCommits(dir, range) {
2194
+ return Number(await this.run(["-C", dir, "rev-list", "--count", range]));
2195
+ }
2196
+ async clone(url, dir, signal) {
2197
+ await this.run(["clone", "--quiet", url, dir], signal);
2198
+ }
2199
+ async fetch(dir, signal) {
2200
+ await this.run(["-C", dir, "fetch", "--quiet"], signal);
2201
+ }
2202
+ async fastForward(dir, ref) {
2203
+ const { code } = await this.runner.capture("git", ["-C", dir, "merge", "--ff-only", "--quiet", ref], {
2204
+ env: this.env
2205
+ });
2206
+ return code === 0;
2207
+ }
2208
+ async query(args) {
2209
+ const { code, stdout } = await this.runner.capture("git", args, { env: this.env });
2210
+ return code === 0 && stdout ? stdout : null;
2211
+ }
2212
+ async run(args, signal) {
2213
+ const { code, stdout, stderr } = await this.runner.capture("git", args, { env: this.env, signal });
2214
+ if (code !== 0) throw new GitError(args, stderr);
2215
+ return stdout;
2216
+ }
2217
+ };
2218
+
2219
+ // src/services/ProcessRunner.ts
2220
+ import { spawn } from "child_process";
2221
+ var FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2222
+ var SIGNAL_NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 };
2223
+ var NodeProcessRunner = class {
2224
+ capture(command, args, options = {}) {
2225
+ return new Promise((resolve, reject) => {
2226
+ const child = spawn(command, args, {
2227
+ cwd: options.cwd,
2228
+ env: options.env ?? process.env,
2229
+ signal: options.signal,
2230
+ stdio: ["ignore", "pipe", "pipe"]
2231
+ });
2232
+ let stdout = "";
2233
+ let stderr = "";
2234
+ child.stdout.on("data", (chunk) => stdout += chunk);
2235
+ child.stderr.on("data", (chunk) => stderr += chunk);
2236
+ child.on("error", (error) => {
2237
+ if (error.code === "ENOENT") resolve({ code: 127, stdout, stderr: `${command}: command not found` });
2238
+ else reject(error);
2239
+ });
2240
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout: stdout.trim(), stderr: stderr.trim() }));
2241
+ });
2242
+ }
2243
+ attach(command, args, options = {}) {
2244
+ return new Promise((resolve, reject) => {
2245
+ const child = spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, stdio: "inherit" });
2246
+ const forward = (signal) => {
2247
+ if (signal !== "SIGINT") child.kill(signal);
2248
+ };
2249
+ for (const signal of FORWARDED_SIGNALS) process.on(signal, forward);
2250
+ const cleanup = () => {
2251
+ for (const signal of FORWARDED_SIGNALS) process.off(signal, forward);
2252
+ };
2253
+ child.on("error", (error) => {
2254
+ cleanup();
2255
+ reject(error);
2256
+ });
2257
+ child.on("close", (code, signal) => {
2258
+ cleanup();
2259
+ resolve(code ?? 128 + (signal ? SIGNAL_NUMBERS[signal] ?? 0 : 0));
2260
+ });
2261
+ });
2262
+ }
2263
+ };
2264
+
2265
+ // src/services/xdg.ts
2266
+ import os2 from "os";
2267
+ import path13 from "path";
2268
+ function stateHome(env) {
2269
+ const base = env.XDG_STATE_HOME;
2270
+ return base && path13.isAbsolute(base) ? base : path13.join(os2.homedir(), ".local", "state");
716
2271
  }
717
2272
 
718
2273
  // src/cli.tsx
719
- import { jsx as jsx14 } from "react/jsx-runtime";
720
- render(/* @__PURE__ */ jsx14(App, {}));
2274
+ for (const stream of [process.stdout, process.stderr]) {
2275
+ stream.on("error", (error) => {
2276
+ if (error.code === "EPIPE") process.exit(0);
2277
+ throw error;
2278
+ });
2279
+ }
2280
+ var runner = new NodeProcessRunner();
2281
+ var git = new CliGit(runner);
2282
+ var registry = new CommandRegistry().register(
2283
+ new DotfilesCommand({
2284
+ repository: new DotfilesRepository(git, {
2285
+ slug: "zion-off/dotfiles",
2286
+ url: "https://github.com/zion-off/dotfiles.git",
2287
+ installer: "bin/dot",
2288
+ installerLink: path14.join(os3.homedir(), ".local", "bin", "dot")
2289
+ }),
2290
+ git,
2291
+ runner,
2292
+ createPrompter,
2293
+ platform: process.platform,
2294
+ arch: process.arch,
2295
+ env: process.env
2296
+ })
2297
+ ).register(
2298
+ new SkillsCommand({
2299
+ api: new HttpSkillsApi("https://zzzzion.com/api/skills"),
2300
+ files: new NodeSkillFiles(),
2301
+ lockfile: new JsonLockfile(path14.join(stateHome(process.env), "zion.json")),
2302
+ targets: skillTargets(os3.homedir()),
2303
+ createPrompter,
2304
+ now: () => /* @__PURE__ */ new Date()
2305
+ })
2306
+ );
2307
+ var fallback = new TuiCommand();
2308
+ var help = new HelpPrinter(registry, fallback);
2309
+ registry.register(new HelpCommand(help, registry));
2310
+ var cli = new Cli({
2311
+ registry,
2312
+ fallback,
2313
+ help,
2314
+ environment: {
2315
+ bin: "npx zion",
2316
+ version,
2317
+ stdin: process.stdin,
2318
+ stdout: process.stdout,
2319
+ stderr: process.stderr,
2320
+ env: process.env
2321
+ }
2322
+ });
2323
+ process.exitCode = await cli.run(process.argv.slice(2));