| import { NextRequest, NextResponse } from "next/server"; |
| import { |
| closeBrowser, |
| initBrowser, |
| isBrowserAlive, |
| navigateTo, |
| } from "@/lib/browser"; |
|
|
| export const runtime = "nodejs"; |
| export const dynamic = "force-dynamic"; |
|
|
| function normalizeUrl(input: string): string { |
| const value = (input || "").trim(); |
| if (!value) throw new Error("URL is required"); |
| if (/^https?:\/\//i.test(value)) return value; |
| return `https://${value}`; |
| } |
|
|
| export async function POST(req: NextRequest) { |
| try { |
| const body = await req.json().catch(() => ({})); |
| const { action, url } = body as { action?: string; url?: string }; |
|
|
| if (action === "init") { |
| await initBrowser(); |
|
|
| return NextResponse.json({ |
| success: true, |
| message: "Browser launched on about:blank", |
| }); |
| } |
|
|
| if (action === "navigate") { |
| const targetUrl = normalizeUrl(url || ""); |
| await navigateTo(targetUrl); |
|
|
| return NextResponse.json({ |
| success: true, |
| message: `Navigated to ${targetUrl}`, |
| url: targetUrl, |
| }); |
| } |
|
|
| if (action === "status") { |
| return NextResponse.json({ |
| success: true, |
| alive: isBrowserAlive(), |
| }); |
| } |
|
|
| if (action === "close") { |
| await closeBrowser(); |
| return NextResponse.json({ |
| success: true, |
| message: "Browser closed", |
| }); |
| } |
|
|
| return NextResponse.json( |
| { |
| error: "Unknown action. Use one of: init, navigate, status, close", |
| }, |
| { status: 400 } |
| ); |
| } catch (e: unknown) { |
| const message = e instanceof Error ? e.message : "Unknown error"; |
| console.error("[/api/browser]", message); |
|
|
| return NextResponse.json( |
| { |
| error: message, |
| }, |
| { status: 500 } |
| ); |
| } |
| } |
|
|
| export async function GET() { |
| try { |
| return NextResponse.json({ |
| success: true, |
| alive: isBrowserAlive(), |
| }); |
| } catch (e: unknown) { |
| const message = e instanceof Error ? e.message : "Unknown error"; |
| return NextResponse.json({ error: message }, { status: 500 }); |
| } |
| } |