import type { Database } from './supabase/types'; export type BindingValue = string | number | null; type Statement = { bind(...values: BindingValue[]): Statement; all(): Promise<{ results: T[] }>; }; export type CommerceBinding = { prepare(sql: string): Statement }; type Table = 'orders' | 'generations' | 'order_reviews' | 'integrations'; type Row = Record; type Result = { data: T | null; error: { code: string; message: string } | null }; type SourceTables = Database['public']['Tables']; type Rows = { orders: Omit & { config: Row; shipping_address: Row | null; cart_reminders_sent: number; rejected_at: string | null; }; generations: SourceTables['generations']['Row']; order_reviews: { id: string; order_id: string; rating: number; comment: string; display_name: string | null; photo_path: string | null; status: string; created_at: string; published_at: string | null; discovery_source: string | null; }; integrations: { key: string; value: string | null; updated_at: string }; }; type Trim = S extends ` ${infer Rest}` ? Trim : S extends `${infer Rest} ` ? Trim : S; type FieldNames = S extends `${infer First},${infer Rest}` ? Trim | FieldNames : Trim; type Projection = S extends '*' ? Rows[T] : string extends S ? Rows[T] : Pick, keyof Rows[T]>>; const jsonColumns = new Set(['config', 'pet_photo_urls', 'shipping_address']); const timestampFields = new Set(['created_at', 'updated_at', 'published_at']); function identifier(name: string): string { if (!/^[a-z][a-z_]*$/.test(name)) throw new Error('Invalid commerce field.'); return `"${name}"`; } function column(name: string): string { if (name === 'config->customerCancellation->>state') return "json_extract(config, '$.customerCancellation.state')"; return identifier(name); } function bindValue(value: unknown): BindingValue { if (value === null || typeof value === 'number' || typeof value === 'string') return value; if (typeof value === 'boolean') return Number(value); const json = JSON.stringify(value); if (json === undefined) throw new Error('Invalid commerce field value.'); return json; } function decode(row: Row): Row { for (const key of jsonColumns) { if (typeof row[key] === 'string') row[key] = JSON.parse(row[key]); } if (typeof row.published === 'number') row.published = Boolean(row.published); return row; } function insertDefaults(table: Table, row: Row): Row { const now = new Date().toISOString(); if (table === 'orders') return { status: 'pending_payment', pet_photo_urls: [], cart_reminders_sent: 0, created_at: now, updated_at: now, ...row, }; if (table === 'generations') return { id: crypto.randomUUID(), published: false, created_at: now, ...row }; if (table === 'order_reviews') return { id: crypto.randomUUID(), status: 'pending', created_at: now, ...row }; return { updated_at: now, ...row }; } function databaseError(error: unknown): Result { const detail = error instanceof Error ? error.message : ''; if (/unique constraint failed|SQLITE_CONSTRAINT_UNIQUE/i.test(detail)) { return { data: null, error: { code: '23505', message: 'That record already exists.' } }; } return { data: null, error: { code: 'D1_ERROR', message: 'The studio database could not complete the request.' } }; } class CommerceQuery implements PromiseLike> { private action: 'select' | 'insert' | 'update' | 'delete' = 'select'; private projection: string | undefined; private filters: string[] = []; private binds: BindingValue[] = []; private ordering = ''; private rowLimit: number | undefined; private fields: Row = {}; private conflictKey: string | undefined; private db: CommerceBinding; private table: T; constructor(db: CommerceBinding, table: T) { this.db = db; this.table = table; } select(fields?: S): CommerceQuery> { this.projection = !fields || fields === '*' ? '*' : fields.split(',').map((name) => identifier(name.trim())).join(', '); return this as unknown as CommerceQuery>; } insert(fields: Row) { this.action = 'insert'; this.fields = fields; return this; } upsert(fields: Row, options: { onConflict: string }) { this.conflictKey = options.onConflict; return this.insert(fields); } update(fields: Row) { this.action = 'update'; this.fields = fields; return this; } delete() { this.action = 'delete'; return this; } private compare(field: string, operator: '=' | '<>' | '<' | '>', value: unknown) { const name = column(field); const dated = (operator === '<' || operator === '>') && timestampFields.has(field); this.filters.push(dated ? `julianday(${name}) ${operator} julianday(?)` : `${name} ${operator} ?`); this.binds.push(bindValue(value)); return this; } eq(field: string, value: unknown) { return this.compare(field, '=', value); } neq(field: string, value: unknown) { return this.compare(field, '<>', value); } lt(field: string, value: unknown) { return this.compare(field, '<', value); } gt(field: string, value: unknown) { return this.compare(field, '>', value); } in(field: string, values: readonly unknown[]) { this.filters.push(values.length ? `${column(field)} IN (${values.map(() => '?').join(', ')})` : '0 = 1'); this.binds.push(...values.map(bindValue)); return this; } order(field: string, options: { ascending?: boolean } = {}) { this.ordering = ` ORDER BY ${column(field)} ${options.ascending === false ? 'DESC' : 'ASC'}`; return this; } limit(count: number) { if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid commerce query limit.'); this.rowLimit = count; return this; } private statement(maximumRows?: number) { const table = identifier(this.table); const where = this.filters.length ? ' WHERE ' + this.filters.join(' AND ') : ''; const select = this.projection ?? '*'; const returning = this.projection ? ' RETURNING ' + this.projection : ''; if (this.action === 'select') { const limit = Math.min(this.rowLimit ?? Infinity, maximumRows ?? Infinity); return { sql: `SELECT ${select} FROM ${table}${where}${this.ordering}${Number.isFinite(limit) ? ' LIMIT ' + limit : ''}`, values: this.binds, }; } if (this.action === 'delete') { if (!where) throw new Error('Commerce delete requires a filter.'); return { sql: `DELETE FROM ${table}${where}${returning}`, values: this.binds }; } const input = this.action === 'insert' ? insertDefaults(this.table, this.fields) : this.fields; const entries = Object.entries(input).filter(([, value]) => value !== undefined); const values = entries.map(([, value]) => bindValue(value)); const columns = entries.map(([key]) => identifier(key)); if (this.action === 'insert') { const conflict = this.conflictKey; const merge = conflict ? ` ON CONFLICT (${identifier(conflict)}) DO UPDATE SET ${entries .filter(([key]) => key !== conflict) .map(([key]) => `${identifier(key)} = excluded.${identifier(key)}`).join(', ')}` : ''; const slots = values.map(() => '?').join(', '); return { sql: `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${slots})${merge}${returning}`, values }; } if (!where) throw new Error('Commerce update requires a filter.'); const assignments = columns.map((name) => name + ' = ?'); if ((this.table === 'orders' || this.table === 'integrations') && !columns.includes('"updated_at"')) { // Keep optimistic claims distinct even when two writes land in the same millisecond. assignments.push(`updated_at = CASE WHEN julianday(updated_at) >= julianday('now') THEN strftime('%Y-%m-%dT%H:%M:%fZ', updated_at, '+0.001 seconds') ELSE strftime('%Y-%m-%dT%H:%M:%fZ', 'now') END`); } return { sql: `UPDATE ${table} SET ${assignments.join(', ')}${where}${returning}`, values: [...values, ...this.binds], }; } private async execute(maximumRows?: number): Promise> { try { const { sql, values } = this.statement(maximumRows); const { results } = await this.db.prepare(sql).bind(...values).all(); const returnsRows = this.action === 'select' || this.projection; return { data: returnsRows ? results.map(decode) as Selected[] : null, error: null }; } catch (error) { return databaseError(error); } } private async one(optional: boolean): Promise> { const result = await this.execute(2); if (result.error) return { data: null, error: result.error }; const rows = result.data ?? []; if (rows.length === 1 || (optional && rows.length === 0)) return { data: rows[0] ?? null, error: null }; return { data: null, error: { code: 'PGRST116', message: 'Expected a single record.' } }; } single() { return this.one(false); } maybeSingle() { return this.one(true); } then, TResult2 = never>( fulfilled?: ((value: Result) => TResult1 | PromiseLike) | null, rejected?: ((reason: unknown) => TResult2 | PromiseLike) | null, ): PromiseLike { return this.execute().then(fulfilled, rejected); } } export function d1Commerce(db: CommerceBinding) { return { from: (table: T) => new CommerceQuery(db, table) }; } export async function sweepAbandonedCheckouts(db: CommerceBinding, cutoff: string) { await db.prepare(` UPDATE orders SET status = 'abandoned', updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE status = 'pending_payment' AND julianday(created_at) < julianday(?) `).bind(cutoff).all(); }