@soleone/showcase-terminal 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Soleone
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # showcase-terminal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Let people try a CLI for real without installing anything: a static page that boots a Node.js sandbox ([WebContainers](https://webcontainers.io)) in the visitor's browser and opens a real shell, with the project's own code and sample data mounted.
4
+
5
+ ```sh
6
+ npm install --save-dev @soleone/showcase-terminal
7
+
8
+ showcase-terminal --serve # builds demo/browser into dist/browser, serves it on 127.0.0.1:4321
9
+ showcase-terminal path/to/recipe --out dist/demo
10
+ ```
11
+
12
+ It is one way to give a CLI the live demo that [showcase](https://github.com/Soleone/showcase) grades S, and it reads the project's facts from the same `showcase.json`. It doesn't need showcase installed.
13
+
14
+ Keep the recipe folder in the project itself (`demo/browser/` by default), so the project owns its sample data and stand-ins. Relative paths in it resolve from the recipe folder. It holds `terminal.json`:
15
+
16
+ - `project`: the project folder. Title, pitch and repo come from its `showcase.json`, and the page's disclosure line is written from `demo.externals` (each stand-in's `note`).
17
+ - `mount`: target path in the sandbox → `{ from, include }`. `from` may use `~` and `$VARS`; `include` limits the top-level entries copied. Binary files (images, loops) are mounted too.
18
+ - `env`: values may use `~` (the sandbox home, always `/home/demo`) and `$PATH` (costs one extra process at boot; write the PATH out instead).
19
+ - `setup`: commands run before the shell opens, e.g. seeding sample data dated relative to today. Until they finish, a spinner stands in for the prompt and keys typed in the terminal are dropped, so nothing ends up in front of `start`.
20
+ - `start`: a command typed into the shell once setup is done, to open the program right away (e.g. a TUI). The visitor sees it run and can run it again after quitting.
21
+ - `onTheme`: a command run whenever the visitor picks a theme. Before it runs, the page writes `~/.config/showcase/theme.json` with the theme's colors and the full terminal palette (`palette`, as hex), so a program that draws its own colors can follow the page. The file is also written once before `setup`.
22
+ - `welcome`, `hints` (buttons that type a command), `seed` (a browser module that adds files computed at visit time, such as dates relative to today), and overrides for `title`, `pitch`, `repo`, `disclosure`, `defaultTheme` (a name from `themes.json`, default the first).
23
+ - `skin`: a folder or URL with the page's look, `themes.json` (palettes, same shape as `page/themes.json`) and `skin.css` (fonts and other touches, loaded after the page's styles). Either may be left out. Without a skin the page is plain: a dark and a light theme and system fonts.
24
+
25
+ The output is static: `index.html`, `files.json`, `terminal.json`, `themes.json`, `skin.css`, `fonts/` and a `vercel.json` with the COOP/COEP headers the sandbox needs.
26
+
27
+ The terminal font is JetBrainsMono Nerd Font Mono, self-hosted as WOFF2 (about 600 KB per weight) so CLI icons render. `page/fonts/build.sh` rebuilds it from a pinned Nerd Fonts release, keeping the Basic Multilingual Plane and dropping the Material Design plane.
28
+
29
+ Sandbox quirks found so far:
30
+
31
+ - Mounted files are not executable; `chmod` them from a setup script (one process is faster than several setup commands).
32
+ - Extensionless ES modules exit silently, so command shims are CommonJS that `import()` the real entry point.
33
+ - A top-level `for await` fails to parse; read streams with events.
34
+ - Model calls: point the project at a stand-in (a setting that names the model command) that returns canned output, so nothing leaves the browser.
35
+
36
+ WebContainers is free for personal and open-source use; check the StackBlitz license before using it commercially.
37
+
38
+ The page has a theme picker when there is more than one theme (the choice is remembered in the visitor's browser). A theme colors the page and the terminal's 16 ANSI colors together, so whatever the CLI prints follows it; the bright colors are derived from the normal ones.
39
+
40
+ From code:
41
+
42
+ ```js
43
+ import { buildTerminal, serveTerminal } from "@soleone/showcase-terminal";
44
+
45
+ await buildTerminal("demo/browser", "dist/browser");
46
+ ```
47
+
48
+ ## Hosting
49
+
50
+ Deploy the output folder to any static host that can set the COOP/COEP headers. On Vercel the generated `vercel.json` sets them: `vercel deploy --prod` from the folder.
51
+
52
+ ## License
53
+
54
+ MIT
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { buildTerminal, serveTerminal } from "../src/terminal.js";
5
+
6
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
7
+
8
+ const usage = `showcase-terminal ${version}: build an in-browser terminal demo for a CLI.
9
+
10
+ Usage:
11
+ showcase-terminal [recipe] Build the page from a folder with terminal.json (default demo/browser)
12
+
13
+ Options:
14
+ --out <dir> Where to write the page (default dist/browser)
15
+ --serve Serve the page on 127.0.0.1 after building it
16
+ --port <n> Port for --serve (default 4321)
17
+ --help, -h Show this help
18
+ --version Show the version`;
19
+
20
+ async function main() {
21
+ const { values, positionals } = parseArgs({
22
+ allowPositionals: true,
23
+ options: {
24
+ out: { type: "string" },
25
+ serve: { type: "boolean" },
26
+ port: { type: "string" },
27
+ help: { type: "boolean", short: "h" },
28
+ version: { type: "boolean" },
29
+ },
30
+ });
31
+ if (values.version) return console.log(version);
32
+ if (values.help) return console.log(usage);
33
+ if (positionals.length > 1) throw new Error("showcase-terminal takes a single recipe folder");
34
+
35
+ const { out, bytes } = await buildTerminal(positionals[0] ?? "demo/browser", values.out ?? "dist/browser");
36
+ console.log(`Built ${out} (${Math.round(bytes / 1024)} KB of files)`);
37
+ if (!values.serve) return;
38
+ const port = Number(values.port ?? 4321);
39
+ if (!Number.isInteger(port)) throw new Error("--port must be a number");
40
+ await serveTerminal(out, port);
41
+ console.log(`Serving at http://127.0.0.1:${port} (Ctrl-C to stop)`);
42
+ }
43
+
44
+ main().catch((error) => {
45
+ console.error(error.message);
46
+ process.exitCode = 1;
47
+ });
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@soleone/showcase-terminal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Build a static page that runs a CLI for real in the visitor's browser (WebContainers).",
5
+ "license": "MIT",
6
+ "author": "Soleone",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Soleone/showcase-terminal.git"
10
+ },
11
+ "homepage": "https://github.com/Soleone/showcase-terminal#readme",
12
+ "bugs": "https://github.com/Soleone/showcase-terminal/issues",
13
+ "keywords": [
14
+ "demo",
15
+ "cli",
16
+ "terminal",
17
+ "webcontainers",
18
+ "showcase"
19
+ ],
20
+ "type": "module",
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "exports": {
28
+ ".": "./src/terminal.js",
29
+ "./package.json": "./package.json"
30
+ },
31
+ "bin": {
32
+ "showcase-terminal": "./bin/showcase-terminal.js"
33
+ },
34
+ "files": [
35
+ "bin/",
36
+ "src/",
37
+ "page/",
38
+ "!page/fonts/build.sh",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "scripts": {
43
+ "test": "node --test",
44
+ "release": "release-it",
45
+ "release:dry-run": "npm test && release-it --dry-run"
46
+ },
47
+ "devDependencies": {
48
+ "@release-it/conventional-changelog": "^10.0.6",
49
+ "release-it": "^19.2.4"
50
+ },
51
+ "overrides": {
52
+ "release-it": {
53
+ "undici": "^7.30.0"
54
+ }
55
+ }
56
+ }
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ https://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,453 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Try it in your browser</title>
7
+ <link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@webcontainer/api@1.6.4/+esm" crossorigin>
8
+ <link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@xterm/xterm@6.0.0/+esm" crossorigin>
9
+ <link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@xterm/addon-webgl@0.19.0/+esm" crossorigin>
10
+ <link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/@xterm/addon-fit@0.11.0/+esm" crossorigin>
11
+ <link rel="preload" href="files.json" as="fetch" crossorigin>
12
+ <link rel="preload" href="terminal.json" as="fetch" crossorigin>
13
+ <link rel="preload" href="themes.json" as="fetch" crossorigin>
14
+ <link rel="preload" href="fonts/JetBrainsMonoNerdFontMono-Regular.woff2" as="font" type="font/woff2" crossorigin>
15
+ <link rel="preload" href="fonts/JetBrainsMonoNerdFontMono-Bold.woff2" as="font" type="font/woff2" crossorigin>
16
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@xterm/xterm@6.0.0/css/xterm.css" crossorigin>
17
+ <script>
18
+ // Puts the visitor's theme on before first paint (themes.js saves the resolved colors when one is picked).
19
+ try {
20
+ const saved = JSON.parse(localStorage.getItem("browser-terminal.theme"));
21
+ for (const [name, value] of Object.entries(saved.vars)) document.documentElement.style.setProperty(`--${name}`, value);
22
+ document.documentElement.style.colorScheme = document.documentElement.dataset.theme = saved.mode;
23
+ } catch {}
24
+ </script>
25
+ <style>
26
+ /* JetBrains Mono with Nerd Font icons (SIL OFL, fonts/OFL.txt), self-hosted; see fonts/build.sh. */
27
+ @font-face {
28
+ font-family: "JetBrainsMono Nerd Font Mono";
29
+ src: url("fonts/JetBrainsMonoNerdFontMono-Regular.woff2") format("woff2");
30
+ font-weight: 400;
31
+ font-display: block;
32
+ }
33
+ @font-face {
34
+ font-family: "JetBrainsMono Nerd Font Mono";
35
+ src: url("fonts/JetBrainsMonoNerdFontMono-Bold.woff2") format("woff2");
36
+ font-weight: 700;
37
+ font-display: block;
38
+ }
39
+ /* The plain look until themes.json has applied a theme. A skin (skin.css, themes.json) brings its own. */
40
+ :root {
41
+ color-scheme: dark;
42
+ --page: #111113;
43
+ --ink: #d4d4d8;
44
+ --ink-strong: #fafafa;
45
+ --muted: #a1a1aa;
46
+ --accent: #60a5fa;
47
+ --surface: #1c1c1f;
48
+ --line: #2e2e33;
49
+ --terminal: #0b0b0c;
50
+ }
51
+ @media (prefers-color-scheme: light) {
52
+ :root:not([data-theme="dark"]) {
53
+ color-scheme: light;
54
+ --page: #fafafa;
55
+ --ink: #27272a;
56
+ --ink-strong: #09090b;
57
+ --muted: #52525b;
58
+ --accent: #2563eb;
59
+ --surface: #f4f4f5;
60
+ --line: #e4e4e7;
61
+ --terminal: #ffffff;
62
+ }
63
+ }
64
+ :root[data-theme="light"] {
65
+ color-scheme: light;
66
+ --page: #fafafa;
67
+ --ink: #27272a;
68
+ --ink-strong: #09090b;
69
+ --muted: #52525b;
70
+ --accent: #2563eb;
71
+ --surface: #f4f4f5;
72
+ --line: #e4e4e7;
73
+ --terminal: #ffffff;
74
+ }
75
+ * { box-sizing: border-box; }
76
+ html, body { margin: 0; min-height: 100%; }
77
+ body {
78
+ background: var(--page);
79
+ color: var(--ink);
80
+ font: 16px/1.5 ui-sans-serif, system-ui, sans-serif;
81
+ display: flex;
82
+ flex-direction: column;
83
+ min-height: 100vh;
84
+ }
85
+ header, main, footer { width: 100%; max-width: 1120px; margin: 0 auto; padding: 0 16px; }
86
+ header { padding-top: 32px; display: flex; flex-wrap: wrap; align-items: end; justify-content: space-between; gap: 8px 24px; }
87
+ h1 { margin: 0; color: var(--ink-strong); font-size: clamp(28px, 5vw, 44px); font-weight: 600; line-height: 1.05; letter-spacing: -0.03em; }
88
+ .pitch { margin: 8px 0 0; color: var(--muted); font-size: 17px; max-width: 62ch; text-wrap: pretty; }
89
+ a { color: var(--accent); text-underline-offset: 3px; }
90
+ .tools { display: flex; align-items: center; gap: 16px; position: relative; }
91
+ .repo { font-size: 15px; white-space: nowrap; }
92
+ #theme-button {
93
+ font: inherit; font-size: 13px; line-height: 1;
94
+ display: inline-flex; align-items: center; gap: 8px;
95
+ background: var(--surface); color: var(--ink);
96
+ border: 1px solid var(--line); border-radius: 6px; padding: 8px 11px; cursor: pointer;
97
+ }
98
+ #theme-button:hover, #theme-button:focus-visible, #theme-button[aria-expanded="true"] { border-color: var(--accent); color: var(--accent); outline: none; }
99
+ .swatch { display: inline-flex; border-radius: 99px; overflow: hidden; border: 1px solid var(--line); flex: none; }
100
+ .swatch i { width: 9px; height: 14px; display: block; }
101
+ #theme-list {
102
+ position: absolute; top: calc(100% + 8px); right: 0; z-index: 10; width: 240px; max-height: min(60vh, 420px); overflow: auto;
103
+ margin: 0; padding: 4px; list-style: none;
104
+ background: var(--surface); border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 12px 32px #0006;
105
+ }
106
+ #theme-list[hidden] { display: none; }
107
+ #theme-list li { display: flex; align-items: center; gap: 10px; padding: 7px 9px; border-radius: 5px; font-size: 14px; cursor: pointer; }
108
+ #theme-list li[aria-selected="true"] { color: var(--accent); }
109
+ #theme-list li.active { background: var(--line); }
110
+ main { flex: 1; display: flex; flex-direction: column; gap: 12px; padding-top: 24px; padding-bottom: 16px; }
111
+ .hints { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
112
+ .hints span { color: var(--muted); font-size: 14px; margin-right: 4px; }
113
+ .hints button {
114
+ font: 13px/1 "JetBrainsMono Nerd Font Mono", ui-monospace, Menlo, Consolas, monospace;
115
+ background: var(--surface);
116
+ color: var(--ink);
117
+ border: 1px solid var(--line);
118
+ border-radius: 6px;
119
+ padding: 8px 11px;
120
+ cursor: pointer;
121
+ transition: border-color 120ms, color 120ms;
122
+ }
123
+ .hints button:hover:not(:disabled), .hints button:focus-visible { border-color: var(--accent); color: var(--accent); outline: none; }
124
+ .hints button:disabled { opacity: 0.45; cursor: progress; }
125
+ .panel {
126
+ flex: 1;
127
+ min-height: 440px;
128
+ display: flex;
129
+ background: var(--terminal);
130
+ border-radius: 8px;
131
+ padding: 14px 6px 6px 14px;
132
+ overflow: hidden;
133
+ }
134
+ #terminal { flex: 1; min-width: 0; }
135
+ #terminal .xterm, #terminal .xterm-viewport, #terminal .xterm-scrollable-element { background-color: var(--terminal) !important; }
136
+ /* No focus ring inside the terminal; the blinking cursor shows focus. */
137
+ #terminal .xterm:focus, #terminal .xterm :focus { outline: none; }
138
+ footer { padding-bottom: 24px; color: var(--muted); font-size: 13px; }
139
+ @media (max-width: 600px) {
140
+ header { padding-top: 20px; }
141
+ .pitch { font-size: 16px; }
142
+ .panel { min-height: 380px; padding: 8px 2px 2px 8px; }
143
+ }
144
+ </style>
145
+ <link rel="stylesheet" href="skin.css">
146
+ </head>
147
+ <body>
148
+ <header>
149
+ <div>
150
+ <h1 id="title">Loading…</h1>
151
+ <p class="pitch" id="pitch"></p>
152
+ </div>
153
+ <div class="tools">
154
+ <a class="repo" id="repo" hidden>Source on GitHub</a>
155
+ <button id="theme-button" type="button" aria-haspopup="listbox" aria-expanded="false" hidden><span class="swatch" id="theme-swatch"></span><span id="theme-name"></span></button>
156
+ <ul id="theme-list" role="listbox" aria-label="Theme" tabindex="-1" hidden></ul>
157
+ </div>
158
+ </header>
159
+ <main>
160
+ <div class="hints" id="hints"><span>Try</span></div>
161
+ <div class="panel"><div id="terminal"></div></div>
162
+ </main>
163
+ <footer id="disclosure">Runs entirely in your browser in a WebContainers Node.js sandbox.</footer>
164
+
165
+ <script type="module">
166
+ import { WebContainer } from "https://cdn.jsdelivr.net/npm/@webcontainer/api@1.6.4/+esm";
167
+
168
+ // Start the slow parts at once and in parallel: the sandbox boot, the files, the config, the terminal code and the font.
169
+ // The sandbox home is always /home/demo, so recipes can write absolute paths into their settings.
170
+ const started = performance.now();
171
+ const timings = {};
172
+ const mark = (name) => { timings[name] = Math.round(performance.now() - started); };
173
+ window.demoTimings = timings;
174
+ const booting = crossOriginIsolated ? WebContainer.boot({ workdirName: "demo" }) : null;
175
+ const filesLoad = fetch("files.json").then((response) => response.json()).then(decode);
176
+ const configLoad = fetch("terminal.json").then((response) => response.json());
177
+ const themesLoad = fetch("themes.json").then((response) => response.json()).catch(() => []);
178
+ const terminalCode = Promise.all([
179
+ import("https://cdn.jsdelivr.net/npm/@xterm/xterm@6.0.0/+esm"),
180
+ import("https://cdn.jsdelivr.net/npm/@xterm/addon-webgl@0.19.0/+esm"),
181
+ import("https://cdn.jsdelivr.net/npm/@xterm/addon-fit@0.11.0/+esm"),
182
+ ]);
183
+ // Both weights before the terminal opens: xterm measures glyphs once and does not redraw when a font arrives.
184
+ const mono = '"JetBrainsMono Nerd Font Mono"';
185
+ const fontLoad = Promise.race([
186
+ Promise.all([document.fonts.load(`14px ${mono}`), document.fonts.load(`bold 14px ${mono}`)]),
187
+ new Promise((resolve) => setTimeout(resolve, 2500)),
188
+ ]);
189
+
190
+ const config = await configLoad;
191
+ const seedLoad = config.seed ? import(new URL(config.seed, location.href)) : null;
192
+ document.title = `${config.title}: try it in your browser`;
193
+ document.getElementById("title").textContent = config.title;
194
+ document.getElementById("pitch").textContent = config.pitch ?? "";
195
+ if (config.repo) Object.assign(document.getElementById("repo"), { href: config.repo, hidden: false });
196
+ if (config.disclosure) document.getElementById("disclosure").textContent = config.disclosure;
197
+ const themes = await themesLoad;
198
+ const storeKey = "browser-terminal.theme";
199
+ const stored = (() => { try { return JSON.parse(localStorage.getItem(storeKey))?.name; } catch { return undefined; } })();
200
+ const pick = (name) => themes.find((theme) => theme.name === name);
201
+ let current = pick(stored) ?? pick(config.defaultTheme) ?? themes[0];
202
+ // Bright ANSI colors are the normal ones lifted a quarter of the way toward the theme's brightest ink.
203
+ const lift = (color, toward) => `#${[1, 3, 5].map((at) => Math.round(parseInt(color.slice(at, at + 2), 16) * 0.75 + parseInt(toward.slice(at, at + 2), 16) * 0.25).toString(16).padStart(2, "0")).join("")}`;
204
+ const terminalColors = ({ terminal, ink, inkStrong, accent, line, ansi }) => ({
205
+ background: terminal, foreground: ink, cursor: accent, cursorAccent: terminal, selectionBackground: line, selectionForeground: inkStrong,
206
+ black: ansi.black, red: ansi.red, green: ansi.green, yellow: ansi.yellow, blue: ansi.blue, magenta: ansi.magenta, cyan: ansi.cyan, white: ansi.white,
207
+ brightBlack: ansi.brightBlack, brightRed: lift(ansi.red, inkStrong), brightGreen: lift(ansi.green, inkStrong), brightYellow: lift(ansi.yellow, inkStrong),
208
+ brightBlue: lift(ansi.blue, inkStrong), brightMagenta: lift(ansi.magenta, inkStrong), brightCyan: lift(ansi.cyan, inkStrong), brightWhite: ansi.brightWhite,
209
+ });
210
+ let term;
211
+ // The sandbox learns the theme too: ~/.config/showcase/theme.json holds the page's colors and the terminal
212
+ // palette, rewritten on every change, and the recipe's onTheme command can turn it into a program's own theme.
213
+ let sandbox = null;
214
+ let shared = Promise.resolve();
215
+ let shareTimer;
216
+ async function writeTheme(theme) {
217
+ if (!sandbox || !theme) return;
218
+ const { container, env } = sandbox;
219
+ const { name, label, mode, page, ink, inkStrong, muted, accent, surface, line, terminal } = theme;
220
+ await container.fs.mkdir(".config/showcase", { recursive: true });
221
+ await container.fs.writeFile(".config/showcase/theme.json", `${JSON.stringify({ name, label, mode, page, ink, inkStrong, muted, accent, surface, line, terminal, palette: terminalColors(theme) }, null, 2)}\n`);
222
+ if (config.onTheme) await run(container, config.onTheme, env);
223
+ }
224
+ function shareTheme(theme) {
225
+ clearTimeout(shareTimer);
226
+ // Arrow keys preview themes quickly; only the one the visitor rests on is written.
227
+ shareTimer = setTimeout(() => { shared = shared.then(() => writeTheme(theme)).catch((error) => console.warn("onTheme failed", error)); }, 150);
228
+ }
229
+ // Page and terminal change together; xterm maps its palette onto whatever the programs print.
230
+ function apply(theme, save) {
231
+ const vars = { page: theme.page, ink: theme.ink, "ink-strong": theme.inkStrong, muted: theme.muted, accent: theme.accent, surface: theme.surface, line: theme.line, terminal: theme.terminal };
232
+ for (const [name, value] of Object.entries(vars)) document.documentElement.style.setProperty(`--${name}`, value);
233
+ document.documentElement.style.colorScheme = document.documentElement.dataset.theme = theme.mode;
234
+ if (term) term.options.theme = terminalColors(theme);
235
+ shareTheme(theme);
236
+ if (save) try { localStorage.setItem(storeKey, JSON.stringify({ name: theme.name, mode: theme.mode, vars })); } catch {}
237
+ }
238
+ if (current) apply(current);
239
+
240
+ const [[{ Terminal }, { WebglAddon }, { FitAddon }]] = await Promise.all([terminalCode, fontLoad]);
241
+ term = new Terminal({
242
+ cursorBlink: true,
243
+ convertEol: true,
244
+ fontFamily: `${mono}, ui-monospace, Menlo, Consolas, monospace`,
245
+ fontSize: 14,
246
+ lineHeight: 1.25,
247
+ scrollback: 5000,
248
+ theme: current ? terminalColors(current) : undefined,
249
+ });
250
+ const fit = new FitAddon();
251
+ term.loadAddon(fit);
252
+ term.open(document.getElementById("terminal"));
253
+ // GPU rendering; the DOM renderer takes over if WebGL is unavailable or its context is lost.
254
+ try {
255
+ const webgl = new WebglAddon();
256
+ webgl.onContextLoss(() => webgl.dispose());
257
+ term.loadAddon(webgl);
258
+ timings.renderer = "webgl";
259
+ } catch {
260
+ timings.renderer = "dom";
261
+ }
262
+ fit.fit();
263
+ mark("terminal");
264
+ // The theme picker: arrows preview a theme in the page and the terminal, Enter keeps it, Esc puts the old one back.
265
+ if (themes.length > 1) {
266
+ const button = document.getElementById("theme-button");
267
+ const list = document.getElementById("theme-list");
268
+ const swatch = (theme) => [theme.page, theme.accent, theme.ink].map((color) => `<i style="background:${color}"></i>`).join("");
269
+ const rows = themes.map((theme) => {
270
+ const row = Object.assign(document.createElement("li"), { role: "option", innerHTML: `<span class="swatch">${swatch(theme)}</span><span>${theme.label}</span>` });
271
+ row.dataset.name = theme.name;
272
+ list.append(row);
273
+ return row;
274
+ });
275
+ let chosen = current;
276
+ let cursor = 0;
277
+ const show = () => {
278
+ document.getElementById("theme-swatch").innerHTML = swatch(current);
279
+ document.getElementById("theme-name").textContent = current.label;
280
+ rows.forEach((row) => row.setAttribute("aria-selected", String(row.dataset.name === current.name)));
281
+ };
282
+ const open = (isOpen) => {
283
+ list.hidden = !isOpen;
284
+ button.setAttribute("aria-expanded", String(isOpen));
285
+ if (isOpen) { chosen = current; move(themes.indexOf(current)); list.focus(); }
286
+ };
287
+ const move = (index) => {
288
+ cursor = (index + themes.length) % themes.length;
289
+ rows.forEach((row, i) => row.classList.toggle("active", i === cursor));
290
+ rows[cursor].scrollIntoView({ block: "nearest" });
291
+ current = themes[cursor];
292
+ apply(current);
293
+ show();
294
+ };
295
+ const close = (keep) => {
296
+ if (keep) apply(current, true); else { current = chosen; apply(current); }
297
+ show();
298
+ open(false);
299
+ button.focus();
300
+ };
301
+ button.hidden = false;
302
+ show();
303
+ button.addEventListener("click", () => open(list.hidden));
304
+ list.addEventListener("click", (event) => {
305
+ const row = event.target.closest("li");
306
+ if (row) { current = pick(row.dataset.name); close(true); }
307
+ });
308
+ list.addEventListener("keydown", (event) => {
309
+ if (event.key === "ArrowDown") move(cursor + 1);
310
+ else if (event.key === "ArrowUp") move(cursor - 1);
311
+ else if (event.key === "Enter") close(true);
312
+ else if (event.key === "Escape" || event.key === "Tab") close(false);
313
+ else return;
314
+ event.preventDefault();
315
+ });
316
+ document.addEventListener("click", (event) => { if (!list.hidden && !event.target.closest(".tools")) close(false); });
317
+ }
318
+
319
+ // For automated checks: the terminal text.
320
+ window.terminalText = () => {
321
+ const buffer = term.buffer.active;
322
+ return Array.from({ length: buffer.length }, (_, row) => buffer.getLine(row)?.translateToString(true) ?? "").join("\n");
323
+ };
324
+
325
+ const dim = (text) => `\x1b[2m${text}\x1b[0m`;
326
+ const red = (text) => `\x1b[31m${text}\x1b[0m`;
327
+ let input;
328
+ const hints = document.getElementById("hints");
329
+ for (const hint of config.hints ?? []) {
330
+ const button = Object.assign(document.createElement("button"), { textContent: hint, disabled: true, title: `Run ${hint}` });
331
+ button.addEventListener("click", () => {
332
+ input?.write(`${hint}\r`);
333
+ term.focus();
334
+ });
335
+ hints.append(button);
336
+ }
337
+
338
+ // Binary files arrive as base64 (see src/terminal.js).
339
+ function decode(tree) {
340
+ for (const node of Object.values(tree)) {
341
+ if (node.directory) decode(node.directory);
342
+ else if (node.file?.base64 !== undefined) node.file = { contents: Uint8Array.from(atob(node.file.base64), (char) => char.charCodeAt(0)) };
343
+ }
344
+ return tree;
345
+ }
346
+
347
+ function merge(tree, extra) {
348
+ for (const [name, node] of Object.entries(extra)) {
349
+ if (node.directory && tree[name]?.directory) merge(tree[name].directory, node.directory);
350
+ else tree[name] = node;
351
+ }
352
+ return tree;
353
+ }
354
+
355
+ async function run(container, command, env) {
356
+ const [name, ...args] = command.split(" ");
357
+ const child = await container.spawn(name, args, { env });
358
+ let output = "";
359
+ child.output.pipeTo(new WritableStream({ write(data) { output += data; } }));
360
+ const code = await child.exit;
361
+ if (code !== 0) throw new Error(`'${command}' exited with ${code}\n${output}`);
362
+ return output;
363
+ }
364
+
365
+ try {
366
+ if (!booting) throw new Error("This page needs cross-origin isolation (COOP/COEP headers) to run the sandbox.");
367
+ term.write(dim("Booting a Node.js sandbox in your browser…"));
368
+ const [container, files, seedModule] = await Promise.all([booting, filesLoad, seedLoad]);
369
+ mark("boot");
370
+ // A recipe's seed adds files computed at visit time (dates relative to today) without starting a process.
371
+ await container.mount(seedModule ? merge(files, seedModule.default(files)) : files);
372
+ mark("mount");
373
+ const home = container.workdir;
374
+ // Env values may use ~ for the sandbox home and $PATH for the default PATH (which costs one extra process).
375
+ const values = Object.entries(config.env ?? {});
376
+ const basePath = values.some(([, value]) => value.includes("$PATH"))
377
+ ? (await run(container, "node -p process.env.PATH", {})).trim()
378
+ : "/usr/local/bin:/usr/bin:/bin";
379
+ const expand = (value) => value.replace(/(^|:)~(?=\/|:|$)/g, `$1${home}`).replace("$PATH", basePath);
380
+ const env = { HOME: home, PATH: basePath, ...Object.fromEntries(values.map(([key, value]) => [key, expand(value)])) };
381
+ sandbox = { container, env };
382
+ // Setup runs while the shell starts; the shell itself never needs the seeded files.
383
+ const steps = config.setup ?? [];
384
+ let progress = "Getting ready";
385
+ const setup = (async () => {
386
+ // The theme is in place before setup, so whatever setup or start launches reads it.
387
+ await writeTheme(current);
388
+ for (const [index, command] of steps.entries()) {
389
+ progress = `Setting up the sandbox (${index + 1}/${steps.length})`;
390
+ await run(container, command, env);
391
+ }
392
+ mark("setup");
393
+ })();
394
+
395
+ term.reset();
396
+ term.write(`${(config.welcome ?? []).join("\n")}\n\n`);
397
+ // Until setup is done the shell is held back: a spinner stands in for its prompt and keys are dropped,
398
+ // so nothing typed early ends up in front of the start command.
399
+ let shellOpen = false;
400
+ let held = "";
401
+ let typedEarly = false;
402
+ const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
403
+ let frame = 0;
404
+ const spin = () => term.write(`\r\x1b[2K${dim(`${frames[frame++ % frames.length]} ${progress}…${typedEarly ? " Typing opens once this is done." : ""}`)}`);
405
+ spin();
406
+ const spinner = setInterval(spin, 80);
407
+ const openShell = () => {
408
+ clearInterval(spinner);
409
+ term.write(`\r\x1b[2K${held}`);
410
+ shellOpen = true;
411
+ };
412
+ const shell = await container.spawn("jsh", { env, terminal: { cols: term.cols, rows: term.rows } });
413
+ let prompted;
414
+ const firstPrompt = new Promise((resolve) => { prompted = resolve; }).then(() => mark("prompt"));
415
+ shell.output.pipeTo(new WritableStream({
416
+ write(data) {
417
+ if (shellOpen) term.write(data); else held += data;
418
+ prompted();
419
+ },
420
+ }));
421
+ // Buttons wait for the first prompt and the setup, so a click never runs ahead of either.
422
+ Promise.all([firstPrompt, setup]).then(() => {
423
+ openShell();
424
+ // The recipe's start command is typed into the shell, so the visitor sees what launched and can run it again.
425
+ if (config.start) input.write(`${config.start}\r`);
426
+ for (const button of hints.querySelectorAll("button")) button.disabled = false;
427
+ mark("ready");
428
+ window.demoReady = true;
429
+ }, (error) => {
430
+ openShell();
431
+ term.write(red(`\nSetup failed: ${error.message}\n`));
432
+ window.demoError = error.message;
433
+ });
434
+ input = shell.input.getWriter();
435
+ term.onData((data) => {
436
+ if (shellOpen) input.write(data);
437
+ else typedEarly = true;
438
+ });
439
+ new ResizeObserver(() => {
440
+ fit.fit();
441
+ shell.resize({ cols: term.cols, rows: term.rows });
442
+ }).observe(document.querySelector(".panel"));
443
+ term.focus();
444
+ } catch (error) {
445
+ term.write(red(`\n${error.message}\n`));
446
+ if (/SharedArrayBuffer|isolation|WebContainer/i.test(error.message)) {
447
+ term.write(dim("Try a recent Chrome, Edge or Firefox on a desktop. Safari support is partial.\n"));
448
+ }
449
+ window.demoError = error.message;
450
+ }
451
+ </script>
452
+ </body>
453
+ </html>
@@ -0,0 +1 @@
1
+ [{"name":"dark","label":"Dark","mode":"dark","page":"#111113","terminal":"#0b0b0c","surface":"#1c1c1f","line":"#2e2e33","ink":"#d4d4d8","inkStrong":"#fafafa","muted":"#a1a1aa","accent":"#60a5fa","ansi":{"red":"#f87171","green":"#4ade80","yellow":"#facc15","blue":"#60a5fa","magenta":"#c084fc","cyan":"#22d3ee","black":"#1c1c1f","white":"#d4d4d8","brightWhite":"#fafafa","brightBlack":"#a1a1aa"}},{"name":"light","label":"Light","mode":"light","page":"#fafafa","terminal":"#ffffff","surface":"#f4f4f5","line":"#e4e4e7","ink":"#27272a","inkStrong":"#09090b","muted":"#52525b","accent":"#2563eb","ansi":{"red":"#dc2626","green":"#16a34a","yellow":"#a16207","blue":"#2563eb","magenta":"#9333ea","cyan":"#0e7490","black":"#e4e4e7","white":"#27272a","brightWhite":"#09090b","brightBlack":"#52525b"}}]
@@ -0,0 +1,146 @@
1
+ // Builds the browser terminal recipe: a static page that boots a Node.js sandbox (WebContainers) and opens a shell in it.
2
+ import { copyFile, cp, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
3
+ import { createServer } from "node:http";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const assets = fileURLToPath(new URL("../page/", import.meta.url));
9
+ const skip = new Set([".git", "node_modules"]);
10
+
11
+ // Paths in terminal.json may start with ~ and use $VARS.
12
+ function resolvePath(raw, base) {
13
+ const expanded = raw
14
+ .replace(/^~(?=$|\/)/, os.homedir())
15
+ .replace(/\$(?:\{(\w+)\}|(\w+))/g, (_, braced, bare) => {
16
+ const value = process.env[braced ?? bare];
17
+ if (value === undefined) throw new Error(`$${braced ?? bare} not set`);
18
+ return value;
19
+ });
20
+ return path.resolve(base, expanded);
21
+ }
22
+
23
+ // The project's facts live in its showcase.json (github.com/Soleone/showcase). Without one, terminal.json
24
+ // carries the title and pitch itself.
25
+ async function readFacts(project) {
26
+ const file = path.join(project, "showcase.json");
27
+ try {
28
+ return JSON.parse(await readFile(file, "utf8"));
29
+ } catch (error) {
30
+ if (error.code === "ENOENT") return {};
31
+ throw new Error(`${file}: ${error.message}`);
32
+ }
33
+ }
34
+
35
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
36
+
37
+ // Text stays readable in files.json; anything else (images, loops) travels as base64 and the page decodes it.
38
+ function fileNode(buffer) {
39
+ try {
40
+ return { file: { contents: utf8.decode(buffer) } };
41
+ } catch {
42
+ return { file: { base64: buffer.toString("base64") } };
43
+ }
44
+ }
45
+
46
+ // Reads a folder into a WebContainer FileSystemTree; `include` limits the top-level entries.
47
+ async function tree(folder, include) {
48
+ const result = {};
49
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
50
+ if (include ? !include.includes(entry.name) : skip.has(entry.name)) continue;
51
+ const file = path.join(folder, entry.name);
52
+ if (entry.isDirectory()) result[entry.name] = { directory: await tree(file) };
53
+ else if (entry.isFile()) result[entry.name] = fileNode(await readFile(file));
54
+ }
55
+ return result;
56
+ }
57
+
58
+ // Places a subtree at a path like "node_modules/my-cli" inside the root tree.
59
+ function place(root, target, subtree) {
60
+ const parts = target.split("/").filter((part) => part && part !== ".");
61
+ let node = root;
62
+ for (const part of parts) {
63
+ node[part] ??= { directory: {} };
64
+ node = node[part].directory;
65
+ }
66
+ Object.assign(node, subtree);
67
+ }
68
+
69
+ const isolationHeaders = { "Cross-Origin-Embedder-Policy": "require-corp", "Cross-Origin-Opener-Policy": "same-origin" };
70
+
71
+ // The page says what is not real, from the project's demo.externals.
72
+ function disclosure(title, externals = []) {
73
+ const notes = externals.filter((external) => external.standIn !== "real").map((external) => external.note ?? `${external.name}: ${external.standIn} stand-in.`);
74
+ return [`The real ${title} runs in a Node.js sandbox in your browser (WebContainers).`, ...notes, "Reload to start over."].join(" ");
75
+ }
76
+
77
+ // A skin is a folder or URL with the page's look: themes.json (the palettes) and skin.css (anything else, such
78
+ // as fonts). Either file may be left out; the recipe's plain look fills in.
79
+ async function skinFile(skin, name, recipeDir) {
80
+ if (!skin) return null;
81
+ if (/^https?:\/\//.test(skin)) {
82
+ const url = `${skin.replace(/\/$/, "")}/${name}`;
83
+ const response = await fetch(url);
84
+ if (response.status === 404) return null;
85
+ if (!response.ok) throw new Error(`${url}: ${response.status}`);
86
+ return response.text();
87
+ }
88
+ return readFile(path.join(resolvePath(skin, recipeDir), name), "utf8").catch((error) => {
89
+ if (error.code === "ENOENT") return null;
90
+ throw error;
91
+ });
92
+ }
93
+
94
+ export async function buildTerminal(recipeDir, out) {
95
+ recipeDir = path.resolve(recipeDir);
96
+ out = path.resolve(out);
97
+ const recipeFile = path.join(recipeDir, "terminal.json");
98
+ const { mount, project, skin, ...recipe } = JSON.parse(await readFile(recipeFile, "utf8").catch(() => {
99
+ throw new Error(`No terminal.json in ${recipeDir}. See https://github.com/Soleone/showcase-terminal#readme`);
100
+ }));
101
+ if (!mount) throw new Error(`${recipeFile}: mount is required`);
102
+ // Facts come from the project's showcase.json; terminal.json only adds what is specific to this page.
103
+ const facts = project ? await readFacts(resolvePath(project, recipeDir)) : {};
104
+ const config = { title: facts.title, pitch: facts.pitch, repo: facts.repo, ...recipe };
105
+ config.disclosure ??= disclosure(config.title, facts.demo?.externals);
106
+ const files = {};
107
+ for (const [target, { from, include }] of Object.entries(mount)) {
108
+ place(files, target, await tree(resolvePath(from, recipeDir), include));
109
+ }
110
+ await mkdir(out, { recursive: true });
111
+ await copyFile(path.join(assets, "index.html"), path.join(out, "index.html"));
112
+ await writeFile(path.join(out, "themes.json"), await skinFile(skin, "themes.json", recipeDir) ?? await readFile(path.join(assets, "themes.json")));
113
+ await writeFile(path.join(out, "skin.css"), await skinFile(skin, "skin.css", recipeDir) ?? "");
114
+ await cp(path.join(assets, "fonts"), path.join(out, "fonts"), { recursive: true, filter: (source) => !source.endsWith(".sh") });
115
+ await writeFile(path.join(out, "files.json"), JSON.stringify(files));
116
+ if (config.seed) await copyFile(path.join(recipeDir, config.seed), path.join(out, config.seed));
117
+ await writeFile(path.join(out, "terminal.json"), `${JSON.stringify(config, null, 2)}\n`);
118
+ await writeFile(path.join(out, "vercel.json"), `${JSON.stringify({
119
+ headers: [
120
+ { source: "/(.*)", headers: Object.entries(isolationHeaders).map(([key, value]) => ({ key, value })) },
121
+ { source: "/fonts/(.*)", headers: [{ key: "Cache-Control", value: "public, max-age=31536000, immutable" }] },
122
+ ],
123
+ }, null, 2)}\n`);
124
+ return { out, bytes: JSON.stringify(files).length };
125
+ }
126
+
127
+ const types = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".js": "text/javascript", ".woff2": "font/woff2", ".txt": "text/plain" };
128
+
129
+ // Serves a built page on this machine only, with the headers the sandbox needs.
130
+ export function serveTerminal(out, port = 4321) {
131
+ out = path.resolve(out);
132
+ return new Promise((resolve, reject) => {
133
+ const server = createServer(async (request, response) => {
134
+ const name = new URL(request.url, "http://localhost").pathname.replace(/\/$/, "/index.html");
135
+ const file = path.join(out, path.normalize(name));
136
+ if (!file.startsWith(out + path.sep)) return response.writeHead(403).end();
137
+ try {
138
+ const body = await readFile(file);
139
+ response.writeHead(200, { "Content-Type": types[path.extname(file)] ?? "application/octet-stream", ...isolationHeaders }).end(body);
140
+ } catch {
141
+ response.writeHead(404).end("Not found");
142
+ }
143
+ });
144
+ server.once("error", reject).listen(port, "127.0.0.1", () => resolve(server));
145
+ });
146
+ }