bliss/index.js

862 lines
26 KiB
JavaScript
Raw Normal View History

2024-02-24 11:12:14 -05:00
const fs = require("fs");
2024-10-29 21:29:40 -04:00
const util = require("util");
2024-06-02 00:39:30 -04:00
const vm = require("node:vm");
2024-02-24 11:12:14 -05:00
const path = require("path");
2025-01-12 11:54:14 -05:00
require('dotenv').config()
2024-02-24 11:12:14 -05:00
const express = require("express");
const session = require("express-session");
2024-06-02 10:20:01 -04:00
const fileUpload = require("express-fileupload");
2024-02-24 11:12:14 -05:00
const SQLiteStore = require("better-sqlite3-session-store")(session);
const { Eta } = require("eta");
2024-06-02 00:39:30 -04:00
const { match } = require("path-to-regexp");
2024-02-24 11:12:14 -05:00
const bcrypt = require("bcrypt");
2024-06-02 00:39:30 -04:00
const cheerio = require("cheerio");
2025-01-12 11:54:14 -05:00
const webPush = require("web-push");
2024-02-03 13:22:50 -05:00
const app = express();
2024-06-08 18:29:31 -04:00
const _expressWs = require("express-ws")(app);
2024-02-24 11:12:14 -05:00
const bodyParser = require("body-parser");
2025-01-09 15:42:56 -05:00
const model = require("./db");
2024-02-03 13:22:50 -05:00
const PORT = 3000;
2025-01-09 15:42:56 -05:00
const db = model.db;
const wsRouter = express.Router()
2024-10-29 21:29:40 -04:00
2024-02-24 11:12:14 -05:00
let viewpath = path.join(__dirname, "views");
2024-06-02 00:39:30 -04:00
let eta = new Eta({ views: viewpath, cache: false, autoEscape: true });
2024-06-08 11:42:27 -04:00
let routes = { GET: [], POST: [], PUT: [], DELETE: [] };
const wsRoutes = {}
2025-01-21 18:13:31 -05:00
const wsConnections = {}
2024-02-03 13:22:50 -05:00
2026-08-02 22:06:42 -04:00
const INSPECT_OPTS = { showHidden: false, depth: null, colors: false, compact: false };
function inspectArgs(args) {
return args.map((v) => util.inspect(v, INSPECT_OPTS)).join(" ");
}
function formatError(e) {
return e.stack ? `${e}\n\n${e.stack}` : `${e}`;
}
// Record a handler error in the structure's logs table.
function logError(structureId, routeId, e) {
model.createLog(structureId, routeId, formatError(e), true);
}
2024-02-24 11:12:14 -05:00
app.use(bodyParser.urlencoded({ extended: true }));
2025-01-12 10:16:33 -05:00
app.use(bodyParser.json());
2024-02-24 11:12:14 -05:00
app.use(express.static("public"));
2024-06-02 10:20:01 -04:00
app.use(fileUpload());
2024-02-24 11:12:14 -05:00
app.use(
session({
2024-02-03 13:22:50 -05:00
store: new SQLiteStore({ client: db, expired: { clear: true } }),
2024-02-24 11:12:14 -05:00
secret: "your secret key",
2024-02-03 13:22:50 -05:00
resave: false,
saveUninitialized: true,
2024-02-24 11:12:14 -05:00
cookie: { secure: false },
2025-01-09 15:42:56 -05:00
}),
2024-02-24 11:12:14 -05:00
);
2024-02-03 13:22:50 -05:00
app.use("/", wsRouter);
2025-01-12 11:54:14 -05:00
const vapidPublicKey = process.env.VAPID_PUBLIC_KEY
const vapidPrivateKey = process.env.VAPID_PRIVATE_KEY
// Configure web-push with your VAPID details
webPush.setVapidDetails(
"mailto:signups@sheepmail.net", // a mailto URL or URL
vapidPublicKey,
vapidPrivateKey,
);
async function saveFile(structureId, req, uploadedFile, asset=false) {
const name = uploadedFile.name;
const [mime_type, mime_subtype] = uploadedFile.mimetype.split("/");
const uploadPath = path.join(__dirname, "public", structureId);
const storedPath = path.join(structureId, uploadedFile.name);
fs.mkdirSync(uploadPath, { recursive: true });
await uploadedFile.mv(path.join(uploadPath, name));
let id = model.createFile(
structureId,
name,
storedPath,
mime_type,
mime_subtype,
asset,
);
2026-08-02 22:06:42 -04:00
let file = model.getFile(id);
file.url = prefixUrlWithHost(req, file.path);
return file
}
// A console whose log() mirrors to stdout and to the structure's logs table.
function makeConsole(structureId, routeId) {
return {
log: function (...content) {
content.forEach((c) => console.log(c));
model.createLog(structureId, routeId, inspectArgs(content));
},
};
}
2024-06-08 18:29:31 -04:00
// Evaluate a db's "library" script with `sql` and `console` bound, returning
// its exports. Each library runs in its own context so nothing leaks between dbs.
function runLibrary(sql, librarySource, console) {
const libContext = vm.createContext({ sql, console, module: { exports: null } });
vm.runInContext(librarySource, libContext);
return libContext.module.exports;
}
// The `require(name)` targets available to a user handler.
function makeLibs(structureId, console) {
const dbs = {};
for (let appDb of model.getDbsForStructure(structureId)) {
const sql = model.getDbInstance(appDb.id);
dbs[appDb.alias] = { library: runLibrary(sql, appDb.library, console), sql };
}
return {
eta: model.getTemplater(structureId),
db: (alias) => dbs[alias],
push: webPush,
files: { saveFile: (...args) => saveFile(structureId, ...args) },
};
}
2024-06-08 18:29:31 -04:00
function bootstrapContext(structureId, routeId, initContext) {
const structure = model.getStructure(structureId);
const console = makeConsole(structureId, routeId);
const libs = makeLibs(structureId, console);
2024-06-08 18:29:31 -04:00
return vm.createContext({
2024-06-08 18:29:31 -04:00
...initContext,
require: (name) => libs[name],
2024-06-08 18:29:31 -04:00
module: { exports: null },
console,
2025-02-04 00:23:03 -05:00
vapidPublicKey: vapidPublicKey,
2025-02-04 01:54:56 -05:00
fetch: fetch,
clearTimeout: clearTimeout,
setTimeout: setTimeout,
route: makeRoute(structure),
2024-06-08 18:29:31 -04:00
});
}
2026-08-02 22:06:42 -04:00
function withPrefix(prefix, url) {
return prefix ? path.join(prefix, url) : url;
}
2024-06-08 18:29:31 -04:00
function routeWithPrefix(route) {
2026-08-02 22:06:42 -04:00
return withPrefix(route.route_prefix, route.path);
2024-06-08 18:29:31 -04:00
}
2024-06-08 18:29:31 -04:00
function bootstrapWebsocketHandler(route) {
// todo only expose app when running the handler, should not be available to the handler itself
// need to move to runscript or whatever...or remove app because we can just call it using the handler?
2024-06-08 18:29:31 -04:00
try {
2026-08-02 22:06:42 -04:00
const context = bootstrapContext(route.structure_id, route.id, { app });
let handler = vm.runInContext(`${route.handler}\n\nhandler;`, context);
if (!wsRoutes[routeWithPrefix(route)]) {
2025-01-21 18:13:31 -05:00
wsConnections[routeWithPrefix(route)] = new Set();
// initialize ws router. future updates will only require updating
// the wsRoutes dict, not create a whole new route
wsRouter.ws(routeWithPrefix(route), (ws, req) => {
2025-02-01 00:10:55 -05:00
const myOn = ws.on.bind(ws)
ws.on = (thing, cb) => {
myOn(thing, (...args) => {
try {
cb(...args)
}
catch (e) {
logError(route.structure_id, route.id, e);
2025-02-01 00:10:55 -05:00
}
})
}
ws.render = (template, context = {}) => {
2026-08-02 22:06:42 -04:00
const structure = model.getStructure(route.structure_id);
context.route = makeRoute(structure);
ws.send(
decorate(renderTemplate(route.structure_id, template, context), {
headInjection: structure.head_injection,
source: sourceFor(route, req),
fragment: true,
}),
);
};
2025-01-21 18:13:31 -05:00
ws.clients = wsConnections[routeWithPrefix(route)];
return wsRoutes[routeWithPrefix(route)](ws, req)
});
}
wsRoutes[routeWithPrefix(route)] = (ws, req) => {
try {
return handler(ws, req)
} catch (e) {
logError(route.structure_id, route.id, e);
}
}
2026-08-02 22:06:42 -04:00
model.updateRoute({ ...route, error: null });
2024-06-08 18:29:31 -04:00
} catch (e) {
logError(route.structure_id, route.id, e);
2026-08-02 22:06:42 -04:00
model.updateRoute({ ...route, error: e.stack });
2024-06-08 18:29:31 -04:00
}
}
2024-06-02 00:39:30 -04:00
function buildRoutes() {
2024-06-08 11:42:27 -04:00
let newRoutes = {
GET: [],
POST: [],
PUT: [],
DELETE: [],
};
2026-08-02 22:06:42 -04:00
for (let route of model.getAllRoutes()) {
2024-06-08 18:29:31 -04:00
const p = routeWithPrefix(route);
if (route.verb == "WS") {
bootstrapWebsocketHandler(route);
} else {
newRoutes[route.verb].push({
matcher: match(p, { decode: decodeURIComponent }),
id: route.id,
path: route.path,
});
}
2024-06-02 00:39:30 -04:00
}
2024-06-08 11:42:27 -04:00
routes = newRoutes;
2024-06-02 00:39:30 -04:00
}
2024-10-29 21:29:40 -04:00
model.applyMigrations();
2024-06-02 00:39:30 -04:00
buildRoutes();
2024-02-03 13:22:50 -05:00
2024-02-24 11:12:14 -05:00
// __ __ _______ _______ ______
// | | | || || || _ |
// | | | || _____|| ___|| | ||
// | |_| || |_____ | |___ | |_||_
// | ||_____ || ___|| __ |
// | | _____| || |___ | | | |
// |_______||_______||_______||___| |_|
app.post("/register", async (req, res) => {
try {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10); // 10 is the saltRounds
2026-08-02 22:06:42 -04:00
const userId = model.createUser(username, hashedPassword);
2024-06-02 00:39:30 -04:00
req.session.userId = userId;
2024-02-24 11:12:14 -05:00
res.redirect("/workshop");
} catch (e) {
2025-01-12 10:13:44 -05:00
return res.send(eta.render("auth/register", { error: e }));
2024-02-24 11:12:14 -05:00
}
});
app.post("/login", async (req, res) => {
const { username, password } = req.body;
2026-08-02 22:06:42 -04:00
const user = model.getUser(username);
2024-02-24 11:12:14 -05:00
if (user && (await bcrypt.compare(password, user.password))) {
req.session.userId = user.id;
return res.redirect("/");
}
return res.send(
eta.render("auth/login", {
error: "are you sure you entered that right?",
2025-01-09 15:42:56 -05:00
}),
2024-02-24 11:12:14 -05:00
);
});
app.get("/register", async (req, res) => {
if (req.session.userId) {
return res.redirect("/");
}
2024-06-02 00:39:30 -04:00
return res.send(eta.render("auth/register", { error: null }));
2024-02-24 11:12:14 -05:00
});
app.get("/login", async (req, res) => {
if (req.session.userId) {
return res.redirect("/");
}
return res.send(eta.render("auth/login", { error: null }));
});
app.all("/logout", async (req, res) => {
return req.session.destroy(() => {
res.redirect("/");
});
});
// _ _ _______ ______ ___ _ _______ __ __ _______ _______
// | | _ | || || _ | | | | || || | | || || |
// | || || || _ || | || | |_| || _____|| |_| || _ || _ |
// | || | | || |_||_ | _|| |_____ | || | | || |_| |
// | || |_| || __ || |_ |_____ || || |_| || ___|
// | _ || || | | || _ | _____| || _ || || |
// |__| |__||_______||___| |_||___| |_||_______||__| |__||_______||___|
2024-10-29 21:29:40 -04:00
//
// The chrome injected into the <head> of every rendered page: the client-side
// stack (htmx/hyperscript/tailwind) plus the in-page editor overlay.
function headChrome(headInjection) {
return `
2024-06-02 00:39:30 -04:00
<script src="/js/hyperscript.js"></script>
<script src="/js/tailwind.js"></script>
<script src="/js/htmx.js"></script>
2024-06-08 18:29:31 -04:00
<script src="https://unpkg.com/htmx.org@1.9.12/dist/ext/ws.js"></script>
2024-06-02 00:39:30 -04:00
<script src="/js/bliss_inspector.js"></script>
2024-10-29 21:29:40 -04:00
<script>
tailwind.config = {
corePlugins: {
preflight: false
}
}
</script>
<style> body { margin: 0; }</style>
2024-06-08 15:30:28 -04:00
${headInjection || ""}
`;
}
2024-06-02 00:39:30 -04:00
// A `source` is the provenance of a rendered fragment: which structure/route
// produced it, and (for GET routes) the snippet that re-embeds it. It becomes
// the data-bliss-* attributes the inspector reads.
function blissAttrs(source) {
if (!source) return null;
const attrs = {
"data-bliss-route": `/workshop/${source.structureId}/route/${source.routeId}`,
"data-bliss-clone": `/workshop/${source.structureId}/clone_modal/`,
};
if (source.copyUrl) attrs["data-bliss-copy"] = source.copyUrl;
return attrs;
}
2024-06-02 00:39:30 -04:00
// Full HTML document: inject the head chrome and stamp provenance on <body>.
function decoratePage(html, { headInjection, source } = {}) {
const $ = cheerio.load(html);
let head = $("head");
if (head.length === 0) {
$("html").prepend("<head></head>");
head = $("head");
}
head.attr("id", "head");
head.append(headChrome(headInjection));
const attrs = blissAttrs(source);
if (attrs) {
for (const [k, v] of Object.entries(attrs)) $("body").attr(k, v);
}
return $.html();
}
// HTMX partial: stamp provenance on the swapped-in elements (an oob swap loses
// its own attrs, so we descend into its children) and append an out-of-band
// <head> so head injection still reaches the page.
function decorateFragment(html, { headInjection, source } = {}) {
const $ = cheerio.load(html, null, false);
const attrs = blissAttrs(source);
if (attrs) {
const targets = [];
for (const child of $.root().children()) {
if (child.attribs && child.attribs["hx-swap-oob"]) {
for (const grandchild of child.children) {
if (grandchild.attribs) targets.push(grandchild);
}
} else {
targets.push(child);
}
}
for (const target of targets) Object.assign(target.attribs, attrs);
}
return (
$.html() +
`<head id="head" hx-oob-swap="beforeend">${headInjection || ""}</head>`
);
}
// Single entry point for turning rendered HTML into a response body. A full
// document (or any non-htmx request) becomes a decorated page; an htmx partial
// carrying provenance becomes a decorated fragment; anything else passes through.
function decorate(html, { headInjection, source, fragment } = {}) {
const lower = html.toLowerCase();
const isFullDoc =
lower.startsWith("<html>") || lower.startsWith("<!doctype");
if (isFullDoc || !fragment) {
return decoratePage(html, { headInjection, source });
}
if (source) return decorateFragment(html, { headInjection, source });
return html;
}
// One prefix-bound route() helper per structure, shared by every render site.
function makeRoute(structure) {
return (url) => withPrefix(structure.route_prefix, url);
}
2024-06-08 18:29:31 -04:00
function renderTemplate(structureId, templateName, context) {
return model.getTemplater(structureId).render(templateName, context);
}
2024-02-24 11:12:14 -05:00
// Provenance for a rendered response: GET routes are re-embeddable, so they
// carry the copy-embed snippet; other verbs don't.
function sourceFor(route, req) {
return {
structureId: route.structure_id,
routeId: route.id,
copyUrl: route.verb === "GET" ? embedHTML(req.originalUrl) : null,
};
2024-02-24 11:12:14 -05:00
}
app.post("/workshop", (req, res) => {
2026-08-02 22:06:42 -04:00
let structId = model.createStructure(req.body.name);
2024-02-24 11:12:14 -05:00
return res.redirect("/workshop/" + structId);
});
app.get("/workshop", (req, res) => {
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/index", {
structures: model.getStructures(),
});
2024-02-24 11:12:14 -05:00
});
2026-08-02 22:06:42 -04:00
function renderWorkshop(res, template, context) {
res.send(decorate(eta.render(template, context)));
2026-08-02 22:06:42 -04:00
}
2024-06-02 00:39:30 -04:00
function smartRedirect(req, res, redirectUrl) {
if (req.headers["hx-request"]) {
res.set("HX-Redirect", redirectUrl);
res.send();
} else {
res.redirect(redirectUrl);
}
}
2026-08-02 22:06:42 -04:00
function sidebarStuff(structId) {
2024-06-02 00:39:30 -04:00
return {
2026-08-02 22:06:42 -04:00
structure: model.getStructure(structId),
routes: model.getRoutes(structId),
templates: model.getTemplates(structId),
dbs: model.getDbsForStructure(structId),
2024-06-02 00:39:30 -04:00
};
}
2024-02-24 11:12:14 -05:00
app.get("/workshop/:structure_id", (req, res) => {
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/editor", sidebarStuff(req.params.structure_id));
2024-06-02 00:39:30 -04:00
});
2024-06-04 03:01:19 -04:00
app.post("/workshop/:structure_id/clone", (req, res) => {
let routePrefix = req.body.route_prefix;
routePrefix = routePrefix[0] == "/" ? routePrefix : "/" + routePrefix;
let newStructureId;
try {
2024-10-29 21:29:40 -04:00
newStructureId = model.cloneStructure(
2024-06-04 03:01:19 -04:00
req.params.structure_id,
req.body.name,
1,
// req.session.userId,
routePrefix,
2025-01-09 15:42:56 -05:00
req.body.clone_dbs,
2024-06-04 03:01:19 -04:00
);
buildRoutes();
} catch (e) {
return res.send(e.stack);
}
return smartRedirect(req, res, `/workshop/${newStructureId}`);
});
2024-06-02 00:39:30 -04:00
app.post("/workshop/:structure_id/db", (req, res) => {
2026-08-02 22:06:42 -04:00
const dbId = model.createDb(req.params.structure_id, req.body.name);
2024-06-02 00:39:30 -04:00
const redirectUrl = `/workshop/${req.params.structure_id}/db/${dbId}`;
return smartRedirect(req, res, redirectUrl);
});
app.post("/workshop/:structure_id/db/attach", (req, res) => {
2026-08-02 22:06:42 -04:00
model.attachDb(req.params.structure_id, req.body.db_id, req.body.alias);
const redirectUrl = `/workshop/${req.params.structure_id}/db/${req.body.db_id}`;
return smartRedirect(req, res, redirectUrl);
});
2024-06-02 00:39:30 -04:00
app.get("/workshop/:structure_id/db/:db_id", (req, res) => {
2024-10-29 21:29:40 -04:00
const structdb = model.getDbForStructure(
2024-06-02 00:39:30 -04:00
req.params.structure_id,
2025-01-09 15:42:56 -05:00
req.params.db_id,
2024-06-02 00:39:30 -04:00
);
if (!structdb) {
return res.send("uh oh");
}
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/db_garden", {
db: structdb,
...sidebarStuff(req.params.structure_id),
});
2024-06-02 00:39:30 -04:00
});
app.post("/workshop/:structure_id/route", (req, res) => {
2024-06-08 18:29:31 -04:00
let p = req.body.path;
let dummyHandler =
"// put your handler code here\n\nfunction handler(req, res) {\n res.send('henlo world') \n}";
2024-06-02 00:44:02 -04:00
2024-06-08 18:29:31 -04:00
if (req.body.verb == "WS") {
dummyHandler = `// put your websocket handler code here\n\nfunction handler(ws, req) {\n ws.on('message', function(msg) {\n ws.send(msg);\n })\n}`;
}
if (p[0] == "/") {
p = p.substring(1);
}
if (p[p.length - 1] == "/") {
p = p.substring(0, p.length - 1);
}
2024-10-29 21:29:40 -04:00
const route = model.createRoute(
2024-06-02 00:39:30 -04:00
req.body.verb,
2024-06-08 18:29:31 -04:00
p[0] == "/" ? p.substring(1) : "/" + p,
2024-06-02 00:39:30 -04:00
req.params.structure_id,
2025-01-09 15:42:56 -05:00
dummyHandler,
2024-06-02 00:39:30 -04:00
);
2024-06-04 03:01:19 -04:00
// todo optimize by only adding new, don't just rebuild all
2024-06-02 00:39:30 -04:00
buildRoutes();
return smartRedirect(
req,
res,
2025-01-09 15:42:56 -05:00
`/workshop/${req.params.structure_id}/route/${route}`,
2024-06-02 00:39:30 -04:00
);
});
app.put("/workshop/:structure_id/route/:route_id", (req, res) => {
2026-08-02 22:06:42 -04:00
const route = model.getRoute(req.params.route_id);
model.updateRoute({ ...route, ...req.body });
2025-01-21 01:08:54 -05:00
if (req.body.scaffold_page) {
// TODO: make this send over scaffold page id too someday
2026-08-02 22:06:42 -04:00
const latestPage = model.getLatestScaffoldPage(req.params.route_id)
model.updateScaffoldPage({ ...latestPage, content: req.body.scaffold_page })
2025-01-21 01:08:54 -05:00
}
if (route.verb == "WS") {
bootstrapWebsocketHandler({ ...route, ...req.body })
}
2024-06-02 00:39:30 -04:00
return res.send("good");
});
app.put("/workshop/:structure_id/db/:db_id/library", (req, res) => {
try {
let dbId = req.params.db_id;
2026-08-02 22:06:42 -04:00
let appDb = model.getDb(dbId);
model.updateDb({ ...appDb, library: req.body.library });
appDb = model.getDb(dbId);
2024-06-02 00:39:30 -04:00
2024-10-29 21:29:40 -04:00
let dbInstance = model.getDbInstance(dbId);
2024-06-02 00:39:30 -04:00
let capturedOutput = [];
let context = vm.createContext({
module: { exports: null },
sql: dbInstance,
console: {
2026-08-02 22:06:42 -04:00
log: (...args) => capturedOutput.push(inspectArgs(args)),
2024-06-02 00:39:30 -04:00
},
});
let evaledCode = vm.runInContext(appDb.library, context);
2026-08-02 22:06:42 -04:00
let stdout = capturedOutput.join("\n");
2024-06-02 00:39:30 -04:00
return res.send(`${stdout}\n\n> ${evaledCode}`.trim());
} catch (e) {
return res.send(`${e}\n\n${e.stack}`);
}
});
app.post("/workshop/:structure_id/db/:db_id/repl", (req, res) => {
try {
let dbId = req.params.db_id;
2026-08-02 22:06:42 -04:00
let appDb = model.getDb(dbId);
2024-10-29 21:29:40 -04:00
let dbInstance = model.getDbInstance(dbId);
2024-06-02 00:39:30 -04:00
let capturedOutput = [];
let context = vm.createContext({
module: { exports: null },
sql: dbInstance,
console: {
2026-08-02 22:06:42 -04:00
log: (...args) => capturedOutput.push(inspectArgs(args)),
2024-06-02 00:39:30 -04:00
},
});
const libraryScript = new vm.Script(appDb.library);
libraryScript.runInContext(context);
context.library = context.module.exports;
const replScript = new vm.Script(req.body.code);
2024-10-29 21:29:40 -04:00
let evaledCode = JSON.stringify(replScript.runInContext(context));
2024-06-02 00:39:30 -04:00
let stdout = capturedOutput.join("\n");
return res.send(`${stdout}\n\n> ${evaledCode}`.trim());
} catch (e) {
return res.send(`${e}\n\n${e.stack}`);
}
});
2024-06-02 10:20:01 -04:00
app.post("/workshop/:structure_id/template", (req, res) => {
let name = req.body.name;
2024-10-29 21:29:40 -04:00
const template = model.createTemplate(
2024-06-02 10:20:01 -04:00
req.params.structure_id,
name,
"<div>henlo <%= it.name %></div>",
2025-01-09 15:42:56 -05:00
"it = { name: 'templates!' };",
2024-06-02 10:20:01 -04:00
);
return smartRedirect(
req,
res,
2025-01-09 15:42:56 -05:00
`/workshop/${req.params.structure_id}/template/${template}`,
2024-06-02 10:20:01 -04:00
);
});
app.put("/workshop/:structure_id/template/:template_id", (req, res) => {
let id = req.params.template_id;
let content = req.body.content;
let test_object = req.body.test_object;
2026-08-02 22:06:42 -04:00
model.updateTemplate({
...model.getTemplate(id),
2025-01-09 15:42:56 -05:00
content,
test_object,
});
2024-06-02 10:20:01 -04:00
return res.send("good");
});
app.get("/workshop/:structure_id/template/:template_id", (req, res) => {
2026-08-02 22:06:42 -04:00
const template = model.getTemplate(req.params.template_id);
2024-10-29 21:29:40 -04:00
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/template", {
template: template,
...sidebarStuff(req.params.structure_id),
});
2024-06-02 10:20:01 -04:00
});
app.get("/workshop/:structure_id/template/:template_id/preview", (req, res) => {
2026-08-02 22:06:42 -04:00
const template = model.getTemplate(req.params.template_id);
const struct = model.getStructure(req.params.structure_id);
2024-06-02 10:20:01 -04:00
const context = vm.createContext({ it: null });
vm.runInContext(template.test_object, context);
context.it.route = makeRoute(struct);
2024-06-04 03:01:19 -04:00
2024-06-02 10:20:01 -04:00
return res.send(
decorate(renderTemplate(req.params.structure_id, template.name, context.it), {
headInjection: struct.head_injection,
}),
2024-06-02 10:20:01 -04:00
);
});
2024-06-02 00:39:30 -04:00
app.get("/workshop/:structure_id/route/:id", (req, res) => {
2026-08-02 22:06:42 -04:00
const route = model.getRoute(req.params.id);
let routePrefix = model.getStructure(req.params.structure_id).route_prefix;
2025-01-21 01:08:54 -05:00
let previewUrl = null;
if (route["verb"] == "GET" ) {
previewUrl = routePrefix
? path.join(routePrefix || "", route.path)
: route.path;
}
else {
previewUrl = `/workshop/${req.params.structure_id}/route/${req.params.id}/preview`;
}
2026-08-02 22:06:42 -04:00
const template = route["verb"] == "GET" ? "workshop/route" : "workshop/cud_route";
2024-06-08 18:29:31 -04:00
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, template, {
route: route,
previewUrl: previewUrl,
...sidebarStuff(req.params.structure_id),
});
2024-06-02 00:39:30 -04:00
});
2025-01-21 01:08:54 -05:00
app.get("/workshop/:structure_id/route/:route_id/preview", (req, res) => {
2026-08-02 22:06:42 -04:00
const route = model.getRoute(req.params.route_id);
const struct = model.getStructure(req.params.structure_id);
2025-01-21 01:08:54 -05:00
const it = { route: makeRoute(struct) };
2025-01-21 01:08:54 -05:00
return res.send(
decorate(eta.renderString(route.scaffold_page_content, it), {
headInjection: struct.head_injection,
}),
2025-01-21 01:08:54 -05:00
);
});
2024-10-29 21:29:40 -04:00
app.get("/workshop/:structure_id/route/:route_id/logs", (req, res) => {
2025-01-09 15:42:56 -05:00
const since = req.query.since;
let logs = [];
2024-10-29 21:29:40 -04:00
if (since != undefined) {
2026-08-02 22:06:42 -04:00
logs = model.getNewLogsByRoute(req.params.route_id, since);
2025-01-09 15:42:56 -05:00
} else {
2026-08-02 22:06:42 -04:00
logs = model.getLogsByRoute(req.params.route_id);
2024-10-29 21:29:40 -04:00
}
2026-08-02 22:06:42 -04:00
const lastId = model.getMostRecentLogIdByRoute(req.params.route_id);
2024-10-29 21:29:40 -04:00
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/logs", {
logs: logs,
structId: req.params.structure_id,
routeId: req.params.route_id,
since: lastId,
});
2024-10-29 21:29:40 -04:00
});
2024-06-03 20:19:26 -04:00
// POST route to handle file upload
app.post("/workshop/:structure_id/files", async (req, res) => {
2024-06-03 20:19:26 -04:00
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("failed to upload that file");
}
const { structure_id } = req.params;
const targetFile = req.files.file;
2024-06-03 20:19:26 -04:00
try {
const uploadedFile = await saveFile(structure_id, req, targetFile)
return res.send(eta.render("workshop/file_detail", { file: uploadedFile }));
}
catch (e) {
console.log(e)
2024-06-03 20:19:26 -04:00
res.status(500);
return res.send(e);
}
2024-06-03 20:19:26 -04:00
});
function prefixUrlWithHost(req, path) {
return req.protocol + "://" + req.get("host") + "/" + path;
}
// POST route to handle file upload
app.get("/workshop/:structure_id/files", (req, res) => {
const { structure_id } = req.params;
2026-08-02 22:06:42 -04:00
const files = model.getFilesForStruct(structure_id);
2024-06-03 20:19:26 -04:00
files.map((it) => {
it.url = prefixUrlWithHost(req, it.path);
});
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/files", {
files,
...sidebarStuff(structure_id),
});
2024-06-02 00:39:30 -04:00
});
2024-06-04 03:01:19 -04:00
app.get("/workshop/:structure_id/settings", (req, res) => {
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/settings", {
...sidebarStuff(req.params.structure_id),
});
2024-06-04 03:01:19 -04:00
});
app.put("/workshop/:structure_id/settings", (req, res) => {
let structId = req.params.structure_id;
2026-08-02 22:06:42 -04:00
let struct = model.getStructure(structId);
2024-06-08 18:29:31 -04:00
let routePrefix = req.body.route_prefix;
if (routePrefix[0] != "/") {
routePrefix = "/" + routePrefix;
}
if (routePrefix[routePrefix.length - 1] == "/") {
routePrefix = routePrefix.substring(0, routePrefix.length - 1);
}
2026-08-02 22:06:42 -04:00
model.updateStruct({
2024-06-08 15:30:28 -04:00
...struct,
2024-06-08 18:29:31 -04:00
route_prefix: routePrefix,
2024-06-08 15:30:28 -04:00
head_injection: req.body.head_injection,
});
2026-08-02 22:06:42 -04:00
struct = model.getStructure(structId);
2024-06-04 03:01:19 -04:00
res.send("success!");
});
2024-06-02 00:39:30 -04:00
app.get("/workshop/:structure_id/new_template_modal", (req, res) => {
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/new_template_modal", {
structure: model.getStructure(req.params.structure_id),
});
2024-06-02 00:39:30 -04:00
});
app.get("/workshop/:structure_id/new_route_modal", (req, res) => {
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/new_route_modal", {
structure: model.getStructure(req.params.structure_id),
});
2024-06-02 00:39:30 -04:00
});
app.get("/workshop/:structure_id/new_db_modal", (req, res) => {
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/new_db_modal", {
structure: model.getStructure(req.params.structure_id),
});
2024-02-24 11:12:14 -05:00
});
2024-06-04 03:01:19 -04:00
app.get("/workshop/:structure_id/clone_modal", (req, res) => {
2026-08-02 22:06:42 -04:00
const structure = model.getStructure(req.params.structure_id);
const dbs = model.getDbsForStructure(req.params.structure_id);
2024-06-08 11:42:27 -04:00
2026-08-02 22:06:42 -04:00
return renderWorkshop(res, "workshop/clone_structure_modal", {
structure,
dbs,
defaultRoutePrefix: path.join(structure.route_prefix || "", "clone"),
});
2024-06-04 03:01:19 -04:00
});
function embedHTML(url) {
return `<div hx-get="${url}" hx-trigger="load"></div>`;
}
2025-01-12 10:16:51 -05:00
app.all("*", async (req, res) => {
2024-06-04 03:01:19 -04:00
const req_path = req.path;
2024-02-24 11:12:14 -05:00
const verb = req.method;
try {
2024-06-02 00:39:30 -04:00
let routeMatch = null;
2024-02-24 11:12:14 -05:00
// routes[verb] is ordered most-recently-updated first (getAllRoutes sorts
// by updated_at DESC), so the first match is the most recently saved route.
2024-06-02 00:39:30 -04:00
for (let { matcher, id } of routes[verb]) {
2024-06-04 03:01:19 -04:00
let matchFromRoute = matcher(req_path);
2024-06-02 00:39:30 -04:00
if (matchFromRoute) {
routeMatch = { params: matchFromRoute.params, id: id };
break;
2024-06-02 00:39:30 -04:00
}
}
if (routeMatch) {
req.params = routeMatch.params;
const route = model.getRoute(routeMatch.id);
2024-06-02 00:39:30 -04:00
2026-08-02 22:06:42 -04:00
const structure = model.getStructure(route.structure_id);
2024-06-02 00:39:30 -04:00
try {
2024-06-08 18:29:31 -04:00
// todo: only add req res to contexst when running the handler()
// which means moving to runscript instead of runincontext for that
2026-08-02 22:06:42 -04:00
let context = bootstrapContext(route.structure_id, route.id, {
2024-06-02 00:39:30 -04:00
req,
res,
2024-06-08 15:30:28 -04:00
eta,
2024-06-02 00:39:30 -04:00
});
res.render = (template, context = {}) => {
context.route = makeRoute(structure);
2024-06-08 15:30:28 -04:00
res.send(
decorate(renderTemplate(route.structure_id, template, context), {
headInjection: structure.head_injection,
source: sourceFor(route, req),
fragment: req.headers["hx-request"],
}),
2024-06-04 03:01:19 -04:00
);
2024-06-02 10:20:01 -04:00
};
2025-01-12 10:16:51 -05:00
const handlerScript = new vm.Script(route.handler, { filename: `handler_${route.id}.js` });
// Prepare the execution code that invokes `handler(req, res)` and awaits it
const executionScript = new vm.Script(`handler(req, res); `, { filename: `execution_${route.id}.js` });
await handlerScript.runInContext(context);
const result = await executionScript.runInContext(context);
2024-06-02 00:39:30 -04:00
} catch (e) {
logError(structure.id, route.id, e);
return res.status(500).send(formatError(e));
2024-06-02 00:39:30 -04:00
}
2024-02-24 11:12:14 -05:00
} else {
res.status(404).json({ success: false, message: "Path not found" });
2024-02-03 13:22:50 -05:00
}
2024-02-24 11:12:14 -05:00
} catch (error) {
console.error(error);
res.status(500).json({ success: false, message: "Internal server error" });
}
2024-02-03 13:22:50 -05:00
});
app.listen(PORT, () => {
2024-02-24 11:12:14 -05:00
console.log(`Server is running on http://localhost:${PORT}`);
2024-02-03 13:22:50 -05:00
});