This commit is contained in:
2026-02-26 04:08:06 +01:00
parent 8177df7dd3
commit f7c0e927c7
39 changed files with 1003 additions and 306 deletions
+26
View File
@@ -0,0 +1,26 @@
import { existsSync } from "fs";
import type { BunextConfig } from "../types";
import grabDirNames from "../utils/grab-dir-names";
import exitWithError from "../utils/exit-with-error";
export default async function grabConfig(): Promise<BunextConfig | undefined> {
try {
const { CONFIG_FILE } = grabDirNames();
if (!existsSync(CONFIG_FILE)) {
exitWithError(`Config file \`${CONFIG_FILE}\` doesn't exist!`);
}
const config = (await import(CONFIG_FILE)).default as BunextConfig;
if (!config) {
exitWithError(
`Config file \`${CONFIG_FILE}\` is invalid! Please provide a valid default export in your config file.`
);
}
return config;
} catch (error) {
return undefined;
}
}
+31
View File
@@ -0,0 +1,31 @@
import { existsSync, mkdirSync, statSync, writeFileSync } from "fs";
import grabDirNames from "../utils/grab-dir-names";
export default async function () {
const dirNames = grabDirNames();
const keys = Object.keys(dirNames) as (keyof ReturnType<
typeof grabDirNames
>)[];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const dir = dirNames[key];
// const stat = statSync(dir);
if (!existsSync(dir) && !dir.match(/\.\w+$/)) {
mkdirSync(dir, { recursive: true });
continue;
}
if (key == "CONFIG_FILE" && !existsSync(dir)) {
let basicConfig = ``;
basicConfig += `const config = {};\n`;
basicConfig += `export default config;\n`;
writeFileSync(dir, basicConfig);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
import grabDirNames from "../../utils/grab-dir-names";
import type { GetRouteReturn } from "../../types";
import grabAssetsPrefix from "../../utils/grab-assets-prefix";
import grabOrigin from "../../utils/grab-origin";
import grabRouter from "../../utils/grab-router";
type Params = {
route: string;
};
export default async function getRoute({
route,
}: Params): Promise<GetRouteReturn | null> {
const { ROUTES_DIR } = grabDirNames();
if (route.match(/\(/)) {
return null;
}
const router = grabRouter();
const match = router.match(route);
if (!match?.filePath) {
console.error(`Route ${route} not found`);
return null;
}
const module = await import(match.filePath);
return {
match,
module,
component: module.default,
serverProps: module.serverProps,
staticProps: module.staticProps,
staticPaths: module.staticPaths,
staticParams: module.staticParams,
};
}
+69
View File
@@ -0,0 +1,69 @@
import type { Server } from "bun";
import type {
APIResponseObject,
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;
server: Server;
};
export default async function ({
req,
server,
}: Params): Promise<APIResponseObject | undefined> {
const url = new URL(req.url);
const { MBInBytes, ServerDefaultRequestBodyLimitBytes } =
await grabConstants();
const router = grabRouter();
const match = router.match(url.pathname);
if (!match?.filePath) {
const errMsg = `Route ${url.pathname} not found`;
console.error(errMsg);
return {
success: false,
status: 401,
msg: errMsg,
};
}
const routeParams: BunxRouteParams = await grabRouteParams({ req, server });
const module = await import(match.filePath);
const config = module.config as BunextServerRouteConfig | undefined;
const contentLength = req.headers.get("content-length");
if (contentLength) {
const size = parseInt(contentLength, 10);
if (
(config?.maxRequestBodyMB &&
size > config.maxRequestBodyMB * MBInBytes) ||
size > ServerDefaultRequestBodyLimitBytes
) {
return {
success: false,
status: 413,
msg: "Request Body Too Large!",
};
}
}
const res: APIResponseObject = await module["default"](
routeParams as BunxRouteParams
);
return res;
}
+74
View File
@@ -0,0 +1,74 @@
import path from "path";
import type { ServeOptions } from "bun";
import grabAppPort from "../../utils/grab-app-port";
import grabDirNames from "../../utils/grab-dir-names";
import handleWebPages from "./web-pages/handle-web-pages";
import handleRoutes from "./handle-routes";
import isDevelopment from "../../utils/is-development";
const port = grabAppPort();
const { PUBLIC_DIR } = grabDirNames();
type Params = {
dev?: boolean;
};
export default async function (params?: Params): Promise<ServeOptions> {
return {
async fetch(req, server) {
try {
const url = new URL(req.url);
if (url.pathname === "/__hmr" && isDevelopment()) {
let controller: ReadableStreamDefaultController<string>;
const stream = new ReadableStream<string>({
start(c) {
controller = c;
global.HMR_CONTROLLERS.add(c);
},
cancel() {
global.HMR_CONTROLLERS.delete(controller);
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
} else if (url.pathname.startsWith("/api/")) {
const res = await handleRoutes({ req, server });
return new Response(JSON.stringify(res), {
status: res?.status,
headers: {
"Content-Type": "application/json",
},
});
} else if (url.pathname.startsWith("/public/")) {
const file = Bun.file(
path.join(
PUBLIC_DIR,
url.pathname.replace(/^\/public/, ""),
),
);
return new Response(file);
} else {
return await handleWebPages({ req, server });
}
} catch (error: any) {
return new Response(`Server Error: ${error.message}`, {
status: 500,
});
}
},
port,
development: isDevelopment() && {
hmr: true,
console: true,
},
} as ServeOptions;
}
+27
View File
@@ -0,0 +1,27 @@
import AppNames from "../../utils/grab-app-names";
import serverParamsGen from "./server-params-gen";
import watcher from "./watcher";
type Params = {
dev?: boolean;
};
export default async function startServer(params?: Params) {
const { name } = AppNames;
const serverParams = await serverParamsGen();
const server = Bun.serve(serverParams);
global.SERVER = server;
console.log(
`${name} Server Running on http://localhost:${server.port} ...`,
);
if (params?.dev) {
watcher();
}
return server;
}
+127
View File
@@ -0,0 +1,127 @@
import { watch } from "fs";
import grabDirNames from "../../utils/grab-dir-names";
import writeWebPageHydrationScript from "./web-pages/write-web-page-hydration-script";
import grabPageName from "../../utils/grab-page-name";
import path from "path";
import { execSync } from "child_process";
import serverParamsGen from "./server-params-gen";
import grabRouter from "../../utils/grab-router";
import type { FC } from "react";
const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, ROUTES_DIR } =
grabDirNames();
export default function watcher() {
watch(
ROOT_DIR,
{ recursive: true, persistent: true },
async (event, filename) => {
if (global.RECOMPILING) return;
if (!filename) return;
if (filename.match(/ /)) return;
if (filename.match(/^node_modules\//)) return;
if (filename.match(/\.bunext|\/public\//)) return;
if (filename.match(/\/routes\//)) {
if (event == "change") {
clearTimeout(global.WATCHER_TIMEOUT);
global.RECOMPILING = true;
const fullPath = path.join(ROOT_DIR, filename);
const pageName = grabPageName({ path: fullPath });
// const router = grabRouter();
// const match = router.match(fullPath);
// if (match?.filePath) {
// const module = await import(match.filePath);
// const serverRes = await (async () => {
// try {
// return await module["server"]();
// } catch (error) {
// return {};
// }
// })();
// const Component = module.default as FC<any>;
// const component = <Component pageProps={serverRes} />;
// await writeWebPageHydrationScript({
// pageName,
// component,
// });
// }
let cmd = `bun build`;
cmd += ` ${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx --outdir ${HYDRATION_DST_DIR}`;
cmd += ` --minify`;
execSync(cmd, { stdio: "inherit" });
global.ROUTER = new Bun.FileSystemRouter({
style: "nextjs",
dir: ROUTES_DIR,
});
const encoder = new TextEncoder();
const msg = encoder.encode(`event: update\ndata: reload\n\n`);
for (const controller of global.HMR_CONTROLLERS) {
controller.enqueue(msg);
}
global.RECOMPILING = false;
} else if (event == "rename") {
await reloadServer();
}
} else if (filename.match(/\.(js|ts|tsx|jsx)$/)) {
clearTimeout(global.WATCHER_TIMEOUT);
await reloadServer();
}
},
);
// watch(BUNX_HYDRATION_SRC_DIR, async (event, filename) => {
// if (!filename) return;
// const targetFile = path.join(BUNX_HYDRATION_SRC_DIR, filename);
// await Bun.build({
// entrypoints: [targetFile],
// outdir: HYDRATION_DST_DIR,
// minify: true,
// target: "browser",
// format: "esm",
// });
// global.SERVER?.publish("__bun_hmr", "update");
// setTimeout(() => {
// global.RECOMPILING = false;
// }, 200);
// });
// watch(HYDRATION_DST_DIR, async (event, filename) => {
// const encoder = new TextEncoder();
// global.HMR_CONTROLLER?.enqueue(encoder.encode(`event: update\ndata: reload\n\n`));
// global.RECOMPILING = false;
// });
// let cmd = `bun build`;
// cmd += ` ${BUNX_HYDRATION_SRC_DIR}/*.tsx --outdir ${HYDRATION_DST_DIR}`;
// cmd += ` --watch --minify`;
// execSync(cmd, { stdio: "inherit" });
}
async function reloadServer() {
const serverParams = await serverParamsGen();
console.log(`Reloading Server ...`);
global.SERVER?.stop();
global.SERVER = Bun.serve(serverParams);
}
@@ -0,0 +1,50 @@
import path from "path";
import { renderToString } from "react-dom/server";
import grabContants from "../../../utils/grab-constants";
import EJSON from "../../../utils/ejson";
import type { PageDistGenParams } from "../../../types";
import isDevelopment from "../../../utils/is-development";
export default async function genWebHTML({
component,
pageProps,
pageName,
module,
}: PageDistGenParams) {
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
const componentHTML = renderToString(component);
const SCRIPT_SRC = path.join("/public/routes", pageName + ".js");
let html = `<!DOCTYPE html>\n`;
if (isDevelopment()) {
html += `<script>
const hmr = new EventSource("/__hmr");
hmr.addEventListener("update", (event) => {
if (event.data === "reload") {
window.location.reload();
}
});
</script>\n`;
}
html += `<html>\n`;
html += ` <head>\n`;
html += ` <meta charset="utf-8" />\n`;
html += ` <title>React SSR with Bun</title>\n`;
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
html += ` <script>window.${ClientWindowPagePropsName} = ${
EJSON.stringify(pageProps || {}) || "{}"
}</script>\n`;
html += ` <script src="${SCRIPT_SRC}" type="module"></script>\n`;
html += ` </body>\n`;
html += `</html>\n`;
return html;
}
@@ -0,0 +1,63 @@
import type { FC } from "react";
import grabDirNames from "../../../utils/grab-dir-names";
import type { Server } from "bun";
import grabPageName from "../../../utils/grab-page-name";
import grabRouteParams from "../../../utils/grab-route-params";
import genWebHTML from "./generate-web-html";
import grabRouter from "../../../utils/grab-router";
import type { BunextPageModule } from "../../../types";
type Params = {
req: Request;
server: Server;
};
export default async function ({ req, server }: Params): Promise<Response> {
const url = new URL(req.url);
try {
const router = grabRouter();
const match = router.match(url.pathname);
if (!match?.filePath) {
const errMsg = `Page ${url.pathname} not found`;
console.error(errMsg);
throw new Error(errMsg);
}
const pageName = grabPageName({ path: match.filePath });
const module: BunextPageModule = await import(match.filePath);
// const config = module.config as ServerRouteConfig | undefined;
const routeParams = await grabRouteParams({ req, server });
const serverRes = await (async () => {
try {
return await module["server"]?.(routeParams);
} catch (error) {
return {};
}
})();
const Component = module.default as FC<any>;
const component = <Component pageProps={serverRes} />;
const html = await genWebHTML({
component,
pageProps: serverRes,
pageName,
module,
});
return new Response(html, {
headers: {
"Content-Type": "text/html",
},
});
} catch (error) {
return new Response(`Page Not Found`, {
status: 404,
});
}
}
@@ -0,0 +1,41 @@
import { writeFileSync } from "fs";
import path from "path";
import grabDirNames from "../../../utils/grab-dir-names";
import grabContants from "../../../utils/grab-constants";
import genWebHTML from "./generate-web-html";
import type { PageDistGenParams } from "../../../types";
const { BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR } = grabDirNames();
export default async function (params: PageDistGenParams) {
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
const PAGE_DIST_DIR = path.join(HYDRATION_DST_DIR, params.pageName);
const pageSrcTs = `index.tsx`;
let script = "";
script += `import React from "react";\n`;
script += `import { hydrateRoot } from "react-dom/client";\n`;
script += `import App from "./";\n`;
script += `declare global {\n`;
script += ` interface Window {\n`;
script += ` ${ClientWindowPagePropsName}: any;\n`;
script += ` }\n`;
script += `}\n`;
script += `const container = document.getElementById("${ClientRootElementIDName}");\n`;
script += `hydrateRoot(container, <App {...window.${ClientWindowPagePropsName}} />);\n`;
const SRC_WRITE_FILE = path.join(PAGE_DIST_DIR, pageSrcTs);
writeFileSync(SRC_WRITE_FILE, script, "utf-8");
let html = await genWebHTML(params);
const pageHtml = `index.html`;
const HTML_WRITE_FILE = path.join(PAGE_DIST_DIR, pageHtml);
writeFileSync(HTML_WRITE_FILE, html, "utf-8");
}
+143
View File
@@ -0,0 +1,143 @@
import type { MatchedRoute, Server } from "bun";
import type { FC, JSX, ReactNode } from "react";
export type ServerProps = {
params: Record<string, string>;
searchParams: Record<string, string>;
headers: Headers;
cookies: Record<string, string>;
body: any;
method: string;
url: string;
pathname: string;
query: Record<string, string>;
search: string;
hash: string;
};
export type StaticProps = {
params: Record<string, string>;
searchParams: Record<string, string>;
headers: Headers;
cookies: Record<string, string>;
body: any;
method: string;
url: string;
pathname: string;
query: Record<string, string>;
search: string;
hash: string;
};
export type StaticPaths = string[];
export type StaticParams = Record<string, string>;
export type PageModule = {
component: React.ComponentType<any>;
serverProps: ServerProps;
staticProps: StaticProps;
staticPaths: StaticPaths;
staticParams: StaticParams;
};
export type BunextConfig = {
distDir?: string;
assetsPrefix?: string;
origin?: string;
globalVars?: { [k: string]: any };
port?: number;
development?: boolean;
};
export type GetRouteReturn = {
match: MatchedRoute;
module: PageModule;
component: React.ComponentType<any>;
serverProps: ServerProps;
staticProps: StaticProps;
staticPaths: StaticPaths;
staticParams: StaticParams;
};
export type BunxRouteParams = {
req: Request;
url: URL;
server: Server;
body?: any;
query?: any;
};
export interface PostInsertReturn {
fieldCount?: number;
affectedRows?: number;
insertId?: number;
serverStatus?: number;
warningCount?: number;
message?: string;
protocol41?: boolean;
changedRows?: number;
}
export type APIResponseObject<
T extends { [k: string]: any } = { [k: string]: any },
> = {
success: boolean;
payload?: T[] | null;
singleRes?: T | null;
stringRes?: string | null;
numberRes?: number | null;
postInsertReturn?: PostInsertReturn | null;
payloadBase64?: string;
payloadThumbnailBase64?: string;
payloadURL?: string;
payloadThumbnailURL?: string;
error?: any;
msg?: string;
queryObject?: any;
countQueryObject?: any;
status?: number;
count?: number;
errors?: any[];
debug?: any;
batchPayload?: any[][] | null;
errorData?: any;
token?: string;
csrf?: string;
cookieNames?: any;
key?: string;
userId?: string | number;
code?: string;
createdAt?: number;
email?: string;
requestOptions?: any;
logoutUser?: boolean;
redirect?: string;
};
export type BunextServerRouteConfig = {
maxRequestBodyMB?: number;
};
export type PageDistGenParams = {
component: ReactNode;
pageProps?: any;
module?: BunextPageModule;
pageName: string;
};
export type BunextPageModule = {
default: FC<any>;
server?: (
routeParams: BunxRouteParams,
) => Promise<BunextPageModuleServerReturn>;
};
export type BunextPageModuleServerReturn = {
props?: any;
};
export type BunextPageModuleMetadata = {
title?: string;
description?: string;
};
+28
View File
@@ -0,0 +1,28 @@
import EJSON from "./ejson";
/**
* # Convert Serialized Query back to object
*/
export default function deserializeQuery(
query: string | { [s: string]: any }
): {
[s: string]: any;
} {
let queryObject: { [s: string]: any } =
typeof query == "object" ? query : Object(EJSON.parse(query));
const keys = Object.keys(queryObject);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = queryObject[key];
if (typeof value == "string") {
if (value.match(/^\{|^\[/)) {
queryObject[key] = EJSON.parse(value);
}
}
}
return queryObject;
}
+38
View File
@@ -0,0 +1,38 @@
/**
* # EJSON parse string
*/
function parse(
string: string | null | number,
reviver?: (this: any, key: string, value: any) => any
): { [s: string]: any } | { [s: string]: any }[] | undefined {
if (!string) return undefined;
if (typeof string == "object") return string;
if (typeof string !== "string") return undefined;
try {
return JSON.parse(string, reviver);
} catch (error) {
return undefined;
}
}
/**
* # EJSON stringify object
*/
function stringify(
value: any,
replacer?: ((this: any, key: string, value: any) => any) | null,
space?: string | number
): string | undefined {
try {
return JSON.stringify(value, replacer || undefined, space);
} catch (error) {
return undefined;
}
}
const EJSON = {
parse,
stringify,
};
export default EJSON;
+4
View File
@@ -0,0 +1,4 @@
export default function exitWithError(msg: string, code?: number) {
console.error(msg);
process.exit(code || 1);
}
+8
View File
@@ -0,0 +1,8 @@
const AppNames = {
defaultPort: 7000,
defaultAssetPrefix: "_bunext/static",
name: "Bunext",
defaultDistDir: ".bunext",
} as const;
export default AppNames;
+20
View File
@@ -0,0 +1,20 @@
import AppNames from "./grab-app-names";
import numberfy from "./numberfy";
export default function grabAppPort() {
const { defaultPort } = AppNames;
try {
if (process.env.PORT) {
return numberfy(process.env.PORT);
}
if (global.CONFIG.port) {
return global.CONFIG.port;
}
return numberfy(defaultPort);
} catch (error) {
return numberfy(defaultPort);
}
}
+11
View File
@@ -0,0 +1,11 @@
import AppNames from "./grab-app-names";
export default function grabAssetsPrefix() {
if (global.CONFIG.assetsPrefix) {
return global.CONFIG.assetsPrefix;
}
const { defaultAssetPrefix } = AppNames;
return defaultAssetPrefix;
}
+19
View File
@@ -0,0 +1,19 @@
import path from "path";
import grabConfig from "../functions/grab-config";
export default async function grabConstants() {
const config = await grabConfig();
const MB_IN_BYTES = 1024 * 1024;
const ClientWindowPagePropsName = "__PAGE_PROPS__";
const ClientRootElementIDName = "__bunext";
const ServerDefaultRequestBodyLimitBytes = MB_IN_BYTES * 10;
return {
ClientRootElementIDName,
ClientWindowPagePropsName,
MBInBytes: MB_IN_BYTES,
ServerDefaultRequestBodyLimitBytes,
};
}
+83
View File
@@ -0,0 +1,83 @@
import path from "path";
export default function grabDirNames() {
const ROOT_DIR = process.cwd();
const SRC_DIR = path.join(ROOT_DIR, "src");
const ROUTES_DIR = path.join(SRC_DIR, "routes");
const API_DIR = path.join(ROUTES_DIR, "api");
const PUBLIC_DIR = path.join(ROOT_DIR, "public");
const HYDRATION_DST_DIR = path.join(PUBLIC_DIR, "routes");
const CONFIG_FILE = path.join(ROOT_DIR, "bunext.config.ts");
const BUNX_CWD_DIR = path.resolve(ROOT_DIR, ".bunext");
const BUNX_TMP_DIR = path.resolve(BUNX_CWD_DIR, ".tmp");
const BUNX_HYDRATION_SRC_DIR = path.resolve(
BUNX_CWD_DIR,
"client",
"hydration-src"
);
const BUNX_ROOT_DIR = path.resolve(__dirname, "../../");
return {
ROOT_DIR,
SRC_DIR,
ROUTES_DIR,
API_DIR,
PUBLIC_DIR,
HYDRATION_DST_DIR,
BUNX_ROOT_DIR,
CONFIG_FILE,
BUNX_TMP_DIR,
BUNX_HYDRATION_SRC_DIR,
};
}
// const rootDir = params?.dir || process.cwd();
// const appDir = path.resolve(__dirname, "..");
// const entrypoint = path.join(
// appDir,
// "functions",
// "server",
// "start-server.ts"
// );
// const bunextDir = path.join(rootDir, ".bunext");
// const bunextClientDir = path.join(bunextDir, "client");
// const bunextClientRoutesDir = path.join(bunextClientDir, "routes");
// const bunextClientRoutesSrcDir = path.join(bunextClientRoutesDir, "src");
// const bunextClientRoutesDstDir = path.join(bunextClientRoutesDir, "dst");
// const bunextServerDir = path.join(bunextDir, "server");
// const bunextServerPagesDir = path.join(bunextServerDir, "pages");
// const publicDir = path.join(rootDir, "public");
// const configFile = path.join(rootDir, "bunext.config.ts");
// const srcDir = path.join(rootDir, "src");
// const pagesDir = path.join(srcDir, "pages");
// const componentsDir = path.join(srcDir, "components");
// const stylesDir = path.join(srcDir, "styles");
// const utilsDir = path.join(srcDir, "utils");
// const typesDir = path.join(srcDir, "types");
// return {
// rootDir,
// pagesDir,
// componentsDir,
// publicDir,
// stylesDir,
// utilsDir,
// typesDir,
// configFile,
// appDir,
// entrypoint,
// srcDir,
// bunextDir,
// bunextClientDir,
// bunextClientRoutesDir,
// bunextClientRoutesSrcDir,
// bunextClientRoutesDstDir,
// bunextServerDir,
// bunextServerPagesDir,
// };
+11
View File
@@ -0,0 +1,11 @@
import grabAppPort from "./grab-app-port";
export default function grabOrigin() {
if (global.CONFIG.origin) {
return global.CONFIG.origin;
}
const port = grabAppPort();
return `http://localhost:${port}`;
}
+18
View File
@@ -0,0 +1,18 @@
type Params = {
path: string;
};
export default function grabPageName(params: Params) {
const pathArr = params.path.split("/");
const routesIndex = pathArr.findIndex((p) => p == "routes");
const newPathArr = [...pathArr].slice(routesIndex + 1);
const filename = newPathArr
.filter((p) => Boolean(p.match(/./)))
.map((p) => p.replace(/\.\w+$/, "").replace(/[^a-z]/g, ""))
.join("-");
return filename;
}
+35
View File
@@ -0,0 +1,35 @@
import type { Server } from "bun";
import type { BunxRouteParams } from "../types";
import deserializeQuery from "./deserialize-query";
type Params = {
req: Request;
server: Server;
};
export default async function grabRouteParams({
req,
server,
}: Params): Promise<BunxRouteParams> {
const url = new URL(req.url);
const query = deserializeQuery(Object.fromEntries(url.searchParams));
const body = await (async () => {
try {
return req.method == "GET" ? undefined : await req.json();
} catch (error) {
return {};
}
})();
const routeParams: BunxRouteParams = {
req,
url,
server,
query,
body,
};
return routeParams;
}
+14
View File
@@ -0,0 +1,14 @@
import grabDirNames from "./grab-dir-names";
export default function grabRouter() {
const { ROUTES_DIR } = grabDirNames();
if (process.env.NODE_ENV == "production") {
return global.ROUTER;
}
return new Bun.FileSystemRouter({
style: "nextjs",
dir: ROUTES_DIR,
});
}
+7
View File
@@ -0,0 +1,7 @@
export default function isDevelopment() {
const config = global.CONFIG;
if (config.development) return true;
return false;
}
+33
View File
@@ -0,0 +1,33 @@
export default function numberfy(num: any, decimals?: number): number {
try {
const numberString = String(num)
.replace(/[^0-9\.]/g, "")
.replace(/\.$/, "");
if (!numberString.match(/./)) return 0;
const existingDecimals = numberString.match(/\./)
? numberString.split(".").pop()?.length
: undefined;
const numberfiedNum = Number(numberString);
if (typeof numberfiedNum !== "number") return 0;
if (isNaN(numberfiedNum)) return 0;
if (decimals == 0) {
return Math.round(Number(numberfiedNum));
} else if (decimals) {
return Number(numberfiedNum.toFixed(decimals));
}
if (existingDecimals)
return Number(numberfiedNum.toFixed(existingDecimals));
return Math.round(numberfiedNum);
} catch (error: any) {
console.log(`Numberfy ERROR: ${error.message}`);
return 0;
}
}
export const _n = numberfy;