import express, { type Express } from "express"; import fs from "fs"; import path from "path"; import { storage } from "./storage"; function escapeHtml(str: string): string { return str.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); } function ogImageUrl(coverImage: string, baseUrl: string): string { if (!coverImage) return ""; let imgPath = coverImage; if (imgPath.endsWith(".webp")) { imgPath = imgPath.replace(/\.webp$/, ".jpg"); } return imgPath.startsWith("http") ? imgPath : `${baseUrl}${imgPath}`; } function stripExistingMeta(html: string): string { html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); html = html.replace(/]*>\s*/gi, ""); return html; } export function serveStatic(app: Express) { const distPath = path.resolve(__dirname, "public"); if (!fs.existsSync(distPath)) { throw new Error( `Could not find the build directory: ${distPath}, make sure to build the client first`, ); } app.use(express.static(distPath, { setHeaders(res, filePath) { if (filePath.endsWith("og-image.jpg") || filePath.includes("/uploads/") || filePath.includes("/images/")) { res.setHeader("Cache-Control", "public, max-age=86400"); } }, })); app.use("/{*path}", async (req, res) => { const url = req.originalUrl; const indexPath = path.resolve(distPath, "index.html"); const canonicalBase = "https://folx.tv"; const host = req.get("host") || "folx.tv"; const protocol = req.get("x-forwarded-proto") || "https"; const baseUrl = `${protocol}://${host}`; const articleMatch = url.match(/^\/article\/([^?#]+)/); if (articleMatch) { try { const slug = decodeURIComponent(articleMatch[1]); const article = await storage.getArticleBySlug(slug); if (article) { const articleUrl = `${canonicalBase}/article/${article.slug}`; const imageUrl = ogImageUrl(article.coverImage || "", canonicalBase); const finalImage = imageUrl || `${canonicalBase}/og-image.jpg`; let template = await fs.promises.readFile(indexPath, "utf-8"); template = stripExistingMeta(template); const pubDate = article.publishedAt ? new Date(article.publishedAt as any).toISOString() : new Date().toISOString(); const jsonLd = { "@context": "https://schema.org", "@type": "NewsArticle", "headline": article.title, "description": article.excerpt, "image": [finalImage], "datePublished": pubDate, "dateModified": pubDate, "articleSection": article.category || "News", "author": { "@type": "Organization", "name": article.author || "Folx Music Television", "url": canonicalBase, }, "publisher": { "@type": "Organization", "name": "Folx Music Television", "logo": { "@type": "ImageObject", "url": `${canonicalBase}/og-image.jpg`, }, }, "mainEntityOfPage": { "@type": "WebPage", "@id": articleUrl, }, }; const jsonLdTag = ``; const ogTags = [ ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, ``, `