ekurt 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,155 @@
1
+ /** Memory in the terminal: flip the cards and match the ekurtOS app icons in as few moves as you can. */
2
+ import chalk from "chalk";
3
+ import { profile } from "../content.js";
4
+ import { accent, bold, COLORS, muted, ok } from "../ui/style.js";
5
+ import { direction, isQuit } from "../ui/screen.js";
6
+ import { pad } from "../ui/text.js";
7
+ import { clock } from "./board.js";
8
+ const PAIRS = 8;
9
+ const COLS = 4;
10
+ /** How long a mismatched pair stays face up. */
11
+ const PEEK_MS = 800;
12
+ const CARD_W = 12;
13
+ let bestMoves = null;
14
+ function deal(random = Math.random) {
15
+ const apps = [...profile().apps].sort(() => random() - 0.5).slice(0, PAIRS);
16
+ const cards = [...apps, ...apps].map((app) => ({ app, matched: false }));
17
+ for (let i = cards.length - 1; i > 0; i--) {
18
+ const j = Math.floor(random() * (i + 1));
19
+ [cards[i], cards[j]] = [cards[j], cards[i]];
20
+ }
21
+ return cards;
22
+ }
23
+ const center = (text, w) => {
24
+ const left = Math.floor((w - text.length) / 2);
25
+ return pad(" ".repeat(left) + text, w);
26
+ };
27
+ export class Memory {
28
+ tick = 1000;
29
+ cards = deal();
30
+ up = [];
31
+ cursor = 0;
32
+ moves = 0;
33
+ startedAt = 0;
34
+ endedAt = 0;
35
+ record = false;
36
+ peek = null;
37
+ redraw = () => { };
38
+ attach(redraw) {
39
+ this.redraw = redraw;
40
+ }
41
+ frameWidth() {
42
+ return COLS * CARD_W + (COLS - 1) * 2;
43
+ }
44
+ get won() {
45
+ return this.cards.every((c) => c.matched);
46
+ }
47
+ restart() {
48
+ if (this.peek)
49
+ clearTimeout(this.peek);
50
+ this.cards = deal();
51
+ this.up = [];
52
+ this.cursor = 0;
53
+ this.moves = 0;
54
+ this.startedAt = 0;
55
+ this.record = false;
56
+ }
57
+ seconds() {
58
+ if (!this.startedAt)
59
+ return 0;
60
+ return Math.floor(((this.won ? this.endedAt : Date.now()) - this.startedAt) / 1000);
61
+ }
62
+ key(key) {
63
+ if (isQuit(key)) {
64
+ if (this.peek)
65
+ clearTimeout(this.peek);
66
+ return "quit";
67
+ }
68
+ const move = direction(key);
69
+ if (move) {
70
+ const x = this.cursor % COLS;
71
+ const y = Math.floor(this.cursor / COLS);
72
+ const rows = this.cards.length / COLS;
73
+ const nx = move === "left" ? (x + COLS - 1) % COLS : move === "right" ? (x + 1) % COLS : x;
74
+ const ny = move === "up" ? (y + rows - 1) % rows : move === "down" ? (y + 1) % rows : y;
75
+ this.cursor = ny * COLS + nx;
76
+ return;
77
+ }
78
+ if (key.name === "r")
79
+ return this.restart();
80
+ if (key.name === "space" || key.name === "return" || key.name === "enter") {
81
+ if (this.won)
82
+ return this.restart();
83
+ this.flip(this.cursor);
84
+ }
85
+ }
86
+ flip(index) {
87
+ const card = this.cards[index];
88
+ if (card.matched || this.up.includes(index) || this.up.length === 2)
89
+ return;
90
+ if (!this.startedAt)
91
+ this.startedAt = Date.now();
92
+ if (!this.up.length) {
93
+ this.up = [index];
94
+ return;
95
+ }
96
+ const first = this.up[0];
97
+ this.moves++;
98
+ if (this.cards[first].app.id === card.app.id) {
99
+ this.cards = this.cards.map((c, i) => (i === index || i === first ? { ...c, matched: true } : c));
100
+ this.up = [];
101
+ if (this.won) {
102
+ this.endedAt = Date.now();
103
+ this.record = bestMoves === null || this.moves < bestMoves;
104
+ if (this.record)
105
+ bestMoves = this.moves;
106
+ }
107
+ return;
108
+ }
109
+ this.up = [first, index];
110
+ this.peek = setTimeout(() => {
111
+ this.up = [];
112
+ this.peek = null;
113
+ this.redraw();
114
+ }, PEEK_MS);
115
+ }
116
+ /** Three lines of one card. */
117
+ card(index) {
118
+ const card = this.cards[index];
119
+ const shown = card.matched || this.up.includes(index);
120
+ const focused = index === this.cursor && !this.won;
121
+ if (!shown) {
122
+ const face = chalk.bgHex(focused ? COLORS.focus : COLORS.surface).hex(focused ? "#ffffff" : "#6e7681");
123
+ return [face(" ".repeat(CARD_W)), face(center("?", CARD_W)), face(" ".repeat(CARD_W))];
124
+ }
125
+ const face = chalk.bgHex(card.app.color).hex("#ffffff");
126
+ const label = center(card.app.title, CARD_W);
127
+ const bottom = card.matched ? pad(" ".repeat(CARD_W - 2) + "✓", CARD_W) : " ".repeat(CARD_W);
128
+ const top = focused ? center("▾", CARD_W) : " ".repeat(CARD_W);
129
+ return [face(top), face.bold(label), face(bottom)];
130
+ }
131
+ render() {
132
+ const lines = [];
133
+ const rows = this.cards.length / COLS;
134
+ for (let y = 0; y < rows; y++) {
135
+ const cards = Array.from({ length: COLS }, (_, x) => this.card(y * COLS + x));
136
+ for (let line = 0; line < 3; line++)
137
+ lines.push(cards.map((c) => c[line]).join(" "));
138
+ const marks = Array.from({ length: COLS }, (_, x) => (y * COLS + x === this.cursor && !this.won ? accent("▔".repeat(CARD_W)) : " ".repeat(CARD_W)));
139
+ lines.push(marks.join(" "));
140
+ }
141
+ const status = this.won
142
+ ? ok(`Cleared in ${this.moves} moves, ${clock(Math.max(1, this.seconds()))}${this.record ? " — new best!" : ""}`) + muted(" space plays again")
143
+ : this.moves === 0 && !this.up.length
144
+ ? muted("Find the eight pairs in as few moves as you can.")
145
+ : muted(`${this.cards.filter((c) => c.matched).length / 2} of ${PAIRS} pairs found`);
146
+ return [
147
+ `${bold("Memory")} ${bold(String(this.moves))} ${muted(this.moves === 1 ? "move" : "moves")} ${muted("time")} ${bold(clock(this.seconds()))}${bestMoves !== null ? ` ${muted("best")} ${bestMoves} moves` : ""}`,
148
+ "",
149
+ ...lines,
150
+ status,
151
+ "",
152
+ muted(`${accent("←↑↓→")} move ${accent("space")} flip ${accent("r")} restart ${accent("q")} quit`),
153
+ ];
154
+ }
155
+ }
@@ -0,0 +1,506 @@
1
+ /**
2
+ * ekurtsh commands: the same set as the Terminal app on ekurt.dev (help, ls, cd, cat, open,
3
+ * whoami, play, neofetch, contact…), plus what a real terminal makes possible: full posts and
4
+ * projects in `cat`, the CV, search, and the Arcade's own games playable right here.
5
+ */
6
+ import { bookmarks, CATEGORY_LABELS, games, posts, profile, projects, SERIES, siteUrl, version } from "../content.js";
7
+ import { mailto, send, validate } from "../contact.js";
8
+ import { Bugsweeper } from "../games/bugsweeper.js";
9
+ import { Memory } from "../games/memory.js";
10
+ import { LEVELS } from "../games/board.js";
11
+ import { aboutPage, bookmarksPage, contactRows, cvPage, postPage, projectPage } from "../ui/pages.js";
12
+ import { accent, bold, dir, error, hex, hint, muted, ok, shortUrl, url, COLORS } from "../ui/style.js";
13
+ import { pad, truncate } from "../ui/text.js";
14
+ import { display, isDir, list, lookup, postPath, projectPath, resolve, seriesLabel, urlFor } from "./fs.js";
15
+ const LOGO = [" ______ ", " / ____/ ", " / __/ ", "/ /___ __ ", "\\____/ /_/ "];
16
+ function uptime(since) {
17
+ const s = Math.floor((Date.now() - since) / 1000);
18
+ if (s < 60)
19
+ return `${s} sec`;
20
+ const m = Math.floor(s / 60);
21
+ return `${m} min${m === 1 ? "" : "s"}`;
22
+ }
23
+ const apps = () => profile().apps;
24
+ const findApp = (arg) => apps().find((a) => a.id === arg.toLowerCase() || a.title.toLowerCase() === arg.toLowerCase());
25
+ async function openAndSay(ctx, href, what) {
26
+ const opened = await ctx.openUrl(href);
27
+ return opened ? [muted(`Opening ${what}… `) + url(href)] : [muted(`Open this in your browser: `) + url(href, href)];
28
+ }
29
+ function terminalName() {
30
+ const env = process.env;
31
+ if (env.TERM_PROGRAM)
32
+ return env.TERM_PROGRAM + (env.TERM_PROGRAM_VERSION ? ` ${env.TERM_PROGRAM_VERSION}` : "");
33
+ if (env.WT_SESSION)
34
+ return "Windows Terminal";
35
+ return env.TERM ?? process.platform;
36
+ }
37
+ /** Edit distance, for "did you mean". */
38
+ function distance(a, b) {
39
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
40
+ for (let i = 1; i <= a.length; i++) {
41
+ let prev = row[0];
42
+ row[0] = i;
43
+ for (let j = 1; j <= b.length; j++) {
44
+ const tmp = row[j];
45
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
46
+ prev = tmp;
47
+ }
48
+ }
49
+ return row[b.length];
50
+ }
51
+ /** The contact form: the Mail app's "New Message", one field at a time. */
52
+ async function compose(ctx) {
53
+ const p = profile();
54
+ const write = (line = "") => process.stdout.write(line + "\n");
55
+ write(bold("New Message"));
56
+ write(`${muted(pad("To:", 9))}${p.name} <${p.email}>`);
57
+ const field = async (label, check) => {
58
+ for (;;) {
59
+ const answer = await ctx.ask(`${muted(pad(label + ":", 9))}`);
60
+ if (answer === null)
61
+ return null;
62
+ const problem = check?.(answer.trim());
63
+ if (!problem)
64
+ return answer.trim();
65
+ write(error(` ${problem}`));
66
+ }
67
+ };
68
+ const name = await field("Name", (v) => (v ? null : "Please tell me your name."));
69
+ if (name === null)
70
+ return [muted("Message discarded.")];
71
+ const email = await field("Email", (v) => (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? null : "Please enter a valid email address."));
72
+ if (email === null)
73
+ return [muted("Message discarded.")];
74
+ const subject = await field("Subject");
75
+ if (subject === null)
76
+ return [muted("Message discarded.")];
77
+ write(muted("Message: (an empty line ends it)"));
78
+ const body = [];
79
+ for (;;) {
80
+ const line = await ctx.ask(muted(" │ "));
81
+ if (line === null)
82
+ return [muted("Message discarded.")];
83
+ if (!line.trim() && body.length)
84
+ break;
85
+ if (line.trim() || body.length)
86
+ body.push(line);
87
+ }
88
+ const message = { name, email, subject, message: body.join("\n").trim() };
89
+ const problem = validate(message);
90
+ if (problem)
91
+ return [error(problem), muted("Nothing was sent. Run ") + accent("contact") + muted(" to try again.")];
92
+ const confirm = await ctx.ask(`Send it to ${p.name}? ${muted("(Y/n)")} `);
93
+ if (confirm === null || /^n/i.test(confirm.trim()))
94
+ return [muted("Message discarded.")];
95
+ write(muted("Sending…"));
96
+ const result = await send(message);
97
+ if (result.ok)
98
+ return [ok("✓ Message sent.") + " Thanks — I read everything and I'll write back to " + accent(email) + "."];
99
+ const lines = [error(result.error)];
100
+ if (result.fallback) {
101
+ const opened = await ctx.openUrl(mailto(message));
102
+ lines.push(opened ? muted("Opened your mail app with the message filled in instead.") : muted("You can email me directly: ") + url(`mailto:${p.email}`, p.email));
103
+ }
104
+ return lines;
105
+ }
106
+ function lsLong(path, entries) {
107
+ const rowsOut = entries.map((e) => {
108
+ const full = [...path, e.name];
109
+ let date = "";
110
+ let note = "";
111
+ if (e.type === "dir") {
112
+ const inside = list(full) ?? [];
113
+ if (full[0] === "blog" && full.length === 2)
114
+ note = `${seriesLabel(e.name)} · ${inside.length} post${inside.length === 1 ? "" : "s"}`;
115
+ else
116
+ note = `${inside.length} ${e.name === "projects" ? "projects" : e.name === "blog" ? "series" : "items"}`;
117
+ if (e.name === "blog")
118
+ note = `${posts().length} posts in ${inside.length} series`;
119
+ }
120
+ else {
121
+ const file = lookup(full);
122
+ if (file?.kind === "project") {
123
+ date = file.project.date ?? "";
124
+ note = [file.project.title, file.project.category ? CATEGORY_LABELS[file.project.category] : null].filter(Boolean).join(" · ");
125
+ }
126
+ else if (file?.kind === "post") {
127
+ date = file.post.date ?? "";
128
+ note = [file.post.lesson, file.post.shortTitle].filter(Boolean).join(" · ");
129
+ }
130
+ else if (file?.kind === "about")
131
+ note = "who I am, in short";
132
+ else if (file?.kind === "bookmarks")
133
+ note = `${bookmarks().length} links I keep coming back to`;
134
+ else if (file?.kind === "cv")
135
+ note = "résumé · one page";
136
+ }
137
+ return { e, date, note };
138
+ });
139
+ const nameW = Math.max(...rowsOut.map((r) => r.e.name.length + (r.e.type === "dir" ? 1 : 0))) + 2;
140
+ return rowsOut.map(({ e, date, note }) => {
141
+ const perm = muted(e.type === "dir" ? "dr-xr-xr-x" : "-r--r--r--");
142
+ const name = e.type === "dir" ? dir(`${e.name}/`) : e.name;
143
+ return `${perm} ${muted(pad(date, 10))} ${pad(name, nameW)}${muted(truncate(note, 60))}`;
144
+ });
145
+ }
146
+ function tree(path) {
147
+ const out = [dir(display(path))];
148
+ const walk = (p, prefix) => {
149
+ const entries = list(p) ?? [];
150
+ entries.forEach((e, i) => {
151
+ const last = i === entries.length - 1;
152
+ out.push(muted(prefix + (last ? "└── " : "├── ")) + (e.type === "dir" ? dir(`${e.name}/`) : e.name));
153
+ if (e.type === "dir")
154
+ walk([...p, e.name], prefix + (last ? " " : "│ "));
155
+ });
156
+ };
157
+ walk(path, "");
158
+ const all = out.length - 1;
159
+ return [...out, "", muted(`${all} entries`)];
160
+ }
161
+ function search(query, max) {
162
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
163
+ const matches = (...fields) => {
164
+ const hay = fields.filter(Boolean).join(" ").toLowerCase();
165
+ return terms.every((t) => hay.includes(t));
166
+ };
167
+ const byTitle = (items, title) => items.sort((a, b) => Number(terms.every((t) => title(b).toLowerCase().includes(t))) - Number(terms.every((t) => title(a).toLowerCase().includes(t))));
168
+ const groups = [];
169
+ const appHits = apps().filter((a) => matches(a.id, a.title));
170
+ if (appHits.length)
171
+ groups.push({ label: "Apps", lines: appHits.map((a) => `${accent(`open ${a.id}`)} ${muted(a.title)}`) });
172
+ const projectHits = byTitle(projects().filter((p) => matches(p.title, p.description, p.category, p.badge, p.body)), (p) => p.title);
173
+ if (projectHits.length) {
174
+ const w = Math.max(...projectHits.map((p) => display(projectPath(p)).length)) + 6;
175
+ groups.push({
176
+ label: "Projects",
177
+ lines: projectHits.map((p) => `${accent(pad(`cat ${display(projectPath(p))}`, w))}${muted(truncate(p.title + " — " + p.description, max - w))}`),
178
+ });
179
+ }
180
+ const postHits = byTitle(posts().filter((p) => matches(p.title, p.description, p.series, p.body)), (p) => p.title);
181
+ if (postHits.length) {
182
+ groups.push({
183
+ label: "Blog",
184
+ lines: postHits.map((p) => {
185
+ const w = Math.min(34, Math.max(...postHits.map((h) => h.shortTitle.length)) + 2);
186
+ return `${hex(SERIES[p.series].color)("●")} ${pad(truncate(p.shortTitle, w - 2), w)}${muted(`cat ${display(postPath(p))}`)}`;
187
+ }),
188
+ });
189
+ }
190
+ const bookmarkHits = byTitle(bookmarks().filter((b) => matches(b.title, b.description, b.url, b.category)), (b) => b.title);
191
+ if (bookmarkHits.length) {
192
+ const w = Math.max(...bookmarkHits.map((b) => b.title.length)) + 2;
193
+ groups.push({ label: "Bookmarks", lines: bookmarkHits.map((b) => `${pad(b.title, w)}${url(b.url)}`) });
194
+ }
195
+ if (!groups.length)
196
+ return [muted(`No results for “${query}”.`), muted("Try a project name, a topic like ") + accent("search git") + muted(", or a tool.")];
197
+ const LIMIT = 8;
198
+ return groups.flatMap((g, i) => [
199
+ ...(i ? [""] : []),
200
+ ok(bold(g.label)) + muted(` ${g.lines.length}`),
201
+ ...g.lines.slice(0, LIMIT).map((l) => ` ${l}`),
202
+ ...(g.lines.length > LIMIT ? [muted(` … and ${g.lines.length - LIMIT} more`)] : []),
203
+ ]);
204
+ }
205
+ export const COMMANDS = {
206
+ help: {
207
+ summary: "list available commands",
208
+ usage: "help [command]",
209
+ choices: () => Object.entries(COMMANDS)
210
+ .filter(([, c]) => !c.hidden)
211
+ .map(([name, c]) => ({ value: name, note: c.summary })),
212
+ run: ([name]) => {
213
+ if (name) {
214
+ const command = COMMANDS[name.toLowerCase()];
215
+ if (!command || command.hidden)
216
+ return [error(`help: no such command: ${name}`)];
217
+ return details(name.toLowerCase());
218
+ }
219
+ const listed = Object.entries(COMMANDS).filter(([, c]) => !c.hidden);
220
+ const w = Math.max(...listed.map(([n, c]) => (c.usage ?? n).length)) + 2;
221
+ return [
222
+ muted("Commands:"),
223
+ ...listed.map(([n, c]) => `${accent(pad(c.usage ?? n, w))}${muted(c.summary)}`),
224
+ "",
225
+ muted("Tip: Tab completes commands, files and options; ↑/↓ walks history, Ctrl+L clears, Ctrl+D leaves."),
226
+ muted("Any command works straight from your shell too: ") + accent("npx ekurt cat about-me.md"),
227
+ ];
228
+ },
229
+ },
230
+ ls: {
231
+ summary: "list a directory",
232
+ usage: "ls [-l] [dir]",
233
+ paths: "any",
234
+ run: ([...args], ctx) => {
235
+ const long = args.some((a) => /^-\w*l/.test(a));
236
+ const arg = args.find((a) => !a.startsWith("-"));
237
+ const path = resolve(ctx.cwd, arg ?? ".");
238
+ const entries = list(path);
239
+ if (!entries) {
240
+ if (lookup(path))
241
+ return [path.at(-1) ?? ""];
242
+ return [error(`ls: ${arg}: No such file or directory`)];
243
+ }
244
+ if (long)
245
+ return lsLong(path, entries);
246
+ const blogRoot = path[0] === "blog" && path.length === 1;
247
+ const w = Math.max(...entries.map((e) => e.name.length)) + 3;
248
+ return entries.map((e) => e.type === "dir" ? (blogRoot ? pad(dir(`${e.name}/`), w) + muted(seriesLabel(e.name)) : dir(`${e.name}/`)) : e.name);
249
+ },
250
+ },
251
+ cd: {
252
+ summary: "change directory",
253
+ usage: "cd [dir]",
254
+ paths: "dir",
255
+ run: ([arg], ctx) => {
256
+ const path = resolve(ctx.cwd, arg ?? "~");
257
+ if (!isDir(path))
258
+ return [error(lookup(path) ? `cd: not a directory: ${arg}` : `cd: no such file or directory: ${arg}`)];
259
+ ctx.setCwd(path);
260
+ return [];
261
+ },
262
+ },
263
+ pwd: { summary: "print working directory", run: (_, ctx) => [display(ctx.cwd)] },
264
+ cat: {
265
+ summary: "print a file: posts and projects in full",
266
+ usage: "cat <file>",
267
+ paths: "any",
268
+ run: ([arg], ctx) => {
269
+ if (!arg)
270
+ return [error("cat: missing file operand"), muted("try ") + accent("cat about-me.md")];
271
+ const path = resolve(ctx.cwd, arg);
272
+ const file = lookup(path);
273
+ if (!file)
274
+ return [error(isDir(path) ? `cat: ${arg}: Is a directory` : `cat: ${arg}: No such file or directory`)];
275
+ switch (file.kind) {
276
+ case "about":
277
+ return aboutPage(ctx.width);
278
+ case "bookmarks":
279
+ return bookmarksPage(ctx.width);
280
+ case "cv":
281
+ return [muted("%PDF-1.7 ��� (binary file)"), hint("cv", "read it here, as text"), hint("open cv.pdf", "the PDF itself")];
282
+ case "project":
283
+ return projectPage(file.project, ctx.width);
284
+ case "post":
285
+ return postPage(file.post, ctx.width);
286
+ }
287
+ },
288
+ },
289
+ open: {
290
+ summary: "open a file, folder or app on ekurt.dev",
291
+ usage: "open <path|app>",
292
+ choices: () => apps().map((a) => ({ value: a.id, note: `${a.title} app` })),
293
+ paths: "any",
294
+ run: async ([arg], ctx) => {
295
+ if (!arg)
296
+ return [error("open: missing operand"), muted(`apps: ${apps().map((a) => a.id).join(", ")}`)];
297
+ const path = resolve(ctx.cwd, arg);
298
+ const href = isDir(path) || lookup(path) ? urlFor(path) : null;
299
+ if (href)
300
+ return openAndSay(ctx, href, display(path));
301
+ const app = findApp(arg);
302
+ if (app)
303
+ return openAndSay(ctx, siteUrl(app.route), app.title);
304
+ return [error(`open: ${arg}: No such file, folder or app`)];
305
+ },
306
+ },
307
+ visit: {
308
+ summary: "open a project's live site",
309
+ usage: "visit <project>",
310
+ choices: () => projects().filter((p) => p.url).map((p) => ({ value: p.slug, note: shortUrl(p.url) })),
311
+ run: async ([arg], ctx) => {
312
+ const live = projects().filter((p) => p.url);
313
+ if (!arg)
314
+ return [muted("projects:"), ...live.map((p) => `${accent(pad(`visit ${p.slug}`, 30))}${muted(shortUrl(p.url))}`)];
315
+ const project = live.find((p) => p.slug === arg.toLowerCase().replace(/\.md$/, "") || p.title.toLowerCase() === arg.toLowerCase());
316
+ if (!project)
317
+ return [error(`visit: ${arg}: no such project`), muted("try ") + accent("visit") + muted(" for the list")];
318
+ return openAndSay(ctx, project.url, project.title);
319
+ },
320
+ },
321
+ whoami: {
322
+ summary: "who is this?",
323
+ run: () => {
324
+ const p = profile();
325
+ return [
326
+ `${ok(bold(p.name))} — ${p.role.toLowerCase()}, ${p.location.split(",")[0]}`,
327
+ muted(p.tagline),
328
+ "",
329
+ ...contactRows(),
330
+ "",
331
+ hint("cat about-me.md") + " " + hint("cv") + " " + hint("contact"),
332
+ hint("coffee", "if something here helped you"),
333
+ ];
334
+ },
335
+ },
336
+ cv: {
337
+ summary: "the résumé, right here",
338
+ run: (_, ctx) => cvPage(ctx.width),
339
+ },
340
+ search: {
341
+ summary: "search projects, posts and bookmarks",
342
+ usage: "search <words>",
343
+ run: (args, ctx) => (args.length ? search(args.join(" "), ctx.width) : [error("usage: search <words>"), muted("e.g. ") + accent("search react state")]),
344
+ },
345
+ tree: {
346
+ summary: "show the whole filesystem",
347
+ usage: "tree [dir]",
348
+ paths: "dir",
349
+ run: ([arg], ctx) => {
350
+ const path = resolve(ctx.cwd, arg ?? ".");
351
+ if (!isDir(path))
352
+ return [error(`tree: ${arg}: not a directory`)];
353
+ return tree(path);
354
+ },
355
+ },
356
+ play: {
357
+ summary: "play a game from the Arcade",
358
+ usage: "play [game]",
359
+ choices: () => games().map((g) => ({ value: g.slug, note: g.kind === "builtin" ? `${g.title} — plays right here` : `${g.title} — opens in your browser` })),
360
+ run: async ([arg, level], ctx) => {
361
+ if (!arg) {
362
+ const w = Math.max(...games().map((g) => g.slug.length)) + 9;
363
+ return [
364
+ muted("games:"),
365
+ ...games().map((g) => `${accent(pad(`→ play ${g.slug}`, w))}${muted(g.kind === "builtin" ? "plays right here" : "opens in your browser")}`),
366
+ ];
367
+ }
368
+ const game = games().find((g) => g.slug === arg.toLowerCase() || g.title.toLowerCase() === arg.toLowerCase());
369
+ if (!game)
370
+ return [error(`play: ${arg}: no such game`), muted(`games: ${games().map((g) => g.slug).join(", ")}`)];
371
+ if (game.kind === "embed")
372
+ return openAndSay(ctx, game.url, game.title);
373
+ if (!ctx.interactive)
374
+ return [error(`play: ${game.title} needs an interactive terminal`), muted("run ") + accent("npx ekurt") + muted(" and type ") + accent(`play ${game.slug}`)];
375
+ if (game.slug === "bugsweeper" && level && !LEVELS.some((l) => l.id === level)) {
376
+ return [error(`play: no such level: ${level}`), muted(`levels: ${LEVELS.map((l) => l.id).join(", ")}`)];
377
+ }
378
+ await ctx.fullscreen(game.slug === "bugsweeper" ? new Bugsweeper(level) : new Memory());
379
+ return [muted(`Thanks for playing ${game.title}.`)];
380
+ },
381
+ },
382
+ contact: {
383
+ summary: "write me a message",
384
+ run: async (_, ctx) => {
385
+ if (!ctx.interactive) {
386
+ const p = profile();
387
+ return [`${muted("Email me at")} ${url(`mailto:${p.email}`, p.email)}${muted(", or run")} ${accent("npx ekurt")} ${muted("and type")} ${accent("contact")}${muted(".")}`];
388
+ }
389
+ return compose(ctx);
390
+ },
391
+ },
392
+ coffee: {
393
+ summary: "buy me a coffee",
394
+ run: async (_, ctx) => {
395
+ const href = profile().coffee.href;
396
+ const opened = await ctx.openUrl(href);
397
+ return [muted(opened ? `Opening ${shortUrl(href)}… thank you! ☕` : "Thank you! ☕ ") + (opened ? "" : url(href, href))];
398
+ },
399
+ },
400
+ neofetch: {
401
+ summary: "system information",
402
+ run: (_, ctx) => {
403
+ const p = profile();
404
+ const key = (k) => accent(pad(`${k}:`, 10));
405
+ const info = [
406
+ ok("visitor") + "@" + ok("ekurt.dev"),
407
+ muted("-".repeat(17)),
408
+ key("OS") + "ekurtOS 1.0",
409
+ key("Host") + shortUrl(p.url),
410
+ key("Shell") + `ekurtsh ${version()}`,
411
+ key("Terminal") + terminalName(),
412
+ key("Runtime") + `Node.js ${process.versions.node}`,
413
+ key("Uptime") + uptime(ctx.bootedAt),
414
+ key("Stack") + p.stack,
415
+ key("Content") + `${posts().length} posts · ${projects().length} projects · ${bookmarks().length} links`,
416
+ "",
417
+ [COLORS.error, COLORS.orange, "#e3b341", COLORS.ok, COLORS.accent, COLORS.dir, COLORS.muted, COLORS.text].map((c) => hex(c)("███")).join(""),
418
+ ];
419
+ return info.map((line, i) => dir(pad(LOGO[i] ?? "", 14)) + line);
420
+ },
421
+ },
422
+ echo: { summary: "print text", usage: "echo <text>", run: (args) => [args.join(" ")] },
423
+ date: { summary: "print the date", run: () => [new Date().toString()] },
424
+ history: {
425
+ summary: "show command history",
426
+ run: (_, ctx) => ctx.history.map((h, i) => muted(`${String(i + 1).padStart(4)} `) + h),
427
+ },
428
+ clear: {
429
+ summary: "clear the screen",
430
+ run: (_, ctx) => {
431
+ ctx.clear();
432
+ return [];
433
+ },
434
+ },
435
+ exit: {
436
+ summary: "leave the shell",
437
+ run: (_, ctx) => {
438
+ ctx.exit();
439
+ return [];
440
+ },
441
+ },
442
+ // Easter eggs and aliases (not listed in help).
443
+ quit: { summary: "", hidden: true, run: (args, ctx) => COMMANDS.exit.run(args, ctx) },
444
+ logout: { summary: "", hidden: true, run: (args, ctx) => COMMANDS.exit.run(args, ctx) },
445
+ man: { summary: "", hidden: true, run: (args, ctx) => COMMANDS.help.run(args, ctx) },
446
+ ll: { summary: "", hidden: true, run: (args, ctx) => COMMANDS.ls.run(["-l", ...args], ctx) },
447
+ panic: {
448
+ summary: "",
449
+ hidden: true,
450
+ run: async (_, ctx) => {
451
+ if (!ctx.interactive)
452
+ return [error("Triggering kernel panic…"), muted("…but there is no screen to crash here. Try it in ") + accent("npx ekurt") + muted(".")];
453
+ process.stdout.write(error("Triggering kernel panic…") + "\n");
454
+ await new Promise((r) => setTimeout(r, 600));
455
+ await ctx.panic();
456
+ return [];
457
+ },
458
+ },
459
+ sudo: { summary: "", hidden: true, run: () => [error("visitor is not in the sudoers file. This incident will be reported. 🙂")] },
460
+ rm: { summary: "", hidden: true, run: () => [error("rm: read-only file system — nice try though.")] },
461
+ vim: { summary: "", hidden: true, run: () => [muted("You are now trapped in vim. Just kidding — try `cat` instead.")] },
462
+ theme: { summary: "", hidden: true, run: () => [muted("Your terminal picks the colours in here. On ekurt.dev: ") + accent("open settings")] },
463
+ wallpaper: { summary: "", hidden: true, run: () => [muted("No wallpaper in a terminal — but the site has four: ") + accent("open settings")] },
464
+ };
465
+ /** `help ls`, or a command plus Tab: what it does and the options it takes. */
466
+ export function details(name) {
467
+ const command = COMMANDS[name];
468
+ const lines = [ok(command.usage ?? name) + muted(` ${command.summary}`)];
469
+ const choices = command.choices?.() ?? [];
470
+ if (choices.length) {
471
+ const w = Math.max(...choices.map((c) => c.value.length)) + 2;
472
+ lines.push(...choices.map((c) => ` ${accent(pad(c.value, w))}${muted(c.note ?? "")}`));
473
+ }
474
+ else if (command.paths)
475
+ lines.push(muted(` takes a ${command.paths === "dir" ? "folder" : "file or folder"}: press Tab to see them`));
476
+ else if (!command.usage)
477
+ lines.push(muted(" no options; press Enter to run it"));
478
+ return lines;
479
+ }
480
+ /** Splits input into words, honouring "quoted strings". */
481
+ export function parse(input) {
482
+ return [...input.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((m) => m[1] ?? m[2] ?? m[3]);
483
+ }
484
+ export async function execute(words, ctx) {
485
+ const [name, ...args] = words;
486
+ if (!name)
487
+ return [];
488
+ const command = COMMANDS[name.toLowerCase()];
489
+ if (!command) {
490
+ const lower = name.toLowerCase();
491
+ const near = Object.keys(COMMANDS)
492
+ .filter((c) => !COMMANDS[c].hidden)
493
+ .map((c) => [c, distance(lower, c)])
494
+ .filter(([c, d]) => d <= (c.length > 3 ? 2 : 1))
495
+ .sort((a, b) => a[1] - b[1])[0];
496
+ // A file name on its own: the visitor probably meant to read it.
497
+ const asFile = lookup(resolve(ctx.cwd, name)) ? `cat ${name}` : isDir(resolve(ctx.cwd, name)) ? `cd ${name}` : null;
498
+ const suggestion = asFile ?? (near ? [near[0], ...args].join(" ") : null);
499
+ return [
500
+ error(`ekurtsh: command not found: ${name}`),
501
+ suggestion ? muted("Did you mean ") + accent(suggestion) + muted("?") : muted("Type ") + accent("help") + muted(" to see what I can do."),
502
+ ];
503
+ }
504
+ return command.run(args, ctx);
505
+ }
506
+ export const runLine = (input, ctx) => execute(parse(input.trim()), ctx);