Core Server Module
The packages/core/src/server directory houses a collection of server-side modules crucial for the application's backend operations. These modules handle tasks ranging from third-party API interactions and security to request handling and utility functions. Below is a breakdown of the modules, grouped by their primary area of responsibility.
Monday.com Integration
This group of modules facilitates communication with the Monday.com platform.
monday-api.ts: This file provides a foundationalMondayApiClientclass. It is a generic client designed to interact with the Monday.com GraphQL API (v2). The client handles the construction of HTTP POST requests, including authentication via an API token, and processes responses, throwing errors if the API returns issues or GraphQL errors.monday.service.ts: Building upon theMondayApiClient, this service offers more specialised functionality for interacting with Monday.com. TheMondayServiceclass is tailored for specific operations, such as creating new contacts within a designated CRM board. It manages the retrieval of the Monday.com API key from environment variables and encapsulates the logic for formatting data according to the specific requirements of the CRM board's columns. It also includes a lazy-loading pattern for the service instance to ensure it's initialised only when needed and can handle potential initialisation failures gracefully during build time.
API Authentication and Security
These modules are central to securing the application's API endpoints.
api-auth.ts: This module is responsible for the validation of API keys. ThevalidateApiKeyfunction checks a provided API key against active keys stored in a Supabase database. It retrieves encrypted keys, decrypts them using theencryption.tsmodule, and if a match is found, updates alast_used_attimestamp for the key. It returns whether the key is valid, the associated user ID, and any error messages.api-middleware.ts: This file provides SvelteKit middleware,requireApiKey, to protect API routes. The middleware first checks if a user is authenticated via a standard session. If no session exists, it attempts to extract an API key from the request headers (supportingx-api-keyor theAuthorization: Bearerscheme). It then usesvalidateApiKeyfromapi-auth.tsto verify the key. Access is granted or denied based on the validation outcome.encryption.ts: This module supplies essential encryption and decryption services using the AES-GCM algorithm. It includesencryptanddecryptfunctions, along with helper utilities for converting data between hexadecimal strings andUint8Arraybyte arrays (hexToBytes,bytesToHex), importing cryptographic keys (getKey), and generating cryptographically secure random strings (generateRandomString). A key feature is the lazy loading of thePRIVATE_ENCRYPTION_KEYfrom environment variables, ensuring it's accessed only when required and after environment bindings are available in serverless environments.
HTTP Utilities
This category contains general-purpose utilities for handling HTTP-related tasks.
response-utils.ts: This module exports a single utility function,cloneResponse. Its purpose is to create a newResponseobject that is a deep copy of an originalResponse(body stream, status, status text, and headers). This is particularly useful for ensuring compatibility across different JavaScript runtimes, such as between Cloudflare Miniflare (used during local development with Wrangler) and the Node.js runtime used by SvelteKit, which may have distinct globalResponseconstructors.
Email Services
This module is dedicated to sending emails, both to administrators and application users, utilising the Resend email platform.
mailer.ts: This file provides functionalities for dispatching emails. It includes:sendAdminEmail: A function to send notification emails to a pre-configured administrator email address. It gracefully handles scenarios where Resend API keys are not configured.sendUserEmail: A function designed to send emails to application users. Before sending, it performs several crucial checks: verifies the user's email address is confirmed (checking bothemail_confirmed_atanduser_metadata.email_verifiedvia a Supabase admin client), and checks if the user has unsubscribed from emails by looking up their profile in the Supabase database.sendTemplatedEmail: A core function that handles the actual sending of emails via Resend. It supports sending emails with directly provided plaintext or HTML bodies. Alternatively, it can use Handlebars (.hbs) templates for both HTML and plaintext versions of an email. It attempts to load these templates (e.g.,template_name_text.hbs,template_name_html.hbs) from anemails/subdirectory. The function ensures that email sending is skipped if API keys are missing or if no email content (from direct input or templates) can be generated. It relies on environment variables for API keys and sender addresses, fetched viaruntimeEnv.ts.
Cross-Cutting Utilities
These modules offer general-purpose functionalities utilised across various server-side operations.
runtimeEnv.ts: This utility module provides a robust, runtime-agnostic method for accessing environment variables. ThegetEnv(name: string)function is designed to work consistently across different JavaScript execution environments:- Cloudflare Workers / Durable Objects: It checks for
globalThis.__workerEnv, which is expected to be populated by the execution environment. - Node.js / SvelteKit: It falls back to
process.envif__workerEnvis not found. - Vite (dev/build): It further falls back to
import.meta.envfor variables injected by Vite during development or build processes. A fallback mechanism also copiesprocess.envtoglobalThis.__workerEnvin non-worker runtimes if__workerEnvisn't initially set, ensuringgetEnv()works during SvelteKit build/prerender phases.
- Cloudflare Workers / Durable Objects: It checks for
load_helpers.ts: This module contains theload_helperasynchronous function, designed to consistently retrieve user session and user data in SvelteKitloadfunctions, whether on the server or in the browser.- On the server, it uses the
server_sessionpassed in (typically populated by hooks likeauthGuard). - In the browser (
isBrowser() === true), it explicitly callssupabase.auth.getSession()to fetch the current session. - It then attempts to retrieve the full user object using
supabase.auth.getUser(). - It includes a workaround for a Supabase auth client warning (
suppressGetSessionWarning) related togetSessioncalls. - It returns an object containing the
sessionanduser, ornullfor both if a session/user cannot be established.
- On the server, it uses the
Module Exports
index.ts: This file acts as the primary CJS-compatible export point for all modules within thepackages/core/src/serverdirectory. It re-exports all the functionalities from the aforementioned files, providing a consolidated and convenient way for other parts of the application to import these server-side utilities.