| 426 | |
| 427 | // URL Scraping Action |
| 428 | export async function scrapeUrl( |
| 429 | prevState: ActionState | null, |
| 430 | formData: { |
| 431 | url: string; |
| 432 | }, |
| 433 | ): Promise<ActionState> { |
| 434 | try { |
| 435 | const url = formData.url; |
| 436 | if (!url) return { error: "URL is required" }; |
| 437 | |
| 438 | // Get metadata from our API |
| 439 | const baseUrl = process.env.VERCEL_URL |
| 440 | ? `https://${process.env.VERCEL_URL}` |
| 441 | : process.env.NODE_ENV === "development" |
| 442 | ? "http://localhost:3000" |
| 443 | : ""; |
| 444 | |
| 445 | const metadataResponse = await fetch( |
| 446 | `${baseUrl}/api/metadata?url=${encodeURIComponent(url)}`, |
| 447 | { |
| 448 | method: "GET", |
| 449 | }, |
| 450 | ); |
| 451 | |
| 452 | if (!metadataResponse.ok) { |
| 453 | throw new Error("Failed to fetch metadata"); |
| 454 | } |
| 455 | |
| 456 | const metadata = await metadataResponse.json(); |
| 457 | |
| 458 | // Get search results using Exa API |
| 459 | const exaResponse = await fetch("https://api.exa.ai/search", { |
| 460 | method: "POST", |
| 461 | headers: { |
| 462 | "Content-Type": "application/json", |
| 463 | Authorization: `Bearer ${process.env.EXASEARCH_API_KEY}`, |
| 464 | }, |
| 465 | body: JSON.stringify({ |
| 466 | query: url, |
| 467 | num_results: 5, |
| 468 | }), |
| 469 | }); |
| 470 | |
| 471 | if (!exaResponse.ok) { |
| 472 | throw new Error("Failed to fetch search results from Exa"); |
| 473 | } |
| 474 | |
| 475 | const searchResults = await exaResponse.json(); |
| 476 | |
| 477 | return { |
| 478 | success: true, |
| 479 | data: { |
| 480 | title: metadata.title || "", |
| 481 | description: metadata.description || "", |
| 482 | favicon: metadata.favicon || "", |
| 483 | ogImage: metadata.ogImage || "", |
| 484 | url: metadata.url || url, |
| 485 | search_results: JSON.stringify(searchResults), |