nomadro/scripts/integrate-apps.mjs
eric 9928c5185b Mount nav/book/community as native App Router routes in one Next process.
Replace reverse-proxy/iframe approach with @ebook/@community/@navmini imports under /nav /book /community so localhost:3000 serves all three products directly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 03:49:16 -05:00

252 lines
7.9 KiB
JavaScript

/**
* Integrate vertical apps into portal App Router as real routes.
* - apps/ebook/src → @ebook/* , routes under app/book
* - apps/nomadweb/frontend/src → @community/* , routes under app/community
* - apps/navmini/src → app/nav (client page)
* No iframe / webview / reverse-proxy.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
function walk(dir, out = []) {
if (!fs.existsSync(dir)) return out;
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
if (ent.name === "node_modules" || ent.name === ".next" || ent.name === "dist") continue;
const p = path.join(dir, ent.name);
if (ent.isDirectory()) walk(p, out);
else out.push(p);
}
return out;
}
function rewriteAlias(file, fromPrefix, toPrefix) {
let t = fs.readFileSync(file, "utf8");
const before = t;
// from '@/x' or "@/x" or from '@/x/y'
const re = new RegExp(`([\"'])${fromPrefix}/`, "g");
t = t.replace(re, `$1${toPrefix}/`);
if (t !== before) {
fs.writeFileSync(file, t);
return true;
}
return false;
}
function ensureDir(p) {
fs.mkdirSync(p, { recursive: true });
}
function relPosix(from, to) {
return path.relative(from, to).split(path.sep).join("/");
}
/** Copy app route files into portal, skipping root layout.tsx/globals.css (handled separately). */
function mirrorAppRoutes(srcAppDir, destAppDir, importAlias) {
const files = walk(srcAppDir).filter((f) => {
const base = path.basename(f);
const rel = path.relative(srcAppDir, f);
if (rel === "layout.tsx" || rel === "globals.css" || rel === "global.css") return false;
if (rel === "favicon.ico") return false;
return /\.(tsx|ts|jsx|js|css|mdx)$/.test(base);
});
let n = 0;
for (const src of files) {
const rel = path.relative(srcAppDir, src);
const dest = path.join(destAppDir, rel);
ensureDir(path.dirname(dest));
// For page/layout/route/loading/error/template/default files: keep as real route modules.
// Rewrite their @/ imports already done in source trees.
let body = fs.readFileSync(src, "utf8");
// If this is a page that was under apps and already uses @ebook/@community, fine.
// Also fix any remaining @/ that slipped through in this file only if still present.
body = body.replace(/(["'])@\//g, `$1${importAlias}/`);
fs.writeFileSync(dest, body);
n++;
}
return n;
}
function stripRootChrome(layoutSrc, outPath, cssImport, extraNote) {
let t = fs.readFileSync(layoutSrc, "utf8");
// Remove html/body wrappers — nested segment layout only.
// Common patterns: return (<html...><body>...</body></html>)
// We'll write a handcrafted layout instead if stripping is too fragile.
fs.writeFileSync(outPath, t);
return t;
}
// --- 1) Rewrite aliases in source trees ---
const ebookSrc = path.join(root, "apps/ebook/src");
const communitySrc = path.join(root, "apps/nomadweb/frontend/src");
let ebookRewrites = 0;
for (const f of walk(ebookSrc).filter((x) => /\.(ts|tsx|js|jsx)$/.test(x))) {
if (rewriteAlias(f, "@", "@ebook")) ebookRewrites++;
}
let communityRewrites = 0;
for (const f of walk(communitySrc).filter((x) => /\.(ts|tsx|js|jsx)$/.test(x))) {
if (rewriteAlias(f, "@", "@community")) communityRewrites++;
}
console.log(`alias rewrite ebook files=${ebookRewrites}, community files=${communityRewrites}`);
// --- 2) Fix ebook content root to apps/ebook/content ---
for (const f of walk(ebookSrc).filter((x) => /\.(ts|tsx)$/.test(x))) {
let t = fs.readFileSync(f, "utf8");
const before = t;
// path.join(process.cwd(), 'content' ...) → path.join(process.cwd(), 'apps/ebook/content' ...)
t = t.replace(
/path\.join\(\s*process\.cwd\(\)\s*,\s*['\"]content['\"]/g,
"path.join(process.cwd(), 'apps/ebook/content'",
);
t = t.replace(
/join\(\s*process\.cwd\(\)\s*,\s*['\"]content['\"]/g,
"join(process.cwd(), 'apps/ebook/content'",
);
if (t !== before) {
fs.writeFileSync(f, t);
console.log("content path fix:", path.relative(root, f));
}
}
// --- 3) Mirror routes into portal app/ ---
const bookDest = path.join(root, "app/book");
const communityDest = path.join(root, "app/community");
fs.rmSync(bookDest, { recursive: true, force: true });
fs.rmSync(communityDest, { recursive: true, force: true });
ensureDir(bookDest);
ensureDir(communityDest);
const bookCount = mirrorAppRoutes(path.join(ebookSrc, "app"), bookDest, "@ebook");
const communityCount = mirrorAppRoutes(
path.join(communitySrc, "app"),
communityDest,
"@community",
);
console.log(`mirrored book routes=${bookCount}, community routes=${communityCount}`);
// --- 4) Write nested layouts (no html/body) ---
const bookLayout = `import { AntdRegistry } from "@ant-design/nextjs-registry";
import { Providers } from "@ebook/components/Providers";
import { getSiteConfig } from "@ebook/lib/site-config.server";
import { getServerFeatures } from "@ebook/lib/features.server";
import { getLocale } from "@ebook/lib/i18n/server";
import "@ebook/app/globals.css";
export default async function BookLayout({
children,
}: {
children: React.ReactNode;
}) {
const locale = await getLocale();
const site = getSiteConfig();
const f = getServerFeatures();
return (
<div className="ebook-root" data-locale={locale}>
<AntdRegistry>
<Providers locale={locale}>
{f.analytics.enabled ? <AnalyticsLazy /> : null}
{f.ads.enabled && f.ads.clientId ? <AdSenseLazy /> : null}
{children}
{f.feedback.enabled ? (
<FeedbackLazy
title={f.feedback.title}
subtitle={f.feedback.subtitle}
contactEmail={site.brand.contactEmail}
xHandle={site.brand.xHandle}
/>
) : null}
</Providers>
</AntdRegistry>
<script
dangerouslySetInnerHTML={{
__html: \`window.__EBOOK_FEATURES__=\${JSON.stringify(f).replace(/</g, "\\\\u003c")};window.__LOCALE__=\${JSON.stringify(locale)};\`,
}}
/>
</div>
);
}
function AnalyticsLazy() {
const { AnalyticsProvider } = require("@ebook/components/AnalyticsProvider");
return <AnalyticsProvider />;
}
function AdSenseLazy() {
const { AdSenseScript } = require("@ebook/components/AdSlot");
return <AdSenseScript />;
}
function FeedbackLazy(props: {
title: string;
subtitle: string;
contactEmail: string;
xHandle: string;
}) {
const { FeedbackPanel } = require("@ebook/components/FeedbackPanel");
return <FeedbackPanel {...props} />;
}
`;
fs.writeFileSync(path.join(bookDest, "layout.tsx"), bookLayout);
const communityLayout = `import { AuthProvider } from "@community/lib/auth";
import { ToastProvider } from "@community/lib/toast";
import { I18nProvider } from "@community/lib/i18n";
import PwaRegister from "@community/components/PwaRegister";
import "@community/app/globals.css";
export default function CommunityLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="community-root">
<I18nProvider>
<AuthProvider>
<ToastProvider>
{children}
<PwaRegister />
</ToastProvider>
</AuthProvider>
</I18nProvider>
</div>
);
}
`;
fs.writeFileSync(path.join(communityDest, "layout.tsx"), communityLayout);
// --- 5) Nav as real React route (no static SPA shell required for entry) ---
const navDir = path.join(root, "app/nav");
ensureDir(navDir);
fs.writeFileSync(
path.join(navDir, "layout.tsx"),
`import "@navmini/styles/global.css";
export default function NavLayout({ children }: { children: React.ReactNode }) {
return <div className="navmini-root">{children}</div>;
}
`,
);
fs.writeFileSync(
path.join(navDir, "page.tsx"),
`"use client";
import NavApp from "@navmini/App";
export default function NavPage() {
return <NavApp />;
}
`,
);
console.log("done: app/book, app/community, app/nav layouts+pages ready");