Update excluded pages paths logic. Add HMR retries on errors.

This commit is contained in:
2026-04-12 05:47:12 +01:00
parent e0c2ab5872
commit 532d0d6b56
29 changed files with 168 additions and 65 deletions
+1
View File
@@ -5,4 +5,5 @@ export const AppData = {
ClientHMRPath: "__bunext_client_hmr__",
BunextClientHydrationScriptID: "bunext-client-hydration-script",
BunextTmpFileExt: ".bunext_tmp.tsx",
BunextHMRRetryRoute: "/.bunext/hmr-retry",
} as const;
+5 -7
View File
@@ -16,7 +16,7 @@ import watcherEsbuildCTX from "./server/watcher-esbuild-ctx";
import allPagesESBuildContextBundler from "./bundler/all-pages-esbuild-context-bundler";
import serverPostBuildFn from "./server/server-post-build-fn";
import reactModulesBundler from "./bundler/react-modules-bundler";
// import initPages from "./bundler/init-pages";
import grabConstants from "../utils/grab-constants";
/**
* # Declare Global Variables
@@ -50,6 +50,7 @@ declare global {
var BUNDLER_CTX_DISPOSED: boolean | undefined;
var REBUILD_RETRIES: number;
var IS_404_PAGE: boolean;
var CONSTANTS: ReturnType<typeof grabConstants>;
}
const dirNames = grabDirNames();
@@ -71,6 +72,9 @@ export default async function bunextInit() {
log.banner();
await init();
global.CONSTANTS = grabConstants();
await reactModulesBundler();
const router = new Bun.FileSystemRouter({
@@ -87,16 +91,10 @@ export default async function bunextInit() {
await allPagesESBuildContextBundler({
post_build_fn: serverPostBuildFn,
});
// initPages({
// log_time: true,
// });
watcherEsbuildCTX();
} else {
log.build(`Building Modules ...`);
await allPagesESBuildContextBundler();
// initPages({
// log_time: true,
// });
cron();
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ export default async function trimCacheKey({
const config = global.CONFIG;
const default_expiry_time_seconds =
config.defaultCacheExpiry ||
config.default_cache_expiry ||
AppData["DefaultCacheExpiryTimeSeconds"];
const default_expiry_time_milliseconds =
+12 -9
View File
@@ -1,11 +1,13 @@
import handleWebPages from "./web-pages/handle-web-pages";
import handleRoutes from "./handle-routes";
import isDevelopment from "../../utils/is-development";
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";
import checkExcludedPatterns from "../../utils/check-excluded-patterns";
import { AppData } from "../../data/app-data";
import fullRebuild from "./full-rebuild";
type Params = {
req: Request;
server: Bun.Server<any>;
@@ -21,12 +23,14 @@ export default async function bunextRequestHandler({
try {
const url = new URL(req.url);
const { config } = grabConstants();
if (checkExcludedPatterns({ path: url.pathname })) {
return Response.json({ success: false, msg: `Invalid Path` });
}
let response: Response | undefined = undefined;
if (config?.middleware) {
const middleware_res = await config.middleware({
if (global.CONSTANTS.config?.middleware) {
const middleware_res = await global.CONSTANTS.config.middleware({
req: initial_req,
url,
});
@@ -40,11 +44,10 @@ export default async function bunextRequestHandler({
}
}
// const server_upgrade = server.upgrade(req);
// if (server_upgrade) {
// return undefined;
// }
if (is_dev && url.pathname == AppData["BunextHMRRetryRoute"]) {
await fullRebuild({ msg: `HMR Retry Rebuild ...` });
return new Response("Modules Rebuilt");
}
if (url.pathname === "/__hmr" && is_dev) {
response = await handleHmr({ req });
+1 -1
View File
@@ -18,6 +18,6 @@ export default async function (): Promise<Bun.Serve.Options<any>> {
idleTimeout: development ? 0 : undefined,
development,
websocket: config?.websocket,
..._.omit(config?.serverOptions || {}, ["fetch"]),
..._.omit(config?.server_options || {}, ["fetch"]),
} as Bun.Serve.Options<any>;
}
+3 -4
View File
@@ -1,11 +1,9 @@
import { watch, existsSync, statSync } from "fs";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import { log } from "../../utils/log";
import allPagesESBuildContextBundler from "../bundler/all-pages-esbuild-context-bundler";
import serverPostBuildFn from "./server-post-build-fn";
import fullRebuild from "./full-rebuild";
import { AppData } from "../../data/app-data";
import checkExcludedPatterns from "../../utils/check-excluded-patterns";
const { ROOT_DIR } = grabDirNames();
@@ -102,7 +100,8 @@ export default async function watcherEsbuildCTX() {
}
if (!filename.match(/^src\/pages\/|\.css$/)) return reloadWatcher();
if (filename.match(/\/(--|\()/)) return reloadWatcher();
if (checkExcludedPatterns({ path: filename }))
return reloadWatcher();
if (filename.match(/ /)) return reloadWatcher();
if (global.RECOMPILING) return;
@@ -23,6 +23,10 @@ export default async function (params?: Params) {
.map((e) => `args[0].includes("${e}")`)
.join(" || ");
script += `let retries = 0;\n`;
script += `let retries_exhausted = false;\n`;
script += `const MAX_RETRIES = 1;\n`;
script += `const _ce = console.error.bind(console);\n`;
script += `console.error = (...args) => {\n`;
script += ` if (typeof args[0] === "string" && (${supress_condition})) return;\n`;
@@ -35,8 +39,16 @@ export default async function (params?: Params) {
script += ` const overlay = document.createElement("div");\n`;
script += ` overlay.id = "__bunext_error_overlay";\n`;
script += ` overlay.style.cssText = "position:fixed;inset:0;z-index:99999;background:#1a1a1a;color:#ff6b6b;font-family:monospace;font-size:14px;padding:24px;overflow:auto;";\n`;
script += ` overlay.innerHTML = \`<div style="max-width:900px;margin:0 auto"><div style="font-size:18px;font-weight:bold;margin-bottom:12px;color:#ff4444">Runtime Error</div><div style="color:#fff;margin-bottom:16px">\${message}</div>\${source ? \`<div style="color:#888;margin-bottom:16px">\${source}</div>\` : ""}\${stack ? \`<pre style="background:#111;padding:16px;border-radius:6px;overflow:auto;color:#ffa07a;white-space:pre-wrap">\${stack}</pre>\` : ""}<button onclick="this.closest('#__bunext_error_overlay').remove()" style="margin-top:16px;padding:8px 16px;background:#333;color:#fff;border:none;border-radius:4px;cursor:pointer">Dismiss</button></div>\`;\n`;
script += ` overlay.innerHTML = \`<div style="max-width:900px;margin:auto"><div style="font-size:18px;font-weight:bold;margin-bottom:12px;color:#ff4444">Runtime Error</div><div style="color:#fff;margin-bottom:16px">\${message}</div>\${source ? \`<div style="color:#888;margin-bottom:16px">\${source}</div>\` : ""}\${stack ? \`<pre style="background:#111;padding:16px;border-radius:6px;overflow:auto;color:#ffa07a;white-space:pre-wrap">\${stack}</pre>\` : ""}<button onclick="this.closest('#__bunext_error_overlay').remove()" style="margin-top:16px;padding:8px 16px;background:#333;color:#fff;border:none;border-radius:4px;cursor:pointer">Dismiss</button></div>\`;\n`;
script += ` document.body.appendChild(overlay);\n`;
script += ` if (retries < MAX_RETRIES) {\n`;
script += ` retries++\n`;
script += ` console.log(\`Retrying \${retries} ...\`)\n`;
script += ` fetch("${AppData["BunextHMRRetryRoute"]}")\n`;
script += ` } else {\n`;
script += ` retries_exhausted = true\n`;
script += ` }\n`;
script += `}\n\n`;
script += `function __bunext_should_suppress_runtime_error(message) {\n`;
script += ` return false;\n`;
@@ -66,7 +78,16 @@ export default async function (params?: Params) {
script += `hmr.addEventListener("update", async (event) => {\n`;
script += ` if (event?.data) {\n`;
script += ` try {\n`;
script += ` document.getElementById("__bunext_error_overlay")?.remove();\n`;
script += ` if (retries_exhausted) {\n`;
script += ` document.getElementById("__bunext_error_overlay")?.remove();\n`;
script += ` retries = 0;\n`;
script += ` retries_exhausted = false;\n`;
script += ` }\n`;
// script += ` if (retries >= MAX_RETRIES && document.getElementById("__bunext_error_overlay")) {\n`;
// script += ` retries = 0;\n`;
// script += ` }\n`;
script += ` const data = JSON.parse(event.data);\n`;
// script += ` console.log("data", data);\n`;
@@ -118,7 +139,9 @@ export default async function (params?: Params) {
// script += ` window.location.reload();\n`;
// script += ` }\n`;
// script += ` console.log("newScript", newScript);\n`;
// script += ` document.getElementById("__bunext_error_overlay")?.remove();\n`;
script += ` document.head.appendChild(newScript);\n\n`;
// script += ` retries = 0;\n\n`;
script += ` } catch (err) {\n`;
script += ` console.error("HMR update failed, falling back to reload:", err.message);\n`;
+10 -5
View File
@@ -49,10 +49,10 @@ export type PageModule = {
};
export type BunextConfig = {
distDir?: string;
assetsPrefix?: string;
dist_dir?: string;
assets_prefix?: string;
origin?: string;
globalVars?: { [k: string]: any };
global_vars?: { [k: string]: any };
port?: number;
development?: boolean;
middleware?: (
@@ -62,9 +62,14 @@ export type BunextConfig = {
| Response
| Request
| undefined;
defaultCacheExpiry?: number;
default_cache_expiry?: number;
websocket?: WebSocketHandler<any>;
serverOptions?: Omit<Bun.Serve.Options<any>, "fetch" | "routes">;
server_options?: Omit<Bun.Serve.Options<any>, "fetch" | "routes">;
/**
* These are patterns in the pages to exclude
* from the router
*/
pages_exclude_patterns?: RegExp[];
};
export type BunextConfigMiddlewareParams = {
+14
View File
@@ -0,0 +1,14 @@
import type { APIResponseObject } from "../types";
type Params = {
path: string;
};
export default function ({ path }: Params): boolean {
for (let i = 0; i < global.CONSTANTS.RouteIgnorePatterns.length; i++) {
const regex = global.CONSTANTS.RouteIgnorePatterns[i];
if (path.match(regex)) return true;
}
return false;
}
+7 -2
View File
@@ -4,6 +4,7 @@ import path from "path";
import type { PageFiles } from "../types";
import AppNames from "./grab-app-names";
import pagePathTransform from "./page-path-transform";
import checkExcludedPatterns from "./check-excluded-patterns";
type Params = {
exclude_api?: boolean;
@@ -49,7 +50,11 @@ function grabPageDirRecursively({ page_dir }: { page_dir: string }) {
continue;
}
if (page.match(/\(|\)|--|\/api\//)) {
if (checkExcludedPatterns({ path: page })) {
continue;
}
if (page.match(/\/api\//)) {
continue;
}
@@ -60,7 +65,7 @@ function grabPageDirRecursively({ page_dir }: { page_dir: string }) {
const page_stat = statSync(full_page_path);
if (page_stat.isDirectory()) {
if (page.match(/\(|\)/)) continue;
if (checkExcludedPatterns({ path: page })) continue;
const new_page_files = grabPageDirRecursively({
page_dir: full_page_path,
});
+2 -2
View File
@@ -1,8 +1,8 @@
import AppNames from "./grab-app-names";
export default function grabAssetsPrefix() {
if (global.CONFIG.assetsPrefix) {
return global.CONFIG.assetsPrefix;
if (global.CONFIG.assets_prefix) {
return global.CONFIG.assets_prefix;
}
const { defaultAssetPrefix } = AppNames;
+6
View File
@@ -9,6 +9,11 @@ export default function grabConstants() {
const ServerDefaultRequestBodyLimitBytes = MB_IN_BYTES * 10;
const MaxBundlerRebuilds = 5;
const RouteIgnorePatterns = [/\/\(/];
if (config.pages_exclude_patterns) {
RouteIgnorePatterns.push(...config.pages_exclude_patterns);
}
return {
ClientRootElementIDName,
@@ -18,5 +23,6 @@ export default function grabConstants() {
ClientRootComponentWindowName,
MaxBundlerRebuilds,
config,
RouteIgnorePatterns,
} as const;
}