PWA - patched deps

This commit is contained in:
Giancarmine Salucci
2025-11-29 17:35:20 +01:00
parent dfa2eb1c4e
commit 0477964009
11 changed files with 10435 additions and 4656 deletions

View File

@@ -0,0 +1,76 @@
import { json } from '@sveltejs/kit';
import { createLLM } from '$lib/server/llm';
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';
import { chromium } from 'playwright';
import fs from 'fs';
import { env } from '$env/dynamic/private';
const RecipeSchema = z.object({
name: z.string(),
description: z.string(),
steps: z.array(z.string()),
ingredients: z.array(z.object({
item: z.string(),
amount: z.string(),
unit: z.string()
}))
});
export async function POST({ request }) {
const { url } = await request.json();
// 1. Browser Connection
// Fallback to localhost if env var not set (e.g. running outside docker)
const wsEndpoint = env.PLAYWRIGHT_WS_ENDPOINT || 'ws://127.0.0.1:3000';
console.log('Connecting to browser at:', wsEndpoint);
const browser = await chromium.connect(wsEndpoint);
// 2. Load Auth if available
const authPath = '/app/secrets/auth.json';
let context;
// We check absolute path (Docker) or relative (Local)
if (fs.existsSync(authPath)) {
context = await browser.newContext({ storageState: authPath });
} else if (fs.existsSync('./secrets/auth.json')) {
context = await browser.newContext({ storageState: './secrets/auth.json' });
} else {
console.warn('No auth.json found. Running as guest.');
context = await browser.newContext();
}
const page = await context.newPage();
let bodyText = '';
try {
await page.goto(url, { waitUntil: 'domcontentloaded' });
// Naive scraper attempt
bodyText = await page.evaluate(() => document.body.innerText);
} catch (e) {
console.error('Scraping error:', e);
return json({ error: 'Failed to scrape URL' }, { status: 500 });
} finally {
await page.close();
await context.close();
await browser.close();
}
// 3. LLM Processing
try {
const { client, model } = createLLM();
const completion = await client.beta.chat.completions.parse({
model,
messages: [
{ role: "system", content: "Extract a recipe structure from this text. If it is not a recipe, return empty arrays." },
{ role: "user", content: bodyText.substring(0, 8000) } // Limit context window
],
response_format: zodResponseFormat(RecipeSchema, "recipe")
});
return json({ recipe: completion.choices[0].message.parsed });
} catch (e) {
console.error('LLM error:', e);
return json({ error: 'Failed to parse recipe' }, { status: 500 });
}
}

View File

@@ -0,0 +1,84 @@
<script lang="ts">
import { page } from '$app/stores';
let status = $state('idle');
let logs = $state<string[]>([]);
let recipe = $state<any>(null);
// URL param parsing for Share Target
// Instagram typically shares text that contains the URL, so we might need to parse it out
let sharedText = $derived($page.url.searchParams.get('text') || '');
let sharedUrl = $derived($page.url.searchParams.get('url') || '');
function extractUrl(text: string) {
const match = text.match(/(https?:\/\/[^\s]+)/);
return match ? match[0] : null;
}
let targetUrl = $derived(sharedUrl || extractUrl(sharedText));
async function process() {
if(!targetUrl) return;
status = 'extracting';
logs = [...logs, 'Sending to server... ' + targetUrl];
try {
const res = await fetch('/api/extract', {
method: 'POST',
body: JSON.stringify({ url: targetUrl }),
headers: { 'Content-Type': 'application/json' }
});
const data = await res.json();
if (data.recipe) {
recipe = data.recipe;
status = 'done';
} else {
logs = [...logs, 'Error: ' + JSON.stringify(data)];
status = 'error';
}
} catch(e) {
logs = [...logs, 'Network Error'];
status = 'error';
}
}
</script>
<div class="p-8 max-w-lg mx-auto space-y-4">
<h1 class="text-2xl font-bold">InstaChef PWA</h1>
{#if targetUrl}
<div class="bg-gray-100 p-2 rounded break-all text-sm border">{targetUrl}</div>
{#if status === 'idle'}
<button onclick={process} class="bg-blue-600 text-white px-4 py-2 rounded shadow hover:bg-blue-700 w-full">
Extract Recipe
</button>
{/if}
{:else}
<p class="text-gray-500">No URL detected. Open this app via Instagram Share Menu.</p>
<div class="text-xs text-gray-400">Debug: Text={sharedText} URL={sharedUrl}</div>
{/if}
{#if status === 'extracting'}
<div class="animate-pulse text-blue-600">Extracting data...</div>
{/if}
{#if recipe}
<div class="border rounded p-4 bg-green-50 space-y-2">
<h2 class="font-bold text-xl">{recipe.name}</h2>
<p class="text-sm">{recipe.description}</p>
<h3 class="font-bold mt-2">Ingredients</h3>
<ul class="list-disc pl-5 text-sm">
{#each recipe.ingredients as ing}
<li>{ing.amount} {ing.unit} {ing.item}</li>
{/each}
</ul>
</div>
{/if}
<div class="font-mono text-xs bg-slate-900 text-green-400 p-4 rounded min-h-[100px] mt-8">
<div class="opacity-50 border-b border-slate-700 mb-2">System Logs</div>
{#each logs as l}<div>> {l}</div>{/each}
</div>
</div>