Refactor Server Paradigm.

This commit is contained in:
2026-03-24 07:18:57 +01:00
parent 342f56f3f5
commit 60ee353bf0
34 changed files with 425 additions and 279 deletions
+10 -5
View File
@@ -7,6 +7,7 @@ import path from "path";
import grabClientHydrationScript from "./grab-client-hydration-script";
import { mkdirSync, rmSync } from "fs";
import recordArtifacts from "./record-artifacts";
import BunSkipNonBrowserPlugin from "./plugins/bun-skip-browser-plugin";
const { HYDRATION_DST_DIR, BUNX_HYDRATION_SRC_DIR, BUNX_TMP_DIR } = grabDirNames();
export default async function allPagesBunBundler(params) {
const { target = "browser", page_file_paths } = params || {};
@@ -37,15 +38,16 @@ export default async function allPagesBunBundler(params) {
if (entryToPage.size === 0)
return;
const buildStart = performance.now();
const define = {
"process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
};
const result = await Bun.build({
entrypoints: [...entryToPage.keys()],
outdir: HYDRATION_DST_DIR,
root: BUNX_HYDRATION_SRC_DIR,
minify: true,
minify: !dev,
format: "esm",
define: {
"process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
},
define,
naming: {
entry: "[dir]/[hash].[ext]",
chunk: "chunks/[hash].[ext]",
@@ -94,7 +96,10 @@ export default async function allPagesBunBundler(params) {
});
}
if (artifacts?.[0]) {
await recordArtifacts({ artifacts });
await recordArtifacts({
artifacts,
page_file_paths,
});
}
const elapsed = (performance.now() - buildStart).toFixed(0);
log.success(`[Built] in ${elapsed}ms`);
+30 -1
View File
@@ -8,6 +8,7 @@ import grabClientHydrationScript from "./grab-client-hydration-script";
import grabArtifactsFromBundledResults from "./grab-artifacts-from-bundled-result";
import { writeFileSync } from "fs";
import recordArtifacts from "./record-artifacts";
import stripServerSideLogic from "./strip-server-side-logic";
const { HYDRATION_DST_DIR, HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
let build_starts = 0;
const MAX_BUILD_STARTS = 10;
@@ -23,7 +24,7 @@ export default async function allPagesBundler(params) {
const virtualEntries = {};
const dev = isDevelopment();
for (const page of target_pages) {
const key = page.transformed_path;
const key = page.local_path;
const txt = await grabClientHydrationScript({
page_local_path: page.local_path,
});
@@ -32,6 +33,11 @@ export default async function allPagesBundler(params) {
// }
if (!txt)
continue;
// const final_tsx = stripServerSideLogic({
// txt_code: txt,
// file_path: key,
// });
// console.log("final_tsx", final_tsx);
virtualEntries[key] = txt;
}
const virtualPlugin = {
@@ -66,6 +72,28 @@ export default async function allPagesBundler(params) {
},
};
const entryPoints = Object.keys(virtualEntries).map((k) => `virtual:${k}`);
// let alias: any = {};
// const excludes = [
// "bun:sqlite",
// "path",
// "url",
// "events",
// "util",
// "crypto",
// "net",
// "tls",
// "fs",
// "node:path",
// "node:url",
// "node:process",
// "node:fs",
// "node:timers/promises",
// ];
// for (let i = 0; i < excludes.length; i++) {
// const exclude = excludes[i];
// alias[exclude] = "./empty.js";
// }
// console.log("alias", alias);
const result = await esbuild.build({
entryPoints,
outdir: HYDRATION_DST_DIR,
@@ -89,6 +117,7 @@ export default async function allPagesBundler(params) {
"react-dom/client",
"react/jsx-runtime",
],
// alias,
});
if (result.errors.length > 0) {
for (const error of result.errors) {
+12 -9
View File
@@ -4,24 +4,27 @@ import grabDirNames from "../../utils/grab-dir-names";
import AppNames from "../../utils/grab-app-names";
import grabConstants from "../../utils/grab-constants";
import pagePathTransform from "../../utils/page-path-transform";
import grabRootFilePath from "../server/web-pages/grab-root-file-path";
const { PAGES_DIR } = grabDirNames();
export default async function grabClientHydrationScript({ page_local_path, }) {
const { ClientRootElementIDName, ClientRootComponentWindowName, ClientWindowPagePropsName, } = grabConstants();
const target_path = pagePathTransform({ page_path: page_local_path });
const root_component_path = path.join(PAGES_DIR, `${AppNames["RootPagesComponentName"]}.tsx`);
const does_root_exist = existsSync(root_component_path);
const { root_file_path } = grabRootFilePath();
// const target_path = pagePathTransform({ page_path: page_local_path });
// const target_root_path = root_file_path
// ? pagePathTransform({ page_path: root_file_path })
// : undefined;
let txt = ``;
txt += `import { hydrateRoot } from "react-dom/client";\n`;
if (does_root_exist) {
txt += `import Root from "${root_component_path}";\n`;
if (root_file_path) {
txt += `import Root from "${root_file_path}";\n`;
}
txt += `import Page from "${target_path}";\n\n`;
txt += `import Page from "${page_local_path}";\n\n`;
txt += `const pageProps = window.${ClientWindowPagePropsName} || {};\n`;
if (does_root_exist) {
txt += `const component = <Root suppressHydrationWarning={true} {...pageProps}><Page {...pageProps} /></Root>\n`;
if (root_file_path) {
txt += `const component = <Root {...pageProps}><Page {...pageProps} /></Root>\n`;
}
else {
txt += `const component = <Page suppressHydrationWarning={true} {...pageProps} />\n`;
txt += `const component = <Page {...pageProps} />\n`;
}
txt += `if (window.${ClientRootComponentWindowName}?.render) {\n`;
txt += ` window.${ClientRootComponentWindowName}.render(component);\n`;
+68 -24
View File
@@ -1,31 +1,75 @@
import { log } from "../../../utils/log";
const BunSkipNonBrowserPlugin = {
name: "skip-non-browser",
setup(build) {
build.onResolve({ filter: /^(bun:|node:)/ }, (args) => {
return { path: args.path, external: true };
const skipFilter = /^(bun:|node:|fs$|path$|os$|crypto$|net$|events$|util$|tls$|url$|process$)/;
// const skipped_modules = new Set<string>();
build.onResolve({ filter: skipFilter }, (args) => {
global.SKIPPED_BROWSER_MODULES.add(args.path);
return {
path: args.path,
namespace: "skipped",
// external: true,
};
});
build.onResolve({ filter: /^[^./]/ }, (args) => {
// If it's a built-in like 'fs' or 'path', skip it immediately
const excludes = [
"fs",
"path",
"os",
"crypto",
"net",
"events",
"util",
];
if (excludes.includes(args.path) || args.path.startsWith("node:")) {
return { path: args.path, external: true };
}
try {
Bun.resolveSync(args.path, args.importer || process.cwd());
return null;
}
catch (e) {
console.warn(`[Skip] Mark as external: ${args.path}`);
return { path: args.path, external: true };
}
// build.onEnd(() => {
// log.warn(`global.SKIPPED_BROWSER_MODULES`, [
// ...global.SKIPPED_BROWSER_MODULES,
// ]);
// });
// build.onResolve({ filter: /^[^./]/ }, (args) => {
// // If it's a built-in like 'fs' or 'path', skip it immediately
// const excludes = [
// "fs",
// "path",
// "os",
// "crypto",
// "net",
// "events",
// "util",
// "tls",
// ];
// if (excludes.includes(args.path) || args.path.startsWith("node:")) {
// return {
// path: args.path,
// // namespace: "skipped",
// external: true,
// };
// }
// try {
// Bun.resolveSync(args.path, args.importer || process.cwd());
// return null;
// } catch (e) {
// console.warn(`[Skip] Mark as external: ${args.path}`);
// return {
// path: args.path,
// // namespace: "skipped",
// external: true,
// };
// }
// });
build.onLoad({ filter: /.*/, namespace: "skipped" }, (args) => {
return {
contents: `
const proxy = new Proxy(() => proxy, {
get: () => proxy,
construct: () => proxy,
});
export const Database = proxy;
export const join = proxy;
export const fileURLToPath = proxy;
export const arch = proxy;
export const platform = proxy;
export const statSync = proxy;
export const $H = proxy;
export const _ = proxy;
export default proxy;
`,
loader: "js",
};
});
},
};
+2 -1
View File
@@ -1,6 +1,7 @@
import type { BundlerCTXMap } from "../../types";
type Params = {
artifacts: BundlerCTXMap[];
page_file_paths?: string[];
};
export default function recordArtifacts({ artifacts }: Params): Promise<void>;
export default function recordArtifacts({ artifacts, page_file_paths, }: Params): Promise<void>;
export {};
+7 -3
View File
@@ -1,6 +1,7 @@
import grabDirNames from "../../utils/grab-dir-names";
import _ from "lodash";
const { HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
export default async function recordArtifacts({ artifacts }) {
export default async function recordArtifacts({ artifacts, page_file_paths, }) {
const artifacts_map = {};
for (const artifact of artifacts) {
if (artifact?.local_path) {
@@ -8,7 +9,10 @@ export default async function recordArtifacts({ artifacts }) {
}
}
if (global.BUNDLER_CTX_MAP) {
global.BUNDLER_CTX_MAP = artifacts_map;
global.BUNDLER_CTX_MAP = _.merge(global.BUNDLER_CTX_MAP, artifacts_map);
}
await Bun.write(HYDRATION_DST_DIR_MAP_JSON_FILE, JSON.stringify(artifacts_map, null, 4));
// await Bun.write(
// HYDRATION_DST_DIR_MAP_JSON_FILE,
// JSON.stringify(artifacts_map, null, 4),
// );
}