/**
* static-export — ดึง HTML ทุกหน้าจาก production server มาเป็นไฟล์ static (มี index.html)
*
* ใช้: node scripts/static-export.mjs [baseUrl] [outDir]
* baseUrl default http://127.0.0.1:8090
* outDir default ./static-export
*
* หมายเหตุสำคัญ: ไฟล์ HTML ที่ได้ "hydrate ได้" (ฟิลเตอร์/ค้นหา/แสดงเพิ่ม ทำงาน)
* แต่การคลิก link ไปหน้าอื่นจะเป็นการโหลดหน้าใหม่แบบเต็ม (ไม่มี `?_data=` บน static host)
*/
import fs from "node:fs";
import path from "node:path";
const BASE = (process.argv[2] ?? "http://127.0.0.1:8090").replace(/\/$/, "");
const OUT = process.argv[3] ?? "static-export";
const STATIC_ROUTES = [
"/",
"/about",
"/for-cinemas",
"/for-film-lovers",
"/sitemap.xml",
"/robots.txt",
];
async function get(urlPath) {
const res = await fetch(`${BASE}${urlPath}`, { redirect: "manual" });
const body = await res.text();
return {
status: res.status,
type: res.headers.get("content-type") ?? "",
body,
};
}
function writeRoute(routePath, body) {
const clean = routePath.split("?")[0].replace(/\/$/, "");
const isFile = /\.[a-z0-9]+$/i.test(clean);
const target = isFile
? path.join(OUT, clean)
: path.join(OUT, clean, "index.html");
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, body);
return target;
}
// 1) อ่าน slug จาก data/content/content.json (การ์ดในหน้าแรก render ฝั่ง client จึงหา link ใน HTML ไม่เจอ)
const contentPath = path.join("data", "content", "content.json");
const home = await get("/");
if (home.status !== 200) {
console.error(`หน้าแรกตอบ ${home.status} — server รันอยู่ไหม? (${BASE})`);
process.exit(1);
}
fs.rmSync(OUT, { recursive: true, force: true });
fs.mkdirSync(OUT, { recursive: true });
let slugs = [];
if (fs.existsSync(contentPath)) {
const content = JSON.parse(fs.readFileSync(contentPath, "utf8"));
slugs = (content.cinemas ?? [])
.filter((cinema) => cinema.hidden !== true && cinema.slug)
.map((cinema) => cinema.slug);
} else {
slugs = [...home.body.matchAll(/\/cinema\/([a-z0-9-]+)/g)].map((m) => m[1]);
}
const uniqueSlugs = [...new Set(slugs)];
const routes = [
...STATIC_ROUTES,
...uniqueSlugs.map((slug) => `/cinema/${slug}`),
];
let ok = 0;
const failed = [];
for (const route of routes) {
const res = await get(route);
if (res.status !== 200) {
failed.push(`${route} (${res.status})`);
continue;
}
writeRoute(route, res.body);
ok++;
}
// 2.5) static host ไม่มี endpoint `?_data=` ของ React Router
// → ดักคลิก link ภายในให้เป็นการโหลดหน้าเต็ม (ทุกหน้ามี HTML ของตัวเองอยู่แล้ว)
const STATIC_NAV_PATCH = ``;
function injectNavPatch(file) {
const html = fs.readFileSync(file, "utf8");
if (html.includes("data-static-export-nav")) return;
const patched = html.includes("