Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

29.7 KB
Raw Blame
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
import sharp from "sharp";
import { chromium } from "playwright-core";

function isPrivateIp(address) {
  const ip = String(address || "").toLowerCase();
  if (!ip) return true;
  if (ip.startsWith("::ffff:")) return isPrivateIp(ip.slice(7));
  if (isIP(ip) === 4) {
    const parts = ip.split(".").map(Number);
    if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n))) return true;
    const [a, b] = parts;
    if (a === 0 || a === 10 || a === 127) return true;
    if (a === 169 && b === 254) return true;
    if (a === 172 && b >= 16 && b <= 31) return true;
    if (a === 192 && b === 168) return true;
    if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
    if (a >= 224) return true; // multicast/reserved
    return false;
  }
  if (isIP(ip) === 6) {
    if (ip === "::" || ip === "::1") return true;
    if (/^(fc|fd|fe8|fe9|fea|feb)/i.test(ip)) return true; // ULA / link-local
    return false;
  }
  return true;
}

const hostSafetyCache = new Map();

export async function assertPublicTargetUrl(rawUrl) {
  let u;
  try {
    u = new URL(rawUrl);
  } catch {
    throw new Error(`Invalid URL: ${rawUrl}`);
  }
  if (u.protocol !== "https:" && u.protocol !== "http:") {
    throw new Error(`Disallowed protocol: ${u.protocol}`);
  }
  const host = u.hostname.toLowerCase();
  if (
    !host ||
    host === "localhost" ||
    host.endsWith(".local") ||
    host.endsWith(".internal") ||
    host.endsWith(".localhost") ||
    isIP(host)
  ) {
    throw new Error(`Disallowed private or direct-IP host: ${host}`);
  }
  if (hostSafetyCache.has(host)) {
    if (!hostSafetyCache.get(host)) {
      throw new Error(`Host resolves to private network: ${host}`);
    }
    return u;
  }
  const records = await lookup(host, { all: true, verbatim: true });
  const safe =
    records.length > 0 && records.every((rec) => !isPrivateIp(rec.address));
  hostSafetyCache.set(host, safe);
  if (!safe) {
    throw new Error(`Host resolves to private network: ${host}`);
  }
  return u;
}

export function findChromiumExecutable() {
  if (process.env.CHROME_PATH && existsSync(process.env.CHROME_PATH)) {
    return process.env.CHROME_PATH;
  }

  const cacheDirs = [
    join(homedir(), "Library/Caches/ms-playwright"),
    join(homedir(), ".cache/ms-playwright"),
  ];

  for (const dir of cacheDirs) {
    if (!existsSync(dir)) continue;
    const entries = readdirSync(dir)
      .filter((name) => name.startsWith("chromium-"))
      .sort()
      .reverse();
    for (const entry of entries) {
      const candidates = [
        join(
          dir,
          entry,
          "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
        ),
        join(
          dir,
          entry,
          "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
        ),
        join(dir, entry, "chrome-linux/chrome"),
      ];
      for (const candidate of candidates) {
        if (existsSync(candidate)) return candidate;
      }
    }
  }

  const systemCandidates = [
    "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    "/Applications/Chromium.app/Contents/MacOS/Chromium",
    "/usr/bin/google-chrome",
    "/usr/bin/chromium",
  ];
  for (const candidate of systemCandidates) {
    if (existsSync(candidate)) return candidate;
  }
  return undefined;
}

export async function launchCaptureBrowser() {
  const executablePath = findChromiumExecutable();
  return chromium.launch({
    executablePath,
    headless: true,
    args: [
      "--disable-blink-features=AutomationControlled",
      "--no-sandbox",
      "--disable-dev-shm-usage",
    ],
  });
}

const BLOCKED_TITLE_RE =
  /^(just a moment|attention required|access denied|403 forbidden|404 not found|page not found|verify you are human|security check|ddos-guard|robot check|pardon our interruption)/i;

async function dismissBanners(page) {
  const selectors = [
    'button:has-text("Accept all")',
    'button:has-text("Accept All")',
    'button:has-text("Accept cookies")',
    'button:has-text("Accept Cookies")',
    'button:has-text("Reject all")',
    'button:has-text("Accept")',
    'button:has-text("Allow all")',
    'button:has-text("Got it")',
    'button:has-text("I agree")',
    '[id*="cookie" i] button:has-text("Accept")',
    '[class*="cookie" i] button:has-text("Accept")',
    '[id*="onetrust" i] button#onetrust-accept-btn-handler',
    '[aria-label="Close cookie banner" i]',
    '[aria-label="Dismiss" i]',
    '[role="dialog"] button[aria-label*="close" i]',
    '[aria-modal="true"] button[aria-label*="close" i]',
    '[class*="modal" i] button[aria-label*="close" i]',
    '[class*="popup" i] button[aria-label*="close" i]',
  ];
  for (const sel of selectors) {
    try {
      const el = page.locator(sel).first();
      if (await el.isVisible({ timeout: 220 })) {
        await el.click({ timeout: 600 }).catch(() => {});
        await page.waitForTimeout(250);
      }
    } catch {}
  }

  // If a fullscreen promo/newsletter modal is still locking scroll, try Escape.
  const hasBlockingModal = await page
    .evaluate(() => {
      const bodyOv = getComputedStyle(document.body).overflow;
      const htmlOv = getComputedStyle(document.documentElement).overflow;
      const locked = bodyOv === "hidden" || htmlOv === "hidden";
      const modal = document.querySelector(
        '[role="dialog"], [aria-modal="true"], [class*="modal" i][style*="display: block"]',
      );
      if (!modal) return false;
      const r = modal.getBoundingClientRect();
      return (locked || r.width >= window.innerWidth * 0.5) && r.height >= window.innerHeight * 0.4;
    })
    .catch(() => false);
  if (hasBlockingModal) {
    await page.keyboard.press("Escape").catch(() => {});
    await page.waitForTimeout(300);
  }
}

async function markVisibleStickyBars(page) {
  await page
    .evaluate(() => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      for (const el of document.querySelectorAll("*")) {
        const style = getComputedStyle(el);
        if (style.position !== "sticky") continue;
        const rect = el.getBoundingClientRect();
        if (rect.width <= 0 || rect.height <= 0) continue;
        if (rect.height > 145) continue;
        if (rect.width < vw * 0.25) continue;
        if (rect.bottom > 0 && rect.top < vh) {
          el.dataset.dtSeenSticky = "1";
        }
      }
    })
    .catch(() => {});
}

async function hideFloatingChrome(page) {
  await page
    .evaluate(() => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      for (const el of document.querySelectorAll("*")) {
        if (el.dataset.dtHidden !== undefined) continue;
        const style = getComputedStyle(el);
        const pos = style.position;
        if (pos !== "fixed" && pos !== "sticky") continue;
        const rect = el.getBoundingClientRect();
        if (rect.width <= 0 || rect.height <= 0) continue;

        const tag = el.tagName;
        const role = (el.getAttribute("role") || "").toLowerCase();
        const idCls = `${el.id || ""} ${typeof el.className === "string" ? el.className : ""}`.toLowerCase();
        const isCookieOrConsent = /cookie|consent|onetrust|transcend|airgap|cookiebot|didomi|usercentrics|gdpr|intercom|crisp|hubspot-messages/.test(
          idCls,
        );
        if (pos === "fixed" && isCookieOrConsent) {
          el.dataset.dtHidden = el.style.visibility || "";
          el.style.setProperty("visibility", "hidden", "important");
          continue;
        }

        // Never hide full-viewport canvases, WebGL backdrops, or scroll-linked scene stages.
        const isFullViewportStage =
          rect.height >= vh * 0.72 && rect.width >= vw * 0.72;
        if (isFullViewportStage) continue;

        const isNavSemantic =
          tag === "HEADER" ||
          tag === "NAV" ||
          role === "banner" ||
          role === "navigation";

        if (pos === "sticky") {
          // NEVER hide large sticky content / storytelling panels (e.g. side-by-side graphic stages).
          // Only hide thin sticky navbars or sticky section subheaders AFTER they've appeared once.
          if (rect.height > 145) continue;
          const isThinStickyNav =
            isNavSemantic ||
            (el.dataset.dtSeenSticky === "1" &&
              rect.width >= vw * 0.25 &&
              rect.top >= -10 &&
              rect.top <= 140) ||
            (rect.height <= 115 &&
              rect.width >= vw * 0.45 &&
              rect.top >= -10 &&
              rect.top <= 48);
          if (!isThinStickyNav) continue;
        } else {
          // position: fixed — only hide overlays currently pinned on-screen as chrome/widgets.
          const isOnScreen = rect.bottom > 0 && rect.top < vh;
          if (!isOnScreen) continue;
          const isThinBar =
            rect.height <= 180 && (rect.top <= 60 || rect.bottom >= vh - 60);
          const isCornerWidget =
            rect.width <= 480 &&
            rect.height <= 340 &&
            (rect.bottom >= vh - 160 || rect.top <= 120);
          if (!isThinBar && !isCornerWidget && !isNavSemantic && !isCookieOrConsent) continue;
        }

        el.dataset.dtHidden = el.style.visibility || "";
        el.style.setProperty("visibility", "hidden", "important");
      }
    })
    .catch(() => {});
}

async function waitForVisibleImages(page, maxWaitMs = 1800) {
  await page
    .evaluate(
      (limit) =>
        Promise.race([
          Promise.all(
            [...document.images]
              .filter((img) => {
                if (img.complete && img.naturalWidth > 0) return false;
                const r = img.getBoundingClientRect();
                return r.bottom > -200 && r.top < window.innerHeight + 300;
              })
              .slice(0, 24)
              .map(
                (img) =>
                  new Promise((resolve) => {
                    img.addEventListener("load", resolve, { once: true });
                    img.addEventListener("error", resolve, { once: true });
                  }),
              ),
          ),
          new Promise((resolve) => setTimeout(resolve, limit)),
        ]),
      maxWaitMs,
    )
    .catch(() => {});
}

async function waitForSettle(page, ms = 650) {
  await page.waitForTimeout(ms);
  await page
    .evaluate(
      () =>
        new Promise((resolve) =>
          requestAnimationFrame(() => requestAnimationFrame(resolve)),
        ),
    )
    .catch(() => {});
}

async function smoothScrollTo(page, targetY) {
  const startY = await page.evaluate(() => Math.round(window.scrollY));
  const delta = targetY - startY;
  if (Math.abs(delta) <= 40) {
    await page.evaluate((top) => window.scrollTo({ top, behavior: "instant" }), targetY);
    return;
  }
  const steps = Math.min(5, Math.max(2, Math.ceil(Math.abs(delta) / 300)));
  for (let i = 1; i <= steps; i++) {
    const nextY = Math.round(startY + (delta * i) / steps);
    await page.evaluate((top) => {
      window.scrollTo({ top, behavior: "instant" });
      window.dispatchEvent(new Event("scroll"));
    }, nextY);
    await page.waitForTimeout(110);
  }
}

async function waitOutPreloader(page) {
  for (let attempt = 0; attempt < 7; attempt++) {
    const hasPreloader = await page
      .evaluate(() => {
        const vw = window.innerWidth;
        const vh = window.innerHeight;
        const els = document.querySelectorAll(
          '[class*="preload" i], [id*="preload" i], [class*="loader" i], [id*="loader" i], [class*="splash" i], [class*="loading" i], [id*="loading" i]',
        );
        for (const el of els) {
          const cs = getComputedStyle(el);
          if (
            cs.display === "none" ||
            cs.visibility === "hidden" ||
            Number(cs.opacity) < 0.1
          ) {
            continue;
          }
          const r = el.getBoundingClientRect();
          if (r.width >= vw * 0.65 && r.height >= vh * 0.65) {
            return true;
          }
        }
        // Also detect sparse numeric percentage preloaders (e.g. "052%" / "48" alone on screen).
        const bodyText = (document.body?.innerText || "").trim();
        if (bodyText.length > 0 && bodyText.length <= 24 && /^\d{1,3}\s*%?$/.test(bodyText)) {
          return true;
        }
        return false;
      })
      .catch(() => false);
    if (!hasPreloader) break;
    await page.waitForTimeout(900);
  }
}

async function primeVisibleVideos(page) {
  await page
    .evaluate(async () => {
      const vids = [...document.querySelectorAll("video")].filter((v) => {
        const r = v.getBoundingClientRect();
        return r.bottom > -200 && r.top < window.innerHeight + 300;
      });
      await Promise.race([
        Promise.all(
          vids.slice(0, 6).map(async (v) => {
            try {
              if (v.readyState < 2) {
                v.muted = true;
                v.play?.().catch(() => {});
                await new Promise((resolve) => {
                  v.addEventListener("loadeddata", resolve, { once: true });
                  v.addEventListener("error", resolve, { once: true });
                });
              }
            } catch {}
          }),
        ),
        new Promise((resolve) => setTimeout(resolve, 900)),
      ]);
    })
    .catch(() => {});
}

export async function captureStitchedWebsite(
  browser,
  url,
  {
    viewportWidth = 1440,
    viewportHeight = 900,
    maxHeight = 4200,
    outputWidth = 1280,
    timeoutMs = 30000,
  } = {},
) {
  await assertPublicTargetUrl(url);

  const context = await browser.newContext({
    viewport: { width: viewportWidth, height: viewportHeight },
    deviceScaleFactor: 1,
    userAgent:
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    locale: "en-US",
  });

  const page = await context.newPage();
  page.setDefaultTimeout(12000);
  page.setDefaultNavigationTimeout(timeoutMs);
  // Block redirects or subresource requests targeting private/loopback networks.
  await page.route("**/*", async (route) => {
    const reqUrl = route.request().url();
    if (reqUrl.startsWith("data:") || reqUrl.startsWith("blob:")) {
      return route.continue().catch(() => {});
    }
    try {
      await assertPublicTargetUrl(reqUrl);
      return route.continue().catch(() => {});
    } catch {
      return route.abort("blockedbyclient").catch(() => {});
    }
  });

  let hardTimer;
  const hardTimeout = new Promise((_, reject) => {
    hardTimer = setTimeout(() => {
      context.close().catch(() => {});
      reject(new Error("Hard capture timeout (75s)"));
    }, 75000);
  });

  const runCapture = async () => {
    let response = null;
    try {
      response = await page.goto(url, {
        waitUntil: "domcontentloaded",
        timeout: timeoutMs,
      });
    } catch {
      response = null;
    }
    await page.waitForLoadState("load", { timeout: 10000 }).catch(() => {});
    await page.waitForLoadState("networkidle", { timeout: 9000 }).catch(() => {});

    const status = response?.status() ?? 0;
    if (status >= 400 && !/404/.test(url)) {
      throw new Error(`HTTP ${status}`);
    }
    // Re-validate final URL after any HTTP/JS redirects so private targets are never captured.
    await assertPublicTargetUrl(page.url());

    await page.waitForTimeout(1200);
    await page
      .evaluate(() => document.fonts?.ready?.catch?.(() => {}))
      .catch(() => {});
    await waitOutPreloader(page);

    const title = (await page.title().catch(() => "")).trim();
    if (BLOCKED_TITLE_RE.test(title) && !/404/.test(url)) {
      throw new Error(`Blocked or error page ("${title}")`);
    }

    await dismissBanners(page);
    await waitForVisibleImages(page, 2000);
    await primeVisibleVideos(page);
    await waitForSettle(page, 450);

    const totalHeight = await page.evaluate(() =>
      Math.max(
        document.body?.scrollHeight || 0,
        document.documentElement?.scrollHeight || 0,
        window.innerHeight,
      ),
    );

    const targetHeight = Math.min(maxHeight, Math.max(viewportHeight, totalHeight));
    const slices = [];

    // First slice at y = 0 keeps the header/hero intact.
    const firstBuf = await page.screenshot({
      type: "png",
      timeout: 10000,
      animations: "allow",
    });
    slices.push({ buf: firstBuf, top: 0, height: viewportHeight, cropTop: 0 });
    await markVisibleStickyBars(page);

    if (targetHeight > viewportHeight + 120) {
      // Hide only thin fixed/sticky nav chrome & floating corner widgets (never sticky graphic stages).
      await hideFloatingChrome(page);

      let y = viewportHeight;
      let lastActualY = 0;
      while (y < targetHeight) {
        const currentTotal = await page.evaluate(() =>
          Math.max(
            document.body?.scrollHeight || 0,
            document.documentElement?.scrollHeight || 0,
            window.innerHeight,
          ),
        );
        const effectiveTarget = Math.min(maxHeight, Math.max(viewportHeight, currentTotal));
        const remaining = effectiveTarget - y;
        if (remaining < 40) break;

        const desiredScroll = Math.min(y, Math.max(0, currentTotal - viewportHeight));
        await smoothScrollTo(page, desiredScroll);
        // Re-check in case a navbar switches to position:fixed or a seen sticky subheader pins at top.
        await hideFloatingChrome(page);
        await waitForVisibleImages(page, 1400);
        await primeVisibleVideos(page);
        await waitForSettle(page, 620);

        const actualY = await page.evaluate(() => Math.round(window.scrollY));
        if (actualY <= lastActualY + 20) break;

        const shot = await page.screenshot({
          type: "png",
          timeout: 10000,
          animations: "allow",
        });
        await markVisibleStickyBars(page);
        const expectedTop = slices[slices.length - 1].top + slices[slices.length - 1].height;
        const overlap = Math.max(0, expectedTop - actualY);
        const usableHeight = Math.min(viewportHeight - overlap, remaining);

        if (usableHeight < 40) break;

        slices.push({
          buf: shot,
          top: expectedTop,
          height: usableHeight,
          cropTop: overlap,
        });
        lastActualY = actualY;
        y = expectedTop + usableHeight;
      }
    }

    const sliceMetas = await Promise.all(
      slices.map((s) => sharp(s.buf).metadata()),
    );
    const canvasWidth = Math.min(
      viewportWidth,
      ...sliceMetas.map((m) => m.width || viewportWidth),
    );
    const composites = [];
    let cursorTop = 0;
    for (let idx = 0; idx < slices.length; idx++) {
      const s = slices[idx];
      const sm = sliceMetas[idx];
      const sh = sm.height || viewportHeight;
      const cropTop = Math.min(Math.max(0, Math.round(s.cropTop)), Math.max(0, sh - 1));
      const extractHeight = Math.min(Math.round(s.height), sh - cropTop);
      if (extractHeight < 20) continue;
      const input = await sharp(s.buf)
        .extract({
          left: 0,
          top: cropTop,
          width: canvasWidth,
          height: extractHeight,
        })
        .toBuffer();
      composites.push({ input, top: cursorTop, left: 0 });
      cursorTop += extractHeight;
    }

    const finalRawHeight = Math.max(1, cursorTop);
    const stitchedPng = await sharp({
      create: {
        width: canvasWidth,
        height: finalRawHeight,
        channels: 3,
        background: { r: 11, g: 11, b: 11 },
      },
    })
      .composite(composites)
      .png()
      .toBuffer();

    const stitchedRaw = await sharp(stitchedPng)
      .resize({ width: outputWidth, withoutEnlargement: true })
      .jpeg({ quality: 83, mozjpeg: true })
      .toBuffer();

    const meta = await sharp(stitchedRaw).metadata();
    const stats = await sharp(stitchedRaw).stats();
    const avgStdDev =
      stats.channels.reduce((sum, c) => sum + c.stdev, 0) / stats.channels.length;

    if (avgStdDev < 4.5) {
      throw new Error(`Blank or uniform screenshot (stdev=${avgStdDev.toFixed(1)})`);
    }

    return {
      buffer: stitchedRaw,
      width: meta.width,
      height: meta.height,
      sha256: createHash("sha256").update(stitchedRaw).digest("hex"),
      title,
      captureMethod:
        slices.length > 1
          ? `Stitched full-page capture at ${viewportWidth}px viewport with repeated sticky chrome hidden.`
          : `Single-viewport capture at ${viewportWidth}×${viewportHeight}.`,
      slices: slices.length,
    };
  };

  try {
    return await Promise.race([runCapture(), hardTimeout]);
  } finally {
    clearTimeout(hardTimer);
    await context.close().catch(() => {});
  }
}

export async function detectScrollMotion(page) {
  return page
    .evaluate(() => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      let tallStickyCount = 0;
      let fullCanvasCount = 0;

      for (const el of document.querySelectorAll("*")) {
        const cs = getComputedStyle(el);
        const r = el.getBoundingClientRect();
        if (r.width <= 0 || r.height <= 0) continue;

        if (cs.position === "sticky") {
          const tag = el.tagName;
          const role = (el.getAttribute("role") || "").toLowerCase();
          const isNav =
            tag === "HEADER" ||
            tag === "NAV" ||
            role === "banner" ||
            role === "navigation";
          if (!isNav && r.height >= 260 && r.width >= vw * 0.28) {
            tallStickyCount++;
          }
        }
        if (
          el.tagName === "CANVAS" &&
          r.width >= vw * 0.7 &&
          r.height >= vh * 0.6
        ) {
          fullCanvasCount++;
        }
      }

      const scrollHeight = Math.max(
        document.body?.scrollHeight || 0,
        document.documentElement?.scrollHeight || 0,
      );
      const isScrollJacked = scrollHeight <= vh + 120 && fullCanvasCount > 0;
      return {
        isScrollMotion: tallStickyCount > 0 || isScrollJacked,
        tallStickyCount,
        fullCanvasCount,
        isScrollJacked,
      };
    })
    .catch(() => ({
      isScrollMotion: false,
      tallStickyCount: 0,
      fullCanvasCount: 0,
      isScrollJacked: false,
    }));
}

export async function captureScrollVideo(
  browser,
  url,
  {
    viewportWidth = 1440,
    viewportHeight = 900,
    outputWidth = 1280,
    outputHeight = 800,
    videoWidth = 960,
    videoHeight = 600,
    maxScrollY = 3800,
    scrollDurationMs = 7400,
    holdStartMs = 650,
    holdEndMs = 850,
    timeoutMs = 30000,
  } = {},
) {
  await assertPublicTargetUrl(url);

  const tmpDir = mkdtempSync(join(tmpdir(), "dt-scroll-vid-"));
  const context = await browser.newContext({
    viewport: { width: viewportWidth, height: viewportHeight },
    deviceScaleFactor: 1,
    recordVideo: {
      dir: tmpDir,
      size: { width: outputWidth, height: outputHeight },
    },
    userAgent:
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    locale: "en-US",
  });

  const recordStart = Date.now();
  const page = await context.newPage();
  page.setDefaultTimeout(12000);
  page.setDefaultNavigationTimeout(timeoutMs);
  await page.route("**/*", async (route) => {
    const reqUrl = route.request().url();
    if (reqUrl.startsWith("data:") || reqUrl.startsWith("blob:")) {
      return route.continue().catch(() => {});
    }
    try {
      await assertPublicTargetUrl(reqUrl);
      return route.continue().catch(() => {});
    } catch {
      return route.abort("blockedbyclient").catch(() => {});
    }
  });

  let hardTimer;
  const hardTimeout = new Promise((_, reject) => {
    hardTimer = setTimeout(() => {
      context.close().catch(() => {});
      reject(new Error("Hard video capture timeout (90s)"));
    }, 90000);
  });

  const runVideoCapture = async () => {
    let response = null;
    try {
      response = await page.goto(url, {
        waitUntil: "domcontentloaded",
        timeout: timeoutMs,
      });
    } catch {
      response = null;
    }
    await page.waitForLoadState("load", { timeout: 10000 }).catch(() => {});
    await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {});

    const status = response?.status() ?? 0;
    if (status >= 400 && !/404/.test(url)) {
      throw new Error(`HTTP ${status}`);
    }
    await assertPublicTargetUrl(page.url());

    await page.waitForTimeout(1000);
    await page
      .evaluate(() => document.fonts?.ready?.catch?.(() => {}))
      .catch(() => {});
    await waitOutPreloader(page);

    const title = (await page.title().catch(() => "")).trim();
    if (BLOCKED_TITLE_RE.test(title) && !/404/.test(url)) {
      throw new Error(`Blocked or error page ("${title}")`);
    }

    await dismissBanners(page);
    await waitForVisibleImages(page, 2000);
    await primeVisibleVideos(page);
    await waitForSettle(page, 450);

    // Pixel-matched hero poster right at y = 0 before scrolling begins.
    const heroPng = await page.screenshot({
      type: "png",
      timeout: 12000,
      animations: "allow",
    });
    const heroJpg = await sharp(heroPng)
      .resize(outputWidth, outputHeight, { fit: "cover", position: "top" })
      .jpeg({ quality: 85, mozjpeg: true })
      .toBuffer();

    const heroMeta = await sharp(heroJpg).metadata();
    const heroStats = await sharp(heroJpg).stats();
    const avgStdDev =
      heroStats.channels.reduce((sum, c) => sum + c.stdev, 0) /
      heroStats.channels.length;
    if (avgStdDev < 4.5) {
      throw new Error(`Blank or uniform hero frame (stdev=${avgStdDev.toFixed(1)})`);
    }

    const trimStartSec = Math.max(0, (Date.now() - recordStart) / 1000);
    await page.waitForTimeout(holdStartMs);

    const totalHeight = await page.evaluate(() =>
      Math.max(
        document.body?.scrollHeight || 0,
        document.documentElement?.scrollHeight || 0,
        window.innerHeight,
      ),
    );
    const maxScroll = Math.min(maxScrollY, Math.max(0, totalHeight - viewportHeight));

    if (maxScroll > 120) {
      // Silky 60fps eased native scroll through sticky/scroll-choreographed sections.
      await page.evaluate(
        async ({ targetY, duration }) => {
          const start = performance.now();
          const ease = (t) =>
            t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
          await new Promise((resolve) => {
            function frame(now) {
              const p = Math.min(1, (now - start) / duration);
              window.scrollTo({
                top: Math.round(targetY * ease(p)),
                behavior: "instant",
              });
              if (p < 1) requestAnimationFrame(frame);
              else resolve();
            }
            requestAnimationFrame(frame);
          });
        },
        { targetY: maxScroll, duration: scrollDurationMs },
      );
    } else {
      // Scroll-jacked / WebGL virtual-scroll site: drive with smooth wheel events.
      await page.mouse.move(viewportWidth / 2, viewportHeight / 2);
      const ticks = 90;
      const tickMs = Math.round(Math.min(6200, scrollDurationMs) / ticks);
      for (let i = 0; i < ticks; i++) {
        await page.mouse.wheel(0, 68);
        await page.waitForTimeout(tickMs);
      }
    }

    await page.waitForTimeout(holdEndMs);

    const videoObj = page.video();
    await page.close();
    const rawWebmPath = await videoObj.path();
    await context.close();

    const outMp4Path = join(tmpDir, "out.mp4");
    execFileSync(
      "ffmpeg",
      [
        "-y",
        "-ss",
        trimStartSec.toFixed(2),
        "-i",
        rawWebmPath,
        "-vf",
        `scale=${videoWidth}:${videoHeight}:flags=lanczos,fps=30`,
        "-c:v",
        "libx264",
        "-pix_fmt",
        "yuv420p",
        "-profile:v",
        "main",
        "-level",
        "3.1",
        "-crf",
        "24",
        "-preset",
        "medium",
        "-movflags",
        "+faststart",
        "-an",
        outMp4Path,
      ],
      { stdio: "pipe" },
    );

    const videoBuffer = readFileSync(outMp4Path);
    if (videoBuffer.length < 16 * 1024) {
      throw new Error(`Recorded video too small (${videoBuffer.length} bytes)`);
    }
    if (videoBuffer.length > 5 * 1024 * 1024) {
      // Re-encode with slightly higher CRF if a dense video exceeded 5MB cap.
      execFileSync(
        "ffmpeg",
        [
          "-y",
          "-ss",
          trimStartSec.toFixed(2),
          "-i",
          rawWebmPath,
          "-vf",
          `scale=${videoWidth}:${videoHeight}:flags=lanczos,fps=24`,
          "-c:v",
          "libx264",
          "-pix_fmt",
          "yuv420p",
          "-profile:v",
          "main",
          "-level",
          "3.1",
          "-crf",
          "28",
          "-preset",
          "medium",
          "-movflags",
          "+faststart",
          "-an",
          outMp4Path,
        ],
        { stdio: "pipe" },
      );
    }

    const finalVideoBuffer = readFileSync(outMp4Path);
    if (finalVideoBuffer.length > 5 * 1024 * 1024) {
      throw new Error(`Recorded video exceeds 5MB cap (${finalVideoBuffer.length} bytes)`);
    }

    return {
      buffer: heroJpg,
      width: heroMeta.width,
      height: heroMeta.height,
      sha256: createHash("sha256").update(heroJpg).digest("hex"),
      videoBuffer: finalVideoBuffer,
      videoSha256: createHash("sha256").update(finalVideoBuffer).digest("hex"),
      videoBytes: finalVideoBuffer.length,
      title,
      captureMethod: `Recorded smooth-scroll video preview at ${viewportWidth}×${viewportHeight} with ${outputWidth}×${outputHeight} hero poster.`,
    };
  };

  try {
    return await Promise.race([runVideoCapture(), hardTimeout]);
  } finally {
    clearTimeout(hardTimer);
    await context.close().catch(() => {});
    try {
      rmSync(tmpDir, { recursive: true, force: true });
    } catch {}
  }
}