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
@@ -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");
}