This commit is contained in:
2026-03-18 17:37:24 +01:00
parent f6db3ab866
commit eec0df83cd
79 changed files with 2333 additions and 1 deletions
+8
View File
@@ -0,0 +1,8 @@
import { AppData } from "../../data/app-data";
import trimAllCache from "../cache/trim-all-cache";
export default async function cron() {
while (true) {
await trimAllCache();
await Bun.sleep(AppData["DefaultCronInterval"]);
}
}
+46
View File
@@ -0,0 +1,46 @@
import grabRouteParams from "../../utils/grab-route-params";
import grabConstants from "../../utils/grab-constants";
import grabRouter from "../../utils/grab-router";
export default async function ({ req, server }) {
const url = new URL(req.url);
const { MBInBytes, ServerDefaultRequestBodyLimitBytes } = grabConstants();
const router = grabRouter();
const match = router.match(url.pathname);
if (!match?.filePath) {
const errMsg = `Route ${url.pathname} not found`;
return Response.json({
success: false,
msg: errMsg,
}, {
status: 401,
headers: {
"Content-Type": "application/json",
},
});
}
const routeParams = await grabRouteParams({ req });
const module = await import(match.filePath);
const config = module.config;
const contentLength = req.headers.get("content-length");
if (contentLength) {
const size = parseInt(contentLength, 10);
if ((config?.maxRequestBodyMB &&
size > config.maxRequestBodyMB * MBInBytes) ||
size > ServerDefaultRequestBodyLimitBytes) {
return Response.json({
success: false,
msg: "Request Body Too Large!",
}, {
status: 413,
headers: {
"Content-Type": "application/json",
},
});
}
}
const res = await module["default"]({
...routeParams,
server,
});
return res;
}
+16
View File
@@ -0,0 +1,16 @@
import allPagesBundler from "../bundler/all-pages-bundler";
import serverPostBuildFn from "./server-post-build-fn";
export default async function rebuildBundler() {
try {
global.ROUTER.reload();
await global.BUNDLER_CTX?.dispose();
global.BUNDLER_CTX = undefined;
await allPagesBundler({
watch: true,
post_build_fn: serverPostBuildFn,
});
}
catch (error) {
console.error(error);
}
}
+91
View File
@@ -0,0 +1,91 @@
import path from "path";
import grabAppPort from "../../utils/grab-app-port";
import grabDirNames from "../../utils/grab-dir-names";
import handleWebPages from "./web-pages/handle-web-pages";
import handleRoutes from "./handle-routes";
import isDevelopment from "../../utils/is-development";
import grabConstants from "../../utils/grab-constants";
import { AppData } from "../../data/app-data";
export default async function (params) {
const port = grabAppPort();
const { PUBLIC_DIR } = grabDirNames();
const is_dev = isDevelopment();
return {
async fetch(req, server) {
try {
const url = new URL(req.url);
const { config } = grabConstants();
if (config?.middleware) {
const middleware_res = await config.middleware({
req,
url,
server,
});
if (typeof middleware_res == "object") {
return middleware_res;
}
}
if (url.pathname === "/__hmr" && is_dev) {
const referer_url = new URL(req.headers.get("referer") || "");
const match = global.ROUTER.match(referer_url.pathname);
const target_map = match?.filePath
? global.BUNDLER_CTX_MAP?.find((m) => m.local_path == match.filePath)
: undefined;
let controller;
const stream = new ReadableStream({
start(c) {
controller = c;
global.HMR_CONTROLLERS.push({
controller: c,
page_url: referer_url.href,
target_map,
});
},
cancel() {
const targetControllerIndex = global.HMR_CONTROLLERS.findIndex((c) => c.controller == controller);
if (typeof targetControllerIndex == "number" &&
targetControllerIndex >= 0) {
global.HMR_CONTROLLERS.splice(targetControllerIndex, 1);
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
if (url.pathname.startsWith("/api/")) {
return await handleRoutes({ req, server });
}
if (url.pathname.startsWith("/public/")) {
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname.replace(/^\/public/, "")));
let res_opts = {};
if (!is_dev && url.pathname.match(/__bunext/)) {
res_opts.headers = {
"Cache-Control": `public, max-age=${AppData["BunextStaticFilesCacheExpiry"]}, must-revalidate`,
};
}
return new Response(file, res_opts);
}
if (url.pathname.startsWith("/favicon.")) {
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname));
return new Response(file);
}
return await handleWebPages({ req });
}
catch (error) {
return new Response(`Server Error: ${error.message}`, {
status: 500,
});
}
},
port,
idleTimeout: 0,
development: {
hmr: true,
},
};
}
+26
View File
@@ -0,0 +1,26 @@
import _ from "lodash";
export default async function serverPostBuildFn({ artifacts }) {
if (!global.IS_FIRST_BUNDLE_READY) {
global.IS_FIRST_BUNDLE_READY = true;
}
if (!global.HMR_CONTROLLERS?.[0]) {
return;
}
for (let i = 0; i < global.HMR_CONTROLLERS.length; i++) {
const controller = global.HMR_CONTROLLERS[i];
const target_artifact = artifacts.find((a) => controller.target_map?.local_path == a.local_path);
const final_artifact = {
..._.omit(controller, ["controller"]),
target_map: target_artifact,
};
if (!target_artifact) {
delete final_artifact.target_map;
}
try {
controller.controller.enqueue(`event: update\ndata: ${JSON.stringify(final_artifact)}\n\n`);
}
catch {
global.HMR_CONTROLLERS.splice(i, 1);
}
}
}
+46
View File
@@ -0,0 +1,46 @@
import _ from "lodash";
import AppNames from "../../utils/grab-app-names";
import allPagesBundler from "../bundler/all-pages-bundler";
import serverParamsGen from "./server-params-gen";
import watcher from "./watcher";
import serverPostBuildFn from "./server-post-build-fn";
import grabDirNames from "../../utils/grab-dir-names";
import EJSON from "../../utils/ejson";
import { readFileSync } from "fs";
import cron from "./cron";
const { HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
export default async function startServer(params) {
const { name } = AppNames;
const serverParams = await serverParamsGen();
if (params?.dev) {
await allPagesBundler({
watch: true,
post_build_fn: serverPostBuildFn,
});
watcher();
}
else {
const artifacts = EJSON.parse(readFileSync(HYDRATION_DST_DIR_MAP_JSON_FILE, "utf-8"));
if (!artifacts?.[0]) {
console.error(`Please build first.`);
process.exit(1);
}
global.BUNDLER_CTX_MAP = artifacts;
global.IS_FIRST_BUNDLE_READY = true;
cron();
}
let bundle_ready_retries = 0;
const MAX_BUNDLE_READY_RETRIES = 10;
while (!global.IS_FIRST_BUNDLE_READY) {
if (bundle_ready_retries > MAX_BUNDLE_READY_RETRIES) {
console.error(`Couldn't grab first bundle for dev environment`);
process.exit(1);
}
bundle_ready_retries++;
await Bun.sleep(500);
}
const server = Bun.serve(serverParams);
global.SERVER = server;
console.log(`${name} Server Running on http://localhost:${server.port} ...`);
return server;
}
+31
View File
@@ -0,0 +1,31 @@
import { watch, existsSync } from "fs";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import rebuildBundler from "./rebuild-bundler";
const { SRC_DIR } = grabDirNames();
export default function watcher() {
watch(SRC_DIR, {
recursive: true,
persistent: true,
}, async (event, filename) => {
if (!filename)
return;
if (event !== "rename")
return;
if (global.RECOMPILING)
return;
const fullPath = path.join(SRC_DIR, filename);
const action = existsSync(fullPath) ? "created" : "deleted";
try {
global.RECOMPILING = true;
console.log(`Page ${action}: ${filename}. Rebuilding ...`);
await rebuildBundler();
}
catch (error) {
console.error(error);
}
finally {
global.RECOMPILING = false;
}
});
}
+42
View File
@@ -0,0 +1,42 @@
import { jsx as _jsx } from "react/jsx-runtime";
import path from "path";
import grabContants from "../../../utils/grab-constants";
import EJSON from "../../../utils/ejson";
import isDevelopment from "../../../utils/is-development";
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
import grabWebMetaHTML from "./grab-web-meta-html";
export default async function genWebHTML({ component, pageProps, bundledMap, head: Head, module, meta, routeParams, }) {
const { ClientRootElementIDName, ClientWindowPagePropsName } = grabContants();
const { renderToString } = await import(path.join(process.cwd(), "node_modules", "react-dom", "server"));
const componentHTML = renderToString(component);
const headHTML = Head
? renderToString(_jsx(Head, { serverRes: pageProps, ctx: routeParams }))
: "";
let html = `<!DOCTYPE html>\n`;
html += `<html>\n`;
html += ` <head>\n`;
html += ` <meta charset="utf-8" />\n`;
html += ` <meta name="viewport" content="width=device-width, initial-scale=1.0">\n`;
if (meta) {
html += ` ${grabWebMetaHTML({ meta })}\n`;
}
if (bundledMap?.css_path) {
html += ` <link rel="stylesheet" href="/${bundledMap.css_path}" />\n`;
}
html += ` <script>window.${ClientWindowPagePropsName} = ${EJSON.stringify(pageProps || {}) || "{}"}</script>\n`;
if (bundledMap?.path) {
html += ` <script src="/${bundledMap.path}" type="module" async></script>\n`;
}
if (isDevelopment()) {
html += `<script defer>\n${await grabWebPageHydrationScript({ bundledMap })}\n</script>\n`;
}
if (headHTML) {
html += ` ${headHTML}\n`;
}
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
html += ` </body>\n`;
html += `</html>\n`;
return html;
}
+109
View File
@@ -0,0 +1,109 @@
import { jsx as _jsx } from "react/jsx-runtime";
import grabDirNames from "../../../utils/grab-dir-names";
import grabRouteParams from "../../../utils/grab-route-params";
import path from "path";
import AppNames from "../../../utils/grab-app-names";
import { existsSync } from "fs";
import grabPageErrorComponent from "./grab-page-error-component";
class NotFoundError extends Error {
}
export default async function grabPageComponent({ req, file_path: passed_file_path, }) {
const url = req?.url ? new URL(req.url) : undefined;
const router = global.ROUTER;
const { PAGES_DIR } = grabDirNames();
let routeParams = undefined;
try {
routeParams = req ? await grabRouteParams({ req }) : undefined;
let url_path = url ? url.pathname : undefined;
if (url_path && url?.search) {
url_path += url.search;
}
const match = url_path ? router.match(url_path) : undefined;
if (!match?.filePath && url?.pathname) {
throw new NotFoundError(`Page ${url.pathname} not found`);
}
const file_path = match?.filePath || passed_file_path;
if (!file_path) {
const errMsg = `No File Path (\`file_path\`) or Request Object (\`req\`) provided not found`;
// console.error(errMsg);
throw new Error(errMsg);
}
const bundledMap = global.BUNDLER_CTX_MAP?.find((m) => m.local_path == file_path);
if (!bundledMap?.path) {
const errMsg = `No Bundled File Path for this request path!`;
console.error(errMsg);
throw new Error(errMsg);
}
// const pageName = grabPageName({ path: file_path });
const root_pages_component_ts_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.ts`;
const root_pages_component_tsx_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.tsx`;
const root_pages_component_js_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.js`;
const root_pages_component_jsx_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.jsx`;
const root_file = existsSync(root_pages_component_tsx_file)
? root_pages_component_tsx_file
: existsSync(root_pages_component_ts_file)
? root_pages_component_ts_file
: existsSync(root_pages_component_jsx_file)
? root_pages_component_jsx_file
: existsSync(root_pages_component_js_file)
? root_pages_component_js_file
: undefined;
const now = Date.now();
const root_module = root_file
? await import(`${root_file}?t=${now}`)
: undefined;
const RootComponent = root_module?.default;
// const component_file_path = root_module
// ? `${file_path}`
// : `${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`;
const module = await import(`${file_path}?t=${now}`);
const serverRes = await (async () => {
try {
if (routeParams) {
const serverData = await module["server"]?.(routeParams);
return {
...serverData,
query: match?.query,
};
}
return {
query: match?.query,
};
}
catch (error) {
return {
query: match?.query,
};
}
})();
const meta = module.meta
? typeof module.meta == "function" && routeParams
? await module.meta({
ctx: routeParams,
serverRes,
})
: typeof module.meta == "object"
? module.meta
: undefined
: undefined;
const Component = module.default;
const Head = module.Head;
const component = RootComponent ? (_jsx(RootComponent, { ...serverRes, children: _jsx(Component, { ...serverRes }) })) : (_jsx(Component, { ...serverRes }));
return {
component,
serverRes,
routeParams,
module,
bundledMap,
meta,
head: Head,
};
}
catch (error) {
return await grabPageErrorComponent({
error,
routeParams,
is404: error instanceof NotFoundError,
});
}
}
@@ -0,0 +1,42 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import grabDirNames from "../../../utils/grab-dir-names";
export default async function grabPageErrorComponent({ error, routeParams, is404, }) {
const router = global.ROUTER;
const { BUNX_ROOT_500_PRESET_COMPONENT, BUNX_ROOT_404_PRESET_COMPONENT } = grabDirNames();
const errorRoute = is404 ? "/404" : "/500";
const presetComponent = is404
? BUNX_ROOT_404_PRESET_COMPONENT
: BUNX_ROOT_500_PRESET_COMPONENT;
try {
const match = router.match(errorRoute);
const filePath = match?.filePath || presetComponent;
const bundledMap = match?.filePath
? (global.BUNDLER_CTX_MAP?.find((m) => m.local_path === match.filePath) ?? {})
: {};
const module = await import(filePath);
const Component = module.default;
const component = _jsx(Component, { children: _jsx("span", { children: error.message }) });
return {
component,
routeParams,
module,
bundledMap,
};
}
catch {
const DefaultNotFound = () => (_jsxs("div", { style: {
width: "100vw",
height: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
}, children: [_jsx("h1", { children: is404 ? "404 Not Found" : "500 Internal Server Error" }), _jsx("span", { children: error.message })] }));
return {
component: _jsx(DefaultNotFound, {}),
routeParams,
module: { default: DefaultNotFound },
bundledMap: {},
};
}
}
+60
View File
@@ -0,0 +1,60 @@
export default function grabWebMetaHTML({ meta }) {
let html = ``;
if (meta.title) {
html += ` <title>${meta.title}</title>\n`;
}
if (meta.description) {
html += ` <meta name="description" content="${meta.description}" />\n`;
}
if (meta.keywords) {
const keywords = Array.isArray(meta.keywords)
? meta.keywords.join(", ")
: meta.keywords;
html += ` <meta name="keywords" content="${keywords}" />\n`;
}
if (meta.author) {
html += ` <meta name="author" content="${meta.author}" />\n`;
}
if (meta.robots) {
html += ` <meta name="robots" content="${meta.robots}" />\n`;
}
if (meta.canonical) {
html += ` <link rel="canonical" href="${meta.canonical}" />\n`;
}
if (meta.themeColor) {
html += ` <meta name="theme-color" content="${meta.themeColor}" />\n`;
}
if (meta.og) {
const { og } = meta;
if (og.title)
html += ` <meta property="og:title" content="${og.title}" />\n`;
if (og.description)
html += ` <meta property="og:description" content="${og.description}" />\n`;
if (og.image)
html += ` <meta property="og:image" content="${og.image}" />\n`;
if (og.url)
html += ` <meta property="og:url" content="${og.url}" />\n`;
if (og.type)
html += ` <meta property="og:type" content="${og.type}" />\n`;
if (og.siteName)
html += ` <meta property="og:site_name" content="${og.siteName}" />\n`;
if (og.locale)
html += ` <meta property="og:locale" content="${og.locale}" />\n`;
}
if (meta.twitter) {
const { twitter } = meta;
if (twitter.card)
html += ` <meta name="twitter:card" content="${twitter.card}" />\n`;
if (twitter.title)
html += ` <meta name="twitter:title" content="${twitter.title}" />\n`;
if (twitter.description)
html += ` <meta name="twitter:description" content="${twitter.description}" />\n`;
if (twitter.image)
html += ` <meta name="twitter:image" content="${twitter.image}" />\n`;
if (twitter.site)
html += ` <meta name="twitter:site" content="${twitter.site}" />\n`;
if (twitter.creator)
html += ` <meta name="twitter:creator" content="${twitter.creator}" />\n`;
}
return html;
}
@@ -0,0 +1,55 @@
import grabDirNames from "../../../utils/grab-dir-names";
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
export default async function ({ bundledMap }) {
let script = "";
// script += `import React from "react";\n`;
// script += `import { hydrateRoot } from "react-dom/client";\n`;
// script += `import App from "${page_file}";\n`;
// script += `declare global {\n`;
// script += ` interface Window {\n`;
// script += ` ${ClientWindowPagePropsName}: any;\n`;
// script += ` }\n`;
// script += `}\n`;
// script += `let root: any = null;\n\n`;
// script += `const component = <App {...window.${ClientWindowPagePropsName}} />;\n\n`;
// script += `const container = document.getElementById("${ClientRootElementIDName}");\n\n`;
// script += `if (container) {\n`;
// script += ` root = hydrateRoot(container, component);\n`;
// script += `}\n\n`;
script += `console.log(\`Development Environment\`);\n`;
// script += `console.log(import.meta);\n`;
// script += `if (import.meta.hot) {\n`;
// script += ` console.log(\`HMR active\`);\n`;
// script += ` import.meta.hot.dispose(() => {\n`;
// script += ` console.log("dispose");\n`;
// script += ` });\n`;
// script += `}\n`;
script += `const hmr = new EventSource("/__hmr");\n`;
script += `hmr.addEventListener("update", async (event) => {\n`;
// script += ` console.log(\`HMR even received:\`, event);\n`;
script += ` if (event.data) {\n`;
script += ` console.log(\`HMR Changes Detected. Reloading ...\`);\n`;
// script += ` console.log("event", event);\n`;
// script += ` console.log("window.${ClientRootComponentWindowName}", window.${ClientRootComponentWindowName});\n\n`;
// script += ` const event_data = JSON.parse(event.data);\n\n`;
// script += ` const new_js_path = \`/\${event_data.target_map.path}\`;\n\n`;
// script += ` console.log("event_data", event_data);\n\n`;
// script += ` console.log("new_js_path", new_js_path);\n\n`;
// script += ` if (window.${ClientRootComponentWindowName}) {\n`;
// script += ` const new_component = await import(new_js_path);\n`;
// script += ` window.${ClientRootComponentWindowName}.render(new_component);\n`;
// script += ` }\n`;
// script += ` import("${page_file}?t=" + event.data.update).then((module) => {\n`;
// script += ` root.render(module.default);\n`;
// script += ` })\n`;
// script += ` console.log("root", root);\n`;
// script += ` root.unmount();\n`;
// script += ` const container = document.getElementById("${ClientRootElementIDName}");\n\n`;
// script += ` root = hydrateRoot(container!, component);\n`;
// script += ` window.history.pushState({ page: 1 }, "New Page Title", \`\${window.location.pathname}?v=\${Date.now()}\`);\n`;
// script += ` root.render(component);\n`;
script += ` window.location.reload();\n`;
script += ` }\n`;
script += ` });\n`;
return script;
}
+77
View File
@@ -0,0 +1,77 @@
import isDevelopment from "../../../utils/is-development";
import getCache from "../../cache/get-cache";
import writeCache from "../../cache/write-cache";
import genWebHTML from "./generate-web-html";
import grabPageComponent from "./grab-page-component";
import grabPageErrorComponent from "./grab-page-error-component";
export default async function handleWebPages({ req, }) {
try {
if (!isDevelopment()) {
const url = new URL(req.url);
const key = url.pathname + (url.search || "");
const existing_cache = getCache({ key, paradigm: "html" });
if (existing_cache) {
const res_opts = {
headers: {
"Content-Type": "text/html",
"X-Bunext-Cache": "HIT",
},
};
return new Response(existing_cache, res_opts);
}
}
const componentRes = await grabPageComponent({ req });
return await generateRes(componentRes);
}
catch (error) {
const componentRes = await grabPageErrorComponent({ error });
return await generateRes(componentRes);
}
}
async function generateRes({ component, module, bundledMap, head, meta, routeParams, serverRes, }) {
const html = await genWebHTML({
component,
pageProps: serverRes,
bundledMap,
module,
meta,
head,
routeParams,
});
if (serverRes?.redirect?.destination) {
return Response.redirect(serverRes.redirect.destination, serverRes.redirect.permanent
? 301
: serverRes.redirect.status_code || 302);
}
const res_opts = {
...serverRes?.responseOptions,
headers: {
"Content-Type": "text/html",
...serverRes?.responseOptions?.headers,
},
};
if (isDevelopment()) {
res_opts.headers = {
...res_opts.headers,
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
Expires: "0",
};
}
const cache_page = module.config?.cachePage || serverRes?.cachePage || false;
const expiry_seconds = module.config?.cacheExpiry || serverRes?.cacheExpiry;
if (cache_page && routeParams?.url) {
const key = routeParams.url.pathname + (routeParams.url.search || "");
writeCache({
key,
value: html,
paradigm: "html",
expiry_seconds,
});
}
const res = new Response(html, res_opts);
if (routeParams?.resTransform) {
return await routeParams.resTransform(res);
}
return res;
}