Major Refactoring. Test update

This commit is contained in:
2026-03-22 16:45:12 +01:00
parent e047539a11
commit 1634eeb213
51 changed files with 389 additions and 319 deletions
+1 -7
View File
@@ -1,9 +1,3 @@
import type { Server } from "bun";
import type { BunextServerRouteConfig, BunxRouteParams } from "../../types";
import grabRouteParams from "../../utils/grab-route-params";
import grabConstants from "../../utils/grab-constants";
import grabRouter from "../../utils/grab-router";
type Params = {
req: Request;
};
@@ -13,7 +7,7 @@ export default async function ({ req }: Params): Promise<Response> {
const match = global.ROUTER.match(referer_url.pathname);
const target_map = match?.filePath
? global.BUNDLER_CTX_MAP?.find((m) => m.local_path == match.filePath)
? global.BUNDLER_CTX_MAP[match.filePath]
: undefined;
let controller: ReadableStreamDefaultController<string>;
+10 -5
View File
@@ -2,17 +2,22 @@ import allPagesBundler from "../bundler/all-pages-bundler";
import serverPostBuildFn from "./server-post-build-fn";
import { log } from "../../utils/log";
export default async function rebuildBundler() {
type Params = {
target_file_paths?: string[];
};
export default async function rebuildBundler(params?: Params) {
try {
global.ROUTER.reload();
await global.BUNDLER_CTX?.dispose();
global.BUNDLER_CTX = undefined;
// await global.BUNDLER_CTX?.dispose();
// global.BUNDLER_CTX = undefined;
await allPagesBundler({
watch: true,
post_build_fn: serverPostBuildFn,
page_file_paths: params?.target_file_paths,
});
await serverPostBuildFn();
} catch (error: any) {
log.error(error);
}
+11 -12
View File
@@ -2,25 +2,24 @@ import _ from "lodash";
import type { BundlerCTXMap, GlobalHMRControllerObject } from "../../types";
import grabPageComponent from "./web-pages/grab-page-component";
type Params = {
artifacts: BundlerCTXMap[];
};
export default async function serverPostBuildFn() {
// if (!global.IS_FIRST_BUNDLE_READY) {
// global.IS_FIRST_BUNDLE_READY = true;
// }
export default async function serverPostBuildFn({ artifacts }: Params) {
if (!global.IS_FIRST_BUNDLE_READY) {
global.IS_FIRST_BUNDLE_READY = true;
}
if (!global.HMR_CONTROLLERS?.[0]) {
if (!global.HMR_CONTROLLERS?.[0] || !global.BUNDLER_CTX_MAP) {
return;
}
for (let i = 0; i < global.HMR_CONTROLLERS.length; i++) {
const controller = global.HMR_CONTROLLERS[i];
const target_artifact = artifacts.find(
(a) => controller.target_map?.local_path == a.local_path,
);
if (!controller.target_map?.local_path) {
continue;
}
const target_artifact =
global.BUNDLER_CTX_MAP[controller.target_map.local_path];
const mock_req = new Request(controller.page_url);
+13 -12
View File
@@ -1,4 +1,4 @@
import { watch, existsSync, statSync } from "fs";
import { watch, existsSync } from "fs";
import path from "path";
import grabDirNames from "../../utils/grab-dir-names";
import rebuildBundler from "./rebuild-bundler";
@@ -45,17 +45,10 @@ export default async function watcher() {
const target_files_match = /\.(tsx?|jsx?|css)$/;
if (event !== "rename") {
if (filename.match(target_files_match) && global.BUNDLER_CTX) {
if (filename.match(target_files_match)) {
if (global.RECOMPILING) return;
global.RECOMPILING = true;
if (full_file_path.match(/\_\_root\.tsx?$/)) {
// log.watch(`__root.tsx file updated. Reloading window.`);
global.ROOT_FILE_UPDATED = true;
}
await rewritePagesModule({ page_url: full_file_path });
await global.BUNDLER_CTX.rebuild();
await fullRebuild();
}
return;
}
@@ -85,15 +78,23 @@ export default async function watcher() {
global.PAGES_SRC_WATCHER = pages_src_watcher;
}
async function fullRebuild({ msg }: { msg?: string }) {
async function fullRebuild(params?: { msg?: string }) {
try {
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 });
if (msg) {
log.watch(msg);
}
await rebuildBundler();
await rebuildBundler({ target_file_paths });
} catch (error: any) {
log.error(error);
} finally {
@@ -4,19 +4,19 @@ import grabTsxStringModule from "./grab-tsx-string-module";
type Params = {
file_path: string;
root_file?: string;
root_file_path?: string;
server_res?: any;
};
export default async function grabPageBundledReactComponent({
file_path,
root_file,
root_file_path,
server_res,
}: Params): Promise<GrabPageReactBundledComponentRes | undefined> {
try {
let tsx = grabPageReactComponentString({
file_path,
root_file,
root_file_path,
server_res,
});
@@ -10,7 +10,7 @@ import grabPageErrorComponent from "./grab-page-error-component";
import grabPageBundledReactComponent from "./grab-page-bundled-react-component";
import _ from "lodash";
import { log } from "../../../utils/log";
import grabRootFile from "./grab-root-file";
import grabRootFilePath from "./grab-root-file-path";
class NotFoundError extends Error {}
@@ -62,9 +62,7 @@ export default async function grabPageComponent({
throw new Error(errMsg);
}
const bundledMap = global.BUNDLER_CTX_MAP?.find(
(m) => m.local_path == file_path,
);
const bundledMap = global.BUNDLER_CTX_MAP[file_path];
if (!bundledMap?.path) {
const errMsg = `No Bundled File Path for this request path!`;
@@ -76,7 +74,7 @@ export default async function grabPageComponent({
log.info(`bundledMap:`, bundledMap);
}
const { root_file } = grabRootFile();
const { root_file_path } = grabRootFilePath();
const module: BunextPageModule = await import(`${file_path}?t=${now}`);
@@ -150,7 +148,7 @@ export default async function grabPageComponent({
const { component } =
(await grabPageBundledReactComponent({
file_path,
root_file,
root_file_path,
server_res: serverRes,
})) || {};
@@ -33,9 +33,7 @@ export default async function grabPageErrorComponent({
const filePath = match?.filePath || presetComponent;
const bundledMap = match?.filePath
? (global.BUNDLER_CTX_MAP?.find(
(m) => m.local_path === match.filePath,
) ?? ({} as BundlerCTXMap))
? global.BUNDLER_CTX_MAP[match.filePath]
: ({} as BundlerCTXMap);
const module: BunextPageModule = await import(filePath);
@@ -49,9 +47,9 @@ export default async function grabPageErrorComponent({
bundledMap,
serverRes: {
responseOptions: {
status: is404 ? 404 : 500
}
} as any
status: is404 ? 404 : 500,
},
} as any,
};
} catch {
const DefaultNotFound: FC = () => (
@@ -77,9 +75,9 @@ export default async function grabPageErrorComponent({
bundledMap: {} as BundlerCTXMap,
serverRes: {
responseOptions: {
status: is404 ? 404 : 500
}
} as any
status: is404 ? 404 : 500,
},
} as any,
};
}
}
@@ -3,13 +3,13 @@ import pagePathTransform from "../../../utils/page-path-transform";
type Params = {
file_path: string;
root_file?: string;
root_file_path?: string;
server_res?: any;
};
export default function grabPageReactComponentString({
file_path,
root_file,
root_file_path,
server_res,
}: Params): string | undefined {
try {
@@ -20,15 +20,15 @@ export default function grabPageReactComponentString({
EJSON.stringify(server_res || {}) ?? "{}",
);
if (root_file) {
tsx += `import Root from "${root_file}"\n`;
if (root_file_path) {
tsx += `import Root from "${root_file_path}"\n`;
}
tsx += `import Page from "${target_path}"\n`;
tsx += `export default function Main() {\n\n`;
tsx += `const props = JSON.parse(${server_res_json})\n\n`;
tsx += ` return (\n`;
if (root_file) {
if (root_file_path) {
tsx += ` <Root suppressHydrationWarning={true} {...props}><Page {...props} /></Root>\n`;
} else {
tsx += ` <Page suppressHydrationWarning={true} {...props} />\n`;
@@ -3,7 +3,7 @@ import path from "path";
import AppNames from "../../../utils/grab-app-names";
import { existsSync } from "fs";
export default function grabRootFile() {
export default function grabRootFilePath() {
const { PAGES_DIR } = grabDirNames();
const root_pages_component_ts_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.ts`;
@@ -11,7 +11,7 @@ export default function grabRootFile() {
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)
const root_file_path = existsSync(root_pages_component_tsx_file)
? root_pages_component_tsx_file
: existsSync(root_pages_component_ts_file)
? root_pages_component_ts_file
@@ -21,5 +21,5 @@ export default function grabRootFile() {
? root_pages_component_js_file
: undefined;
return { root_file };
return { root_file_path };
}
@@ -12,6 +12,7 @@ export default async function (params?: Params) {
let script = "";
script += `console.log(\`Development Environment\`);\n\n`;
script += `const _ce = console.error.bind(console);\n`;
script += `console.error = (...args) => {\n`;
script += ` if (typeof args[0] === "string" && args[0].includes("hydrat")) return;\n`;
@@ -27,7 +28,9 @@ export default async function (params?: Params) {
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 += ` document.body.appendChild(overlay);\n`;
script += `}\n\n`;
script += `window.addEventListener("error", (e) => __bunext_show_error(e.message, e.filename ? e.filename + ":" + e.lineno + ":" + e.colno : "", e.error?.stack ?? ""));\n`;
script += `window.addEventListener("error", (e) => {\n`;
script += ` __bunext_show_error(e.message, e.filename ? e.filename + ":" + e.lineno + ":" + e.colno : "", e.error?.stack ?? "");\n`;
script += `});\n`;
script += `window.addEventListener("unhandledrejection", (e) => __bunext_show_error(String(e.reason?.message ?? e.reason), "", e.reason?.stack ?? ""));\n\n`;
script += `const hmr = new EventSource("/__hmr");\n`;
@@ -73,6 +76,9 @@ export default async function (params?: Params) {
script += ` newScript.id = "${AppData["BunextClientHydrationScriptID"]}";\n`;
script += ` newScript.type = "module";\n`;
script += ` newScript.src = newScriptPath;\n`;
// script += ` newScript.onerror = (e) => {\n`;
// script += ` window.location.reload();\n`;
// script += ` }\n`;
// script += ` console.log("newScript", newScript);\n`;
script += ` document.head.appendChild(newScript);\n\n`;
script += ` } catch (err) {\n`;