1import { Hono } from "https://esm.sh/hono@3.11.7";
2import { readFile, serveFile } from "https://esm.town/v/std/utils/index.ts";
3import { runMigrations } from "./database/migrations.ts";
4import recipesApp from "./routes/recipes.ts";
5import parseApp from "./routes/parse.ts";
13});
1415// Initialize database on startup
16let dbInitialized = false;
17async function initializeDatabase() {
18if (!dbInitialized) {
19try {
20await runMigrations();
21dbInitialized = true;
22console.log('Database initialized successfully');
23} catch (error) {
24console.error('Failed to initialize database:', error);
25throw error;
26}
31app.get('/api/health', async (c) => {
32try {
33await initializeDatabase();
34return c.json({ status: 'ok', timestamp: new Date().toISOString() });
35} catch (error) {
40// Test endpoint for debugging delete operations
41app.get('/api/test-delete', async (c) => {
42await initializeDatabase();
43return c.json({ message: 'Delete test endpoint - check logs for database operations' });
44});
4553app.get("/shared/*", c => serveFile(c.req.path, import.meta.url));
5455// Serve main HTML page with database initialization
56app.get("/", async (c) => {
57try {
58await initializeDatabase();
59let html = await readFile("/frontend/index.html", import.meta.url);
60
25## Technical Implementation
2627- **Database**:[Val Town SQLite](https://docs.val.town/std/sqlite/) for storing users, sessions, and magic link tokens
28- **Frontend**: React with Tailwind CSS
29- **Backend**: Hono.js for API routes and middleware
luciaMagicLinkStartermagic-links.ts2 matches
59const tokenHash = hashToken(token);
6061// Get the token from the database using its hash
62const { rows } = await sqlite.execute(
63`SELECT email, expires_at FROM ${MAGIC_LINKS_TABLE} WHERE id = ?`,
6667if (rows.length === 0) {
68console.log("Did not find magic link token in database");
69return { valid: false };
70}
3import { Hono } from "npm:hono";
4import { authMiddleware } from "./auth.ts";
5import { USER_TABLE } from "./database/schema.ts";
67const app = new Hono();
luciaMagicLinkStarterauth.ts2 matches
1import { getCookie, setCookie } from "npm:hono/cookie";
2import { createMiddleware } from "npm:hono/factory";
3import { createMagicLinkToken, sendMagicLinkEmail, validateMagicLinkToken } from "./database/magic-links.ts";
4import { createSession, generateSessionToken, invalidateSession, validateSessionToken } from "./database/sessions.ts";
56export const authMiddleware = createMiddleware(async (c, next) => {
cardamomshopping-lists.ts1 match
7updateShoppingListItem,
8deleteShoppingList
9} from "../database/queries.ts";
1011const app = new Hono();
cardamomqueries.ts2 matches
39if (!recipeId) {
40console.error('Failed to get recipe ID from insert result:', recipeResult);
41throw new Error('Failed to create recipe: no ID returned from database');
42}
43
47if (isNaN(numericRecipeId) || numericRecipeId <= 0) {
48console.error('Recipe ID is not a valid number:', recipeId);
49throw new Error('Failed to create recipe: invalid ID returned from database');
50}
51
cardamommigrations.ts3 matches
78export async function runMigrations() {
9console.log('Running database migrations...');
10
11try {
90`);
9192console.log('Database migrations completed successfully');
93} catch (error) {
94console.error('Database migration failed:', error);
95throw error;
96}
29- **Frontend**: React 18.2.0 with TypeScript, TailwindCSS
30- **Backend**: Hono API framework with TypeScript
31- **Database**: SQLite with normalized schema (recipes + ingredients tables)
32- **AI**: OpenAI GPT-4o-mini for intelligent recipe parsing
33- **File Processing**:
40```
41โโโ backend/
42โ โโโ database/
43โ โ โโโ migrations.ts # Database schema
44โ โ โโโ queries.ts # Database operations
45โ โโโ routes/
46โ โ โโโ recipes.ts # Recipe CRUD operations
955. **Manage**: View, search, filter, edit, or delete saved recipes
9697## Database Schema
9899The app uses a normalized SQLite database with two main tables:
100101### Recipes Table (`recipes_v1`)
143### Backend Architecture
144- Hono-based REST API with TypeScript
145- Normalized database design with proper foreign key relationships
146- Comprehensive error handling and validation
147- Database migrations with versioned table names
148- Performance optimizations with database indexes
149150## Development Setup
163### File Structure Notes
164- **Static Files**: Served via Val Town's utility functions (`serveFile`, `readFile`)
165- **Database**: SQLite with automatic table creation on startup
166- **Error Handling**: Client-side error catching enabled via Val Town's error capture script
167168### Development Workflow
1691. **Database Changes**: Update table names (e.g., `_v1` โ `_v2`) when modifying schemas
1702. **Testing**: Use built-in test endpoints and browser developer tools
1713. **Debugging**: Check Val Town logs for server-side issues
177- **PDF Parsing Fails**: Ensure PDF contains readable text (not scanned images)
178- **Image Upload Issues**: Verify image is properly base64 encoded
179- **Database Errors**: Check if migrations ran successfully on startup
180- **OpenAI Errors**: Verify API quota and model availability
181182### Debug Endpoints
183- `GET /api/health` - Check if API is responding
184- `GET /api/test-delete` - Test database delete operations
185- Browser console logs for client-side debugging
186- Server logs in Val Town interface for backend issues
cardamomval-town.mdc2 matches
179```
180โโโ backend/
181โ โโโ database/
182โ โ โโโ migrations.ts # Schema definitions
183โ โ โโโ queries.ts # DB query functions
239```
240241### Database Patterns
242- Run migrations on startup or comment out for performance
243- Change table names when modifying schemas rather than altering