import { Glob } from "bun"; import path from "node:path"; import { mkdir, unlink } from "node:fs/promises"; // --- KONFIGURASI --- const BASE_URL = "https://dalam.web.id"; const TARGET_FOLDER = process.argv[2] || "artikel"; const CHUNK_SIZE = 10; // User-Agent identitas transparan untuk mencegah rate-limit CDN (Wikimedia, dll) const MIRROR_USER_AGENT = "LayarKosongImageMirror/2.4 (+https://dalam.web.id/about; kontak via halaman /about) Bun-fetch"; // Set Lock untuk mencegah Race Condition (TOCTOU) saat parallel download const downloadingUrls = new Set(); // Deteksi encoder WebP CLI sistem sekali di awal const CWEBP_BIN = Bun.which("cwebp"); const MAGICK_BIN = Bun.which("magick") || Bun.which("convert"); // --- NATIVE BINARY IMAGE DIMENSIONS --- interface ImageDimensions { width: number; height: number; } function parseExifOrientation(view: DataView, tiffOffset: number): number { if (tiffOffset + 8 > view.byteLength) return 1; const endian = view.getUint16(tiffOffset, false); const little = endian === 0x4949; // "II" if (!little && endian !== 0x4d4d) return 1; // "MM" const firstIfdOffset = view.getUint32(tiffOffset + 4, little); const ifdStart = tiffOffset + firstIfdOffset; if (ifdStart + 2 > view.byteLength) return 1; const entries = view.getUint16(ifdStart, little); for (let i = 0; i < entries; i++) { const entryOffset = ifdStart + 2 + i * 12; if (entryOffset + 12 > view.byteLength) break; const tag = view.getUint16(entryOffset, little); if (tag === 0x0112) { return view.getUint16(entryOffset + 8, little); } } return 1; } function parseImageHeaderBuffer(buf: ArrayBuffer): ImageDimensions | null { const bytes = new Uint8Array(buf); const view = new DataView(buf); const len = bytes.length; if (len < 12) return null; // 1. PNG (\x89PNG\r\n\x1a\n) if ( bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && len >= 24 ) { return { width: view.getUint32(16, false), height: view.getUint32(20, false), }; } // 2. GIF (GIF87a / GIF89a) if ( bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && len >= 10 ) { return { width: view.getUint16(6, true), height: view.getUint16(8, true), }; } // 3. WebP (RIFF....WEBP) if ( bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50 && len >= 30 ) { const chunk = String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]); if (chunk === "VP8 " && len >= 30) { return { width: view.getUint16(26, true) & 0x3fff, height: view.getUint16(28, true) & 0x3fff, }; } if (chunk === "VP8L" && len >= 25) { const bits = view.getUint32(21, true); return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1, }; } if (chunk === "VP8X" && len >= 30) { return { width: 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)), height: 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)), }; } } // 4. JPEG (0xFF 0xD8) if (bytes[0] === 0xff && bytes[1] === 0xd8) { let pos = 2; let orientation = 1; while (pos + 4 < len) { if (bytes[pos] !== 0xff) { pos++; continue; } const marker = bytes[pos + 1]; if (marker === 0xff) { pos++; continue; } if (marker === 0xd9 || marker === 0xda) break; if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { pos += 2; continue; } const segLen = view.getUint16(pos + 2, false); if (segLen < 2) break; if ( marker === 0xe1 && pos + 10 < len && bytes[pos + 4] === 0x45 && bytes[pos + 5] === 0x78 && bytes[pos + 6] === 0x69 && bytes[pos + 7] === 0x66 ) { orientation = parseExifOrientation(view, pos + 10); } if ( marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc && pos + 9 < len ) { let height = view.getUint16(pos + 5, false); let width = view.getUint16(pos + 7, false); if (orientation >= 5) { [width, height] = [height, width]; } return { width, height }; } pos += 2 + segLen; } } // 5. AVIF / HEIF (ISO BMFF ispe box) const strHead = new TextDecoder("latin1").decode(bytes); const ispeIdx = strHead.indexOf("ispe"); if (ispeIdx !== -1 && ispeIdx + 16 <= len) { return { width: view.getUint32(ispeIdx + 8, false), height: view.getUint32(ispeIdx + 12, false), }; } return null; } async function getImageDimensionsNative(filePath: string): Promise { try { const f = Bun.file(filePath); const headBuf = await f.slice(0, 65536).arrayBuffer(); const meta = parseImageHeaderBuffer(headBuf); if (meta) return meta; if (f.size > 65536) { const largerBuf = await f.slice(0, 524288).arrayBuffer(); return parseImageHeaderBuffer(largerBuf); } return null; } catch { return null; } } async function convertBufferToWebp(buffer: Buffer, destPath: string): Promise { await mkdir(path.dirname(destPath), { recursive: true }); const tmpPath = `${destPath}.${Bun.randomUUIDv7()}.tmp`; try { await Bun.write(tmpPath, buffer); if (CWEBP_BIN) { try { await Bun.$`${CWEBP_BIN} -quiet -q 95 -m 6 -preset text ${tmpPath} -o ${destPath}`; return; } catch { // Fallback ke magick jika cwebp tidak mendukung format input tertentu (mis. AVIF) } } if (MAGICK_BIN) { await Bun.$`${MAGICK_BIN} ${tmpPath} -auto-orient -unsharp 0x0.3 -quality 95 -define webp:method=6 -define webp:preprocessing=2 ${destPath}`; return; } throw new Error("Encoder WebP (cwebp / magick) tidak ditemukan di sistem."); } finally { await unlink(tmpPath).catch(() => {}); } } // --- HELPER UTILS --- const escapeHtml = (str: string): string => String(str || "") .replace(/&/g, "\x26amp;") .replace(//g, "\x26gt;"); const escapeAttr = (str: string): string => String(str || "") .replace(/&/g, "\x26amp;") .replace(/"/g, "\x26quot;") .replace(//g, "\x26gt;"); const normalizeText = (text: string): string => { return String(text || "") .replace(/\s+/g, " ") .trim(); }; const prepareDesc = (text: string): string => { return normalizeText(text); }; const toWebPath = (value: string): string => { return String(value || "") .replace(/\\/g, "/") .replace(/^\.\//, "") .replace(/^\/+/, "") .replace(/\/+$/, ""); }; const getImageMimeType = (imageUrl: string): string => { try { const parsed = imageUrl.startsWith("http") ? new URL(imageUrl) : new URL(imageUrl, BASE_URL); const ext = path.extname(parsed.pathname).toLowerCase(); if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg"; if (ext === ".png") return "image/png"; if (ext === ".webp") return "image/webp"; if (ext === ".avif") return "image/avif"; if (ext === ".gif") return "image/gif"; if (ext === ".svg") return "image/svg+xml"; return "image/webp"; } catch { return "image/webp"; } }; /** * Deteksi WebP dari MAGIC BYTES (RIFF...WEBP) */ const isWebpBuffer = (buffer: Buffer): boolean => { return ( buffer.length > 12 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP" ); }; const toUTCIso = (val: string | undefined, fallback: string): string => { if (!val) return fallback; const parsed = new Date(val); return isNaN(parsed.getTime()) ? fallback : parsed.toISOString(); }; /** * Ekstraksi Regex Tahan Banting untuk Tanggal Publikasi */ const extractExistingDate = async (file: string): Promise => { const content = await Bun.file(file).text(); const match = content.match(/property="article:published_time"[^>]*content="(\d{4}-\d{2}-\d{2})/i) || content.match(/content="(\d{4}-\d{2}-\d{2})[^"]*"[^>]*property="article:published_time"/i); return match ? match[1] : new Date().toISOString().split("T")[0]; }; /** * Pre-generate fallback timestamps secara DETERMINISTIK per file */ const buildFallbackMap = async (files: string[]) => { const map = new Map(); const dateParts = await Promise.all(files.map(extractExistingDate)); const usedSecondsPerDate = new Map>(); for (let i = 0; i < files.length; i++) { const file = files[i]; const datePart = dateParts[i]; if (!usedSecondsPerDate.has(datePart)) { usedSecondsPerDate.set(datePart, new Set()); } const usedSeconds = usedSecondsPerDate.get(datePart)!; let sec: number; let hashVal = BigInt(Bun.hash(file) as number); do { sec = Number(hashVal % 86400n); hashVal += 1n; } while (usedSeconds.has(sec)); usedSeconds.add(sec); const hh = Math.floor(sec / 3600).toString().padStart(2, "0"); const mm = Math.floor((sec % 3600) / 60).toString().padStart(2, "0"); const ss = (sec % 60).toString().padStart(2, "0"); const ms = (Number(Bun.hash(file + "ms")) % 1000).toString().padStart(3, "0"); map.set(file, `${datePart}T${hh}:${mm}:${ss}.${ms}Z`); } return map; }; // --- CORE FUNCTIONS --- async function mirrorAndConvert(externalUrl: string, baseUrl: string): Promise { try { const url = new URL(externalUrl); const baseHostname = new URL(baseUrl).hostname; if ( url.hostname === baseHostname || url.hostname === "localhost" || url.hostname === "schema.org" ) { return externalUrl.replace(baseUrl, ""); } const cleanUrl = externalUrl.split("?")[0]; const fileHash = Bun.hash(cleanUrl).toString(16); const paramFormat = url.searchParams.get("format"); const pathExt = path.extname(url.pathname).toLowerCase(); const detectedExt = paramFormat ? `.${paramFormat}` : pathExt; const isSvg = detectedExt === ".svg"; const isGif = detectedExt === ".gif"; const finalExt = isSvg || isGif ? detectedExt : ".webp"; const safeHostname = url.hostname.replace(/[^a-z0-9.]/gi, "_"); const localPath = path.join("img", safeHostname, `${fileHash}${finalExt}`); const fileTarget = Bun.file(localPath); if (downloadingUrls.has(cleanUrl)) { while (downloadingUrls.has(cleanUrl)) { await Bun.sleep(100); } if (await fileTarget.exists()) { return `/${localPath.replace(/\\/g, "/")}`; } } downloadingUrls.add(cleanUrl); try { if (await fileTarget.exists()) { return `/${localPath.replace(/\\/g, "/")}`; } const response = await fetch(externalUrl, { signal: AbortSignal.timeout(20_000), headers: { "User-Agent": MIRROR_USER_AGENT, }, }); if (!response.ok) { console.warn(`โš ๏ธ Mirror gagal [${response.status} ${response.statusText}]: ${externalUrl}`); throw new Error(`Download Gagal: ${response.status} ${response.statusText}`); } const buffer = Buffer.from(await response.arrayBuffer()); await mkdir(path.dirname(localPath), { recursive: true }); const passthrough = isSvg || isGif || isWebpBuffer(buffer); if (passthrough) { await Bun.write(localPath, buffer); if (!isSvg && !isGif) { const kb = (buffer.length / 1024).toFixed(1); console.log(` โ†ณ ๐Ÿ“ฆ WebP asli disalin tanpa re-encode (${kb} KB): ${cleanUrl}`); } } else { await convertBufferToWebp(buffer, localPath); } return `/${localPath.replace(/\\/g, "/")}`; } finally { downloadingUrls.delete(cleanUrl); } } catch (e: any) { console.error(`โŒ mirrorAndConvert gagal untuk ${externalUrl}: ${e?.message || e}`); return externalUrl; } } const EXACT_REMOVE_META_NAMES = new Set([ "application-name", "apple-mobile-web-app-title", "author", "color-scheme", "description", "googlebot", "news_keywords", "promphint", "referrer", "robots", "theme-color", "viewport", ]); const PREFIX_REMOVE_META_NAMES = ["bluesky:", "fediverse:", "twitter:"]; const EXACT_REMOVE_META_PROPS = new Set([ "description", "fb:app_id", "fb:pages", ]); const PREFIX_REMOVE_META_PROPS = ["article:", "og:", "twitter:"]; const REMOVE_LINK_RELS = new Set([ "canonical", "icon", "shortcut icon", "alternate icon", "license", "sitemap", "search", "manifest", "alternate", "me", ]); async function processFile(file: string, baseUrl: string, fallbackTime: string) { const rawText = await Bun.file(file).text(); const rawContent = rawText.replace(/\r\n/g, "\n"); const baseName = path.basename(file); console.log(`๐Ÿš€ SEO Turbo: ${baseName}`); // --- TAHAP 1: EKSTRAKSI DATA & KANDIDAT URL VIA HTMLREWRITER --- let hasHead = false; let titleBuffer = ""; let inTitle = false; let hasTitle = false; let firstPBuffer = ""; let inFirstP = false; let pCount = 0; let rawMetaDesc = ""; let rawOgDesc = ""; let rawTwitterDesc = ""; let rawNewsKeys = ""; let rawPromphint = ""; let existingPublished = ""; let existingModified = ""; let ogImageMeta = ""; let twitterImageMeta = ""; let firstImgSrc = ""; const existingTags: string[] = []; const externalUrls = new Set(); const scanRewriter = new HTMLRewriter() .on("head", { element() { hasHead = true; }, }) .on("title", { element(el) { if (!hasTitle) { inTitle = true; el.onEndTag(() => { inTitle = false; hasTitle = true; }); } }, text(chunk) { if (inTitle && !hasTitle) { titleBuffer += chunk.text; } }, }) .on("p", { element(el) { if (pCount === 0) { inFirstP = true; el.onEndTag(() => { inFirstP = false; }); } else { inFirstP = false; } pCount++; }, text(chunk) { if (inFirstP) { firstPBuffer += chunk.text; } }, }) .on("meta", { element(el) { const name = el.getAttribute("name")?.toLowerCase() || ""; const prop = el.getAttribute("property")?.toLowerCase() || ""; const content = el.getAttribute("content") ?? ""; if (!rawMetaDesc && (name === "description" || prop === "description")) { rawMetaDesc = content; } if (!rawOgDesc && prop === "og:description") { rawOgDesc = content; } if (!rawTwitterDesc && name === "twitter:description") { rawTwitterDesc = content; } if (!rawNewsKeys && name === "news_keywords") { rawNewsKeys = content; } if (!rawPromphint && name === "promphint") { rawPromphint = content; } if (!existingPublished && prop === "article:published_time") { existingPublished = content; } if ( !existingModified && (prop === "article:modified_time" || prop === "og:updated_time") ) { existingModified = content; } if (prop === "article:tag" && content.trim()) { existingTags.push(content.trim()); } if (!ogImageMeta && prop === "og:image" && content) { ogImageMeta = content; if (content.startsWith("http")) externalUrls.add(content); } if (!twitterImageMeta && name === "twitter:image" && content) { twitterImageMeta = content; if (content.startsWith("http")) externalUrls.add(content); } }, }) .on("img", { element(el) { const src = el.getAttribute("src"); if (src) { if (!firstImgSrc) firstImgSrc = src; if (src.startsWith("http")) externalUrls.add(src); } }, }) .on("source", { element(el) { const srcset = el.getAttribute("srcset"); if (!srcset) return; for (const part of srcset.split(",").map((s) => s.trim())) { const [url] = part.split(/\s+/); if (url && url.startsWith("http")) { externalUrls.add(url); } } }, }) .on("image", { element(el) { const src = el.getAttribute("href") ?? el.getAttribute("xlink:href"); if (src && src.startsWith("http")) { externalUrls.add(src); } }, }); scanRewriter.transform(rawContent); if (!hasHead) { console.warn(`โš ๏ธ File dilewati karena tidak punya : ${file}`); return; } // --- TAHAP 1B: MIRROR SEMUA URL EKSTERNAL SEKALIGUS --- const mirroredMap = new Map(); await Promise.all( Array.from(externalUrls).map(async (url) => { const mirrored = await mirrorAndConvert(url, baseUrl); mirroredMap.set(url, mirrored); }) ); // --- TAHAP 2: LOGIKA DATA SEO --- const rawTitle = titleBuffer.trim() || "Layar Kosong"; const ogTitle = rawTitle.replace(/\s*-\s*Layar Kosong$/i, "").trim() || "Layar Kosong"; const seoTitle = ogTitle === "Layar Kosong" ? "Layar Kosong" : `${ogTitle} - Layar Kosong`; const cleanFileName = baseName.replace(/\.html$/i, ""); const canonicalBase = toWebPath(TARGET_FOLDER); const canonicalPath = canonicalBase ? `${canonicalBase}/${cleanFileName}` : cleanFileName; const canonicalUrl = `${baseUrl}/${canonicalPath}`.replace(/\/$/, ""); const publishedTime = existingPublished ? toUTCIso(existingPublished, fallbackTime) : fallbackTime; if (!existingPublished) { console.log(` ๐Ÿ“… ${baseName}: No existing published_time, using fallback: ${publishedTime}`); } let modifiedTime: string; if (existingModified) { modifiedTime = toUTCIso(existingModified, new Date().toISOString()); } else { const pubDateObj = new Date(publishedTime); const offsetMs = (Number(Bun.hash(file + "mod")) % 540000) + 60000; modifiedTime = new Date(pubDateObj.getTime() + offsetMs).toISOString(); } const uniqueTags = Array.from(new Set(existingTags)); const firstP = firstPBuffer.trim(); const fallbackDesc = firstP ? prepareDesc(firstP.substring(0, 160)) : "Layar Kosong - Catatan dan Opini."; const finalMetaDesc = prepareDesc(rawMetaDesc || fallbackDesc); const finalOgDesc = prepareDesc(rawOgDesc || rawMetaDesc || fallbackDesc); const finalTwitterDesc = prepareDesc(rawTwitterDesc || rawMetaDesc || fallbackDesc); const finalNewsKeywords = prepareDesc( rawNewsKeys || uniqueTags.join(", ") || `${ogTitle}, Layar Kosong` ); const finalPromphint = prepareDesc( rawPromphint || `${ogTitle} | ${fallbackDesc}` ); let metaImgUrl = ogImageMeta || twitterImageMeta || firstImgSrc || "/thumbnail.webp"; if (metaImgUrl && metaImgUrl.startsWith("http")) { const mirroredPath = mirroredMap.get(metaImgUrl) ?? await mirrorAndConvert(metaImgUrl, baseUrl); if (mirroredPath.startsWith("/img")) { metaImgUrl = `${baseUrl}${mirroredPath}`; } else { metaImgUrl = mirroredPath; } } else { metaImgUrl = new URL(metaImgUrl, canonicalUrl).href; } const imageMimeType = getImageMimeType(metaImgUrl); let ogImageWidth = "1024"; let ogImageHeight = "633"; try { let localImgPathForMeta = ""; if (metaImgUrl.startsWith(baseUrl)) { localImgPathForMeta = path.join(process.cwd(), metaImgUrl.replace(baseUrl, "")); } else if (metaImgUrl.startsWith("/img")) { localImgPathForMeta = path.join(process.cwd(), metaImgUrl); } if (localImgPathForMeta && await Bun.file(localImgPathForMeta).exists()) { const imgMeta = await getImageDimensionsNative(localImgPathForMeta); ogImageWidth = imgMeta?.width?.toString() || "1024"; ogImageHeight = imgMeta?.height?.toString() || "633"; } } catch { // Fallback 1024x633 } // --- TAHAP 3: SUSUN TAG METADATA BARU --- const htmlTag = { title(text: string) { return `${escapeHtml(text)}`; }, metaCharset(charset: string) { return ``; }, metaName(name: string, content: string) { return ``; }, metaProperty(property: string, content: string) { return ``; }, link(attrs: Record) { const attrStr = Object.entries(attrs) .map(([key, value]) => `${key}="${escapeAttr(value)}"`) .join(" "); return ``; }, script(attrs: Record) { const attrStr = Object.entries(attrs) .map(([key, value]) => `${key}="${escapeAttr(value)}"`) .join(" "); return ``; }, }; const metaTags = [ htmlTag.metaCharset("UTF-8"), htmlTag.metaName("viewport", "width=device-width,initial-scale=1"), htmlTag.title(seoTitle), htmlTag.metaName("description", finalMetaDesc), htmlTag.link({ rel: "canonical", href: canonicalUrl }), htmlTag.metaName("robots", "index,follow,max-snippet:-1,max-video-preview:-1,max-image-preview:large"), htmlTag.metaName("googlebot", "index,follow,max-snippet:-1,max-video-preview:-1,max-image-preview:large"), htmlTag.metaName("author", "Fakhrul Rijal"), htmlTag.metaName("theme-color", "#00b0ed"), htmlTag.metaName("color-scheme", "light dark"), htmlTag.metaName("referrer", "strict-origin-when-cross-origin"), htmlTag.metaName("application-name", "Layar Kosong"), htmlTag.metaName("apple-mobile-web-app-title", "Layar Kosong"), htmlTag.metaName("news_keywords", finalNewsKeywords), htmlTag.metaName("promphint", finalPromphint), htmlTag.metaProperty("og:site_name", "Layar Kosong"), htmlTag.metaProperty("og:locale", "id_ID"), htmlTag.metaProperty("og:type", "article"), htmlTag.metaProperty("og:url", canonicalUrl), htmlTag.metaProperty("og:title", ogTitle), htmlTag.metaProperty("og:description", finalOgDesc), htmlTag.metaProperty("og:updated_time", modifiedTime), htmlTag.metaProperty("og:image", metaImgUrl), htmlTag.metaProperty("og:image:url", metaImgUrl), htmlTag.metaProperty("og:image:secure_url", metaImgUrl), htmlTag.metaProperty("og:image:alt", ogTitle), htmlTag.metaProperty("og:image:width", ogImageWidth), htmlTag.metaProperty("og:image:height", ogImageHeight), htmlTag.metaProperty("og:image:type", imageMimeType), htmlTag.metaName("twitter:card", "summary_large_image"), htmlTag.metaName("twitter:domain", "dalam.web.id"), htmlTag.metaName("twitter:url", canonicalUrl), htmlTag.metaName("twitter:title", ogTitle), htmlTag.metaName("twitter:description", finalTwitterDesc), htmlTag.metaName("twitter:image", metaImgUrl), htmlTag.metaName("twitter:image:alt", ogTitle), htmlTag.metaName("twitter:widgets:new-embed-design", "on"), htmlTag.metaName("twitter:site", "@responaja"), htmlTag.metaName("twitter:creator", "@responaja"), htmlTag.metaName("twitter:account_id", "1872520777138122752"), htmlTag.metaName("fediverse:creator", "@frijal@mastodon.social"), htmlTag.metaProperty("article:author", "https://facebook.com/frijal"), htmlTag.metaProperty("article:publisher", "https://facebook.com/frijalpage"), htmlTag.metaProperty("fb:app_id", "175216696195384"), htmlTag.metaProperty("fb:pages", "917962134736490"), htmlTag.link({ rel: "icon", href: "/favicon.svg", type: "image/svg+xml", sizes: "any" }), htmlTag.link({ rel: "alternate icon", href: "/favicon.ico", type: "image/x-icon" }), htmlTag.link({ rel: "manifest", href: "/site.webmanifest" }), htmlTag.link({ rel: "alternate", type: "application/rss+xml", title: "Feed 30 artikel baru bikin.", href: `${baseUrl}/rss.rss` }), htmlTag.link({ rel: "alternate", type: "application/atom+xml", title: "Atom 30 artikel baru bikin.", href: `${baseUrl}/atom.atom` }), htmlTag.link({ rel: "search", type: "application/opensearchdescription+xml", title: "Layar Kosong", href: "/opensearch.xml" }), htmlTag.link({ rel: "license", href: "https://creativecommons.org/licenses/by/4.0/" }), htmlTag.link({ rel: "me", href: "https://mastodon.social/@frijal" }), htmlTag.link({ rel: "me", href: "https://codeberg.org/frijal" }), htmlTag.link({ rel: "me", href: "https://github.com/frijal" }), htmlTag.script({ defer: "", src: "/ext/data-provider.js" }), ]; uniqueTags.forEach((tag) => { metaTags.push(htmlTag.metaProperty("article:tag", tag)); }); metaTags.push(htmlTag.metaProperty("article:published_time", publishedTime)); metaTags.push(htmlTag.metaProperty("article:modified_time", modifiedTime)); // --- TAHAP 4: MUTASI DOM & INJEKSI METADATA VIA HTMLREWRITER --- const mutateRewriter = new HTMLRewriter() .on("html", { element(el) { el.setAttribute("lang", "id-ID"); el.setAttribute("prefix", "og: https://ogp.me/ns# article: https://ogp.me/ns/article#"); }, }) .on("head", { element(el) { el.prepend("\n " + metaTags.join("\n ") + "\n", { html: true }); }, }) .on("title", { element(el) { el.remove(); }, }) .on('script[src="/ext/data-provider.js"]', { element(el) { el.remove(); }, }) .on("link", { element(el) { const rel = el.getAttribute("rel")?.toLowerCase().trim() || ""; if (REMOVE_LINK_RELS.has(rel)) { el.remove(); } }, }) .on("meta", { element(el) { if (el.hasAttribute("charset")) { el.remove(); return; } if (el.getAttribute("itemprop")?.toLowerCase() === "image") { el.remove(); return; } const name = el.getAttribute("name")?.toLowerCase() || ""; if ( name && (EXACT_REMOVE_META_NAMES.has(name) || PREFIX_REMOVE_META_NAMES.some((p) => name.startsWith(p))) ) { el.remove(); return; } const prop = el.getAttribute("property")?.toLowerCase() || ""; if ( prop && (EXACT_REMOVE_META_PROPS.has(prop) || PREFIX_REMOVE_META_PROPS.some((p) => prop.startsWith(p))) ) { el.remove(); } }, }) .on("img", { element(el) { const src = el.getAttribute("src"); if (src && src.startsWith("http")) { const localPath = mirroredMap.get(src); if (localPath && localPath.startsWith("/img")) { el.setAttribute("src", `${baseUrl}${localPath}`); } else { console.warn(` โ†ณ tetap memakai URL eksternal (mirror gagal): ${src}`); } } if (!el.getAttribute("alt")) { el.setAttribute("alt", seoTitle); } }, }) .on("source", { element(el) { const srcset = el.getAttribute("srcset"); if (!srcset) return; const parts = srcset.split(",").map((s) => s.trim()); const newParts = parts.map((part) => { const [url, size] = part.split(/\s+/); if (url && url.startsWith("http")) { const mirrored = mirroredMap.get(url) ?? url; const finalUrl = mirrored.startsWith("/img") ? `${baseUrl}${mirrored}` : mirrored; if (!mirrored.startsWith("/img")) { console.warn(` โ†ณ tetap memakai URL eksternal (mirror gagal): ${url}`); } return size ? `${finalUrl} ${size}` : finalUrl; } return part; }); el.setAttribute("srcset", newParts.join(", ")); }, }) .on("image", { element(el) { const hrefAttr = el.getAttribute("href") !== null ? "href" : el.getAttribute("xlink:href") !== null ? "xlink:href" : null; if (!hrefAttr) return; const src = el.getAttribute(hrefAttr); if (src && src.startsWith("http")) { const localPath = mirroredMap.get(src); if (localPath && localPath.startsWith("/img")) { el.setAttribute(hrefAttr, `${baseUrl}${localPath}`); } else { console.warn(` โ†ณ SVG tetap memakai URL eksternal (mirror gagal): ${src}`); } } }, }); const transformedHtml = mutateRewriter.transform(rawContent); const finalHtml = transformedHtml .replace(/\u00A0/g, " ") .replace(/[\u200B\u200C\u200D\uFEFF]/g, "") .replace(/^\s*[\r\n]/gm, ""); await Bun.write(file, finalHtml); } async function fixSEO() { const baseUrl = BASE_URL; console.log("๐Ÿงผ Memulai SEO Fixer v2 (Bun Turbo TS Mode โ€” 100% Native)"); console.log("๐Ÿ”’ SEO Timestamp: published_time โ‰ค modified_time GUARANTEED"); console.log("๐Ÿ“ฆ WebP Passthrough: gambar sumber WebP disalin apa adanya (deteksi magic bytes)"); console.log(`๐Ÿชช Mirror User-Agent: ${MIRROR_USER_AGENT}\n`); const startTime = performance.now(); const glob = new Glob(`${TARGET_FOLDER}/*.html`); const files: string[] = []; for await (const file of glob.scan(".")) { files.push(file); } if (files.length === 0) { console.log(`โš ๏ธ Tidak ada file HTML ditemukan di folder: ${TARGET_FOLDER}`); return; } files.sort(); const fallbackMap = await buildFallbackMap(files); console.log(`๐Ÿ“… ${fallbackMap.size} fallback timestamps di-generate (published_time locked ke tanggal asli).\n`); for (let i = 0; i < files.length; i += CHUNK_SIZE) { const chunk = files.slice(i, i + CHUNK_SIZE); await Promise.all( chunk.map((file) => processFile(file, baseUrl, fallbackMap.get(file)!)) ); } const duration = (performance.now() - startTime) / 1000; console.log(`\nโœ… Selesai! ${files.length} artikel diproses dalam ${duration.toFixed(2)} detik.`); console.log("โœ… SEO Fixer v2: Semua timestamps sudah valid (published โ‰ค modified) sebelum Diet Mode!\n"); } fixSEO().catch((err) => { console.error(err); process.exit(1); });