First working version

This commit is contained in:
2026-03-16 20:44:15 +01:00
parent ca9d6a75ff
commit 19d0ceb7db
24 changed files with 873 additions and 276 deletions
@@ -4,12 +4,12 @@ import grabDirNames from "../../../utils/grab-dir-names";
import EJSON from "../../../utils/ejson";
import type { LivePageDistGenParams } from "../../../types";
import isDevelopment from "../../../utils/is-development";
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
export default async function genWebHTML({
component,
pageProps,
pageName,
module,
bundledMap,
}: LivePageDistGenParams) {
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
@@ -20,38 +20,31 @@ export default async function genWebHTML({
const componentHTML = renderToString(component);
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();
// const SCRIPT_SRC = path.join("/public/pages", bundledMap.path);
// const CSS_SRC = bundledMap.css_path
// ? path.join("/public/pages", bundledMap.css_path)
// : undefined;
// const { HYDRATION_DST_DIR } = grabDirNames();
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 (bundledMap.css_path) {
html += ` <link rel="stylesheet" href="/${bundledMap.css_path}" />\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 += ` <script src="/${bundledMap.path}" type="module" defer></script>\n`;
if (isDevelopment()) {
html += `<script defer>\n${await grabWebPageHydrationScript({ bundledMap })}\n</script>\n`;
}
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
html += ` </body>\n`;
html += `</html>\n`;
@@ -1,6 +1,5 @@
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";
@@ -20,12 +19,7 @@ export default async function grabPageComponent({
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 { BUNX_ROOT_500_PRESET_COMPONENT, PAGES_DIR } = grabDirNames();
const routeParams = req ? await grabRouteParams({ req }) : undefined;
@@ -34,7 +28,7 @@ export default async function grabPageComponent({
if (!match?.filePath && url?.pathname) {
const errMsg = `Page ${url.pathname} not found`;
console.error(errMsg);
// console.error(errMsg);
throw new Error(errMsg);
}
@@ -42,11 +36,21 @@ export default async function grabPageComponent({
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 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`;
@@ -63,17 +67,19 @@ export default async function grabPageComponent({
? root_pages_component_js_file
: undefined;
const now = Date.now();
const root_module = root_file
? await import(`${root_file}?t=${global.LAST_BUILD_TIME ?? 0}`)
? await import(`${root_file}?t=${now}`)
: 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 component_file_path = root_module
// ? `${file_path}`
// : `${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`;
const module: BunextPageModule = await import(component_file_path);
const module: BunextPageModule = await import(`${file_path}?t=${now}`);
const serverRes = await (async () => {
try {
@@ -87,6 +93,7 @@ export default async function grabPageComponent({
})();
const Component = module.default as FC<any>;
const component = RootComponent ? (
<RootComponent {...serverRes}>
<Component {...serverRes} />
@@ -95,34 +102,30 @@ export default async function grabPageComponent({
<Component {...serverRes} />
);
return { component, serverRes, routeParams, pageName, module };
return {
component,
serverRes,
routeParams,
module,
bundledMap,
};
} catch (error: any) {
// console.log(`Grab page component ERROR =>`, error.message);
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);
// 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,
bundledMap: {},
};
}
}
@@ -0,0 +1,75 @@
import grabDirNames from "../../../utils/grab-dir-names";
import type { BundlerCTXMap, PageDistGenParams } from "../../../types";
import grabConstants from "../../../utils/grab-constants";
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
type Params = {
bundledMap: BundlerCTXMap;
};
export default async function ({ bundledMap }: Params) {
const { ClientRootElementIDName, ClientRootComponentWindowName } =
await grabConstants();
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;
}
@@ -8,23 +8,16 @@ type Params = {
export default async function ({ req }: Params): Promise<Response> {
try {
const { component, pageName, module, serverRes } =
const { component, bundledMap, module, serverRes } =
await grabPageComponent({ req });
const html = await genWebHTML({
component,
pageProps: serverRes,
pageName,
bundledMap,
module,
});
// writeWebPageHydrationScript({
// component,
// pageName,
// module,
// pageProps: serverRes,
// });
const res_opts: ResponseInit = {
headers: {
"Content-Type": "text/html",
@@ -44,6 +37,8 @@ export default async function ({ req }: Params): Promise<Response> {
return res;
} catch (error: any) {
console.log(`Handle web pages Error =>`, error.message);
return new Response(error.message || `Page Not Found`, {
status: 404,
});
@@ -1,56 +0,0 @@
import { writeFileSync } from "fs";
import path from "path";
import grabDirNames from "../../../utils/grab-dir-names";
import grabContants from "../../../utils/grab-constants";
import type { PageDistGenParams } from "../../../types";
import isDevelopment from "../../../utils/is-development";
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
export default async function (params: PageDistGenParams) {
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 += `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`;
if (isDevelopment()) {
script += `const hmr = new EventSource("/__hmr");\n`;
script += `hmr.addEventListener("update", (event) => {\n`;
// script += ` console.log(\`HMR even received:\`, event);\n`;
script += ` if (event.data && root) {\n`;
script += ` console.log(\`HMR Changes Detected. Reloading ...\`);\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 += ` root.render(component);\n`;
script += ` window.location.reload();\n`;
script += ` }\n`;
script += ` });\n`;
}
const SRC_WRITE_FILE = path.join(BUNX_HYDRATION_SRC_DIR, pageSrcTsFileName);
writeFileSync(SRC_WRITE_FILE, script, "utf-8");
}