This commit is contained in:
2026-03-23 07:42:00 +01:00
parent 567fb4f746
commit 4b8b610e32
43 changed files with 635 additions and 169 deletions
+4
View File
@@ -5,6 +5,7 @@ import grabConstants from "../../utils/grab-constants";
import handleHmr from "./handle-hmr";
import handlePublic from "./handle-public";
import handleFiles from "./handle-files";
import handleBunextPublicAssets from "./handle-bunext-public-assets";
export default async function bunextRequestHandler({ req: initial_req, }) {
const is_dev = isDevelopment();
let req = initial_req.clone();
@@ -27,6 +28,9 @@ export default async function bunextRequestHandler({ req: initial_req, }) {
if (url.pathname === "/__hmr" && is_dev) {
response = await handleHmr({ req });
}
else if (url.pathname.startsWith("/.bunext/public/pages")) {
response = await handleBunextPublicAssets({ req });
}
else if (url.pathname.startsWith("/api/")) {
response = await handleRoutes({ req });
}
+6
View File
@@ -0,0 +1,6 @@
import type { BundlerCTXMap } from "../../types";
type Params = {
new_artifacts: BundlerCTXMap[];
};
export default function cleanupArtifacts({ new_artifacts }: Params): Promise<void>;
export {};
+33
View File
@@ -0,0 +1,33 @@
import { log } from "../../utils/log";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import { existsSync, readdirSync, statSync, unlinkSync } from "fs";
const { ROOT_DIR, HYDRATION_DST_DIR_MAP_JSON_FILE_NAME } = grabDirNames();
export default async function cleanupArtifacts({ new_artifacts }) {
try {
for (let i = 0; i < new_artifacts.length; i++) {
const new_artifact = new_artifacts[i];
const artifact_public_dir = path.dirname(path.join(ROOT_DIR, new_artifact.path));
const dir_content = readdirSync(artifact_public_dir);
for (let d = 0; d < dir_content.length; d++) {
const dir_or_file = dir_content[d];
const full_path = path.join(artifact_public_dir, dir_or_file);
const file_or_path_stats = statSync(full_path);
if (file_or_path_stats.isDirectory() ||
dir_or_file == HYDRATION_DST_DIR_MAP_JSON_FILE_NAME) {
continue;
}
if (new_artifact.path.includes(dir_or_file) ||
new_artifact.css_path?.includes(dir_or_file)) {
continue;
}
if (existsSync(full_path)) {
unlinkSync(full_path);
}
}
}
}
catch (error) {
log.error(error);
}
}
@@ -0,0 +1,5 @@
type Params = {
req: Request;
};
export default function ({ req }: Params): Promise<Response>;
export {};
+27
View File
@@ -0,0 +1,27 @@
import grabDirNames from "../../utils/grab-dir-names";
import path from "path";
import isDevelopment from "../../utils/is-development";
import { existsSync } from "fs";
const { HYDRATION_DST_DIR } = grabDirNames();
export default async function ({ req }) {
try {
const is_dev = isDevelopment();
const url = new URL(req.url);
const file_path = path.join(HYDRATION_DST_DIR, url.pathname.replace(/\/\.bunext\/public\/pages\//, ""));
if (!file_path.startsWith(HYDRATION_DST_DIR + path.sep)) {
return new Response("Forbidden", { status: 403 });
}
if (!existsSync(file_path)) {
return new Response(`File Doesn't Exist`, {
status: 404,
});
}
const file = Bun.file(file_path);
return new Response(file);
}
catch (error) {
return new Response(`File Not Found`, {
status: 404,
});
}
}
+3
View File
@@ -8,6 +8,9 @@ export default async function ({ req }) {
const is_dev = isDevelopment();
const url = new URL(req.url);
const file_path = path.join(PUBLIC_DIR, url.pathname);
if (!file_path.startsWith(PUBLIC_DIR + path.sep)) {
return new Response("Forbidden", { status: 403 });
}
if (!existsSync(file_path)) {
return new Response(`File Doesn't Exist`, {
status: 404,
+1 -1
View File
@@ -2,7 +2,7 @@ export default async function ({ req }) {
const referer_url = new URL(req.headers.get("referer") || "");
const match = global.ROUTER.match(referer_url.pathname);
const target_map = match?.filePath
? global.BUNDLER_CTX_MAP[match.filePath]
? global.BUNDLER_CTX_MAP?.[match.filePath]
: undefined;
let controller;
let heartbeat;
+3
View File
@@ -8,6 +8,9 @@ export default async function ({ req }) {
const is_dev = isDevelopment();
const url = new URL(req.url);
const file_path = path.join(PUBLIC_DIR, url.pathname.replace(/^\/public/, ""));
if (!file_path.startsWith(PUBLIC_DIR + path.sep)) {
return new Response("Forbidden", { status: 403 });
}
if (!existsSync(file_path)) {
return new Response(`Public File Doesn't Exist`, {
status: 404,
+1 -1
View File
@@ -14,7 +14,7 @@ export default async function ({ req }) {
success: false,
msg: errMsg,
}, {
status: 401,
status: 404,
headers: {
"Content-Type": "application/json",
},
+6 -2
View File
@@ -1,15 +1,19 @@
import allPagesBundler from "../bundler/all-pages-bundler";
import serverPostBuildFn from "./server-post-build-fn";
import { log } from "../../utils/log";
import allPagesBunBundler from "../bundler/all-pages-bun-bundler";
import cleanupArtifacts from "./cleanup-artifacts";
export default async function rebuildBundler(params) {
try {
global.ROUTER.reload();
// await global.BUNDLER_CTX?.dispose();
// global.BUNDLER_CTX = undefined;
await allPagesBundler({
const new_artifacts = await allPagesBunBundler({
page_file_paths: params?.target_file_paths,
});
await serverPostBuildFn();
if (new_artifacts?.[0]) {
cleanupArtifacts({ new_artifacts });
}
}
catch (error) {
log.error(error);
+1 -1
View File
@@ -7,7 +7,7 @@ export default async function serverPostBuildFn() {
if (!global.HMR_CONTROLLERS?.[0] || !global.BUNDLER_CTX_MAP) {
return;
}
for (let i = 0; i < global.HMR_CONTROLLERS.length; i++) {
for (let i = global.HMR_CONTROLLERS.length - 1; i >= 0; i--) {
const controller = global.HMR_CONTROLLERS[i];
if (!controller.target_map?.local_path) {
continue;
+3 -2
View File
@@ -6,7 +6,6 @@ import { log } from "../../utils/log";
import rewritePagesModule from "../../utils/rewrite-pages-module";
const { ROOT_DIR } = grabDirNames();
export default async function watcher() {
await Bun.sleep(1000);
const pages_src_watcher = watch(ROOT_DIR, {
recursive: true,
persistent: true,
@@ -64,7 +63,9 @@ async function fullRebuild(params) {
const { msg } = params || {};
global.RECOMPILING = true;
const target_file_paths = global.HMR_CONTROLLERS.map((hmr) => hmr.target_map?.local_path).filter((f) => typeof f == "string");
await rewritePagesModule({ page_file_path: target_file_paths });
await rewritePagesModule({
page_file_path: target_file_paths,
});
if (msg) {
log.watch(msg);
}
+21 -1
View File
@@ -7,6 +7,13 @@ import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
import grabWebMetaHTML from "./grab-web-meta-html";
import { log } from "../../../utils/log";
import { AppData } from "../../../data/app-data";
import { readFileSync } from "fs";
import path from "path";
let _reactVersion = "19";
try {
_reactVersion = JSON.parse(readFileSync(path.join(process.cwd(), "node_modules/react/package.json"), "utf-8")).version;
}
catch { }
export default async function genWebHTML({ component, pageProps, bundledMap, head: Head, module, meta, routeParams, debug, }) {
const { ClientRootElementIDName, ClientWindowPagePropsName } = grabContants();
if (debug) {
@@ -30,8 +37,21 @@ export default async function genWebHTML({ component, pageProps, bundledMap, hea
if (bundledMap?.css_path) {
html += ` <link rel="stylesheet" href="/${bundledMap.css_path}" />\n`;
}
html += ` <script>window.${ClientWindowPagePropsName} = ${EJSON.stringify(pageProps || {}) || "{}"}</script>\n`;
const serializedProps = (EJSON.stringify(pageProps || {}) || "{}").replace(/<\//g, "<\\/");
html += ` <script>window.${ClientWindowPagePropsName} = ${serializedProps}</script>\n`;
if (bundledMap?.path) {
const dev = isDevelopment();
const devSuffix = dev ? "?dev" : "";
const importMap = JSON.stringify({
imports: {
react: `https://esm.sh/react@${_reactVersion}${devSuffix}`,
"react-dom": `https://esm.sh/react-dom@${_reactVersion}${devSuffix}`,
"react-dom/client": `https://esm.sh/react-dom@${_reactVersion}/client${devSuffix}`,
"react/jsx-runtime": `https://esm.sh/react@${_reactVersion}/jsx-runtime${devSuffix}`,
"react/jsx-dev-runtime": `https://esm.sh/react@${_reactVersion}/jsx-dev-runtime${devSuffix}`,
},
});
html += ` <script type="importmap">${importMap}</script>\n`;
html += ` <script src="/${bundledMap.path}" type="module" id="${AppData["BunextClientHydrationScriptID"]}" async></script>\n`;
}
if (isDevelopment()) {
+1 -1
View File
@@ -33,7 +33,7 @@ export default async function grabPageComponent({ req, file_path: passed_file_pa
// log.error(errMsg);
throw new Error(errMsg);
}
const bundledMap = global.BUNDLER_CTX_MAP[file_path];
const bundledMap = global.BUNDLER_CTX_MAP?.[file_path];
if (!bundledMap?.path) {
const errMsg = `No Bundled File Path for this request path!`;
log.error(errMsg);
@@ -11,8 +11,8 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
const match = router.match(errorRoute);
const filePath = match?.filePath || presetComponent;
const bundledMap = match?.filePath
? global.BUNDLER_CTX_MAP[match.filePath]
: {};
? global.BUNDLER_CTX_MAP?.[match.filePath]
: undefined;
const module = await import(filePath);
const Component = module.default;
const component = _jsx(Component, { children: _jsx("span", { children: error.message }) });
@@ -41,7 +41,7 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
component: _jsx(DefaultNotFound, {}),
routeParams,
module: { default: DefaultNotFound },
bundledMap: {},
bundledMap: undefined,
serverRes: {
responseOptions: {
status: is404 ? 404 : 500,
+21 -20
View File
@@ -1,60 +1,61 @@
import { escape } from "lodash";
export default function grabWebMetaHTML({ meta }) {
let html = ``;
if (meta.title) {
html += ` <title>${meta.title}</title>\n`;
html += ` <title>${escape(meta.title)}</title>\n`;
}
if (meta.description) {
html += ` <meta name="description" content="${meta.description}" />\n`;
html += ` <meta name="description" content="${escape(meta.description)}" />\n`;
}
if (meta.keywords) {
const keywords = Array.isArray(meta.keywords)
? meta.keywords.join(", ")
: meta.keywords;
html += ` <meta name="keywords" content="${keywords}" />\n`;
html += ` <meta name="keywords" content="${escape(keywords)}" />\n`;
}
if (meta.author) {
html += ` <meta name="author" content="${meta.author}" />\n`;
html += ` <meta name="author" content="${escape(meta.author)}" />\n`;
}
if (meta.robots) {
html += ` <meta name="robots" content="${meta.robots}" />\n`;
html += ` <meta name="robots" content="${escape(meta.robots)}" />\n`;
}
if (meta.canonical) {
html += ` <link rel="canonical" href="${meta.canonical}" />\n`;
html += ` <link rel="canonical" href="${escape(meta.canonical)}" />\n`;
}
if (meta.themeColor) {
html += ` <meta name="theme-color" content="${meta.themeColor}" />\n`;
html += ` <meta name="theme-color" content="${escape(meta.themeColor)}" />\n`;
}
if (meta.og) {
const { og } = meta;
if (og.title)
html += ` <meta property="og:title" content="${og.title}" />\n`;
html += ` <meta property="og:title" content="${escape(og.title)}" />\n`;
if (og.description)
html += ` <meta property="og:description" content="${og.description}" />\n`;
html += ` <meta property="og:description" content="${escape(og.description)}" />\n`;
if (og.image)
html += ` <meta property="og:image" content="${og.image}" />\n`;
html += ` <meta property="og:image" content="${escape(og.image)}" />\n`;
if (og.url)
html += ` <meta property="og:url" content="${og.url}" />\n`;
html += ` <meta property="og:url" content="${escape(og.url)}" />\n`;
if (og.type)
html += ` <meta property="og:type" content="${og.type}" />\n`;
html += ` <meta property="og:type" content="${escape(og.type)}" />\n`;
if (og.siteName)
html += ` <meta property="og:site_name" content="${og.siteName}" />\n`;
html += ` <meta property="og:site_name" content="${escape(og.siteName)}" />\n`;
if (og.locale)
html += ` <meta property="og:locale" content="${og.locale}" />\n`;
html += ` <meta property="og:locale" content="${escape(og.locale)}" />\n`;
}
if (meta.twitter) {
const { twitter } = meta;
if (twitter.card)
html += ` <meta name="twitter:card" content="${twitter.card}" />\n`;
html += ` <meta name="twitter:card" content="${escape(twitter.card)}" />\n`;
if (twitter.title)
html += ` <meta name="twitter:title" content="${twitter.title}" />\n`;
html += ` <meta name="twitter:title" content="${escape(twitter.title)}" />\n`;
if (twitter.description)
html += ` <meta name="twitter:description" content="${twitter.description}" />\n`;
html += ` <meta name="twitter:description" content="${escape(twitter.description)}" />\n`;
if (twitter.image)
html += ` <meta name="twitter:image" content="${twitter.image}" />\n`;
html += ` <meta name="twitter:image" content="${escape(twitter.image)}" />\n`;
if (twitter.site)
html += ` <meta name="twitter:site" content="${twitter.site}" />\n`;
html += ` <meta name="twitter:site" content="${escape(twitter.site)}" />\n`;
if (twitter.creator)
html += ` <meta name="twitter:creator" content="${twitter.creator}" />\n`;
html += ` <meta name="twitter:creator" content="${escape(twitter.creator)}" />\n`;
}
return html;
}