create-volt 0.11.0 → 0.13.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,265 @@
1
+ // volt.js — a tiny, no-build, signals-based UI library.
2
+ //
3
+ // Not React: there is no JSX, no virtual DOM, and no "re-render the whole
4
+ // component" step. State lives in *signals*; reading a signal inside a piece of
5
+ // UI subscribes that exact piece; writing the signal re-runs only those
6
+ // subscribers and touches only the precise text node / attribute that changed.
7
+ //
8
+ // Two ways to author UI, same engine underneath:
9
+ // 1. html`` — tagged-template markup with ${signal} holes
10
+ // 2. el(...) — imperative DOM helpers with function-children
11
+ // They interoperate freely (drop an el() node into an html`` template, etc.).
12
+ //
13
+ // Public API: signal, computed, effect, el, html, mount.
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Reactive core (signals + effects with ownership-based disposal)
17
+ // ---------------------------------------------------------------------------
18
+
19
+ let activeEffect = null;
20
+
21
+ // A signal is a function: call with no args to read, one arg to write.
22
+ // const n = signal(0); n(); // read → 0
23
+ // n(n()+1); // write → notifies subscribers
24
+ export function signal(value) {
25
+ const subs = new Set();
26
+ return function sig(...args) {
27
+ if (args.length) {
28
+ const next = args[0];
29
+ if (next === value) return value; // no-op on identical value
30
+ value = next;
31
+ for (const eff of [...subs]) eff.run(); // copy: run() mutates subs
32
+ return value;
33
+ }
34
+ if (activeEffect) {
35
+ subs.add(activeEffect);
36
+ activeEffect.deps.add(subs);
37
+ }
38
+ return value;
39
+ };
40
+ }
41
+
42
+ // effect(fn) runs fn now, tracks every signal it reads, and re-runs it whenever
43
+ // any of those change. Effects created *inside* another effect are owned by it
44
+ // and disposed before each re-run — so dynamic regions clean up after themselves.
45
+ export function effect(fn) {
46
+ const eff = {
47
+ deps: new Set(),
48
+ children: new Set(),
49
+ parent: activeEffect,
50
+ run() {
51
+ disposeChildren(eff);
52
+ cleanupDeps(eff);
53
+ const prev = activeEffect;
54
+ activeEffect = eff;
55
+ try {
56
+ fn();
57
+ } finally {
58
+ activeEffect = prev;
59
+ }
60
+ },
61
+ dispose() {
62
+ disposeChildren(eff);
63
+ cleanupDeps(eff);
64
+ if (eff.parent) eff.parent.children.delete(eff);
65
+ },
66
+ };
67
+ if (activeEffect) activeEffect.children.add(eff);
68
+ eff.run();
69
+ return () => eff.dispose();
70
+ }
71
+
72
+ // computed(fn) is a read-only derived signal: () => value, auto-updating.
73
+ export function computed(fn) {
74
+ const s = signal(undefined);
75
+ effect(() => s(fn()));
76
+ return () => s();
77
+ }
78
+
79
+ function cleanupDeps(eff) {
80
+ for (const subs of eff.deps) subs.delete(eff);
81
+ eff.deps.clear();
82
+ }
83
+
84
+ function disposeChildren(eff) {
85
+ for (const child of [...eff.children]) child.dispose();
86
+ eff.children.clear();
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // DOM helpers
91
+ // ---------------------------------------------------------------------------
92
+
93
+ // el(tag, props?, ...children) → a real DOM element.
94
+ // props: { onClick: fn } → event listener
95
+ // { class: () => ... } → reactive attribute (function = live)
96
+ // { id: 'x' } → static attribute
97
+ // children: strings, numbers, nodes, arrays, or functions (functions = live)
98
+ export function el(tag, props, ...children) {
99
+ const node = document.createElement(tag);
100
+ if (props) {
101
+ for (const [key, val] of Object.entries(props)) {
102
+ if (key.startsWith("on") && typeof val === "function") {
103
+ node.addEventListener(key.slice(2).toLowerCase(), val);
104
+ } else if (typeof val === "function") {
105
+ effect(() => setAttr(node, key, val()));
106
+ } else {
107
+ setAttr(node, key, val);
108
+ }
109
+ }
110
+ }
111
+ for (const child of children) appendChild(node, child);
112
+ return node;
113
+ }
114
+
115
+ // mount(target, ...children) appends children into target (selector or element).
116
+ // Top-level function-children are reactive too.
117
+ export function mount(target, ...children) {
118
+ const parent = typeof target === "string" ? document.querySelector(target) : target;
119
+ for (const child of children) appendChild(parent, child);
120
+ return parent;
121
+ }
122
+
123
+ function setAttr(node, name, value) {
124
+ if (name === "value") {
125
+ node.value = value ?? "";
126
+ return;
127
+ }
128
+ if (name === "checked" || name === "disabled" || name === "selected") {
129
+ node[name] = !!value && value !== "false";
130
+ return;
131
+ }
132
+ if (value === false || value == null) {
133
+ node.removeAttribute(name);
134
+ return;
135
+ }
136
+ node.setAttribute(name, value);
137
+ }
138
+
139
+ // Append a child, making function-children into self-updating dynamic regions
140
+ // bounded by two comment anchors (so they can render text, nodes, or lists).
141
+ function appendChild(parent, child) {
142
+ if (typeof child === "function") {
143
+ const start = document.createComment("");
144
+ const end = document.createComment("");
145
+ parent.appendChild(start);
146
+ parent.appendChild(end);
147
+ effect(() => renderRange(start, end, child()));
148
+ return;
149
+ }
150
+ for (const node of toNodes(child)) parent.appendChild(node);
151
+ }
152
+
153
+ // Replace everything between the start/end anchors with `value`'s nodes.
154
+ function renderRange(start, end, value) {
155
+ let n = start.nextSibling;
156
+ while (n && n !== end) {
157
+ const t = n.nextSibling;
158
+ n.remove();
159
+ n = t;
160
+ }
161
+ for (const node of toNodes(value)) end.parentNode.insertBefore(node, end);
162
+ }
163
+
164
+ // Normalize any child value into an array of DOM nodes.
165
+ function toNodes(value) {
166
+ if (value == null || value === false || value === true) return [];
167
+ if (Array.isArray(value)) return value.flatMap(toNodes);
168
+ if (value instanceof Node) return [value];
169
+ return [document.createTextNode(String(value))];
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // html`` template layer (parses once, wires holes to the same primitives)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ const PH = (i) => `__voltph${i}__`;
177
+ const PH_RE = /__voltph(\d+)__/g;
178
+
179
+ // We're inside an open tag (attribute context) if the last '<' comes after the
180
+ // last '>' in the accumulated string.
181
+ function isAttrContext(str) {
182
+ return str.lastIndexOf("<") > str.lastIndexOf(">");
183
+ }
184
+
185
+ export function html(strings, ...values) {
186
+ let acc = "";
187
+ strings.forEach((str, i) => {
188
+ acc += str;
189
+ if (i < values.length) {
190
+ acc += isAttrContext(acc) ? PH(i) : `<!--${PH(i)}-->`;
191
+ }
192
+ });
193
+
194
+ const tpl = document.createElement("template");
195
+ tpl.innerHTML = acc.trim();
196
+
197
+ // Bind attribute holes.
198
+ for (const node of tpl.content.querySelectorAll("*")) {
199
+ for (const attr of [...node.attributes]) {
200
+ PH_RE.lastIndex = 0;
201
+ if (PH_RE.test(attr.value)) bindAttr(node, attr, values);
202
+ }
203
+ }
204
+
205
+ // Bind node holes (comment placeholders).
206
+ const walker = document.createTreeWalker(tpl.content, NodeFilter.SHOW_COMMENT);
207
+ const holes = [];
208
+ let c;
209
+ while ((c = walker.nextNode())) {
210
+ const m = c.data.match(/^__voltph(\d+)__$/);
211
+ if (m) holes.push([c, Number(m[1])]);
212
+ }
213
+ for (const [comment, i] of holes) bindNodeHole(comment, values[i]);
214
+
215
+ const nodes = [...tpl.content.childNodes];
216
+ return nodes.length === 1 ? nodes[0] : nodes;
217
+ }
218
+
219
+ function bindAttr(node, attr, values) {
220
+ const name = attr.name;
221
+ const raw = attr.value;
222
+ const single = raw.match(/^__voltph(\d+)__$/);
223
+ node.removeAttribute(name);
224
+
225
+ // onX=${fn} → event listener
226
+ if (name.startsWith("on") && single) {
227
+ node.addEventListener(name.slice(2).toLowerCase(), values[Number(single[1])]);
228
+ return;
229
+ }
230
+
231
+ // Otherwise a (possibly mixed) attribute value. If any hole is a function it
232
+ // is read inside the effect, so the attribute stays live.
233
+ effect(() => {
234
+ const text = raw.replace(PH_RE, (_, j) => {
235
+ const v = values[Number(j)];
236
+ return String(typeof v === "function" ? v() : v ?? "");
237
+ });
238
+ setAttr(node, name, text);
239
+ });
240
+ }
241
+
242
+ function bindNodeHole(comment, value) {
243
+ const start = document.createComment("");
244
+ comment.parentNode.insertBefore(start, comment); // `comment` becomes the end anchor
245
+ if (typeof value === "function") {
246
+ effect(() => renderRange(start, comment, value()));
247
+ } else {
248
+ renderRange(start, comment, value);
249
+ }
250
+ }
251
+
252
+ // ---------------------------------------------------------------------------
253
+ // Hot reload client — listens for the dev server's reload event over Socket.io
254
+ // ---------------------------------------------------------------------------
255
+
256
+ (function startHotReload() {
257
+ const connect = () => {
258
+ if (!window.io) return false;
259
+ const socket = window.io();
260
+ socket.on("volt:reload", () => location.reload());
261
+ console.log("[volt] hot reload connected");
262
+ return true;
263
+ };
264
+ if (!connect()) window.addEventListener("load", connect);
265
+ })();
@@ -0,0 +1,426 @@
1
+ // server.js — dev server with a built-in first-run setup wizard.
2
+ //
3
+ // First run (no .env) or `node server.js --edit` (-e) opens a disposable, local
4
+ // config page: tick add-ons, fill settings, Apply. Apply writes .env (a
5
+ // VOLT_ADDONS list + settings) and adds any needed packages to package.json,
6
+ // runs npm install, then starts the app — which wires whatever .env enables.
7
+ // Add-on code is bundled under .volt/addons; nothing is copied into your code.
8
+ //
9
+ // No build step, no env-file flag: .env is auto-loaded below.
10
+
11
+ import http from "node:http";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import crypto from "node:crypto";
15
+ import { spawn } from "node:child_process";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import express from "express";
18
+ import { Server as SocketServer } from "socket.io";
19
+
20
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
+ const ENV_PATH = path.join(__dirname, ".env");
22
+ const PKG_PATH = path.join(__dirname, "package.json");
23
+ const ADDONS_DIR = path.join(__dirname, ".volt", "addons"); // bundled add-on sources
24
+ const DEFAULT_PORT = 26628; // create-volt stamps this with the project's date-port
25
+ const PKG_VERSIONS = { mongodb: "^6.8.0", mysql2: "^3.11.0", pg: "^8.12.0", nodemailer: "^6.9.0" };
26
+ const LIB_FILE = { db: "store.js", mailer: "mailer.js", auth: "auth.js", realtime: "realtime.js", admin: "admin.js" };
27
+
28
+ // --- tiny .env loader (no dependency); never overrides an existing env var ---
29
+ function readEnvFile() {
30
+ const out = {};
31
+ if (!fs.existsSync(ENV_PATH)) return out;
32
+ for (const line of fs.readFileSync(ENV_PATH, "utf8").split("\n")) {
33
+ const m = line.match(/^\s*([A-Za-z0-9_]+)\s*=\s*(.*?)\s*$/);
34
+ if (m) out[m[1]] = m[2];
35
+ }
36
+ return out;
37
+ }
38
+ function loadEnv() {
39
+ for (const [k, v] of Object.entries(readEnvFile())) if (!(k in process.env)) process.env[k] = v;
40
+ }
41
+
42
+ // Add-ons available to enable (bundled under .volt/addons by create-volt).
43
+ function availableAddons() {
44
+ if (!fs.existsSync(ADDONS_DIR)) return [];
45
+ return fs
46
+ .readdirSync(ADDONS_DIR, { withFileTypes: true })
47
+ .filter((e) => e.isDirectory())
48
+ .map((e) => {
49
+ const m = JSON.parse(fs.readFileSync(path.join(ADDONS_DIR, e.name, "meta.json"), "utf8"));
50
+ return { name: e.name, description: m.description, dependsOn: m.dependsOn || [] };
51
+ });
52
+ }
53
+
54
+ // Which add-ons does VOLT_ADDONS turn on (dependencies expanded)?
55
+ function enabledFrom(env) {
56
+ const metas = Object.fromEntries(availableAddons().map((a) => [a.name, a]));
57
+ const out = new Set();
58
+ const visit = (n) => {
59
+ if (!metas[n] || out.has(n)) return;
60
+ out.add(n);
61
+ for (const d of metas[n].dependsOn) visit(d);
62
+ };
63
+ for (const n of String(env.VOLT_ADDONS || "").split(",").map((s) => s.trim()).filter(Boolean)) visit(n);
64
+ return out;
65
+ }
66
+
67
+ const imp = (rel) => import(pathToFileURL(path.join(__dirname, rel)).href);
68
+ const addonMod = (n) => imp(path.join(".volt", "addons", n, "files", "lib", LIB_FILE[n]));
69
+
70
+ function openBrowser(url) {
71
+ if (process.env.VOLT_NO_OPEN || process.argv.includes("--no-open")) return false;
72
+ const plat = process.platform;
73
+ if (plat === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return false;
74
+ const cmd = plat === "darwin" ? "open" : plat === "win32" ? "cmd" : "xdg-open";
75
+ const args = plat === "win32" ? ["/c", "start", "", url] : [url];
76
+ try {
77
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
78
+ child.on("error", () => {}); // launcher missing — emits async, don't crash
79
+ child.unref();
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ // --- the actual app: wires whichever add-ons .env enables ---
87
+ async function startApp() {
88
+ const PORT = Number(process.env.PORT) || DEFAULT_PORT;
89
+ const enabled = enabledFrom(process.env);
90
+ const app = express();
91
+ app.disable("x-powered-by");
92
+ app.use((_req, res, next) => {
93
+ res.setHeader("X-Content-Type-Options", "nosniff");
94
+ res.setHeader("X-Frame-Options", "SAMEORIGIN");
95
+ res.setHeader("Referrer-Policy", "same-origin");
96
+ next();
97
+ });
98
+ app.use(express.static(path.join(__dirname, "public")));
99
+
100
+ let store = null;
101
+ let mailer = null;
102
+ if (enabled.has("db")) store = await (await addonMod("db")).createStore();
103
+ if (enabled.has("mailer")) mailer = await (await addonMod("mailer")).createMailer();
104
+ if (enabled.has("auth") && store && mailer) app.use((await addonMod("auth")).authRouter({ store, mailer }));
105
+ if (enabled.has("admin") && store && enabled.has("auth")) {
106
+ const adminEmails = String(process.env.ADMIN_EMAILS || "").split(",").map((s) => s.trim()).filter(Boolean);
107
+ const requireAuth = (await addonMod("auth")).requireAuth(store);
108
+ app.use((await addonMod("admin")).adminRouter({ store, requireAuth, adminEmails }));
109
+ }
110
+
111
+ // notes — a per-user CRUD example (auth-gated, owner-scoped, db-backed)
112
+ if (enabled.has("db") && enabled.has("auth") && store) {
113
+ const guard = (await addonMod("auth")).requireAuth(store);
114
+ const notes = store.collection("notes");
115
+ const r = express.Router();
116
+ r.use(express.json());
117
+ r.get("/api/notes", guard, async (req, res) => {
118
+ const list = (await notes.find({ owner: req.user.email })).sort((a, b) => b.createdAt - a.createdAt);
119
+ res.json({ notes: list });
120
+ });
121
+ r.post("/api/notes", guard, async (req, res) => {
122
+ const text = String(req.body?.text || "").trim().slice(0, 2000);
123
+ if (!text) return res.status(400).json({ ok: false, error: "Empty note." });
124
+ const note = { id: crypto.randomBytes(8).toString("hex"), owner: req.user.email, text, createdAt: Date.now() };
125
+ await notes.put(note.id, note);
126
+ res.json({ ok: true, note });
127
+ });
128
+ r.delete("/api/notes/:id", guard, async (req, res) => {
129
+ const n = await notes.get(req.params.id);
130
+ if (n && n.owner === req.user.email) await notes.delete(req.params.id);
131
+ res.json({ ok: true });
132
+ });
133
+ app.use(r);
134
+ }
135
+
136
+ // expose which add-ons are on, and serve each enabled add-on's frontend assets
137
+ app.get("/__volt/addons", (_req, res) => res.json([...enabled]));
138
+ for (const n of enabled) {
139
+ const pub = path.join(ADDONS_DIR, n, "files", "public");
140
+ if (fs.existsSync(pub)) app.use(express.static(pub));
141
+ }
142
+
143
+ app.get("/", (_req, res) => res.sendFile(path.join(__dirname, "views", "index.html")));
144
+
145
+ const server = http.createServer(app);
146
+ const io = new SocketServer(server);
147
+ if (enabled.has("realtime") && store) (await addonMod("realtime")).attachRealtime(io, { store });
148
+
149
+ let timer = null;
150
+ const onChange = (file) => {
151
+ clearTimeout(timer);
152
+ timer = setTimeout(() => {
153
+ console.log(`[volt] change: ${file ?? "?"} → reload`);
154
+ io.emit("volt:reload");
155
+ }, 80);
156
+ };
157
+ const watchRecursive = (dir) => {
158
+ try {
159
+ fs.watch(dir, { recursive: true }, (_e, f) => onChange(f));
160
+ return;
161
+ } catch {
162
+ /* per-dir fallback */
163
+ }
164
+ const w = (d) => {
165
+ try {
166
+ fs.watch(d, (_e, f) => onChange(f));
167
+ } catch {
168
+ /* ignore */
169
+ }
170
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) if (e.isDirectory()) w(path.join(d, e.name));
171
+ };
172
+ w(dir);
173
+ };
174
+ for (const d of ["views", "public"]) watchRecursive(path.join(__dirname, d));
175
+
176
+ const on = [...enabled];
177
+ server.listen(PORT, () => console.log(`⚡ Volt → http://localhost:${PORT}${on.length ? " (add-ons: " + on.join(", ") + ")" : ""}`));
178
+ }
179
+
180
+ // Packages an .env's selections need, beyond what package.json already has.
181
+ function neededPackages(env) {
182
+ const pkg = JSON.parse(fs.readFileSync(PKG_PATH, "utf8"));
183
+ const deps = pkg.dependencies || {};
184
+ const want = [];
185
+ const driver = (env.match(/^\s*DB_DRIVER\s*=\s*(\w+)/m) || [])[1];
186
+ if (driver === "mongodb") want.push("mongodb");
187
+ if (driver === "mysql") want.push("mysql2");
188
+ if (driver === "postgres") want.push("pg");
189
+ if (/^\s*SMTP_URL\s*=\s*\S/m.test(env)) want.push("nodemailer");
190
+ return want.filter((p) => !deps[p]);
191
+ }
192
+
193
+ // --- the disposable setup wizard (localhost only) ---
194
+ function startSetup() {
195
+ const PORT = Number(process.env.PORT) || Number(readEnvFile().PORT) || DEFAULT_PORT;
196
+ const assets = {
197
+ "/setup.js": ["text/javascript; charset=utf-8", fs.readFileSync(path.join(__dirname, "setup", "setup.js"))],
198
+ "/volt.js": ["text/javascript; charset=utf-8", fs.readFileSync(path.join(__dirname, "public", "volt.js"))],
199
+ };
200
+ const indexHtml = fs.readFileSync(path.join(__dirname, "setup", "index.html"));
201
+
202
+ const server = http.createServer((req, res) => {
203
+ const u = new URL(req.url, "http://localhost");
204
+ const p = u.pathname;
205
+ if (req.method === "GET" && p === "/") {
206
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
207
+ return res.end(indexHtml);
208
+ }
209
+ if (req.method === "GET" && assets[p]) {
210
+ res.setHeader("Content-Type", assets[p][0]);
211
+ return res.end(assets[p][1]);
212
+ }
213
+ if (req.method === "GET" && p === "/setup/state") {
214
+ res.setHeader("Content-Type", "application/json");
215
+ return res.end(JSON.stringify({ available: availableAddons(), current: readEnvFile(), defaultPort: DEFAULT_PORT }));
216
+ }
217
+ if (req.method === "POST" && p === "/setup/test-db") {
218
+ let body = "";
219
+ req.on("data", (c) => (body += c));
220
+ req.on("end", async () => {
221
+ const keys = ["DB_DRIVER", "MONGODB_URI", "MONGODB_DATABASE", "DATABASE_URL"];
222
+ const saved = Object.fromEntries(keys.map((k) => [k, process.env[k]]));
223
+ try {
224
+ const { env = {} } = JSON.parse(body);
225
+ for (const k of keys) {
226
+ if (env[k]) process.env[k] = env[k];
227
+ else delete process.env[k];
228
+ }
229
+ const store = await (await addonMod("db")).createStore();
230
+ await store.collection("__voltcheck").all();
231
+ res.setHeader("Content-Type", "application/json");
232
+ res.end(JSON.stringify({ ok: true, driver: store.name }));
233
+ } catch (e) {
234
+ res.setHeader("Content-Type", "application/json");
235
+ res.end(JSON.stringify({ ok: false, error: e.message }));
236
+ } finally {
237
+ for (const k of keys) {
238
+ if (saved[k] == null) delete process.env[k];
239
+ else process.env[k] = saved[k];
240
+ }
241
+ }
242
+ });
243
+ return;
244
+ }
245
+ if (req.method === "POST" && p === "/setup/apply") {
246
+ let body = "";
247
+ req.on("data", (c) => (body += c));
248
+ req.on("end", () => {
249
+ try {
250
+ const { env } = JSON.parse(body);
251
+ if (typeof env !== "string") throw new Error("missing env");
252
+
253
+ // 1) write .env, preserving any custom keys the form doesn't manage
254
+ let finalEnv = env;
255
+ if (fs.existsSync(ENV_PATH)) {
256
+ const managed = new Set([...env.matchAll(/^\s*([A-Za-z0-9_]+)\s*=/gm)].map((m) => m[1]));
257
+ const extra = readEnvFileLines().filter((line) => {
258
+ const m = line.match(/^\s*([A-Za-z0-9_]+)\s*=/);
259
+ return m && !managed.has(m[1]);
260
+ });
261
+ if (extra.length) finalEnv = env.replace(/\n*$/, "\n") + extra.join("\n") + "\n";
262
+ }
263
+ fs.writeFileSync(ENV_PATH, finalEnv);
264
+
265
+ // 2) declare any needed packages in package.json
266
+ const added = neededPackages(env);
267
+ if (added.length) {
268
+ const pkg = JSON.parse(fs.readFileSync(PKG_PATH, "utf8"));
269
+ pkg.dependencies = pkg.dependencies || {};
270
+ for (const name of added) pkg.dependencies[name] = PKG_VERSIONS[name] || "latest";
271
+ fs.writeFileSync(PKG_PATH, JSON.stringify(pkg, null, 2) + "\n");
272
+ }
273
+
274
+ const envPort = Number((env.match(/^\s*PORT\s*=\s*(\d+)/m) || [])[1]);
275
+ const newPort = process.env.PORT ? Number(process.env.PORT) : envPort || DEFAULT_PORT;
276
+ res.setHeader("Content-Type", "application/json");
277
+ res.end(JSON.stringify({ ok: true, port: newPort, installing: added }));
278
+
279
+ // 3) install (if needed), then hand off to the app
280
+ res.on("finish", () => {
281
+ const handoff = () => {
282
+ server.close(() => {
283
+ loadEnv();
284
+ startApp();
285
+ });
286
+ server.closeIdleConnections?.();
287
+ };
288
+ if (added.length) {
289
+ console.log(`[volt] installing ${added.join(", ")}…`);
290
+ const npm = spawn("npm", ["install"], { cwd: __dirname, stdio: "inherit", shell: process.platform === "win32" });
291
+ npm.on("error", () => handoff());
292
+ npm.on("close", () => {
293
+ console.log("[volt] saved .env — starting the app…");
294
+ handoff();
295
+ });
296
+ } else {
297
+ console.log("[volt] saved .env — starting the app…");
298
+ handoff();
299
+ }
300
+ });
301
+ } catch (e) {
302
+ res.statusCode = 400;
303
+ res.end(JSON.stringify({ ok: false, error: e.message }));
304
+ }
305
+ });
306
+ return;
307
+ }
308
+ res.statusCode = 404;
309
+ res.end("not found");
310
+ });
311
+
312
+ server.listen(PORT, "127.0.0.1", () => {
313
+ const url = `http://localhost:${PORT}`;
314
+ console.log(`\n⚡ Volt setup → ${url}`);
315
+ console.log(" Configure your app; it starts automatically on Apply. (reopen later: npm run dev -- --edit)");
316
+ const ssh = process.env.SSH_CONNECTION;
317
+ if (ssh) {
318
+ const host = ssh.split(" ")[2];
319
+ const user = process.env.USER || process.env.USERNAME || "you";
320
+ console.log(" Remote box — the server is up here; bridge it from your LOCAL machine:");
321
+ console.log(` ssh -N -L 127.0.0.1:${PORT}:localhost:${PORT} ${user}@${host}`);
322
+ console.log(` …then open ${url} on your machine (the tunnel points it here).`);
323
+ }
324
+ console.log("");
325
+ if (openBrowser(url)) console.log(" (opening your browser…)\n");
326
+ });
327
+ }
328
+
329
+ function readEnvFileLines() {
330
+ return fs.existsSync(ENV_PATH) ? fs.readFileSync(ENV_PATH, "utf8").split("\n") : [];
331
+ }
332
+
333
+ // --- Studio: an ephemeral, localhost-only data browser (à la Prisma Studio).
334
+ // Not a route in the running app — it only exists while you run `--studio`, on
335
+ // loopback, and disappears on Ctrl-C. Shell/SSH access is the auth. ---
336
+ const HIDDEN_COLLECTIONS = new Set(["auth_tokens", "auth_sessions", "__voltcheck"]);
337
+ async function startStudio() {
338
+ loadEnv();
339
+ if (!enabledFrom(process.env).has("db")) {
340
+ console.error("Studio needs the db add-on. Enable it: npm run dev -- --edit");
341
+ process.exit(1);
342
+ }
343
+ let store;
344
+ try {
345
+ store = await (await addonMod("db")).createStore();
346
+ } catch (e) {
347
+ console.error("Studio: couldn't connect the store — " + e.message);
348
+ process.exit(1);
349
+ }
350
+ const PORT = Number(process.env.PORT) || Number(readEnvFile().PORT) || DEFAULT_PORT;
351
+ const visible = (n) => n && !HIDDEN_COLLECTIONS.has(n);
352
+ const assets = {
353
+ "/volt.js": ["text/javascript; charset=utf-8", fs.readFileSync(path.join(__dirname, "public", "volt.js"))],
354
+ "/db-admin-ui.js": ["text/javascript; charset=utf-8", fs.readFileSync(path.join(ADDONS_DIR, "db", "files", "public", "db-admin-ui.js"))],
355
+ };
356
+ const studioHtml = fs.readFileSync(path.join(__dirname, "setup", "studio.html"));
357
+ const json = (res, code, obj) => {
358
+ res.statusCode = code;
359
+ res.setHeader("Content-Type", "application/json");
360
+ res.end(JSON.stringify(obj));
361
+ };
362
+
363
+ const server = http.createServer(async (req, res) => {
364
+ const u = new URL(req.url, "http://localhost");
365
+ const p = u.pathname;
366
+ try {
367
+ if (req.method === "GET" && p === "/") {
368
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
369
+ return res.end(studioHtml);
370
+ }
371
+ if (req.method === "GET" && assets[p]) {
372
+ res.setHeader("Content-Type", assets[p][0]);
373
+ return res.end(assets[p][1]);
374
+ }
375
+ if (req.method === "GET" && p === "/admin/db/collections") {
376
+ const all = (await store.collections()) || [];
377
+ return json(res, 200, { driver: store.name, collections: all.filter(visible) });
378
+ }
379
+ if (req.method === "GET" && p === "/admin/db/collection") {
380
+ const name = u.searchParams.get("name") || "";
381
+ if (!visible(name)) return json(res, 403, { ok: false, error: "hidden" });
382
+ const docs = (await store.collection(name).all()).slice(0, 500);
383
+ return json(res, 200, { ok: true, name, docs });
384
+ }
385
+ if (req.method === "DELETE" && p === "/admin/db/doc") {
386
+ const name = u.searchParams.get("name") || "";
387
+ const id = u.searchParams.get("id") || "";
388
+ if (!visible(name)) return json(res, 403, { ok: false, error: "hidden" });
389
+ if (!id) return json(res, 400, { ok: false, error: "missing id" });
390
+ await store.collection(name).delete(id);
391
+ return json(res, 200, { ok: true });
392
+ }
393
+ res.statusCode = 404;
394
+ res.end("not found");
395
+ } catch (e) {
396
+ json(res, 500, { ok: false, error: e.message });
397
+ }
398
+ });
399
+
400
+ server.listen(PORT, "127.0.0.1", () => {
401
+ const url = `http://localhost:${PORT}`;
402
+ console.log(`\n⚡ Volt Studio → ${url} (${store.name})`);
403
+ console.log(" Browse your data. localhost-only, disposable — Ctrl-C when done.");
404
+ const ssh = process.env.SSH_CONNECTION;
405
+ if (ssh) {
406
+ const host = ssh.split(" ")[2];
407
+ const user = process.env.USER || process.env.USERNAME || "you";
408
+ console.log(" Remote box — from your LOCAL machine:");
409
+ console.log(` ssh -N -L 127.0.0.1:${PORT}:localhost:${PORT} ${user}@${host}`);
410
+ console.log(` …then open ${url}.`);
411
+ }
412
+ console.log("");
413
+ openBrowser(url);
414
+ });
415
+ }
416
+
417
+ // --- gate: studio / setup (first run, --edit) / the app ---
418
+ const editMode = process.argv.includes("--edit") || process.argv.includes("-e");
419
+ if (process.argv.includes("--studio")) {
420
+ startStudio();
421
+ } else if (editMode || !fs.existsSync(ENV_PATH)) {
422
+ startSetup();
423
+ } else {
424
+ loadEnv();
425
+ startApp();
426
+ }