ekurt 0.0.0-stage → 1.0.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.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Tab completion for readline: command names first, then the first argument (a command's fixed
3
+ * choices and, for path commands, the entries of the folder being typed).
4
+ */
5
+ import { COMMANDS } from "./commands.js";
6
+ import { list, resolve } from "./fs.js";
7
+ function candidates(name, partial, cwd, first) {
8
+ const command = COMMANDS[name];
9
+ const out = first ? (command.choices?.() ?? []).map((c) => ({ insert: c.value })) : [];
10
+ if (command.paths) {
11
+ const slash = partial.lastIndexOf("/");
12
+ const dirPart = slash >= 0 ? partial.slice(0, slash + 1) : "";
13
+ for (const e of list(resolve(cwd, dirPart || ".")) ?? []) {
14
+ if (command.paths === "dir" && e.type !== "dir")
15
+ continue;
16
+ const dir = e.type === "dir";
17
+ out.push({ insert: `${dirPart}${e.name}${dir ? "/" : ""}`, dir });
18
+ }
19
+ }
20
+ const lower = partial.toLowerCase();
21
+ const seen = new Set();
22
+ return out.filter((c) => c.insert.toLowerCase().startsWith(lower) && !seen.has(c.insert) && seen.add(c.insert));
23
+ }
24
+ /** readline's completer: [what can replace `partial`, `partial`]. */
25
+ export function complete(line, cwd) {
26
+ const endsWithSpace = /\s$/.test(line);
27
+ const words = line.trimStart().split(/\s+/).filter(Boolean);
28
+ if (words.length <= 1 && !endsWithSpace) {
29
+ const prefix = (words[0] ?? "").toLowerCase();
30
+ const names = Object.keys(COMMANDS).filter((c) => !COMMANDS[c].hidden && c.startsWith(prefix));
31
+ return [names.length === 1 ? [`${names[0]} `] : names, words[0] ?? ""];
32
+ }
33
+ const name = words[0].toLowerCase();
34
+ const command = COMMANDS[name];
35
+ if (!command || command.hidden)
36
+ return [[], ""];
37
+ const partial = endsWithSpace ? "" : words.at(-1);
38
+ const before = words.slice(1, endsWithSpace ? undefined : -1);
39
+ // Flags such as `ls -l` do not count as the first argument.
40
+ const first = before.every((w) => w.startsWith("-"));
41
+ if (!first && !command.paths)
42
+ return [[], partial];
43
+ const options = candidates(name, partial, cwd, first);
44
+ if (options.length === 1)
45
+ return [[options[0].insert + (options[0].dir ? "" : " ")], partial];
46
+ return [options.map((o) => o.insert), partial];
47
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The same read-only filesystem as the Terminal on ekurt.dev, made of the site's real content:
3
+ *
4
+ * ~/about-me.md ~/cv.pdf ~/bookmarks.txt
5
+ * ~/projects/<slug>.md
6
+ * ~/blog/<series>/<slug>.md
7
+ */
8
+ import { posts, postsIn, projects, SERIES, SERIES_ORDER, siteUrl } from "../content.js";
9
+ const md = (slug) => `${slug}.md`;
10
+ const unmd = (name) => name.replace(/\.md$/, "");
11
+ /** Resolves `arg` against `cwd`. Supports ~, /, . and .. */
12
+ export function resolve(cwd, arg = "~") {
13
+ const absolute = arg.startsWith("~") || arg.startsWith("/");
14
+ const parts = arg.replace(/^~\/?|^\//, "").split("/").filter(Boolean);
15
+ const out = absolute ? [] : [...cwd];
16
+ for (const part of parts) {
17
+ if (part === ".")
18
+ continue;
19
+ if (part === "..")
20
+ out.pop();
21
+ else
22
+ out.push(part);
23
+ }
24
+ return out;
25
+ }
26
+ export const display = (path) => (path.length ? `~/${path.join("/")}` : "~");
27
+ const seriesPresent = () => SERIES_ORDER.filter((s) => postsIn(s).length);
28
+ export function list(path) {
29
+ const [root, sub, extra] = path;
30
+ if (!root) {
31
+ return [
32
+ { name: "blog", type: "dir" },
33
+ { name: "projects", type: "dir" },
34
+ { name: "about-me.md", type: "file" },
35
+ { name: "bookmarks.txt", type: "file" },
36
+ { name: "cv.pdf", type: "file" },
37
+ ];
38
+ }
39
+ if (root === "projects" && !sub)
40
+ return projects().map((p) => ({ name: md(p.slug), type: "file" }));
41
+ if (root === "blog" && !sub)
42
+ return seriesPresent().map((s) => ({ name: s, type: "dir" }));
43
+ if (root === "blog" && sub && !extra) {
44
+ const inSeries = postsIn(sub);
45
+ return inSeries.length ? inSeries.map((p) => ({ name: md(p.slug), type: "file" })) : null;
46
+ }
47
+ return null;
48
+ }
49
+ export const isDir = (path) => list(path) !== null;
50
+ /** The file at `path`; "projects/ruta" works as well as "projects/ruta.md". */
51
+ export function lookup(path) {
52
+ const [root, sub, extra] = path;
53
+ if (path.length === 1) {
54
+ if (root === "about-me.md" || root === "about-me")
55
+ return { kind: "about" };
56
+ if (root === "bookmarks.txt" || root === "bookmarks")
57
+ return { kind: "bookmarks" };
58
+ if (root === "cv.pdf")
59
+ return { kind: "cv" };
60
+ }
61
+ if (path.length === 2 && root === "projects") {
62
+ const project = projects().find((p) => p.slug === unmd(sub));
63
+ return project ? { kind: "project", project } : null;
64
+ }
65
+ if (path.length === 3 && root === "blog") {
66
+ const post = posts().find((p) => p.series === sub && p.slug === unmd(extra));
67
+ return post ? { kind: "post", post } : null;
68
+ }
69
+ return null;
70
+ }
71
+ /** Where a post lives in the tree. */
72
+ export const postPath = (post) => ["blog", post.series, md(post.slug)];
73
+ export const projectPath = (project) => ["projects", md(project.slug)];
74
+ /** The page on ekurt.dev for a path, used by `open`. */
75
+ export function urlFor(path) {
76
+ const [root, sub, extra] = path;
77
+ if (!path.length)
78
+ return siteUrl("/");
79
+ if (root === "about-me.md")
80
+ return siteUrl("/about");
81
+ if (root === "cv.pdf")
82
+ return siteUrl("/cv.pdf");
83
+ if (root === "bookmarks.txt")
84
+ return siteUrl("/bookmarks");
85
+ if (root === "projects")
86
+ return siteUrl(sub ? `/projects/${unmd(sub)}` : "/projects");
87
+ if (root === "blog")
88
+ return siteUrl(extra ? `/blog/${unmd(extra)}` : "/blog");
89
+ return null;
90
+ }
91
+ export const seriesLabel = (id) => SERIES[id]?.label ?? id;
@@ -0,0 +1,199 @@
1
+ /**
2
+ * The shell around the commands: an interactive prompt on a TTY, a single command from the
3
+ * command line (`npx ekurt cat about-me.md`), or a script piped into stdin.
4
+ */
5
+ import * as readline from "node:readline";
6
+ import open from "open";
7
+ import { boot, panic } from "../ui/boot.js";
8
+ import { welcome } from "../ui/pages.js";
9
+ import { fullscreen } from "../ui/screen.js";
10
+ import { dir, error, muted, ok, url } from "../ui/style.js";
11
+ import { measure } from "../ui/text.js";
12
+ import { execute, parse } from "./commands.js";
13
+ import { complete } from "./complete.js";
14
+ import { display } from "./fs.js";
15
+ import { profile } from "../content.js";
16
+ const print = (lines) => {
17
+ if (lines.length)
18
+ process.stdout.write(lines.join("\n") + "\n");
19
+ };
20
+ export const prompt = (cwd) => `${ok("visitor@ekurt")} ${dir(display(cwd))} ${muted("%")} `;
21
+ async function openUrl(href) {
22
+ try {
23
+ const child = await open(href);
24
+ // A missing opener (e.g. no xdg-open on a server) fails after spawning.
25
+ return await new Promise((done) => {
26
+ child.once("error", () => done(false));
27
+ setTimeout(() => done(true), 150);
28
+ });
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ /** For one-off commands and piped scripts: no questions, no full-screen views. */
35
+ function batchContext(state) {
36
+ return {
37
+ get cwd() {
38
+ return state.cwd;
39
+ },
40
+ setCwd: (path) => {
41
+ state.cwd = path;
42
+ },
43
+ history: state.history,
44
+ bootedAt: Date.now(),
45
+ interactive: false,
46
+ ask: async () => null,
47
+ fullscreen: async () => { },
48
+ openUrl: process.stdout.isTTY ? openUrl : async () => false,
49
+ clear: () => { },
50
+ exit: () => { },
51
+ panic: async () => { },
52
+ width: process.stdout.isTTY ? measure() : 88,
53
+ };
54
+ }
55
+ /** `npx ekurt ls projects`: runs the words as one command. */
56
+ export async function runOnce(words) {
57
+ const state = { cwd: [], history: [words.join(" ")] };
58
+ print(await execute(words, batchContext(state)));
59
+ }
60
+ /** `echo "ls; cat about-me.md" | npx ekurt`: every line (or `;`-separated part) as a command, echoed after a prompt. */
61
+ export async function runScript(source) {
62
+ const state = { cwd: [], history: [] };
63
+ const ctx = batchContext(state);
64
+ const commands = source
65
+ .split(/\r?\n|;/)
66
+ .map((l) => l.trim())
67
+ .filter((l) => l && !l.startsWith("#"));
68
+ for (const command of commands) {
69
+ state.history.push(command);
70
+ print([prompt(state.cwd) + command]);
71
+ print(await execute(parse(command), ctx));
72
+ if (/^(exit|quit|logout)\b/.test(command))
73
+ break;
74
+ }
75
+ }
76
+ const INTERRUPTED = Symbol("interrupted");
77
+ class Shell {
78
+ cwd = [];
79
+ history = [];
80
+ bootedAt = Date.now();
81
+ rl;
82
+ pending = null;
83
+ done = false;
84
+ constructor() {
85
+ this.rl = this.createInterface([]);
86
+ }
87
+ createInterface(history) {
88
+ const rl = readline.createInterface({
89
+ input: process.stdin,
90
+ output: process.stdout,
91
+ terminal: true,
92
+ history,
93
+ historySize: 500,
94
+ removeHistoryDuplicates: true,
95
+ tabSize: 4,
96
+ completer: (line) => complete(line, this.cwd),
97
+ });
98
+ rl.on("SIGINT", () => {
99
+ if (this.pending) {
100
+ // Like a real shell: show ^C, drop the line, give a fresh prompt.
101
+ process.stdout.write(muted("^C"));
102
+ this.pending.abort();
103
+ }
104
+ });
105
+ return rl;
106
+ }
107
+ /** One line of input; null when input ends (Ctrl+D), INTERRUPTED on Ctrl+C. */
108
+ read(query) {
109
+ return new Promise((resolve) => {
110
+ const controller = new AbortController();
111
+ this.pending = controller;
112
+ const onClose = () => resolve(null);
113
+ this.rl.once("close", onClose);
114
+ controller.signal.addEventListener("abort", () => {
115
+ this.rl.off("close", onClose);
116
+ this.pending = null;
117
+ resolve(INTERRUPTED);
118
+ });
119
+ this.rl.question(query, { signal: controller.signal }, (answer) => {
120
+ this.rl.off("close", onClose);
121
+ this.pending = null;
122
+ resolve(answer);
123
+ });
124
+ });
125
+ }
126
+ /** Hands the terminal to a full-screen view, then takes it back with history intact. */
127
+ async suspend(run) {
128
+ const history = [...(this.rl.history ?? [])];
129
+ this.rl.close();
130
+ try {
131
+ await run();
132
+ }
133
+ finally {
134
+ this.rl = this.createInterface(history);
135
+ }
136
+ }
137
+ context() {
138
+ const shell = this;
139
+ return {
140
+ get cwd() {
141
+ return shell.cwd;
142
+ },
143
+ setCwd: (path) => {
144
+ shell.cwd = path;
145
+ },
146
+ history: this.history,
147
+ bootedAt: this.bootedAt,
148
+ interactive: true,
149
+ ask: async (question) => {
150
+ const answer = await this.read(question);
151
+ return typeof answer === "string" ? answer : null;
152
+ },
153
+ fullscreen: (view) => this.suspend(() => fullscreen(view)),
154
+ openUrl,
155
+ clear: () => {
156
+ process.stdout.write("\u001B[2J\u001B[3J\u001B[H");
157
+ },
158
+ exit: () => {
159
+ this.done = true;
160
+ },
161
+ panic: () => this.suspend(async () => {
162
+ await panic(Math.floor((Date.now() - this.bootedAt) / 1000));
163
+ this.cwd = [];
164
+ this.bootedAt = Date.now();
165
+ print(welcome(measure()));
166
+ }),
167
+ width: measure(),
168
+ };
169
+ }
170
+ async loop() {
171
+ while (!this.done) {
172
+ const line = await this.read(prompt(this.cwd));
173
+ if (line === null) {
174
+ process.stdout.write("\n");
175
+ break;
176
+ }
177
+ if (line === INTERRUPTED)
178
+ continue;
179
+ const command = line.trim();
180
+ if (!command)
181
+ continue;
182
+ this.history.push(command);
183
+ try {
184
+ print(await execute(parse(command), this.context()));
185
+ }
186
+ catch (e) {
187
+ print([error(`ekurtsh: ${e instanceof Error ? e.message : String(e)}`)]);
188
+ }
189
+ }
190
+ this.rl.close();
191
+ print([muted("logout"), muted("Thanks for stopping by — ") + url(profile().url) + muted(" has the rest.")]);
192
+ }
193
+ }
194
+ export async function interactive({ showBoot }) {
195
+ if (showBoot)
196
+ await boot();
197
+ print(welcome(measure()));
198
+ await new Shell().loop();
199
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The start-up screen from ekurt.dev: the e_ mark with a blinking underscore and a progress bar,
3
+ * 1.5 s, skipped by any key. Then the kernel panic screen that the hidden `panic` command shows.
4
+ */
5
+ import { emitKeypressEvents } from "node:readline";
6
+ import chalk from "chalk";
7
+ import { COLORS, bold, error, muted, ok } from "./style.js";
8
+ import { draw, enterScreen, fullscreen, leaveScreen } from "./screen.js";
9
+ const DURATION_MS = 1500;
10
+ const BAR = 28;
11
+ const E = [" ▄▄████▄▄ ", " ▄██▀ ▀██▄ ", " ████████████ ", " ██▄ ", " ▀██▄▄▄▄▄██▀ ", " ▀▀▀▀ "];
12
+ const UNDERSCORE = ["", "", "", "", " ▄▄▄▄▄▄▄▄", " ▀▀▀▀▀▀▀▀"];
13
+ export function logo(cursorOn = true) {
14
+ return E.map((row, i) => chalk.hex("#f2f4f8")(row) + (cursorOn ? ok(UNDERSCORE[i]) : " ".repeat(UNDERSCORE[i].length)));
15
+ }
16
+ function frame(elapsed) {
17
+ const filled = Math.round((Math.min(elapsed, DURATION_MS) / DURATION_MS) * BAR);
18
+ const bar = chalk.hex("#f2f4f8")("━".repeat(filled)) + chalk.hex(COLORS.surfaceHi)("━".repeat(BAR - filled));
19
+ const blink = Math.floor(elapsed / 500) % 2 === 0;
20
+ return [...logo(blink), "", "", " " + bar];
21
+ }
22
+ /** Plays the start-up screen. Resolves when it ends or a key skips it; Ctrl+C quits. */
23
+ export function boot() {
24
+ const stdin = process.stdin;
25
+ if (!process.stdout.isTTY || !stdin.isTTY)
26
+ return Promise.resolve();
27
+ return new Promise((resolve) => {
28
+ emitKeypressEvents(stdin);
29
+ stdin.setRawMode(true);
30
+ stdin.resume();
31
+ enterScreen();
32
+ const start = Date.now();
33
+ const timer = setInterval(() => {
34
+ const elapsed = Date.now() - start;
35
+ draw(frame(elapsed));
36
+ if (elapsed >= DURATION_MS + 200)
37
+ finish();
38
+ }, 50);
39
+ const onKey = (_, key) => {
40
+ if (key?.ctrl && key.name === "c") {
41
+ finish();
42
+ process.exit(130);
43
+ }
44
+ finish();
45
+ };
46
+ function finish() {
47
+ clearInterval(timer);
48
+ stdin.off("keypress", onKey);
49
+ leaveScreen();
50
+ stdin.setRawMode(false);
51
+ stdin.pause();
52
+ resolve();
53
+ }
54
+ stdin.on("keypress", onKey);
55
+ draw(frame(0));
56
+ });
57
+ }
58
+ const PANIC_LOG = (uptime) => [
59
+ `panic(cpu 0 caller 0xffffff8012a4b3c0): "Kernel panic requested by visitor (ekurtsh: panic)"`,
60
+ "",
61
+ "Backtrace (CPU 0), Frame : Return Address",
62
+ " 0xffffff8012a4b3c0 : ekurtsh.commands.panic",
63
+ " 0xffffff8012a4b410 : node.readline.onLine",
64
+ " 0xffffff8012a4b480 : ekurtos.shell.terminal",
65
+ " 0xffffff8012a4b4f0 : ekurtos.kernel.main",
66
+ "",
67
+ "Process name corresponding to current thread: ekurtsh",
68
+ `Kernel version: ekurtOS 1.0 (Node.js ${process.versions.node})`,
69
+ `System uptime in seconds: ${uptime}`,
70
+ ];
71
+ /** The kernel panic screen: the log types itself out, then any key reboots. */
72
+ class Panic {
73
+ center = false;
74
+ shown = 0;
75
+ log;
76
+ redraw = () => { };
77
+ timer;
78
+ constructor(uptime) {
79
+ this.log = PANIC_LOG(uptime);
80
+ this.timer = setInterval(() => {
81
+ this.shown++;
82
+ this.redraw();
83
+ if (this.shown >= this.log.length)
84
+ clearInterval(this.timer);
85
+ }, 70);
86
+ }
87
+ attach(redraw) {
88
+ this.redraw = redraw;
89
+ }
90
+ render() {
91
+ const lines = ["", ...this.log.slice(0, this.shown).map((l) => " " + chalk.hex("#c9ced8")(l))];
92
+ if (this.shown >= this.log.length) {
93
+ lines.push("", "", ` ${bold("e")}${error(bold("_"))} ${bold("ekurtOS ran into a problem and needs to restart")}`, "", muted(" Something went wrong while running this shell. Nothing is lost — this is just a CV."), muted(" Restart to start fresh from the home directory."), "", ` ${chalk.bgHex(COLORS.focus).hex("#ffffff").bold(" Reboot ")} ${muted("press any key")}`);
94
+ }
95
+ return lines;
96
+ }
97
+ key() {
98
+ if (this.shown < this.log.length) {
99
+ // A key during the log skips to the end of it.
100
+ this.shown = this.log.length;
101
+ clearInterval(this.timer);
102
+ return;
103
+ }
104
+ return "quit";
105
+ }
106
+ }
107
+ export async function panic(uptime) {
108
+ await fullscreen(new Panic(uptime));
109
+ await boot();
110
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * A small syntax highlighter for the code in blog posts (js/jsx/ts, bash, html, css, json, env),
3
+ * coloured like the GitHub dark theme the site uses. It works line by line and remembers only
4
+ * open block comments, which is all the lessons need.
5
+ */
6
+ import { COLORS, hex, italic } from "./style.js";
7
+ const keyword = hex(COLORS.error);
8
+ const string = hex(COLORS.string);
9
+ const comment = (s) => italic(hex(COLORS.comment)(s));
10
+ const constant = hex(COLORS.accent);
11
+ const fn = hex(COLORS.dir);
12
+ const tag = hex(COLORS.ok);
13
+ const variable = hex(COLORS.orange);
14
+ const JS_KEYWORDS = new Set(("const let var function return if else for while do switch case break continue new class extends import from export " +
15
+ "default async await try catch finally throw typeof instanceof in of this yield delete void super static get set as " +
16
+ "type interface enum implements").split(" "));
17
+ const JS_CONSTANTS = new Set(["true", "false", "null", "undefined", "NaN", "Infinity"]);
18
+ const STRINGS = [/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/y, string];
19
+ const js = [
20
+ [/\/\/.*/y, comment],
21
+ [/\/\*.*?\*\//y, comment],
22
+ STRINGS,
23
+ [/<\/?[A-Za-z][\w.]*|\/?>/y, tag],
24
+ [/\b\d[\d_]*(\.\d+)?\b/y, constant],
25
+ [/[A-Za-z_$][\w$]*(?=\s*\()/y, (s) => (JS_KEYWORDS.has(s) ? keyword(s) : fn(s))],
26
+ [/[A-Za-z_$][\w$]*/y, (s) => (JS_KEYWORDS.has(s) ? keyword(s) : JS_CONSTANTS.has(s) ? constant(s) : s)],
27
+ [/=>|[=!]==?|&&|\|\||\?\?|\.\.\./y, keyword],
28
+ ];
29
+ const bash = [
30
+ [/(?<=^|\s)#.*/y, comment],
31
+ STRINGS,
32
+ [/^\s*\$(?=\s)/y, hex(COLORS.muted)],
33
+ [/\$\{?\w+\}?/y, variable],
34
+ [/(?<=\s)--?[\w-]+/y, constant],
35
+ [/(?<=^\s*(?:\$\s+)?)[\w./-]+/y, fn],
36
+ [/(?<=(?:&&|\||;)\s*)[\w./-]+/y, fn],
37
+ [/&&|\|\||[|;>]/y, keyword],
38
+ ];
39
+ const html = [
40
+ [/<!--.*?-->/y, comment],
41
+ [/<\/?[A-Za-z][\w-]*|\/?>/y, tag],
42
+ [/"[^"]*"|'[^']*'/y, string],
43
+ [/[A-Za-z-:@]+(?==)/y, constant],
44
+ ];
45
+ const css = [
46
+ [/\/\*.*?\*\//y, comment],
47
+ STRINGS,
48
+ [/#[0-9a-fA-F]{3,8}\b/y, constant],
49
+ [/-?\d+(\.\d+)?(px|rem|em|%|vh|vw|s|ms|fr|deg)?/y, constant],
50
+ [/[\w-]+(?=\s*:[^:])/y, constant],
51
+ [/@[\w-]+/y, keyword],
52
+ [/[.#][\w-]+/y, tag],
53
+ ];
54
+ const json = [
55
+ [/"(?:\\.|[^"\\])*"(?=\s*:)/y, constant],
56
+ [/"(?:\\.|[^"\\])*"/y, string],
57
+ [/-?\d+(\.\d+)?|true|false|null/y, constant],
58
+ ];
59
+ const env = [
60
+ [/#.*/y, comment],
61
+ [/^[A-Z_][A-Z0-9_]*(?==)/y, constant],
62
+ [/(?<==).+/y, string],
63
+ ];
64
+ const LANGUAGES = {
65
+ js,
66
+ jsx: js,
67
+ ts: js,
68
+ tsx: js,
69
+ javascript: js,
70
+ typescript: js,
71
+ mjs: js,
72
+ bash,
73
+ sh: bash,
74
+ shell: bash,
75
+ zsh: bash,
76
+ console: bash,
77
+ html,
78
+ xml: html,
79
+ svg: html,
80
+ css,
81
+ scss: css,
82
+ json,
83
+ env,
84
+ dotenv: env,
85
+ ini: env,
86
+ };
87
+ function tokenize(line, rules) {
88
+ let out = "";
89
+ let plain = "";
90
+ let i = 0;
91
+ outer: while (i < line.length) {
92
+ for (const [re, paint] of rules) {
93
+ re.lastIndex = i;
94
+ const m = re.exec(line);
95
+ if (m && m[0].length) {
96
+ out += plain + paint(m[0]);
97
+ plain = "";
98
+ i += m[0].length;
99
+ continue outer;
100
+ }
101
+ }
102
+ plain += line[i++];
103
+ }
104
+ return out + plain;
105
+ }
106
+ /** Highlights `code`, returning one styled string per line. Unknown languages stay plain. */
107
+ export function highlight(code, lang) {
108
+ const lines = code.replace(/\t/g, " ").split("\n");
109
+ const rules = LANGUAGES[lang.toLowerCase()];
110
+ if (!rules)
111
+ return lines;
112
+ const blockComments = rules === js || rules === css;
113
+ let inComment = false;
114
+ return lines.map((line) => {
115
+ if (!blockComments)
116
+ return tokenize(line, rules);
117
+ let prefix = "";
118
+ let rest = line;
119
+ if (inComment) {
120
+ const end = line.indexOf("*/");
121
+ if (end === -1)
122
+ return comment(line);
123
+ prefix = comment(line.slice(0, end + 2));
124
+ rest = line.slice(end + 2);
125
+ inComment = false;
126
+ }
127
+ const open = rest.lastIndexOf("/*");
128
+ if (open !== -1 && rest.indexOf("*/", open) === -1 && !/\/\/.*\/\*/.test(rest)) {
129
+ inComment = true;
130
+ return prefix + tokenize(rest.slice(0, open), rules) + comment(rest.slice(open));
131
+ }
132
+ return prefix + tokenize(rest, rules);
133
+ });
134
+ }