← Public packages
@kentcdodds/pie-night
Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.
Files
import { packageStorage } from 'kody:runtime'
import { DEFAULT_BLURB, LIMITS, cleanHosts, cleanUsername, slugify, themeName, validSlug, type EventInfo, type PieInput } from './pies.ts'
export type PieRow = {
id: string
who: string
pie: string
note: string
createdAt: number
updatedAt: number
deletedAt: number | null
}
type Binding = string | number | null
type Row = Record<string, unknown>
async function sql(query: string, bindings: Binding[] = []): Promise<Row[]> {
const result = (await packageStorage().sql(query, bindings)) as { rows?: unknown[] } | unknown[] | null
if (!result) return []
if (Array.isArray(result)) return result as Row[]
return Array.isArray(result.rows) ? (result.rows as Row[]) : []
}
let schemaReady: Promise<void> | null = null
function ensureSchema() {
schemaReady ??= (async () => {
await sql(`CREATE TABLE IF NOT EXISTS pies (
id TEXT PRIMARY KEY,
night TEXT NOT NULL,
who TEXT NOT NULL,
pie TEXT NOT NULL,
note TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
deleted_at INTEGER
)`)
await sql('CREATE INDEX IF NOT EXISTS pies_night ON pies (night, deleted_at, created_at)')
await sql(`CREATE TABLE IF NOT EXISTS events (
slug TEXT PRIMARY KEY,
code TEXT NOT NULL,
title TEXT NOT NULL,
date TEXT NOT NULL,
time TEXT NOT NULL,
place TEXT NOT NULL DEFAULT '',
blurb TEXT NOT NULL DEFAULT '',
theme TEXT NOT NULL DEFAULT 'harvest',
night TEXT NOT NULL,
creator TEXT NOT NULL,
hosts TEXT NOT NULL DEFAULT '[]',
version INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)`)
await sql('CREATE INDEX IF NOT EXISTS events_creator ON events (creator, created_at)')
await sql(`CREATE TABLE IF NOT EXISTS event_presence (
event TEXT NOT NULL,
sid TEXT NOT NULL,
name TEXT NOT NULL DEFAULT '',
typing INTEGER NOT NULL DEFAULT 0,
seen INTEGER NOT NULL,
PRIMARY KEY (event, sid)
)`)
await sql(`CREATE TABLE IF NOT EXISTS push_subs (
event TEXT NOT NULL,
endpoint TEXT NOT NULL,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
host INTEGER NOT NULL DEFAULT 0,
username TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
PRIMARY KEY (event, endpoint)
)`)
})().catch((error) => {
schemaReady = null
throw error
})
return schemaReady
}
function toPie(row: Row): PieRow {
return {
id: String(row.id),
who: String(row.who ?? ''),
pie: String(row.pie ?? ''),
note: String(row.note ?? ''),
createdAt: Number(row.created_at ?? 0),
updatedAt: Number(row.updated_at ?? 0),
deletedAt: row.deleted_at == null ? null : Number(row.deleted_at),
}
}
function toEvent(row: Row): EventInfo {
const hosts = safeJson(String(row.hosts ?? '[]'))
return {
slug: String(row.slug),
code: String(row.code ?? row.slug),
title: String(row.title ?? ''),
date: String(row.date ?? ''),
time: String(row.time ?? ''),
place: String(row.place ?? ''),
blurb: String(row.blurb ?? ''),
theme: themeName(row.theme),
night: String(row.night ?? ''),
creator: String(row.creator ?? ''),
hosts: Array.isArray(hosts) ? hosts.map(String) : [],
version: Number(row.version ?? 1),
}
}
export async function getEvent(slug: string): Promise<EventInfo | null> {
if (!validSlug(slug)) return null
await ensureSchema()
const rows = await sql('SELECT * FROM events WHERE slug = ?', [slug])
return rows[0] ? toEvent(rows[0]) : null
}
export async function listEventsFor(username: string): Promise<EventInfo[]> {
await ensureSchema()
const name = cleanUsername(username)
if (!name) return []
const rows = await sql(`SELECT * FROM events WHERE creator = ? OR hosts LIKE ? ORDER BY date DESC, created_at DESC LIMIT 50`, [name, `%"${name}"%`])
return rows.map(toEvent).filter((e) => e.creator === name || e.hosts.includes(name))
}
export async function countEventsBy(username: string): Promise<number> {
await ensureSchema()
const rows = await sql('SELECT COUNT(*) AS n FROM events WHERE creator = ?', [username])
return Number(rows[0]?.n ?? 0)
}
/** Create an event. Returns null when the code is taken. */
export async function createEvent(input: Omit<EventInfo, 'night' | 'version' | 'hosts'> & { hosts?: string[]; night?: string }): Promise<EventInfo | null> {
await ensureSchema()
if (await getEvent(input.slug)) return null
const now = Date.now()
const event: EventInfo = { ...input, hosts: cleanHosts(input.hosts ?? [], input.creator), night: input.night ?? newNight(input.slug), version: 1 }
try {
await sql('INSERT INTO events (slug, code, title, date, time, place, blurb, theme, night, creator, hosts, version, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [event.slug, event.code, event.title, event.date, event.time, event.place, event.blurb, event.theme, event.night, event.creator, JSON.stringify(event.hosts), event.version, now, now])
} catch {
return null
}
return event
}
export function newNight(slug: string) {
return `${slug}:${crypto.randomUUID().slice(0, 8)}`
}
/** Save changed details. Bumps `version`, which also busts the cached share image. */
export async function updateEvent(event: EventInfo): Promise<EventInfo> {
await ensureSchema()
const next = { ...event, hosts: cleanHosts(event.hosts, event.creator), version: event.version + 1 }
await sql('UPDATE events SET code = ?, title = ?, date = ?, time = ?, place = ?, blurb = ?, theme = ?, night = ?, hosts = ?, version = ?, updated_at = ? WHERE slug = ?', [next.code, next.title, next.date, next.time, next.place, next.blurb, next.theme, next.night, JSON.stringify(next.hosts), next.version, Date.now(), next.slug])
return next
}
const LEGACY_EVENT_KEY = 'event'
const LEGACY_ADMINS_KEY = 'admin_usernames'
/** Built-in details of the old single-event version, used when a host never saved any. */
const LEGACY_DEFAULT_EVENT = { title: 'Pie Night', date: '2026-11-27', time: '18:00', blurb: "Thanks for your help making pies. It's going to be great. Let us know what you're bringing.", night: '2026-11-27' }
const LEGACY_OLD_BLURB = 'Bring a pie (or two)! Nobody is assigning anything. Just pick a pie you love and add it here so everyone can see what is coming.'
/**
* One-time move from the single-event version of this app (storage keys
* `event` and `admin_usernames`, pies keyed by that event's night) into a
* named event. Pie rows are left as they are: the new event reuses the old
* night id, so the old and new versions show the same list while both serve.
*/
export async function migrateLegacy(input: { code: string; place?: string; creator: string; title?: string; theme?: string }): Promise<{ ok: boolean; slug: string; created: boolean; pies: number; message: string }> {
await ensureSchema()
const slug = slugify(input.code)
if (!validSlug(slug)) return { ok: false, slug, created: false, pies: 0, message: 'That code is not a valid event code.' }
const creator = cleanUsername(input.creator)
if (!creator) return { ok: false, slug, created: false, pies: 0, message: 'Give the Kody username of the host.' }
const existing = await getEvent(slug)
if (existing) return { ok: true, slug, created: false, pies: await countPies(existing.night), message: 'Already migrated.' }
const rawEvent = await packageStorage().get(LEGACY_EVENT_KEY)
const saved = (typeof rawEvent === 'string' ? safeJson(rawEvent) : rawEvent) as Record<string, unknown> | null
// The old version used built-in defaults until a host first saved the details.
const legacy: Record<string, unknown> = { ...LEGACY_DEFAULT_EVENT, ...(saved && typeof saved === 'object' ? saved : {}) }
if (legacy.blurb === LEGACY_OLD_BLURB) legacy.blurb = LEGACY_DEFAULT_EVENT.blurb
const rawAdmins = await packageStorage().get(LEGACY_ADMINS_KEY)
const admins = (typeof rawAdmins === 'string' ? safeJson(rawAdmins) : rawAdmins) as unknown
const legacyNight = typeof legacy.night === 'string' && legacy.night ? legacy.night : String(legacy.date)
const created = await createEvent({
slug,
code: String(input.code).trim().slice(0, LIMITS.code),
title: String(input.title ?? legacy.title ?? 'Pie Night').slice(0, LIMITS.title),
date: String(legacy.date ?? ''),
time: String(legacy.time ?? '18:00'),
place: String(input.place ?? '').slice(0, LIMITS.place),
blurb: String(legacy.blurb ?? DEFAULT_BLURB).slice(0, LIMITS.blurb),
theme: themeName(input.theme),
creator,
hosts: Array.isArray(admins) ? admins.map(String) : [],
night: legacyNight,
})
if (!created) return { ok: false, slug, created: false, pies: 0, message: 'Could not create the event.' }
return { ok: true, slug, created: true, pies: await countPies(created.night), message: saved ? 'Migrated.' : 'Created from the single-event defaults (no saved details).' }
}
function safeJson(value: string): unknown {
try {
return JSON.parse(value)
} catch {
return null
}
}
export async function listPies(night: string): Promise<PieRow[]> {
await ensureSchema()
const rows = await sql('SELECT * FROM pies WHERE night = ? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT ?', [night, LIMITS.maxPies])
return rows.map(toPie)
}
export async function listRemoved(night: string): Promise<PieRow[]> {
await ensureSchema()
const rows = await sql('SELECT * FROM pies WHERE night = ? AND deleted_at IS NOT NULL ORDER BY deleted_at DESC LIMIT 30', [night])
return rows.map(toPie)
}
export async function countPies(night: string): Promise<number> {
await ensureSchema()
const rows = await sql('SELECT COUNT(*) AS n FROM pies WHERE night = ? AND deleted_at IS NULL', [night])
return Number(rows[0]?.n ?? 0)
}
export async function addPie(night: string, input: PieInput): Promise<PieRow> {
await ensureSchema()
const now = Date.now()
const id = crypto.randomUUID()
await sql('INSERT INTO pies (id, night, who, pie, note, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)', [id, night, input.who, input.pie, input.note, now, now])
return { id, ...input, createdAt: now, updatedAt: now, deletedAt: null }
}
/** Insert all rows together in a single SQL statement, keeping their order. */
export async function addPies(night: string, inputs: PieInput[]): Promise<PieRow[]> {
await ensureSchema()
const now = Date.now()
const rows: PieRow[] = inputs.map((input, i) => ({ id: crypto.randomUUID(), ...input, createdAt: now + i, updatedAt: now + i, deletedAt: null }))
const values = rows.map(() => '(?, ?, ?, ?, ?, ?, ?)').join(', ')
const bindings: Binding[] = rows.flatMap((r) => [r.id, night, r.who, r.pie, r.note, r.createdAt, r.updatedAt])
await sql(`INSERT INTO pies (id, night, who, pie, note, created_at, updated_at) VALUES ${values}`, bindings)
return rows
}
export async function getPie(night: string, id: string): Promise<PieRow | null> {
await ensureSchema()
const rows = await sql('SELECT * FROM pies WHERE night = ? AND id = ?', [night, id])
return rows[0] ? toPie(rows[0]) : null
}
export async function updatePie(night: string, id: string, input: PieInput): Promise<PieRow | null> {
await ensureSchema()
await sql('UPDATE pies SET who = ?, pie = ?, note = ?, updated_at = ? WHERE night = ? AND id = ? AND deleted_at IS NULL', [input.who, input.pie, input.note, Date.now(), night, id])
const pie = await getPie(night, id)
return pie && pie.deletedAt == null ? pie : null
}
export async function removePie(night: string, id: string): Promise<boolean> {
await ensureSchema()
const before = await getPie(night, id)
if (!before || before.deletedAt != null) return false
await sql('UPDATE pies SET deleted_at = ? WHERE night = ? AND id = ?', [Date.now(), night, id])
return true
}
export async function restorePie(night: string, id: string): Promise<boolean> {
await ensureSchema()
const before = await getPie(night, id)
if (!before || before.deletedAt == null) return false
await sql('UPDATE pies SET deleted_at = NULL, updated_at = ? WHERE night = ? AND id = ?', [Date.now(), night, id])
return true
}
export type PresenceRow = { sid: string; name: string; typing: boolean; seen: number }
const PRESENCE_ACTIVE_MS = 40_000
/**
* Record a heartbeat for one open tab of one event, drop stale tabs, and return
* everyone here now. `changed` is true when this tab is new, its name or typing
* state changed, or someone timed out, so the caller only broadcasts presence
* when something visible changed.
*/
export async function heartbeat(event: string, input: { sid: string; name: string; typing: boolean } | null): Promise<{ people: PresenceRow[]; changed: boolean }> {
await ensureSchema()
const now = Date.now()
let changed = false
if (input) {
const before = await sql('SELECT name, typing, seen FROM event_presence WHERE event = ? AND sid = ?', [event, input.sid])
const prev = before[0]
changed = !prev || String(prev.name ?? '') !== input.name || (Number(prev.typing) === 1) !== input.typing || Number(prev.seen) < now - PRESENCE_ACTIVE_MS
await sql('INSERT INTO event_presence (event, sid, name, typing, seen) VALUES (?, ?, ?, ?, ?) ON CONFLICT(event, sid) DO UPDATE SET name = excluded.name, typing = excluded.typing, seen = excluded.seen', [event, input.sid, input.name, input.typing ? 1 : 0, now])
}
const stale = await sql('SELECT COUNT(*) AS n FROM event_presence WHERE event = ? AND seen < ?', [event, now - PRESENCE_ACTIVE_MS])
if (Number(stale[0]?.n ?? 0) > 0) {
await sql('DELETE FROM event_presence WHERE event = ? AND seen < ?', [event, now - PRESENCE_ACTIVE_MS])
changed = true
}
if (Math.random() < 0.02) await sql('DELETE FROM event_presence WHERE seen < ?', [now - 10 * 60_000])
const rows = await sql('SELECT sid, name, typing, seen FROM event_presence WHERE event = ? AND seen >= ? ORDER BY seen DESC LIMIT 40', [event, now - PRESENCE_ACTIVE_MS])
const people = rows.map((r) => ({ sid: String(r.sid), name: String(r.name ?? ''), typing: Number(r.typing) === 1 && Number(r.seen) >= now - 15_000, seen: Number(r.seen) }))
return { people, changed }
}
export async function presentPeople(event: string): Promise<PresenceRow[]> {
return (await heartbeat(event, null)).people
}
export async function leave(event: string, sid: string) {
await ensureSchema()
await sql('DELETE FROM event_presence WHERE event = ? AND sid = ?', [event, sid])
}
// ---------- Web push subscriptions ----------
export type PushSub = { event: string; endpoint: string; p256dh: string; auth: string; host: boolean; username: string }
const PUSH_KEY = 'web_push_public_key'
/** The VAPID public key that matches the `webPush` signing credential (see ./setup-push.ts). */
export async function getPushPublicKey(): Promise<string> {
const raw = await packageStorage().get(PUSH_KEY)
return typeof raw === 'string' && /^[A-Za-z0-9_-]{80,100}$/.test(raw) ? raw : ''
}
export async function setPushPublicKey(key: string) {
await packageStorage().set(PUSH_KEY, key)
}
export async function savePushSub(sub: PushSub) {
await ensureSchema()
const count = await sql('SELECT COUNT(*) AS n FROM push_subs WHERE event = ?', [sub.event])
if (Number(count[0]?.n ?? 0) >= 500) throw new Error('Too many devices are already following this pie night.')
await sql('INSERT INTO push_subs (event, endpoint, p256dh, auth, host, username, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(event, endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth, host = excluded.host, username = excluded.username', [sub.event, sub.endpoint, sub.p256dh, sub.auth, sub.host ? 1 : 0, sub.username, Date.now()])
}
export async function removePushSub(event: string, endpoint: string) {
await ensureSchema()
await sql('DELETE FROM push_subs WHERE event = ? AND endpoint = ?', [event, endpoint])
}
export async function hasPushSub(event: string, endpoint: string): Promise<{ host: boolean } | null> {
await ensureSchema()
const rows = await sql('SELECT host FROM push_subs WHERE event = ? AND endpoint = ?', [event, endpoint])
return rows[0] ? { host: Number(rows[0].host) === 1 } : null
}
export async function listPushSubs(event: string, opts: { hostsOnly?: boolean } = {}): Promise<PushSub[]> {
await ensureSchema()
const rows = await sql(`SELECT * FROM push_subs WHERE event = ?${opts.hostsOnly ? ' AND host = 1' : ''} LIMIT 500`, [event])
return rows.map((r) => ({ event: String(r.event), endpoint: String(r.endpoint), p256dh: String(r.p256dh), auth: String(r.auth), host: Number(r.host) === 1, username: String(r.username ?? '') }))
}