Chobble Tickets

A self-hosted ticket reservation system built on Deno with libsql.

Features

  • Free and paid events (Stripe/Square integration)
  • Standard events (fixed capacity) and daily events (date-based booking)
  • Multi-event bookings in one checkout
  • Hybrid RSA-OAEP + AES-256-GCM encryption for PII at rest
  • Check-in with QR codes (built-in scanner)
  • Apple Wallet pass support
  • Admin dashboard with multi-user management
  • Email notifications (Resend, Postmark, SendGrid, Mailgun)
  • Public JSON API (optional)
  • Webhooks on registration
  • ICS/RSS calendar feeds
  • Embeddable widget via iframe

Modules

Module Description
Database ORM, table abstractions, and entity CRUD
Crypto Encryption, hashing, and CSRF
Payments Stripe and Square integration
Email Email sending and templates
Tickets QR codes, SVG tickets, Apple Wallet
Events Event fields, sorting, availability
Config Settings, environment, sessions
Utilities FP helpers, formatting, caching
Embed Widget embedding and CDN
Webhooks Webhook delivery and API examples
Demo Demo mode and seed data

Deployment Options

  • Bunny Edge Scripting (edge-deployed)
  • Docker containers
  • Any Deno-compatible environment

Classes

c
PaymentUserError

Error subclass for user-facing payment validation errors (e.g. invalid phone number). These propagate through safeAsync so the message can be shown to the user.

Functions

f
activateUser

Activate a user by wrapping the data key with their KEK

f
addDays

Add days to a YYYY-MM-DD date string

f
addPendingWork

Queue a promise that must complete before the response is sent

f
addQueryLogEntry

Record a query (no-op when logging is disabled)

f
appendIframeParam

Append iframe=true query param to a URL when in iframe mode

f
applyDemoOverrides

Replace form field values with demo data when demo mode is active. Only replaces fields that are present and non-empty in the form. Mutates and returns the same URLSearchParams for chaining.

f
assignEventsToGroup

Assign events to a group by updating their group_id.

f
boundedLru

Create a bounded LRU (Least Recently Used) cache. Evicts the least-recently-used entry when capacity is reached. Uses a doubly-linked list for O(1) LRU tracking so that get() does not mutate the key-value index.

f
bracket

Resource management pattern (like Haskell's bracket or try-with-resources). Ensures cleanup happens even if the operation throws.

f
buildEmbedSnippets

Build embed snippets (script and iframe variants) for a ticket URL

f
buildFrameAncestors

Build a frame-ancestors CSP value from allowed embed hosts. Returns null if the list is empty (allow embedding from anywhere).

f
buildInfoLines

Build info lines from ticket data (non-PII event and booking details)

f
buildInputKeyMap

Build input key mapping from DB columns snake_case DB column → camelCase input key

f
buildMultiIntentMetadata

Build intent metadata for a multi-event checkout. Common fields: multi flag, name, email, serialized items, optional phone/date.

f
buildPkpass

Build a complete .pkpass file as a Uint8Array (ZIP archive)

f
buildSessionCookie
No documentation available
f
buildSingleIntentMetadata

Build intent metadata for a single-event checkout. Common fields: event_id, name, email, quantity, optional phone/address/date.

f
buildSvgTicketData

Build SVG ticket data from an email entry (non-PII only)

f
buildTemplateData

Build the data object exposed to Liquid templates

f
buildTicketAttachments

Generate SVG ticket attachments for all entries

f
buildTicketUrl
No documentation available
f
buildWebhookPayload

Build a consolidated webhook payload from registration entries

f
checkBatchAvailability

Wrapper for test mocking - delegates to attendeesApi at runtime

f
clearEncryptionKeyCache

Clear all crypto caches (encryption key, HMAC key, private key, hybrid decrypt LRU) Called on key rotation and during test setup/teardown

f
clearLoginAttempts

Clear login attempts for an IP (on successful login)

f
clearPaymentProvider

Clear the active payment provider (disables payments)

f
clearSessionCookie
No documentation available
f
clearSetupCompleteCache

Clear setup complete cache (for testing)

f
collectionCache

Create an in-memory collection cache with TTL. Loads all items via fetchAll on first access or after invalidation/expiry, then serves from memory until the TTL expires or invalidate() is called. Accepts an optional clock function for testing.

f
compact

Remove null and undefined values from array

f
completeSetup

Complete initial setup by storing all configuration Generates the encryption key hierarchy:

f
computeGroupSlugIndex

Compute slug index from slug for blind index lookup

f
computeHmacSha256

Compute HMAC-SHA256 using Web Crypto API, returning raw ArrayBuffer

f
computeSlugIndex

Compute slug index from slug for blind index lookup

f
computeTicketTokenIndex

Compute ticket token index using HMAC for blind lookups Similar to slug_index for events - allows lookup without decrypting

f
constantTimeEqual

Constant-time string comparison to prevent timing attacks Always iterates over the longer string and XORs the lengths so that different-length inputs don't leak via an early return.

f
createAttendeeAtomic

Wrapper for test mocking - delegates to attendeesApi at runtime

f
createInvitedUser

Create an invited user (no password yet, has invite code)

f
createManifest

Create manifest.json mapping filenames to SHA-1 hashes

f
createRequestTimer

Create a request timer for measuring duration

f
createSeeds

Create seed events and attendees using efficient batch writes. Encrypts all data before inserting, matching production behavior. Assigns random ticket quantities (1-4) per attendee without overselling.

f
createSession

Create a new session with CSRF token, wrapped data key, and user ID Token is hashed before storage for security

f
createUser

Create a new user with encrypted fields

f
createWithClient

Create a withClient helper that runs an operation with a lazily-resolved client. Returns null if the client is not available or the operation fails.

f
decrypt

Decrypt a string value encrypted with encrypt() Expects format: enc:1:$base64iv:$base64ciphertext

f
decryptAdminLevel

Decrypt a user's admin level

f
decryptAttendeeOrNull

Decrypt a single raw attendee, handling null input. Used when attendee is fetched via batch query.

f
decryptAttendeePII

Decrypt attendee PII using the private key Used in admin views after obtaining private key from session

f
decryptAttendees

Decrypt a list of raw attendees (all fields). Used when attendees are fetched via batch query.

f
decryptAttendeesForTable

Decrypt attendees for table display, skipping contact fields not configured on the event and payment fields for free events. For a free event that only collects email, this skips up to 6 RSA decryptions per attendee (phone, address, special_instructions, payment_id, refunded, plus 1 symmetric for price_paid).

f
decryptBytes

Decrypt binary data encrypted with encryptBytes().

f
decryptUsername

Decrypt a user's username

f
decryptWithKey

Decrypt data with a symmetric key

f
defineIdTable

Helper for tables whose primary key column is id.

f
defineTable

Define a table with CRUD operations

f
deleteAllSessions

Delete all sessions (used when password is changed)

f
deleteAllStaleReservations

Delete all stale reservations (unfinalized and older than STALE_RESERVATION_MS). Called from admin event views to clean up abandoned checkouts.

f
deleteAttendee

Delete an attendee and its processed payments in a single database round-trip. Uses write batch to cascade: processed_payments → attendee. Reduces 2 sequential HTTP round-trips to 1.

f
deleteEvent

Delete an event and all its attendees in a single database round-trip. Uses write batch to cascade: processed_payments → attendees → event. Reduces 3 sequential HTTP round-trips to 1.

f
deleteImage

Delete an image from Bunny storage.

f
deleteOtherSessions

Delete all sessions except the current one Token is hashed before database comparison

f
deleteSession

Delete a session by token Token is hashed before database lookup

f
deleteStaleReservation

Delete a stale reservation to allow retry

f
deleteUser

Delete a user and all their sessions

f
deriveKEK

Derive a Key Encryption Key (KEK) from password hash and DB_ENCRYPTION_KEY Uses PBKDF2 with the password hash as input and DB_ENCRYPTION_KEY as salt

f
detectIframeMode

Detect iframe mode from a request URL and store it for the current request

f
detectImageType

Detect the actual image type from magic bytes. Returns the MIME type if matched, null otherwise.

f
downloadImage

Download and decrypt an image from Bunny storage. Uses the storage SDK directly (same as upload/delete) instead of a CDN pull zone URL, which requires a separate pull zone linked to the storage zone. Returns the decrypted image bytes, or null if the file does not exist.

f
enableQueryLog

Enable query logging and clear previous entries

f
encrypt

Encrypt a string value using AES-256-GCM via Web Crypto API Returns format: enc:1:$base64iv:$base64ciphertext Note: ciphertext includes auth tag appended (Web Crypto API does this automatically)

f
encryptAttendeePII

Encrypt attendee PII using the public key from settings This can be called without authentication (for public ticket forms)

f
encryptBytes

Encrypt binary data with AES-256-GCM. Delegates to encrypt() via base64 encoding for maximum code reuse. Used for encrypting image files before CDN storage.

f
encryptedNameSchema

Shared encrypted name column for tables that store a display name.

f
encryptWithKey

Encrypt data with a symmetric key (for wrapping private key with DATA_KEY)

f
err

Create a failed result

f
errorMessage

Extract a human-readable message from an unknown caught value

f
eventDateToCalendarDate

Convert a UTC ISO datetime to a YYYY-MM-DD calendar date in the given timezone. Returns null if the input is empty or invalid. Used by the calendar view to map standard event dates to calendar days.

f
executeBatch

Execute multiple write statements in a single round-trip using Turso batch API. Statements are executed in order within a single transaction, making this ideal for cascading deletes and multi-step writes. Reduces N sequential HTTP round-trips to 1.

f
executeByField

Execute delete by field

f
extractSessionMetadata

Normalize validated session metadata into the canonical SessionMetadata shape.

f
extractSvgContent

Extract the inner content of an SVG element (strip the outer <svg> wrapper)

f
extractViewBox

Extract the viewBox from an SVG element to compute its coordinate space

f
filter

Curried filter

f
finalizeSession

Finalize a reserved session with the created attendee ID (second phase)

f
flatMap

Curried flatMap

f
flushPendingWork

Await all queued work. Call before returning the response.

f
formatCurrency

Format an amount in minor units (pence/cents) as a currency string. e.g. formatCurrency(1050) → "£10.50" (when currency is GBP)

f
formatDateLabel

Format a YYYY-MM-DD date for display. Returns "Monday 15 March 2026"

f
formatDatetimeInTz

Format a UTC ISO datetime string for display in the given timezone. Returns e.g. "Monday 15 June 2026 at 14:00 BST"

f
formatDatetimeLabel

Format an ISO datetime string for display in the given timezone. Returns e.g. "Monday 15 June 2026 at 14:00 BST"

f
formatErrorMessage

Format an error context into a human-readable activity log message

f
generateDataKey

Generate a random 256-bit symmetric key for data encryption

f
generateImageFilename

Generate a random filename with the correct extension

f
generateKeyPair

Generate an RSA key pair for asymmetric encryption Returns { publicKey, privateKey } as exportable JWK strings

f
generatePassJson

Build the pass.json content from pass data and signing credentials

f
generateQrSvg

Generate an SVG string for a QR code encoding the given text. Returns a complete <svg> element suitable for inline embedding.

f
generateSecureToken

Generate a cryptographically secure random token Uses Web Crypto API getRandomValues

f
generateSlug

Generate a random slug with at least 2 digits and 2 letters. Uses Fisher-Yates shuffle on the fixed positions to avoid bias.

f
generateSvgTicket

Generate a standalone SVG ticket with QR code and event/booking details. Returns a complete SVG document string.

f
generateTicketToken

Generate a 5-byte uppercase hex ticket token for public ticket URLs

f
generateUniqueSlug

Generate a unique slug by retrying until one is not taken.

f
getActiveEventsByGroupId

Get active events in a group with attendee counts.

f
getActiveEventStats

Get aggregated statistics for active events. Filters active events from the provided list, computes attendees (sum of quantities) from cached EventWithCount data, and queries ticket count (rows) and income (sum of decrypted price_paid).

f
getActiveHolidays

Get active holidays (end_date >= today) for date computation (from cache). "today" is computed in the configured timezone.

f
getActivePaymentProvider

Resolve the active payment provider based on admin settings. Lazy-loads the provider module to avoid importing unused SDKs. Returns null if no provider is configured.

f
getAllActivityLog

Get all activity log entries (most recent first)

f
getAllCacheStats

Collect stats from all registered caches

f
getAllDailyEvents

Get all daily events with attendee counts (from cache).

f
getAllEvents

Get all events with attendee counts (from cache)

f
getAllGroups

Get all groups, decrypted, ordered by id (from cache)

f
getAllHolidays

Get all holidays, decrypted, ordered by start_date (from cache)

f
getAllowedDomain

Get allowed domain for security validation (runtime config via Bunny secrets) This is a required configuration that hardens origin validation

f
getAllSessions

Get all sessions ordered by expiration (newest first)

f
getAllStandardEvents

Get all standard events with attendee counts (from cache). Used by the calendar view to include one-time events on their scheduled date.

f
getAllUsers

Get all users (for admin user management page, from cache)

f
getAppleWalletConfig

Get Apple Wallet config for pass generation. DB settings take priority, falls back to env vars.

f
getAppleWalletDbConfig

Get Apple Wallet config from DB (decrypted). Returns null if incomplete.

f
getAttendee

Get an attendee by ID (decrypted) Requires private key for decryption - only available to authenticated sessions

f
getAttendeeRaw

Get an attendee by ID without decrypting PII Used for payment callbacks and webhooks where decryption is not needed Returns the attendee with encrypted fields (id, event_id, quantity are plaintext)

f
getAttendeesByEventIds

Get raw attendees for a set of event IDs. Used by the calendar to load attendees for standard events whose decrypted date matches the selected calendar date.

f
getAttendeesByTokens

Get attendees by ticket tokens (plaintext tokens, looked up via HMAC index) Returns attendees in the same order as the input tokens.

f
getAttendeesRaw

Get attendees for an event without decrypting PII Used for tests and operations that don't need decrypted data

f
getAvailableDates

Compute available booking dates for a daily event. Filters by bookable days of the week and excludes holidays. Returns sorted array of YYYY-MM-DD strings.

f
getBunnyApiKey

Get the Bunny CDN API key from environment

f
getBusinessEmailFromDb

Gets the business email from the database (uses settings cache). Returns decrypted email or empty string if not set.

f
getCachedSession

Return the cached session if already resolved, or undefined if not yet resolved

f
getCdnHostname

Get the CDN hostname derived from ALLOWED_DOMAIN. Replaces ".bunny.run" with ".b-cdn.net" for the CNAME target.

f
getCurrencyCode

Get currency code from database Defaults to GBP if not set

f
getCurrencyCodeFromDb

Get currency code from database

f
getCurrentCsrfToken

Get the most recently generated CSRF token (for synchronous JSX rendering)

f
getCustomDomainLastValidatedFromDb

Get the custom domain last validated timestamp. Returns null if never validated.

f
getDailyEventAttendeeDates

Get distinct attendee dates for daily events. Used for the calendar date picker (lightweight, no attendee data).

f
getDailyEventAttendeesByDate

Get raw attendees for daily events on a specific date. Bounded query: only returns attendees matching the given date.

f
getDateAttendeeCount

Get the total attendee quantity for a specific event + date

f
getDb

Get or create database client

f
getDecimalPlaces

Get the number of decimal places for a currency code

f
getEmailConfig

Read email config from DB settings. Falls back to business email for fromAddress. Returns null if not configured.

f
getEmailTemplate

Get a custom email template (decrypted). Returns null if not customised (use default).

f
getEmailTemplateSet

Get all 3 parts of a custom email template (subject, html, text). Nulls mean "use default".

f
getEmbedHosts

Get allowed embed hosts from database (encrypted, parsed to array) Returns empty array if not configured (embedding allowed from anywhere)

f
getEmbedHostsFromDb

Get allowed embed hosts from database (decrypted) Returns null if not configured (embedding allowed from anywhere)

f
getEnv

Get an environment variable value Checks process.env first (Bunny Edge), falls back to Deno.env (local dev)

f
getEvent

Get a single event by ID (from cache)

f
getEventActivityLog

Get activity log entries for an event (most recent first)

f
getEventsByGroupId

Get all events in a group with attendee counts (including inactive).

f
getEventsBySlugsBatch

Get multiple events by slugs (from cache). Returns events in the same order as the input slugs. Missing or inactive events are returned as null.

f
getEventWithActivityLog

Get event and its activity log in a single database round-trip. Uses batch API to reduce latency for remote databases.

f
getEventWithAttendeeRaw

Get event and a single attendee in a single database round-trip. Used for attendee management pages where we need both the event context and the specific attendee data.

f
getEventWithAttendeesRaw

Get event and all attendees in a single database round-trip. Uses batch API to execute both queries together, reducing latency for remote databases like Turso from 2 RTTs to 1. Computes attendee_count from the attendees array.

f
getEventWithCount

Get event with attendee count (from cache)

f
getEventWithCountBySlug

Get event with attendee count by slug (from cache)

f
getGroupBySlugIndex

Get a single group by slug_index (from cache)

f
getHostAppleWalletConfig

Read Apple Wallet config from environment variables. Returns null if not fully configured.

f
getHostEmailConfig

Read host-level email config from environment variables. Returns null if not fully configured.

f
getIframeMode

Get the current request's iframe mode

f
getImageProxyUrl

Get the proxy URL path for serving a decrypted image. Images are encrypted on CDN, so they must be served through the proxy.

f
getMimeTypeFromFilename

Get the MIME type for an image filename from its extension.

f
getNewestAttendeesRaw

Get the newest attendees across all events without decrypting PII. Used for the admin dashboard to show recent registrations.

f
getNextBookableDate

Get the next available booking date for a daily event. More efficient than getAvailableDates()[0] — stops at first match. Returns null if no bookable dates are available.

f
getPaymentProvider

Get the configured payment provider type Returns null if no provider is configured

f
getPaymentProviderFromDb

Get the configured payment provider type Returns null if no provider is configured

f
getPhonePrefixFromDb

Get the configured phone prefix from database. Returns the country calling code, defaulting to "44" (UK).

f
getPrivateKeyFromSession

Derive the private key from session credentials Used to decrypt attendee PII in admin views Results are cached per session token for 10 seconds

f
getProcessedAttendeeId

Get the attendee ID for an already-processed session Used to return success for idempotent webhook retries

f
getPublicKey

Get the public key for encrypting attendee PII Always available (it's meant to be public)

f
getQueryLog

Return a snapshot of all logged queries

f
getQueryLogStartTime

Return the start time recorded by enableQueryLog()

f
getSession

Get a session by token (with 10s TTL cache) Token is hashed for database lookup

f
getSessionCookieName
No documentation available
f
getSetting

Get a setting value. Reads from the in-memory cache, loading all settings in one query on first access or after TTL expiry.

f
getShowPublicSiteCached

Get the "show public site" setting synchronously from cache. Returns false if the cache is not populated or the setting is not "true". Safe to call from synchronous template code after the settings cache is warmed.

f
getSquareAccessToken

Get Square access token from database (encrypted) Returns null if not configured

f
getSquareLocationId

Get Square location ID from database Returns null if not configured

f
getSquareLocationIdFromDb

Get Square location ID from database Returns null if not configured

f
getSquareSandbox

Get Square sandbox mode setting from database Returns true if sandbox mode is enabled

f
getSquareWebhookSignatureKey

Get Square webhook signature key from database (encrypted) Returns null if not configured

f
getStripePublishableKey

Get Stripe publishable key from environment variable Returns null if not set

f
getStripeSecretKey

Get Stripe secret key from database (encrypted) Returns null if not configured (payments disabled)

f
getStripeWebhookEndpointId

Get Stripe webhook endpoint ID from database Returns null if not configured

f
getStripeWebhookSecret

Get Stripe webhook signing secret from database (encrypted) Automatically configured when Stripe secret key is saved

f
getTermsAndConditionsFromDb

Get terms and conditions text from database (30m cached). Returns null if not configured.

f
getTheme

Get the current theme ("light" or "dark")

f
getThemeFromDb

Get the configured theme from database. Returns "light" or "dark", defaulting to "light".

f
getTimezoneCached

Get the configured timezone synchronously. Reads from the permanent cache, falling back to the TTL settings cache, then to the default timezone. Safe to call from synchronous template code because the middleware populates the settings cache on every request.

f
getTimezoneFromDb

Get the configured timezone from database. Returns the IANA timezone identifier, defaulting to Europe/London. Also populates the permanent timezone cache for sync access via getTimezoneCached().

f
getTz

Get the configured timezone synchronously from cache. Safe to call from synchronous code (templates, helpers) because the settings cache is populated by middleware on every request.

f
getUngroupedEvents

Get ungrouped events (group_id = 0) with attendee counts.

f
getUserById

Get a user by ID (from cache)

f
getUserByInviteCode

Find a user by invite code hash Scans all users, decrypts invite_code_hash, and compares

f
getUserByUsername

Look up a user by username (using blind index, from cache)

f
getWrappedPrivateKey

Get the wrapped private key (needs DATA_KEY to decrypt)

f
groupBy

Group array items by a key function

f
hasAppleWalletConfig

Check if Apple Wallet is configured (DB settings or env vars).

f
hasAppleWalletDbConfig

Check if Apple Wallet DB settings are fully configured (all 5 settings present).

f
hasAvailableSpots

Wrapper for test mocking - delegates to attendeesApi at runtime

f
hasEmailApiKey

Check if an email API key has been configured in the database

f
hashInviteCode

Hash an invite code using SHA-256

f
hashPassword

Hash a password using PBKDF2 Returns format: pbkdf2:iterations:$base64salt:$base64hash

f
hashSessionToken

Hash a session token using SHA-256 Used to store session lookups without exposing the actual token

f
hasPassword

Check if a user has set their password (password_hash is non-empty encrypted value)

f
hasRequiredSessionMetadata

Validate that session metadata contains required fields (name) and either event_id (single) or multi+items (multi). Returns false if validation fails.

f
hasSquareToken

Check if a Square access token has been configured in the database

f
hasStripeKey

Check if a Stripe key has been configured in the database

f
hmacHash

HMAC-SHA256 hash using DB_ENCRYPTION_KEY Used for blind indexes and hashing limited keyspace values Returns deterministic output for same input (unlike encrypt)

f
hmacToBase64

Convert ArrayBuffer to base64 string

f
hmacToHex

Convert ArrayBuffer to hex string

f
hybridDecrypt

Decrypt data using hybrid encryption Expects format: hyb:1:$base64WrappedKey:$base64iv:$base64ciphertext Results are cached in a bounded LRU (ciphertext -> plaintext)

f
hybridEncrypt

Encrypt data using hybrid encryption (RSA + AES)

f
idAndEncryptedSlugSchema

Shared columns for tables with encrypted slug + blind-index slug_index.

f
identity

Identity function

f
importPrivateKey

Import a private key from JWK string

f
importPublicKey

Import a public key from JWK string

f
initDb

Initialize database tables

f
inPlaceholders

Build SQL placeholders for an IN clause, e.g. "?, ?, ?"

f
invalidateEventsCache

Invalidate the events cache (for testing or after writes).

f
invalidateGroupsCache

Invalidate the groups cache (for testing or after writes).

f
invalidateHolidaysCache

Invalidate the holidays cache (for testing or after writes).

f
invalidatePageCache

Clear the entire page content cache (for testing or after bulk changes).

f
invalidateSettingsCache

Invalidate the settings cache (for testing or after writes). Also clears the permanent timezone cache since it derives from settings, and the page content cache since it derives from encrypted settings.

f
invalidateUsersCache

Invalidate the users cache (for testing or after writes).

f
isAdminLevel

Type guard: check if a string is a valid AdminLevel

f
isBunnyCdnEnabled

Check if Bunny CDN pull zone management is enabled Requires BUNNY_API_KEY to be set

f
isContactField

Type guard: check if an arbitrary string is a valid ContactField

f
isDefined

Check if value is not null or undefined

f
isDemoMode

Check if demo mode is enabled

f
isEmailProvider

Type guard: checks if a string is a valid EmailProvider

f
isEventType

Type guard: check if an arbitrary string is a valid EventType

f
isGroupSlugTaken

Check if a group slug is already in use. Checks both events and groups for cross-table uniqueness.

f
isInviteExpired

Check if a user's invite has expired. Callers should skip this for users who have already set a password.

f
isInviteValid

Check if a user's invite is still valid (not expired, has invite code)

f
isLoginRateLimited

Check if IP is rate limited for login

f
isMaskSentinel

Check whether a submitted form value is the mask sentinel (i.e. unchanged)

f
isPaidEvent

Whether an event can accept payments (has a price or allows pay-what-you-want)

f
isPaymentsEnabled

Check if payments are enabled (any provider configured with valid keys)

f
isPaymentStatus

Type guard: check if a string is a valid PaymentStatus

f
isQueryLogEnabled

Whether query logging is currently active

f
isReservationStale

Check if a reservation is stale (abandoned by a crashed process)

f
isSecureMode
No documentation available
f
isSessionProcessed

Check if a payment session has already been processed

f
isSetupComplete

Check if initial setup has been completed Result is cached in memory - once true, we never query again.

f
isSignedCsrfToken

Check whether a token uses the signed format

f
isSlugTaken

Check if a slug is already in use (optionally excluding a specific event ID) Uses slug_index for lookup (blind index)

f
isStorageEnabled

Check if image storage is enabled (both env vars are set)

f
isUsernameTaken

Check if a username is already taken

f
isValidBusinessEmail

Validates a basic email format: something@something.something

f
isValidDatetime

Check if a naive datetime-local string is a parseable datetime. Does not interpret timezone — purely a format check.

f
isValidPemCertificate

Validate that a string is a parseable PEM certificate

f
isValidPemPrivateKey

Validate that a string is a parseable PEM private key

f
isValidTimezone

Validate that a string is a valid IANA timezone identifier.

f
lazyRef

Resettable lazy reference - like once() but can be reset for testing. Returns [get, set] tuple where set(null) resets to uncomputed state.

f
loadAllSettings

Load every setting row into the in-memory cache with a single query.

f
loadCurrencyCode

Load currency code from settings into sync-accessible state. Called once per request in routes/index.ts before templates render. Settings are already cached so this is cheap on repeat calls.

f
loadTheme

Load theme from settings into sync-accessible state. Called once per request in routes/index.ts before templates render. Settings are already cached so this is cheap on repeat calls.

f
localToUtc

Convert a naive datetime-local value (YYYY-MM-DDTHH:MM) to a UTC ISO string, interpreting the value as local time in the given timezone.

f
logActivity

Log an activity

f
logAndNotifyMultiRegistration

Log and send consolidated webhook for multi-event registrations

f
logAndNotifyRegistration

Log attendee registration and send consolidated webhook Used for single-event registrations

f
logDebug

Log a debug message with category prefix For detailed debugging during development

f
logError

Log a classified error to console.error and persist to the activity log. Console output uses error codes and safe metadata (never PII). Activity log entry is encrypted and visible to admins on the log pages.

f
logErrorLocal

Log a classified error to console.error only (no ntfy, no activity log). Use this where calling logError would cause infinite recursion (e.g. ntfy.ts).

f
logRequest

Log a completed request to console.debug Path is automatically redacted for privacy

f
map

Curried map

f
mapParallel

Map over a promise-returning function in parallel (Promise.all)

f
mapSequential

Map over a promise-returning function sequentially (one at a time)

f
markRefunded

Mark an attendee as refunded (set refunded to encrypted "true"). Keeps payment_id intact so payment details can still be viewed.

f
mergeEventFields

Determine which contact fields to collect for multiple events. Returns the union of all field settings, sorted by canonical CONTACT_FIELDS order.

f
normalizeBusinessEmail

Normalizes email: trim and lowercase

f
normalizeDatetime

Normalize datetime-local "YYYY-MM-DDTHH:MM" to full UTC ISO string. The input is interpreted as local time in the given timezone and converted to UTC.

f
normalizePhone

Strip non-numeric characters from a phone number, then prefix if it starts with 0

f
normalizeSlug

Normalize a user-provided slug: trim, lowercase, replace spaces with hyphens

f
now

Current time as a Date

f
nowIso

Full ISO-8601 timestamp for created/logged_at fields

f
nowMs

Epoch milliseconds for numeric comparisons

f
ok

Create a successful result

f
once

Lazy evaluation - compute once on first call, cache forever. Use instead of let x = null; const getX = () => x ??= compute();

f
parseEmbedHosts

Parse a comma-separated list of hosts into trimmed, lowercased entries. Filters out empty strings from trailing commas etc.

f
parseEventFields

Parse a comma-separated fields string into individual ContactField names

f
pick

Pick specific keys from an object

f
pipe

Compose functions left-to-right (pipe) Uses recursive conditional types for arbitrary-length type safety.

f
pipeAsync

Async pipe - compose async functions left-to-right Each function receives the awaited result of the previous one. Uses recursive conditional types for arbitrary-length type safety.

f
processBooking

Process a single-event booking.

f
queryAll

Query all rows, returning a typed array

f
queryAndMap

Execute a SQL query and map result rows through an async transformer.

f
queryBatch

Execute multiple read queries in a single round-trip using Turso batch API. Significantly reduces latency for remote databases.

f
queryOne

Query single row, returning null if not found

f
randomChoice

Pick a random element from an array

f
randomName

Generate a random full name from first name + surname arrays

f
recordFailedLogin

Record a failed login attempt Returns true if the account is now locked

f
redactPath

Redact dynamic segments from paths for privacy-safe logging Replaces:

f
reduce

Curried reduce

f
registerCache

Register a cache stat provider (called at module load time)

f
renderEmailContent

Render all 3 parts (subject, html, text) using custom templates with fallback to defaults

f
renderMarkdown

Render markdown to HTML (block-level: paragraphs, lists, etc.). Raw HTML is escaped.

f
renderMarkdownInline

Render markdown to inline HTML (no wrapping <p> tags). Raw HTML is escaped.

f
renderTemplate

Render a single Liquid template string with the given data

f
requireEnv

Get a required environment variable, throwing if not set. Use this instead of getEnv(key) as string when the variable must exist.

f
reserveSession

Reserve a payment session for processing (first phase of two-phase lock) Inserts with NULL attendee_id to claim the session. Returns { reserved: true } if we claimed it, or { reserved: false, existing } if already claimed.

f
resetCacheRegistry

Reset the registry (for testing)

f
resetCurrencyCode

For testing: reset the currency code to default

f
resetDatabase

Reset the database by dropping all tables

f
resetDemoMode

Reset cached demo mode value (for testing and cache invalidation)

f
resetEngine

For testing: reset the engine (so filters can be re-registered after currency changes)

f
resetGroupEvents

Reset group assignment on all events in a group.

f
resetSessionCache

Clear session cache (exported for testing)

f
resetTheme

For testing: reset the theme to default

f
resultRows

Cast libsql ResultSet rows to a typed array (single centralized assertion)

f
runWithPendingWork

Run a function within a pending-work scope

f
runWithQueryLogContext
No documentation available
f
runWithRequestId

Run a function with a request-scoped random ID for log correlation

f
runWithSessionContext

Run a function within a session-memoization scope

f
safeAsync

Safely execute async operation, returning null on error. Re-throws PaymentUserError so user-facing messages propagate.

f
secureCompare

Constant-time string comparison to prevent timing attacks

f
sendEmail

Send a single email via the configured provider. Logs errors, never throws. Returns HTTP status or undefined on non-HTTP errors.

f
sendNtfyError

Send an error notification to the configured ntfy URL Returns a promise so callers can await delivery if needed. Delivery failures are logged locally (via logErrorLocal) but never throw.

f
sendRegistrationEmails

Send registration confirmation + admin notification emails. Entries is an array because one registration can cover multiple events. Silently skips if email is not configured. Attaches one SVG ticket per entry to the confirmation email.

f
sendRegistrationWebhooks

Send consolidated webhook to all unique webhook URLs for the given entries

f
sendTestEmail

Send a test email to the business email address. Returns HTTP status or undefined on non-HTTP errors.

f
sendWebhook

Send a webhook payload to a URL Fires and forgets - errors are logged but don't block registration

f
serializeMultiItems

Serialize multi-ticket items for metadata storage (compact JSON)

f
setCachedSession

Store the resolved session in the current request scope

f
setCurrencyCodeForTest

For testing: set the currency code directly

f
setDb

Set database client (for testing)

f
setDemoModeForTest

Explicitly set demo mode on or off (for testing). Bypasses Deno.env to avoid races between parallel test workers.

f
setPaymentProvider

Set the active payment provider type

f
setSetting

Set a setting value. Invalidates the cache so the next read will pick up the new value.

f
setStripeWebhookConfig

Store Stripe webhook configuration (secret encrypted, endpoint ID plaintext)

f
setThemeForTest

For testing: set the theme directly

f
setUserPassword

Set a user's password (for invite flow)

f
sha1Hex

Compute SHA-1 hex digest of a Uint8Array

f
signCsrfToken

Create a signed CSRF token: s1.{timestamp}.{nonce}.{hmac}

f
signManifest

Sign the manifest with PKCS#7 detached signature

f
sort

Non-mutating sort with comparator

f
sortBy

Sort by a key or getter function

f
sortEvents

Sort events in unified 3-tier order. Works with any Event subtype (Event, EventWithCount, etc.).

f
toCamelCase

Convert snake_case to camelCase

f
toCheckoutResult

Convert a provider-specific checkout result to a CheckoutSessionResult. Returns null if session ID or URL is missing.

f
todayInTz

Get today's date as YYYY-MM-DD in the given timezone.

f
toMajorUnits

Convert minor units to major units string for form display. e.g. toMajorUnits(1050) → "10.50" (for GBP)

f
toMinorUnits

Convert major units (decimal) to minor units (integer). e.g. toMinorUnits(10.50) → 1050 (for GBP)

f
toSnakeCase

Convert camelCase to snake_case

f
trackQuery

Run an async DB operation and log it when tracking is active

f
tryDeleteImage

Try to delete an image from CDN storage, logging errors on failure

f
ttlCache

Create a TTL (Time-To-Live) cache. Entries expire after ttlMs milliseconds. Accepts an optional clock function for testing.

f
unique

Remove duplicate values (by reference/value equality)

f
uniqueBy

Remove duplicates by a key function

f
unwrapKey

Unwrap a symmetric key Expects format: wk:1:$base64iv:$base64wrapped

f
unwrapKeyWithToken

Unwrap a key using a session token

f
updateAttendee

Update an attendee's information (encrypted fields) Caller must be authenticated admin (public key always exists after setup)

f
updateBusinessEmail

Updates the business email in the database and invalidates the settings cache. Pass empty string to clear the business email. Email is encrypted at rest.

f
updateCheckedIn

Update an attendee's checked_in status (encrypted) Caller must be authenticated admin (public key always exists after setup)

f
updateCustomDomainLastValidated

Update the custom domain last validated timestamp to now (UTC ISO 8601).

f
updateEmailTemplate

Update a custom email template (encrypted at rest). Pass empty string to clear (revert to default).

f
updateEmbedHosts

Update allowed embed hosts (encrypted at rest) Pass empty string to clear the restriction

f
updatePhonePrefix

Update the configured phone prefix.

f
updateSquareLocationId

Store Square location ID (plaintext - not sensitive)

f
updateTermsAndConditions

Update terms and conditions text Pass empty string to clear

f
updateTheme

Update the configured theme.

f
updateTimezone

Update the configured timezone.

f
updateUserPassword

Update a user's password and re-wrap DATA_KEY with new KEK Requires the user's old password hash (decrypted) and their user row

f
uploadImage

Upload an image to Bunny storage. Encrypts the image bytes before uploading. Returns the filename (without path) on success.

f
utcToLocalInput

Convert a UTC ISO datetime string to a datetime-local input value (YYYY-MM-DDTHH:MM) in the given timezone. Used for pre-populating form inputs with timezone-adjusted values.

f
validateCustomDomain

Validate a custom domain (delegates to bunnyCdnApi for testability).

f
validateEmbedHosts

Validate a comma-separated list of host patterns. Returns null if all valid, or the first error message.

f
validateEncryptionKey

Validate encryption key is present and valid Call this on startup to fail fast if key is missing

f
validateHostPattern

Validate a single host pattern Returns null if valid, or an error message if invalid

f
validateImage

Validate an image file: check MIME type, size, and magic bytes.

f
validatePrice

Validate and convert a raw price string to minor units. Returns ok with 0 if raw is empty and minPrice is 0 (pay-what-you-want with no input). Returns error if raw is empty and minPrice > 0, or if parsed value is out of range.

f
validateSlug

Validate a normalized slug. Returns error message or null.

f
validateTemplate

Validate a Liquid template by parsing it (no rendering). Returns null if valid, or an error message string if invalid.

f
verifyPassword

Verify a password against a hash Uses constant-time comparison to prevent timing attacks

f
verifySignedCsrfToken

Verify a signed CSRF token's signature and expiry

f
verifyUserPassword

Verify a user's password (decrypt stored hash, then verify) Returns the decrypted password hash if valid (needed for KEK derivation)

f
wrapKey

Wrap a symmetric key with another key using AES-GCM Returns format: wk:1:$base64iv:$base64wrapped

f
wrapKeyWithToken

Wrap a key using a session token (derives a wrapping key from the token)

f
wrapResourceForDemo

Wrap a named resource so create/update apply demo overrides to the form

f
writeClosesAt

Encrypt closes_at for DB storage (null/empty → encrypted empty)

f
writeEventDate

Encrypt event date for DB storage

Interfaces

Type Aliases

T
ActiveEventStats

Aggregated statistics for active events

T
ActivityLogInput

Activity log input for create

T
AdminLevel

Admin role levels

T
AdminSession

Session data needed by admin page templates

T
AttendeeInput

Input for creating an attendee atomically

T
BatchAvailabilityItem

Item for batch availability check

T
BookingResult

Booking result — callers map this to their response format

T
BoundedLru

Bounded LRU cache returned by boundedLru()

T
CacheStat

A single cache's stats snapshot

T
CheckoutSessionResult

Result of creating a checkout session.

T
CollectionCache

Collection cache returned by collectionCache()

T
ColumnDef

Column definition for a table

T
ContactField

Individual contact field name

T
ContactFields

Required name+email with optional phone/address/special_instructions from ContactInfo

T
ContactInfo

Attendee contact details — the core PII fields collected at registration

T
CreateAttendeeResult

Result of atomic attendee creation

T
DemoFieldMap

Maps form field names to arrays of possible demo values

T
EmailAttachment

A base64-encoded email attachment

T
EmailConfig
No documentation available
T
EmailEntry

Attendee + event pair for email rendering

T
EmailEvent

Event data needed for email rendering (extends webhook event with display fields)

T
EmailProvider

Union of all supported email provider keys, derived from the PROVIDERS map

T
EmailTemplateFormat

Valid email template formats

T
EmailTemplateType

Valid email template types

T
EmbedSnippets
No documentation available
T
ErrorCodeType
No documentation available
T
ErrorContext

Error log context (privacy-safe metadata only)

T
EventFields

Contact fields setting for an event (comma-separated ContactField names, or empty for name-only)

T
EventType

Event type: standard (one-time) or daily (date-based booking)

T
EventWithActivityLog

Result type for event + activity log batch query

T
EventWithAttendeeRaw

Result type for event + single attendee query

T
EventWithAttendees

Result type for combined event + attendees query

T
GroupInput

Group input fields for create/update (camelCase)

T
HolidayInput

Holiday input fields for create/update (camelCase)

T
ImageValidationError

Image validation error

T
ImageValidationResult

Image validation result

T
InputFor

Derive Input type from Row type and Schema

T
LogCategory

Log categories for debug logging

T
MultiRegistrationIntent

Registration intent for multi-event checkout

T
MultiRegistrationItem

Single item within a multi-event checkout

T
PaymentProviderType

Supported payment provider identifiers

T
PaymentStatus

Valid payment status values

T
PriceResult

Result type for price validation

T
QueryLogEntry

A single logged query

T
RegistrationEntry

Registration entry: event + attendee pair

T
RegistrationIntent

Registration intent for a single event checkout

T
ReserveSessionResult

Result of session reservation attempt

T
Result

Result type for operations that can fail with a Response

T
SeedResult

Result of a seed operation

T
SlugWithIndex

Slug-with-index pair

T
TableSchema

Table schema definition Keys are DB column names (snake_case), values are column definitions

T
TemplateData

Data object passed to Liquid templates

T
TtlCache

TTL cache returned by ttlCache()

T
ValidatedPaymentSession

A validated payment session returned after checkout completion

T
WebhookAttendee

Attendee data needed for webhook notifications

T
WebhookEvent

Provider-agnostic webhook event

T
WebhookPayload

Consolidated payload sent to webhook endpoints

T
WebhookSetupResult

Result of webhook endpoint setup

T
WebhookVerifyResult

Result of webhook signature verification

Variables

v
activityLogTable

Activity log table definition message is encrypted - decrypted only for admin view

v
API_AVAILABILITY_EXAMPLE_JSON

Example availability response JSON

v
API_BOOK_FREE_EXAMPLE_JSON

Example free booking response JSON

v
API_BOOK_PAID_EXAMPLE_JSON

Example paid booking response JSON

v
API_BOOK_REQUEST_JSON

Example booking request body

v
API_EXAMPLE_EVENT

Example event matching the webhook example data

v
API_EXAMPLE_PUBLIC_EVENT

The example PublicEvent, produced by toPublicEvent

v
API_LIST_EXAMPLE_JSON

Example list response JSON

v
API_SINGLE_EXAMPLE_JSON

Example single-event response JSON

v
ATTENDEE_DEMO_FIELDS

Attendee PII fields

v
v
v
configApi

Stubbable API for internal calls (testable via spyOn, like stripeApi/squareApi)

v
CONTACT_FIELDS

All valid contact field names (runtime array matching the ContactField union)

v
CSRF_INVALID_FORM_MESSAGE

Default message for invalid/expired CSRF form submissions

v
DAY_NAMES

Day name lookup from Date.getUTCDay() index (Sunday=0)

v
DEFAULT_BOOKABLE_DAYS

Default bookable days (all days of the week)

v
DEFAULT_TIMEZONE

Default timezone when none is configured

v
DEMO_ADDRESSES

Demo addresses

v
DEMO_BANNER

Demo mode banner HTML

v
DEMO_EMAILS

Demo email addresses

v
DEMO_EVENT_DESCRIPTIONS

Demo event descriptions

v
DEMO_EVENT_LOCATIONS

Demo event locations

v
DEMO_EVENT_NAMES

Demo event names

v
DEMO_FIRST_NAMES

Demo first names for seed data (combined with surnames for more variety)

v
DEMO_GROUP_NAMES

Demo group names

v
DEMO_HOLIDAY_NAMES

Demo holiday names

v
DEMO_NAMES

Demo attendee names (full names for demo mode overrides)

v
DEMO_PAGE_TEXT

Demo page text (homepage / contact)

v
DEMO_PHONES

Demo phone numbers (UK format)

v
DEMO_SPECIAL_INSTRUCTIONS

Demo special instructions

v
DEMO_SURNAMES

Demo surnames for seed data (combined with first names for more variety)

v
DEMO_TERMS

Demo terms and conditions

v
DEMO_WEBSITE_TITLES

Demo website titles

v
DOMAIN_PATTERN

Matches a valid hostname like "example.com" or "sub.example.com"

v
EMAIL_PROVIDER_LABELS

Display labels for email providers — keys must match EmailProvider

v
ErrorCode

Error code strings for use in logError calls

v
errorCodeLabel

Human-readable labels for error codes (shown in admin activity log)

v
EVENT_DEMO_FIELDS

Event metadata fields

v
EVENTS_CACHE_TTL_MS

In-memory events cache. Loads all events with attendee counts in a single query and serves subsequent reads from memory until the TTL expires or a write invalidates the cache.

v
eventsTable
No documentation available
v
EXAMPLE_BUSINESS_EMAIL
No documentation available
v
EXAMPLE_CURRENCY
No documentation available
v
EXAMPLE_EVENT

Example inputs used by both the fixture and the test

v
getAppleWalletPassTypeIdFromDb
No documentation available
v
getAppleWalletSigningCertFromDb
No documentation available
v
getAppleWalletSigningKeyFromDb
No documentation available
v
getAppleWalletTeamIdFromDb
No documentation available
v
getAppleWalletWwdrCertFromDb
No documentation available
v
getContactPageTextFromDb
No documentation available
v
getCustomDomainFromDb
No documentation available
v
getEmailApiKeyFromDb
No documentation available
v
getEmailFromAddressFromDb
No documentation available
v
getEmailProviderFromDb
No documentation available
v
getHeaderImageUrlFromDb
No documentation available
v
getHomepageTextFromDb
No documentation available
v
getShowPublicApiFromDb
No documentation available
v
getShowPublicSiteFromDb
No documentation available
v
getSquareAccessTokenFromDb
No documentation available
v
getSquareSandboxFromDb
No documentation available
v
getSquareWebhookSignatureKeyFromDb
No documentation available
v
getStripeSecretKeyFromDb
No documentation available
v
getStripeWebhookSecretFromDb
No documentation available
v
getWebsiteTitleFromDb
No documentation available
v
GROUP_DEMO_FIELDS

Group name field

v
GROUPS_CACHE_TTL_MS

In-memory groups cache. Loads all groups in a single query and serves subsequent reads from memory until the TTL expires or a write invalidates the cache.

v
groupsTable

Groups table with CRUD operations — writes auto-invalidate the cache

v
HOLIDAY_DEMO_FIELDS

Holiday name field

v
HOLIDAYS_CACHE_TTL_MS

In-memory holidays cache. Loads all holidays in a single query and serves subsequent reads from memory until the TTL expires or a write invalidates the cache.

v
holidaysTable

Holidays table with CRUD operations — writes auto-invalidate the cache

v
IMAGE_ERROR_MESSAGES

User-facing messages for image validation errors

v
LATEST_UPDATE

The latest database update identifier - update this when changing schema

v
MASK_SENTINEL

Sentinel value rendered in password fields for configured secrets. The actual secret is never sent to the browser — only this placeholder. On form submission, if the value equals the sentinel, the update is skipped.

v
MAX_EMAIL_TEMPLATE_LENGTH

Max length for email templates

v
MAX_PAGE_TEXT_LENGTH

Max length for page text content

v
MAX_TERMS_LENGTH

Max length for terms and conditions text

v
MAX_WEBSITE_TITLE_LENGTH

Max length for website title

v
paymentsApi

Stubbable API for internal calls (testable via spyOn, like stripeApi/squareApi)

v
SEED_MAX_ATTENDEES

Max attendees per seeded event

v
SETTINGS_CACHE_TTL_MS

In-memory settings cache. Loads all rows in a single query and serves subsequent reads from memory until the TTL expires or a write invalidates the cache.

v
settingsApi

Stubbable API for testing - allows mocking in ES modules Use spyOn(settingsApi, "method") instead of spyOn(settingsModule, "method")

v
SITE_CONTACT_DEMO_FIELDS

Site contact page fields

v
SITE_HOME_DEMO_FIELDS

Site homepage fields

v
STALE_RESERVATION_MS

Threshold for considering an unfinalized reservation abandoned (5 minutes)

v
TERMS_DEMO_FIELDS

Terms and conditions field

v
updateAppleWalletPassTypeId
No documentation available
v
updateAppleWalletSigningCert
No documentation available
v
updateAppleWalletSigningKey
No documentation available
v
updateAppleWalletTeamId
No documentation available
v
updateAppleWalletWwdrCert
No documentation available
v
updateContactPageText
No documentation available
v
updateCustomDomain
No documentation available
v
updateEmailApiKey
No documentation available
v
updateEmailFromAddress
No documentation available
v
updateEmailProvider
No documentation available
v
updateHeaderImageUrl
No documentation available
v
updateHomepageText
No documentation available
v
updateShowPublicApi
No documentation available
v
updateShowPublicSite
No documentation available
v
updateSquareAccessToken
No documentation available
v
updateSquareSandbox
No documentation available
v
updateSquareWebhookSignatureKey
No documentation available
v
updateStripeKey
No documentation available
v
updateWebsiteTitle
No documentation available
v
USERS_CACHE_TTL_MS

In-memory users cache. Loads all rows in a single query and serves subsequent reads from memory until the TTL expires or a write invalidates the cache.

v
VALID_EMAIL_PROVIDERS

Valid provider names, derived from the PROVIDERS map

v
WALLET_ICONS

Decoded icon files for inclusion in .pkpass bundles

v
WEBHOOK_EXAMPLE_JSON

Pretty-printed JSON for embedding in documentation

v
WEBHOOK_EXAMPLE_PAYLOAD

The example payload, matching what buildWebhookPayload would produce

Usage

import * as mod from "doc.ts";