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
+52
View File
@@ -0,0 +1,52 @@
import { readdirSync, statSync, unlinkSync } from "fs";
import grabAllPages from "../../utils/grab-all-pages";
import grabDirNames from "../../utils/grab-dir-names";
import grabPageName from "../../utils/grab-page-name";
import writeWebPageHydrationScript from "../server/web-pages/write-web-page-hydration-script";
import path from "path";
import bundle from "../../utils/bundle";
const { BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR } = grabDirNames();
export default async function allPagesBundler() {
console.time("build");
const pages = grabAllPages({ exclude_api: true });
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
const pageName = grabPageName({ path: page.local_path });
writeWebPageHydrationScript({
pageName,
page_file: page.local_path,
});
}
const hydration_files = readdirSync(BUNX_HYDRATION_SRC_DIR);
for (let i = 0; i < hydration_files.length; i++) {
const hydration_file = hydration_files[i];
const valid_file = pages.find((p) => {
const pageName = grabPageName({ path: p.local_path });
const file_tsx_name = `${pageName}.tsx`;
if (file_tsx_name == hydration_file) {
return true;
}
return false;
});
if (!valid_file) {
unlinkSync(path.join(BUNX_HYDRATION_SRC_DIR, hydration_file));
}
}
const entrypoints = readdirSync(BUNX_HYDRATION_SRC_DIR)
.filter((f) => f.endsWith(".tsx"))
.map((f) => path.join(BUNX_HYDRATION_SRC_DIR, f))
.filter((f) => statSync(f).isFile());
// await Bun.build({
// entrypoints,
// outdir: HYDRATION_DST_DIR,
// minify: true,
// target: "browser",
// format: "esm",
// });
bundle({
src: entrypoints.join(" "),
out_dir: HYDRATION_DST_DIR,
exec_options: { stdio: "ignore" },
});
console.timeEnd("build");
}
+19
View File
@@ -0,0 +1,19 @@
import { existsSync } from "fs";
import grabDirNames from "../utils/grab-dir-names";
import exitWithError from "../utils/exit-with-error";
export default async function grabConfig() {
try {
const { CONFIG_FILE } = grabDirNames();
if (!existsSync(CONFIG_FILE)) {
exitWithError(`Config file \`${CONFIG_FILE}\` doesn't exist!`);
}
const config = (await import(CONFIG_FILE)).default;
if (!config) {
exitWithError(`Config file \`${CONFIG_FILE}\` is invalid! Please provide a valid default export in your config file.`);
}
return config;
}
catch (error) {
return undefined;
}
}
+20
View File
@@ -0,0 +1,20 @@
import { existsSync, mkdirSync, statSync, writeFileSync } from "fs";
import grabDirNames from "../utils/grab-dir-names";
export default async function () {
const dirNames = grabDirNames();
const keys = Object.keys(dirNames);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const dir = dirNames[key];
if (!existsSync(dir) && !dir.match(/\.\w+$/)) {
mkdirSync(dir, { recursive: true });
continue;
}
if (key == "CONFIG_FILE" && !existsSync(dir)) {
let basicConfig = ``;
basicConfig += `const config = {};\n`;
basicConfig += `export default config;\n`;
writeFileSync(dir, basicConfig);
}
}
}
+26
View File
@@ -0,0 +1,26 @@
import grabDirNames from "../../utils/grab-dir-names";
import grabAssetsPrefix from "../../utils/grab-assets-prefix";
import grabOrigin from "../../utils/grab-origin";
import grabRouter from "../../utils/grab-router";
export default async function getRoute({ route, }) {
const {} = grabDirNames();
if (route.match(/\(/)) {
return null;
}
const router = grabRouter();
const match = router.match(route);
if (!match?.filePath) {
console.error(`Route ${route} not found`);
return null;
}
const module = await import(match.filePath);
return {
match,
module,
component: module.default,
serverProps: module.serverProps,
staticProps: module.staticProps,
staticPaths: module.staticPaths,
staticParams: module.staticParams,
};
}
+36
View File
@@ -0,0 +1,36 @@
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 } = await grabConstants();
const router = grabRouter();
const match = router.match(url.pathname);
if (!match?.filePath) {
const errMsg = `Route ${url.pathname} not found`;
console.error(errMsg);
return {
success: false,
status: 401,
msg: errMsg,
};
}
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 {
success: false,
status: 413,
msg: "Request Body Too Large!",
};
}
}
const res = await module["default"](routeParams);
return res;
}
+62
View File
@@ -0,0 +1,62 @@
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";
export default async function (params) {
const port = grabAppPort();
const { PUBLIC_DIR } = grabDirNames();
return {
async fetch(req, server) {
try {
const url = new URL(req.url);
if (url.pathname === "/__hmr" && isDevelopment()) {
let controller;
const stream = new ReadableStream({
start(c) {
controller = c;
global.HMR_CONTROLLERS.add(c);
},
cancel() {
global.HMR_CONTROLLERS.delete(controller);
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
else if (url.pathname.startsWith("/api/")) {
const res = await handleRoutes({ req, server });
return new Response(JSON.stringify(res), {
status: res?.status,
headers: {
"Content-Type": "application/json",
},
});
}
else if (url.pathname.startsWith("/public/")) {
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname.replace(/^\/public/, "")));
return new Response(file);
}
else if (url.pathname.startsWith("/favicon.")) {
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname));
return new Response(file);
}
else {
return await handleWebPages({ req });
}
}
catch (error) {
return new Response(`Server Error: ${error.message}`, {
status: 500,
});
}
},
port,
};
}
+14
View File
@@ -0,0 +1,14 @@
import AppNames from "../../utils/grab-app-names";
import serverParamsGen from "./server-params-gen";
import watcher from "./watcher";
export default async function startServer(params) {
const { name } = AppNames;
const serverParams = await serverParamsGen();
const server = Bun.serve(serverParams);
global.SERVER = server;
console.log(`${name} Server Running on http://localhost:${server.port} ...`);
if (params?.dev) {
watcher();
}
return server;
}
+78
View File
@@ -0,0 +1,78 @@
import { watch } from "fs";
import grabDirNames from "../../utils/grab-dir-names";
import grabPageName from "../../utils/grab-page-name";
import path from "path";
import serverParamsGen from "./server-params-gen";
import bundle from "../../utils/bundle";
import grabRouter from "../../utils/grab-router";
import allPagesBundler from "../bundler/all-pages-bundler";
const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, PAGES_DIR } = grabDirNames();
export default function watcher() {
watch(ROOT_DIR, { recursive: true, persistent: true }, async (event, filename) => {
if (global.RECOMPILING)
return;
if (!filename)
return;
if (filename.match(/ /))
return;
if (filename.match(/^node_modules\//))
return;
if (filename.match(/\.bunext|\/?public\//))
return;
if (!filename.match(/\.(tsx|ts|css|js|jsx)$/))
return;
if (filename.match(/\/pages\//)) {
try {
clearTimeout(global.WATCHER_TIMEOUT);
global.RECOMPILING = true;
await allPagesBundler();
global.LAST_BUILD_TIME = Date.now();
for (const controller of global.HMR_CONTROLLERS) {
controller.enqueue(`event: update\ndata: reload\n\n`);
}
global.RECOMPILING = false;
}
catch (error) {
console.error(`Bundler ERROR => ${error.message.substring(0, 120)} ...`);
}
// if (event == "change") {
// } else if (event == "rename") {
// await reloadServer();
// }
}
else if (filename.match(/\.(js|ts|tsx|jsx)$/)) {
clearTimeout(global.WATCHER_TIMEOUT);
await reloadServer();
}
});
// watch(BUNX_HYDRATION_SRC_DIR, async (event, filename) => {
// if (!filename) return;
// const targetFile = path.join(BUNX_HYDRATION_SRC_DIR, filename);
// await Bun.build({
// entrypoints: [targetFile],
// outdir: HYDRATION_DST_DIR,
// minify: true,
// target: "browser",
// format: "esm",
// });
// global.SERVER?.publish("__bun_hmr", "update");
// setTimeout(() => {
// global.RECOMPILING = false;
// }, 200);
// });
// watch(HYDRATION_DST_DIR, async (event, filename) => {
// const encoder = new TextEncoder();
// global.HMR_CONTROLLER?.enqueue(encoder.encode(`event: update\ndata: reload\n\n`));
// global.RECOMPILING = false;
// });
// let cmd = `bun build`;
// cmd += ` ${BUNX_HYDRATION_SRC_DIR}/*.tsx --outdir ${HYDRATION_DST_DIR}`;
// cmd += ` --watch --minify`;
// execSync(cmd, { stdio: "inherit" });
}
async function reloadServer() {
const serverParams = await serverParamsGen();
console.log(`Reloading Server ...`);
global.SERVER?.stop();
global.SERVER = Bun.serve(serverParams);
}
@@ -0,0 +1,32 @@
import path from "path";
import { renderToString } from "react-dom/server";
import grabContants from "../../../utils/grab-constants";
import EJSON from "../../../utils/ejson";
import isDevelopment from "../../../utils/is-development";
export default async function genWebHTML({ component, pageProps, pageName, module, }) {
const { ClientRootElementIDName, ClientWindowPagePropsName } = await grabContants();
const componentHTML = renderToString(component);
const SCRIPT_SRC = path.join("/public/pages", pageName + ".js");
let html = `<!DOCTYPE html>\n`;
html += `<html>\n`;
html += ` <head>\n`;
html += ` <meta charset="utf-8" />\n`;
if (isDevelopment()) {
html += `<script>
const hmr = new EventSource("/__hmr");
hmr.addEventListener("update", (event) => {
if (event.data === "reload") {
window.location.reload();
}
});
</script>\n`;
}
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
html += ` <script>window.${ClientWindowPagePropsName} = ${EJSON.stringify(pageProps || {}) || "{}"}</script>\n`;
html += ` <script src="${SCRIPT_SRC}" type="module"></script>\n`;
html += ` </body>\n`;
html += `</html>\n`;
return html;
}
@@ -0,0 +1,62 @@
import { jsx as _jsx } from "react/jsx-runtime";
import grabDirNames from "../../../utils/grab-dir-names";
import grabPageName from "../../../utils/grab-page-name";
import grabRouteParams from "../../../utils/grab-route-params";
import grabRouter from "../../../utils/grab-router";
import bundle from "../../../utils/bundle";
export default async function grabPageComponent({ req, file_path: passed_file_path, }) {
const url = req?.url ? new URL(req.url) : undefined;
const router = grabRouter();
const { BUNX_ROOT_500_PRESET_COMPONENT, HYDRATION_DST_DIR, BUNX_ROOT_500_FILE_NAME, } = grabDirNames();
const routeParams = req ? await grabRouteParams({ req }) : undefined;
try {
const match = url ? router.match(url.pathname) : undefined;
if (!match?.filePath && url?.pathname) {
const errMsg = `Page ${url.pathname} not found`;
console.error(errMsg);
throw new Error(errMsg);
}
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 pageName = grabPageName({ path: file_path });
const module = await import(`${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`);
const serverRes = await (async () => {
try {
if (routeParams) {
return await module["server"]?.(routeParams);
}
return {};
}
catch (error) {
return {};
}
})();
const Component = module.default;
const component = _jsx(Component, { ...serverRes });
return { component, serverRes, routeParams, pageName, module };
}
catch (error) {
const match = router.match("/500");
const filePath = match?.filePath || BUNX_ROOT_500_PRESET_COMPONENT;
// if (!match?.filePath) {
// bundle({
// out_dir: HYDRATION_DST_DIR,
// src: `${BUNX_ROOT_500_PRESET_COMPONENT}`,
// debug: true,
// });
// }
const module = await import(`${filePath}?t=${global.LAST_BUILD_TIME ?? 0}`);
const Component = module.default;
const component = _jsx(Component, {});
return {
component,
pageName: BUNX_ROOT_500_FILE_NAME,
routeParams,
module,
};
}
}
+30
View File
@@ -0,0 +1,30 @@
import genWebHTML from "./generate-web-html";
import grabPageComponent from "./grab-page-component";
import writeWebPageHydrationScript from "./write-web-page-hydration-script";
export default async function ({ req }) {
try {
const { component, pageName, module, serverRes } = await grabPageComponent({ req });
const html = await genWebHTML({
component,
pageProps: serverRes,
pageName,
module,
});
// writeWebPageHydrationScript({
// component,
// pageName,
// module,
// pageProps: serverRes,
// });
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
}
catch (error) {
return new Response(error.message || `Page Not Found`, {
status: 404,
});
}
}
@@ -0,0 +1,23 @@
import { writeFileSync } from "fs";
import path from "path";
import grabDirNames from "../../../utils/grab-dir-names";
import grabContants from "../../../utils/grab-constants";
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
export default async function (params) {
const { pageName, page_file } = params;
const { ClientRootElementIDName, ClientWindowPagePropsName } = await grabContants();
const pageSrcTsFileName = `${pageName}.tsx`;
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 += `const container = document.getElementById("${ClientRootElementIDName}");\n`;
script += `hydrateRoot(container, <App {...window.${ClientWindowPagePropsName}} />);\n`;
const SRC_WRITE_FILE = path.join(BUNX_HYDRATION_SRC_DIR, pageSrcTsFileName);
writeFileSync(SRC_WRITE_FILE, script, "utf-8");
}