This commit is contained in:
2026-03-15 08:30:54 +01:00
parent 6dd00f2561
commit ec2dc0c4dc
26 changed files with 673 additions and 247 deletions
@@ -0,0 +1,81 @@
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";
import AppNames from "../../utils/grab-app-names";
import type { PageFiles } from "../../types";
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];
if (!isPageValid(page)) {
continue;
}
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) => {
if (!isPageValid(p)) {
return false;
}
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());
bundle({
src: entrypoints.join(" "),
out_dir: HYDRATION_DST_DIR,
exec_options: { stdio: "ignore" },
});
console.timeEnd("build");
}
function isPageValid(page: PageFiles): boolean {
if (page.file_name == AppNames["RootPagesComponentName"]) {
return false;
}
if (page.url_path.match(/\(|\)|--/)) {
return false;
}
return true;
}
-2
View File
@@ -12,8 +12,6 @@ export default async function () {
const key = keys[i];
const dir = dirNames[key];
// const stat = statSync(dir);
if (!existsSync(dir) && !dir.match(/\.\w+$/)) {
mkdirSync(dir, { recursive: true });
continue;
+1 -1
View File
@@ -11,7 +11,7 @@ type Params = {
export default async function getRoute({
route,
}: Params): Promise<GetRouteReturn | null> {
const { ROUTES_DIR } = grabDirNames();
const {} = grabDirNames();
if (route.match(/\(/)) {
return null;
+2 -2
View File
@@ -38,7 +38,7 @@ export default async function ({
};
}
const routeParams: BunxRouteParams = await grabRouteParams({ req, server });
const routeParams: BunxRouteParams = await grabRouteParams({ req });
const module = await import(match.filePath);
const config = module.config as BunextServerRouteConfig | undefined;
@@ -62,7 +62,7 @@ export default async function ({
}
const res: APIResponseObject = await module["default"](
routeParams as BunxRouteParams
routeParams as BunxRouteParams,
);
return res;
+5 -8
View File
@@ -6,14 +6,14 @@ import handleWebPages from "./web-pages/handle-web-pages";
import handleRoutes from "./handle-routes";
import isDevelopment from "../../utils/is-development";
const port = grabAppPort();
const { PUBLIC_DIR } = grabDirNames();
type Params = {
dev?: boolean;
};
export default async function (params?: Params): Promise<ServeOptions> {
const port = grabAppPort();
const { PUBLIC_DIR } = grabDirNames();
return {
async fetch(req, server) {
try {
@@ -61,7 +61,7 @@ export default async function (params?: Params): Promise<ServeOptions> {
return new Response(file);
} else {
return await handleWebPages({ req, server });
return await handleWebPages({ req });
}
} catch (error: any) {
return new Response(`Server Error: ${error.message}`, {
@@ -70,9 +70,6 @@ export default async function (params?: Params): Promise<ServeOptions> {
}
},
port,
development: isDevelopment() && {
hmr: true,
console: true,
},
idleTimeout: 0,
} as ServeOptions;
}
+3
View File
@@ -1,4 +1,5 @@
import AppNames from "../../utils/grab-app-names";
import allPagesBundler from "../bundler/all-pages-bundler";
import serverParamsGen from "./server-params-gen";
import watcher from "./watcher";
@@ -15,6 +16,8 @@ export default async function startServer(params?: Params) {
global.SERVER = server;
await allPagesBundler();
console.log(
`${name} Server Running on http://localhost:${server.port} ...`,
);
+35 -79
View File
@@ -1,101 +1,57 @@
import { watch } from "fs";
import grabDirNames from "../../utils/grab-dir-names";
import grabPageName from "../../utils/grab-page-name";
import path from "path";
import { execSync } from "child_process";
import serverParamsGen from "./server-params-gen";
import allPagesBundler from "../bundler/all-pages-bundler";
const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, ROUTES_DIR } =
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) => {
{
recursive: true,
persistent: true,
},
(event, filename) => {
// 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 (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(/\/routes\//)) {
if (event == "change") {
clearTimeout(global.WATCHER_TIMEOUT);
clearTimeout(global.WATCHER_TIMEOUT);
global.WATCHER_TIMEOUT = setTimeout(async () => {
try {
global.RECOMPILING = true;
const fullPath = path.join(ROOT_DIR, filename);
await allPagesBundler();
const pageName = grabPageName({ path: fullPath });
// const router = grabRouter();
// const match = router.match(fullPath);
// if (match?.filePath) {
// const module = await import(match.filePath);
// const serverRes = await (async () => {
// try {
// return await module["server"]();
// } catch (error) {
// return {};
// }
// })();
// const Component = module.default as FC<any>;
// const component = <Component pageProps={serverRes} />;
// await writeWebPageHydrationScript({
// pageName,
// component,
// });
// }
// await Bun.build({
// entrypoints: [
// `${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx`,
// ],
// outdir: HYDRATION_DST_DIR,
// minify: true,
// });
let cmd = `bun build`;
cmd += ` ${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx --outdir ${HYDRATION_DST_DIR}`;
cmd += ` --minify`;
// cmd += ` && bun pm cache rm`;
execSync(cmd, { stdio: "inherit" });
global.ROUTER = new Bun.FileSystemRouter({
style: "nextjs",
dir: ROUTES_DIR,
});
const encoder = new TextEncoder();
const msg = encoder.encode(
`event: update\ndata: reload\n\n`,
);
global.LAST_BUILD_TIME = Date.now();
for (const controller of global.HMR_CONTROLLERS) {
controller.enqueue(msg.toString());
try {
controller.enqueue(
`event: update\ndata: ${global.LAST_BUILD_TIME}\n\n`,
);
} catch {
global.HMR_CONTROLLERS.delete(controller);
}
}
// Let the SSE event flush before restarting the server.
// The server restart is required to clear Bun's module cache
// so the next request renders the updated route, not the
// stale cached module (which causes a hydration mismatch).
// await Bun.sleep(500);
// await reloadServer();
} catch (error: any) {
console.log(error);
} finally {
global.RECOMPILING = false;
} else if (event == "rename") {
await reloadServer();
}
} else if (filename.match(/\.(js|ts|tsx|jsx)$/)) {
clearTimeout(global.WATCHER_TIMEOUT);
await reloadServer();
}
}, 150);
// if (filename.match(/\/pages\//)) {
// } else if (filename.match(/\.(js|ts|tsx|jsx)$/)) {
// clearTimeout(global.WATCHER_TIMEOUT);
// global.WATCHER_TIMEOUT = setTimeout(() => reloadServer(), 150);
// }
},
);
@@ -1,8 +1,8 @@
import path from "path";
import { renderToString } from "react-dom/server";
import grabContants from "../../../utils/grab-constants";
import grabDirNames from "../../../utils/grab-dir-names";
import EJSON from "../../../utils/ejson";
import type { PageDistGenParams } from "../../../types";
import type { LivePageDistGenParams } from "../../../types";
import isDevelopment from "../../../utils/is-development";
export default async function genWebHTML({
@@ -10,16 +10,28 @@ export default async function genWebHTML({
pageProps,
pageName,
module,
}: PageDistGenParams) {
}: LivePageDistGenParams) {
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
const { renderToString } = await import(
path.join(process.cwd(), "node_modules", "react-dom", "server")
);
const componentHTML = renderToString(component);
const SCRIPT_SRC = path.join("/public/routes", pageName + ".js");
const SCRIPT_SRC = path.join("/public/pages", pageName + ".js");
const CSS_SRC = path.join("/public/pages", pageName + ".css");
const { HYDRATION_DST_DIR } = grabDirNames();
const cssExists = await Bun.file(path.join(HYDRATION_DST_DIR, pageName + ".css")).exists();
let html = `<!DOCTYPE html>\n`;
html += `<html>\n`;
html += ` <head>\n`;
html += ` <meta charset="utf-8" />\n`;
if (cssExists) {
html += ` <link rel="stylesheet" href="${CSS_SRC}" />\n`;
}
if (isDevelopment()) {
html += `<script>
const hmr = new EventSource("/__hmr");
@@ -30,11 +42,6 @@ export default async function genWebHTML({
});
</script>\n`;
}
html += `<html>\n`;
html += ` <head>\n`;
html += ` <meta charset="utf-8" />\n`;
html += ` <title>React SSR with Bun</title>\n`;
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
@@ -0,0 +1,127 @@
import type { FC } from "react";
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 type { BunextPageModule, GrabPageComponentRes } from "../../../types";
import bundle from "../../../utils/bundle";
import path from "path";
import AppNames from "../../../utils/grab-app-names";
import { existsSync } from "fs";
type Params = {
req?: Request;
file_path?: string;
};
export default async function grabPageComponent({
req,
file_path: passed_file_path,
}: Params): Promise<GrabPageComponentRes> {
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,
PAGES_DIR,
} = 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 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 root_module = root_file
? await import(`${root_file}?t=${global.LAST_BUILD_TIME ?? 0}`)
: undefined;
const RootComponent = root_module?.default as FC<any> | undefined;
const component_file_path = root_module
? `${file_path}`
: `${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`;
const module: BunextPageModule = await import(component_file_path);
const serverRes = await (async () => {
try {
if (routeParams) {
return await module["server"]?.(routeParams);
}
return {};
} catch (error) {
return {};
}
})();
const Component = module.default as FC<any>;
const component = RootComponent ? (
<RootComponent {...serverRes}>
<Component {...serverRes} />
</RootComponent>
) : (
<Component {...serverRes} />
);
return { component, serverRes, routeParams, pageName, module };
} catch (error: any) {
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: BunextPageModule = await import(
`${filePath}?t=${global.LAST_BUILD_TIME ?? 0}`
);
const Component = module.default as FC<any>;
const component = <Component />;
return {
component,
pageName: BUNX_ROOT_500_FILE_NAME,
routeParams,
module,
};
}
}
@@ -1,47 +1,15 @@
import type { FC } from "react";
import grabDirNames from "../../../utils/grab-dir-names";
import type { Server } from "bun";
import grabPageName from "../../../utils/grab-page-name";
import grabRouteParams from "../../../utils/grab-route-params";
import genWebHTML from "./generate-web-html";
import grabRouter from "../../../utils/grab-router";
import type { BunextPageModule } from "../../../types";
import grabPageComponent from "./grab-page-component";
import writeWebPageHydrationScript from "./write-web-page-hydration-script";
type Params = {
req: Request;
server: Server;
};
export default async function ({ req, server }: Params): Promise<Response> {
const url = new URL(req.url);
export default async function ({ req }: Params): Promise<Response> {
try {
const router = grabRouter();
const match = router.match(url.pathname);
if (!match?.filePath) {
const errMsg = `Page ${url.pathname} not found`;
console.error(errMsg);
throw new Error(errMsg);
}
const pageName = grabPageName({ path: match.filePath });
const module: BunextPageModule = await import(match.filePath);
// const config = module.config as ServerRouteConfig | undefined;
const routeParams = await grabRouteParams({ req, server });
const serverRes = await (async () => {
try {
return await module["server"]?.(routeParams);
} catch (error) {
return {};
}
})();
const Component = module.default as FC<any>;
const component = <Component pageProps={serverRes} />;
const { component, pageName, module, serverRes } =
await grabPageComponent({ req });
const html = await genWebHTML({
component,
@@ -50,13 +18,20 @@ export default async function ({ req, server }: Params): Promise<Response> {
module,
});
// writeWebPageHydrationScript({
// component,
// pageName,
// module,
// pageProps: serverRes,
// });
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
} catch (error) {
return new Response(`Page Not Found`, {
} catch (error: any) {
return new Response(error.message || `Page Not Found`, {
status: 404,
});
}
@@ -2,24 +2,22 @@ import { writeFileSync } from "fs";
import path from "path";
import grabDirNames from "../../../utils/grab-dir-names";
import grabContants from "../../../utils/grab-constants";
import genWebHTML from "./generate-web-html";
import type { PageDistGenParams } from "../../../types";
const { BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR } = grabDirNames();
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
export default async function (params: PageDistGenParams) {
const { pageName, page_file } = params;
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
const PAGE_DIST_DIR = path.join(HYDRATION_DST_DIR, params.pageName);
const pageSrcTs = `index.tsx`;
const pageSrcTsFileName = `${pageName}.tsx`;
let script = "";
script += `import React from "react";\n`;
script += `import { hydrateRoot } from "react-dom/client";\n`;
script += `import App from "./";\n`;
script += `import App from "${page_file}";\n`;
script += `declare global {\n`;
script += ` interface Window {\n`;
@@ -30,12 +28,6 @@ export default async function (params: PageDistGenParams) {
script += `const container = document.getElementById("${ClientRootElementIDName}");\n`;
script += `hydrateRoot(container, <App {...window.${ClientWindowPagePropsName}} />);\n`;
const SRC_WRITE_FILE = path.join(PAGE_DIST_DIR, pageSrcTs);
const SRC_WRITE_FILE = path.join(BUNX_HYDRATION_SRC_DIR, pageSrcTsFileName);
writeFileSync(SRC_WRITE_FILE, script, "utf-8");
let html = await genWebHTML(params);
const pageHtml = `index.html`;
const HTML_WRITE_FILE = path.join(PAGE_DIST_DIR, pageHtml);
writeFileSync(HTML_WRITE_FILE, html, "utf-8");
}