diff --git a/app/srv/ws/sync/code/parts/init/frontend.ts b/app/srv/ws/sync/code/parts/init/frontend.ts index b1caff8d..c6ea2e56 100644 --- a/app/srv/ws/sync/code/parts/init/frontend.ts +++ b/app/srv/ws/sync/code/parts/init/frontend.ts @@ -12,6 +12,7 @@ import { sendWS } from "../../../sync-handler"; import { SyncType } from "../../../type"; import { code } from "../../code"; import { existsAsync } from "fs-jetpack"; +import { prasiDefineLocalRoute } from "../../utlis/local-routers"; const pending = {} as any; export const initFrontEnd = async ( @@ -116,6 +117,7 @@ export const initFrontEnd = async ( }, ], }); + prasiDefineLocalRoute(id_site); code.internal.frontend[id_site] = { ctx: build_ctx, timeout: null, @@ -128,6 +130,9 @@ export const initFrontEnd = async ( async (event, filename) => { const fe = code.internal.frontend[id_site]; const srv = code.internal.server[id_site]; + if (filename?.startsWith("app/routes")) { + prasiDefineLocalRoute(id_site); + } if (filename?.startsWith("node_modules")) return; if ( filename?.endsWith(".tsx") || diff --git a/app/srv/ws/sync/code/utlis/local-routers.ts b/app/srv/ws/sync/code/utlis/local-routers.ts new file mode 100644 index 00000000..6db2063d --- /dev/null +++ b/app/srv/ws/sync/code/utlis/local-routers.ts @@ -0,0 +1,54 @@ +import { dir } from "dir"; +import { dirAsync } from "fs-jetpack"; +import { simpleHash } from "../../../../../web/src/nova/vi/utils/simple-hash"; +const local_routes = { + timeout: null as any, +}; + +export const prasiDefineLocalRoute = (id_site: string) => { + clearTimeout(local_routes.timeout); + local_routes.timeout = setTimeout(async () => { + const path = dir.data(`code/${id_site}/site/src/app/routes`); + await dirAsync(path); + const glob = new Bun.Glob(`*.{ts,tsx}`); + const imports = new Set(); + for await (const f of glob.scan(path)) { + const file = Bun.file(path + `/${f}`); + if (file.size > 0) { + if (f.endsWith(".tsx")) { + imports.add(f.substring(0, f.length - 4)); + } else if (f.endsWith(".ts")) { + imports.add(f.substring(0, f.length - 3)); + } + } + } + + const content = `\ +${[...imports] + .map( + (e) => `import { route as ${e.replace(/\W/g, "_")} } from "./routes/${e}"` + ) + .join("\n")} + +export const router = { + ${[...imports].map((e) => `${e.replace(/\W/g, "_")}`).join(",\n ")} +} +`; + const hash = simpleHash(content); + const router = Bun.file( + dir.data(`code/${id_site}/site/src/app/router.tsx`) + ); + + let should_write = true; + if (await router.exists()) { + const rhash = simpleHash(await router.text()); + if (rhash === hash) { + should_write = false; + } + } + + if (should_write) { + await Bun.write(router, content); + } + }, 300); +};