Add dist
This commit is contained in:
@@ -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;
|
||||
}
|
||||
@@ -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: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user