Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🔥 Remove standalone API app (apps/api) (#2444)
Luke Vella6a88b9edf036
diff --git a/apps/api/.env.sample b/apps/api/.env.sampledeleted file mode 100644index 7a90150be..000000000--- a/apps/api/.env.sample+++ /dev/null@@ -1,16 +0,0 @@-# A connection string to your Postgres database (required)-DATABASE_URL=postgres://postgres:postgres@localhost:5450/rallly--# The base URL of the web app, used to build adminUrl/inviteUrl in API responses (required)-WEB_BASE_URL=https://web.local.rallly.co--# Optional short URL base for invite links. Defaults to WEB_BASE_URL.-WEB_SHORT_URL=--# Port the API server listens on (defaults to 4000)-PORT=4000--# Upstash Redis for distributed rate limiting (optional)-# When unset, hono-rate-limiter falls back to in-memory.-KV_REST_API_URL=-KV_REST_API_TOKEN=diff --git a/apps/api/.gitignore b/apps/api/.gitignoredeleted file mode 100644index 849ddff3b..000000000--- a/apps/api/.gitignore+++ /dev/null@@ -1 +0,0 @@-dist/diff --git a/apps/api/package.json b/apps/api/package.jsondeleted file mode 100644index ed3351d69..000000000--- a/apps/api/package.json+++ /dev/null@@ -1,37 +0,0 @@-{- "name": "@rallly/api",- "version": "0.0.0",- "private": true,- "main": "dist/index.js",- "scripts": {- "dev": "portless api.local.rallly tsx watch --clear-screen=false --include 'src/**/*.ts' --env-file-if-exists=.env src/index.ts",- "build": "tsc",- "start": "node --env-file-if-exists=.env dist/index.js",- "test:unit": "vitest run",- "type-check": "tsc --noEmit"- },- "dependencies": {- "@hono-rate-limiter/redis": "^0.1.4",- "@hono/node-server": "^1.19.9",- "@hono/zod-openapi": "^1.2.0",- "@rallly/api-core": "workspace:*",- "@rallly/database": "workspace:*",- "@rallly/logger": "workspace:*",- "@rallly/utils": "workspace:*",- "@scalar/hono-api-reference": "^0.9.30",- "@t3-oss/env-core": "^0.13.10",- "@upstash/redis": "^1.36.2",- "dayjs": "^1.11.13",- "hono": "^4.11.1",- "hono-openapi": "^1.1.2",- "hono-rate-limiter": "^0.2.1",- "zod": "^4.3.6"- },- "devDependencies": {- "@rallly/tsconfig": "workspace:*",- "@types/node": "^24.1.0",- "tsx": "^4.6.2",- "typescript": "^5.8.2",- "vitest": "^4.0.16"- }-}diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsdeleted file mode 100644index 3bb458ec4..000000000--- a/apps/api/src/app.ts+++ /dev/null@@ -1,41 +0,0 @@-import { Scalar } from "@scalar/hono-api-reference";-import { Hono } from "hono";-import { openAPIRouteHandler } from "hono-openapi";-import { polls } from "./routes/polls";-import { updates } from "./routes/updates";--export const app = new Hono();--app.get("/health", (c) => c.json({ ok: true }));--app.route("/v1/polls", polls);-app.route("/updates", updates);--app.get(- "/openapi",- openAPIRouteHandler(app, {- documentation: {- info: {- title: "Rallly API",- version: "0.0.1",- },- components: {- securitySchemes: {- bearerAuth: {- type: "http",- scheme: "bearer",- },- },- },- },- }),-);--app.get(- "/docs",- Scalar({- url: "/openapi",- pageTitle: "Rallly API Documentation",- theme: "purple",- }),-);diff --git a/apps/api/src/env.ts b/apps/api/src/env.tsdeleted file mode 100644index 27239a83d..000000000--- a/apps/api/src/env.ts+++ /dev/null@@ -1,15 +0,0 @@-import { createEnv } from "@t3-oss/env-core";-import * as z from "zod";--export const env = createEnv({- server: {- DATABASE_URL: z.url(),- KV_REST_API_URL: z.url().optional(),- KV_REST_API_TOKEN: z.string().optional(),- PORT: z.coerce.number().int().positive().default(4000),- WEB_BASE_URL: z.url(),- WEB_SHORT_URL: z.url().optional(),- },- runtimeEnv: process.env,- emptyStringAsUndefined: true,-});diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsdeleted file mode 100644index c38ad9c7d..000000000--- a/apps/api/src/index.ts+++ /dev/null@@ -1,5 +0,0 @@-import { serve } from "@hono/node-server";-import { app } from "./app";-import { env } from "./env";--serve({ fetch: app.fetch, port: env.PORT });diff --git a/apps/api/src/lib/redis.ts b/apps/api/src/lib/redis.tsdeleted file mode 100644index 095c47081..000000000--- a/apps/api/src/lib/redis.ts+++ /dev/null@@ -1,26 +0,0 @@-import { createLogger } from "@rallly/logger";-import { Redis } from "@upstash/redis";-import { env } from "../env";--const logger = createLogger("api/lib/redis");--function createRedis() {- if (!env.KV_REST_API_URL || !env.KV_REST_API_TOKEN) {- return null;- }-- try {- return new Redis({- url: env.KV_REST_API_URL,- token: env.KV_REST_API_TOKEN,- });- } catch (error) {- logger.error(- { error },- "Redis has been configured but failed to initialize Redis client",- );- return null;- }-}--export const redis = createRedis();diff --git a/apps/api/src/middleware/api-key.ts b/apps/api/src/middleware/api-key.tsdeleted file mode 100644index 587828ddd..000000000--- a/apps/api/src/middleware/api-key.ts+++ /dev/null@@ -1,84 +0,0 @@-import crypto from "node:crypto";-import {- extractApiKeyPrefix,- verifyApiKey,-} from "@rallly/api-core/auth/api-key";-import { prisma } from "@rallly/database";-import { createLogger } from "@rallly/logger";-import { bearerAuth } from "hono/bearer-auth";--const logger = createLogger("api/middleware/api-key");--export const spaceApiKeyAuth = bearerAuth({- verifyToken: async (rawKey, c) => {- const prefix = extractApiKeyPrefix(rawKey);- const prefixBuffer = Buffer.from(prefix);-- // Query candidate keys to avoid timing attack via database lookup- // We use a partial prefix match to narrow the search space- const now = new Date();- const candidateKeys = await prisma.spaceApiKey.findMany({- where: {- prefix: {- startsWith: prefix.slice(0, Math.min(4, prefix.length)),- },- revokedAt: null,- OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],- },- select: {- id: true,- prefix: true,- spaceId: true,- hashedKey: true,- expiresAt: true,- revokedAt: true,- space: {- select: {- ownerId: true,- },- },- },- });-- let apiKeyId: string | null = null;- let spaceId: string | null = null;- let spaceOwnerId: string | null = null;- for (const candidate of candidateKeys) {- // Timing-safe prefix comparison- const candidateBuffer = Buffer.from(candidate.prefix);- if (- prefixBuffer.length === candidateBuffer.length &&- crypto.timingSafeEqual(prefixBuffer, candidateBuffer)- ) {- // Verify the full key hash- const isValid = await verifyApiKey(rawKey, candidate.hashedKey);- if (isValid) {- apiKeyId = candidate.id;- spaceId = candidate.spaceId;- spaceOwnerId = candidate.space.ownerId;- }- }- }-- if (!apiKeyId || !spaceId || !spaceOwnerId) {- return false;- }-- c.set("apiAuth", {- spaceId,- spaceOwnerId,- apiKeyId,- });-- prisma.spaceApiKey- .update({- where: { id: apiKeyId },- data: { lastUsedAt: new Date() },- })- .catch((error) => {- logger.error({ error, apiKeyId }, "failed to update lastUsedAt");- });-- return true;- },-});diff --git a/apps/api/src/routes/polls.ts b/apps/api/src/routes/polls.tsdeleted file mode 100644index f68287ec5..000000000--- a/apps/api/src/routes/polls.ts+++ /dev/null@@ -1,568 +0,0 @@-import { RedisStore } from "@hono-rate-limiter/redis";-import {- getPollParticipants,- getPollResults,-} from "@rallly/api-core/polls/data";-import { createPoll, deletePoll } from "@rallly/api-core/polls/mutations";-import { prisma } from "@rallly/database";-import { Hono } from "hono";-import { describeRoute, resolver, validator } from "hono-openapi";-import { rateLimiter } from "hono-rate-limiter";-import { env } from "../env";-import { redis } from "../lib/redis";-import { spaceApiKeyAuth } from "../middleware/api-key";-import {- createPollInputSchema,- createPollSuccessResponseSchema,- deletePollSuccessResponseSchema,- errorResponseSchema,- getPollParticipantsSuccessResponseSchema,- getPollResultsSuccessResponseSchema,- getPollSuccessResponseSchema,-} from "../schemas";-import { apiError } from "../utils/error";-import type { SlotGeneratorInput } from "../utils/time-slots";-import {- dedupeTimeSlots,- generateTimeSlots,- parseStartTime,-} from "../utils/time-slots";--type Env = {- Variables: {- apiAuth: {- spaceId: string;- spaceOwnerId: string;- apiKeyId: string;- };- };-};--export const polls = new Hono<Env>();-const app = polls;--const MAX_OPTIONS = 100;--app.post(- "/",- spaceApiKeyAuth,- rateLimiter<Env>({- windowMs: 60 * 1000,- limit: 60,- keyGenerator: (c) => {- const { apiKeyId } = c.get("apiAuth");- return `private-api:polls-create:${apiKeyId}`;- },- store: redis ? new RedisStore({ client: redis }) : undefined,- }),- describeRoute({- tags: ["Polls"],- summary: "Create a poll",- description:- "Creates a new poll with the specified options or slot generators.",- security: [{ bearerAuth: [] }],- responses: {- 200: {- description: "Successful response",- content: {- "application/json": {- schema: resolver(createPollSuccessResponseSchema),- },- },- },- 400: {- description: "Invalid input or no valid options generated",- content: {- "application/json": {- schema: resolver(errorResponseSchema),- },- },- },- },- }),- validator("json", createPollInputSchema),- async (c) => {- const input = c.req.valid("json");- const { spaceId, spaceOwnerId } = c.get("apiAuth");-- // Determine the organizer userId- let organizerUserId = spaceOwnerId;-- if (input.organizer) {- const spaceMember = await prisma.spaceMember.findFirst({- where: {- spaceId,- user: {- email: input.organizer.email,- },- },- include: {- user: {- select: { id: true, email: true },- },- },- });-- if (!spaceMember) {- return c.json(- apiError(- "ORGANIZER_NOT_MEMBER",- "The specified organizer is not a member of this space.",- ),- 400,- );- }-- organizerUserId = spaceMember.user.id;- }-- // Process dates (all-day options)- if (input.dates) {- if (input.dates.length > MAX_OPTIONS) {- return c.json(- apiError(- "TOO_MANY_OPTIONS",- `Too many options (${input.dates.length}). Maximum allowed is ${MAX_OPTIONS}.`,- ),- 400,- );- }-- const uniqueDates = [...new Set(input.dates)];- if (uniqueDates.length < input.dates.length) {- const duplicateCount = input.dates.length - uniqueDates.length;- return c.json(- apiError(- "DUPLICATE_DATES",- `Duplicate dates found. Please remove ${duplicateCount} duplicate date${duplicateCount > 1 ? "s" : ""}.`,- ),- 400,- );- }-- const options = uniqueDates.map((date) => ({- startTime: new Date(`${date}T00:00:00.000Z`),- duration: 0,- }));-- const poll = await createPoll({- userId: organizerUserId,- title: input.title,- description: input.description,- location: input.location,- requireParticipantEmail: input.requireEmail,- hideParticipants: input.hideParticipants,- hideScores: input.hideScores,- disableComments: input.disableComments,- options,- spaceId,- });-- return c.json({- data: {- id: poll.id,- title: poll.title,- description: poll.description,- location: poll.location,- timezone: poll.timeZone,- status: poll.status,- createdAt: poll.createdAt.toISOString(),- user: poll.user- ? {- name: poll.user.name,- image: poll.user.image,- }- : null,- options: poll.options.map((option) => ({- id: option.id,- startTime: option.startTime.toISOString(),- duration: option.duration,- })),- adminUrl: `${env.WEB_BASE_URL}/poll/${poll.id}`,- inviteUrl: `${env.WEB_SHORT_URL ?? env.WEB_BASE_URL}/invite/${poll.id}`,- },- });- }-- // Process slots (time-based options)- if (!input.slots) {- return c.json(- apiError("INVALID_INPUT", "Either 'dates' or 'slots' must be provided"),- 400,- );- }-- const slots = input.slots;- const timeZone = slots.timezone;-- const duration = slots.duration;- const times = Array.isArray(slots.times) ? slots.times : [slots.times];-- const timeSlots = times.flatMap((time) => {- if (typeof time === "string") {- return parseStartTime(time, timeZone, duration);- }- const slotGenerator: SlotGeneratorInput = {- startDate: time.startDate,- endDate: time.endDate,- daysOfWeek: time.days,- fromTime: time.startTime,- toTime: time.endTime,- interval: time.interval,- };- return generateTimeSlots(slotGenerator, timeZone, duration);- });-- const options = dedupeTimeSlots(timeSlots);-- if (!options.length) {- return c.json(- apiError(- "NO_OPTIONS_GENERATED",- "No valid options were generated. Check that your slot generators produce valid time slots.",- ),- 400,- );- }-- if (options.length > MAX_OPTIONS) {- return c.json(- apiError(- "TOO_MANY_OPTIONS",- `Too many options generated (${options.length}). Maximum allowed is ${MAX_OPTIONS}.`,- ),- 400,- );- }-- const poll = await createPoll({- userId: organizerUserId,- title: input.title,- description: input.description,- location: input.location,- timeZone,- requireParticipantEmail: input.requireEmail,- hideParticipants: input.hideParticipants,- hideScores: input.hideScores,- disableComments: input.disableComments,- options,- spaceId,- });-- return c.json({- data: {- id: poll.id,- title: poll.title,- description: poll.description,- location: poll.location,- timezone: poll.timeZone,- status: poll.status,- createdAt: poll.createdAt.toISOString(),- user: poll.user- ? {- name: poll.user.name,- image: poll.user.image,- }- : null,- options: poll.options.map((option) => ({- id: option.id,- startTime: option.startTime.toISOString(),- duration: option.duration,- })),- adminUrl: `${env.WEB_BASE_URL}/poll/${poll.id}`,- inviteUrl: `${env.WEB_SHORT_URL ?? env.WEB_BASE_URL}/invite/${poll.id}`,- },- });- },-);--app.get(- "/:pollId",- spaceApiKeyAuth,- rateLimiter<Env>({- windowMs: 60 * 1000,- limit: 120,- keyGenerator: (c) => {- const { apiKeyId } = c.get("apiAuth");- return `private-api:polls-get:${apiKeyId}`;- },- store: redis ? new RedisStore({ client: redis }) : undefined,- }),- describeRoute({- tags: ["Polls"],- summary: "Get a poll",- description:- "Retrieves poll metadata by ID. The poll must belong to the space associated with the API key.",- security: [{ bearerAuth: [] }],- responses: {- 200: {- description: "Successful response",- content: {- "application/json": {- schema: resolver(getPollSuccessResponseSchema),- },- },- },- 404: {- description: "Poll not found",- content: {- "application/json": {- schema: resolver(errorResponseSchema),- },- },- },- },- }),- async (c) => {- const { pollId } = c.req.param();- const { spaceId } = c.get("apiAuth");-- const poll = await prisma.poll.findFirst({- where: {- id: pollId,- spaceId,- deleted: false,- },- select: {- id: true,- title: true,- description: true,- location: true,- timeZone: true,- status: true,- createdAt: true,- user: {- select: {- name: true,- image: true,- },- },- options: {- select: {- id: true,- startTime: true,- duration: true,- },- orderBy: {- startTime: "asc",- },- },- },- });-- if (!poll) {- return c.json(- apiError(- "POLL_NOT_FOUND",- "Poll not found or does not belong to this space.",- ),- 404,- );- }-- return c.json({- data: {- id: poll.id,- title: poll.title,- description: poll.description,- location: poll.location,- timezone: poll.timeZone,- status: poll.status,- createdAt: poll.createdAt.toISOString(),- user: poll.user- ? {- name: poll.user.name,- image: poll.user.image,- }- : null,- options: poll.options.map((option) => ({- id: option.id,- startTime: option.startTime.toISOString(),- duration: option.duration,- })),- adminUrl: `${env.WEB_BASE_URL}/poll/${poll.id}`,- inviteUrl: `${env.WEB_SHORT_URL ?? env.WEB_BASE_URL}/invite/${poll.id}`,- },- });- },-);--app.get(- "/:pollId/results",- spaceApiKeyAuth,- rateLimiter<Env>({- windowMs: 60 * 1000,- limit: 120,- keyGenerator: (c) => {- const { apiKeyId } = c.get("apiAuth");- return `private-api:polls-results:${apiKeyId}`;- },- store: redis ? new RedisStore({ client: redis }) : undefined,- }),- describeRoute({- tags: ["Polls"],- summary: "Get poll results",- description:- "Retrieves aggregated voting results for a poll. Returns vote counts per option without individual participant data.",- security: [{ bearerAuth: [] }],- responses: {- 200: {- description: "Successful response",- content: {- "application/json": {- schema: resolver(getPollResultsSuccessResponseSchema),- },- },- },- 404: {- description: "Poll not found",- content: {- "application/json": {- schema: resolver(errorResponseSchema),- },- },- },- },- }),- async (c) => {- const { pollId } = c.req.param();- const { spaceId } = c.get("apiAuth");-- const data = await getPollResults({ pollId, spaceId });-- if (!data) {- return c.json(- apiError(- "POLL_NOT_FOUND",- "Poll not found or does not belong to this space.",- ),- 404,- );- }-- return c.json({- data,- });- },-);--app.get(- "/:pollId/participants",- spaceApiKeyAuth,- rateLimiter<Env>({- windowMs: 60 * 1000,- limit: 120,- keyGenerator: (c) => {- const { apiKeyId } = c.get("apiAuth");- return `private-api:polls-participants:${apiKeyId}`;- },- store: redis ? new RedisStore({ client: redis }) : undefined,- }),- describeRoute({- tags: ["Polls"],- summary: "Get poll participants",- description:- "Retrieves all participants and their votes for a poll. The poll must belong to the space associated with the API key.",- security: [{ bearerAuth: [] }],- responses: {- 200: {- description: "Successful response",- content: {- "application/json": {- schema: resolver(getPollParticipantsSuccessResponseSchema),- },- },- },- 404: {- description: "Poll not found",- content: {- "application/json": {- schema: resolver(errorResponseSchema),- },- },- },- },- }),- async (c) => {- const { pollId } = c.req.param();- const { spaceId } = c.get("apiAuth");-- const data = await getPollParticipants({ pollId, spaceId });-- if (!data) {- return c.json(- apiError(- "POLL_NOT_FOUND",- "Poll not found or does not belong to this space.",- ),- 404,- );- }-- return c.json({- data,- });- },-);--app.delete(- "/:pollId",- spaceApiKeyAuth,- rateLimiter<Env>({- windowMs: 60 * 1000,- limit: 60,- keyGenerator: (c) => {- const { apiKeyId } = c.get("apiAuth");- return `private-api:polls-delete:${apiKeyId}`;- },- store: redis ? new RedisStore({ client: redis }) : undefined,- }),- describeRoute({- tags: ["Polls"],- summary: "Delete a poll",- description:- "Deletes a poll by ID. The poll must belong to the space associated with the API key.",- security: [{ bearerAuth: [] }],- responses: {- 200: {- description: "Poll deleted successfully",- content: {- "application/json": {- schema: resolver(deletePollSuccessResponseSchema),- },- },- },- 404: {- description: "Poll not found",- content: {- "application/json": {- schema: resolver(errorResponseSchema),- },- },- },- },- }),- async (c) => {- const { pollId } = c.req.param();- const { spaceId } = c.get("apiAuth");-- const result = await deletePoll(pollId, spaceId);-- if (!result) {- return c.json(- apiError(- "POLL_NOT_FOUND",- "Poll not found or does not belong to this space.",- ),- 404,- );- }-- return c.json({- data: {- id: result.id,- deleted: true as const,- },- });- },-);diff --git a/apps/api/src/routes/updates.ts b/apps/api/src/routes/updates.tsdeleted file mode 100644index c0eb3f9ff..000000000--- a/apps/api/src/routes/updates.ts+++ /dev/null@@ -1,130 +0,0 @@-import { RedisStore } from "@hono-rate-limiter/redis";-import { prisma } from "@rallly/database";-import { createLogger } from "@rallly/logger";-import { Hono } from "hono";-import { rateLimiter } from "hono-rate-limiter";-import * as z from "zod";-import { redis } from "../lib/redis";-import { apiError } from "../utils/error";--const logger = createLogger("api/routes/updates");--const GITHUB_RELEASES_URL =- "https://api.github.com/repos/lukevella/rallly/releases/latest";--const upstreamSchema = z.object({- tag_name: z.string().min(1),- html_url: z.string().min(1),- published_at: z.string().min(1),-});--type UpdatesPayload = {- latest: string;- url: string;- publishedAt: string;-};--const versionSchema = z- .string()- .max(64)- .regex(/^v?\d+(\.\d+){0,2}([-+][0-9A-Za-z.-]+)?$/);-const instanceIdSchema = z.uuid();--const LATEST_RELEASE_KEY = "updates:latest-release:latest";-const LATEST_RELEASE_TTL_SECONDS = 60 * 60;-const SEEN_INSTANCE_TTL_SECONDS = 60 * 60 * 24;-const seenInstanceKey = (instanceId: string) =>- `updates:seen-instance:${instanceId}`;--async function fetchLatestRelease(): Promise<UpdatesPayload | null> {- const res = await fetch(GITHUB_RELEASES_URL, {- headers: {- Accept: "application/vnd.github+json",- "User-Agent": "Rallly",- },- });- if (!res.ok) return null;-- const parsed = upstreamSchema.safeParse(await res.json());- if (!parsed.success) return null;-- return {- latest: parsed.data.tag_name,- url: parsed.data.html_url,- publishedAt: parsed.data.published_at,- };-}--async function getLatestRelease(): Promise<UpdatesPayload | null> {- if (redis) {- const cached = await redis.get<UpdatesPayload>(LATEST_RELEASE_KEY);- if (cached) return cached;- }-- const fresh = await fetchLatestRelease();- if (fresh && redis) {- await redis.set(LATEST_RELEASE_KEY, fresh, {- ex: LATEST_RELEASE_TTL_SECONDS,- });- }- return fresh;-}--async function recordSeenInstance(instanceId: string, version: string) {- if (redis) {- const cachedVersion = await redis.get<string>(seenInstanceKey(instanceId));- if (cachedVersion === version) return;- }-- await prisma.registeredInstance.upsert({- where: { instanceId },- create: { instanceId, version },- update: { version, lastSeenAt: new Date() },- });-- if (redis) {- await redis.set(seenInstanceKey(instanceId), version, {- ex: SEEN_INSTANCE_TTL_SECONDS,- });- }-}--export const updates = new Hono();--updates.get(- "/",- rateLimiter({- windowMs: 60 * 60 * 1000,- limit: 60,- keyGenerator: (c) => {- const ip =- c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";- return `updates:rate-limit:${ip}`;- },- store: redis ? new RedisStore({ client: redis }) : undefined,- }),- async (c) => {- const payload = await getLatestRelease();-- if (!payload) {- return c.json(- apiError("UPSTREAM_UNAVAILABLE", "Upstream is unavailable."),- 502,- );- }-- const parsedVersion = versionSchema.safeParse(c.req.query("version"));- const parsedInstanceId = instanceIdSchema.safeParse(- c.req.query("instanceId"),- );-- if (parsedVersion.success && parsedInstanceId.success) {- void recordSeenInstance(parsedInstanceId.data, parsedVersion.data).catch(- (error) =>- logger.error({ error }, "Failed to upsert RegisteredInstance"),- );- }-- return c.json(payload);- },-);diff --git a/apps/api/src/schemas.ts b/apps/api/src/schemas.tsdeleted file mode 100644index d14312791..000000000--- a/apps/api/src/schemas.ts+++ /dev/null@@ -1,272 +0,0 @@-import { z } from "@hono/zod-openapi";-import { timezoneSchema } from "./utils/timezone-schema";--export const dateSchema = z.iso.date().openapi({- description: "Date in YYYY-MM-DD format",- example: "2025-12-23",-});--export const timeSchema = z.iso.time().openapi({- description: "Time in HH:mm (24-hour) format",- example: "09:30",-});--export const slotGeneratorSchema = z- .object({- startDate: dateSchema,- endDate: dateSchema,- days: z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])),- startTime: timeSchema,- endTime: timeSchema,- interval: z.number().int().min(15).max(1440).optional().openapi({- description: "Interval in minutes between slots. Defaults to duration.",- example: 30,- }),- })- .openapi("SlotGenerator");--const slotsInputSchema = z- .object({- duration: z.number().int().min(15).max(1440).openapi({- description: "Duration in minutes for each time slot",- example: 30,- }),- timezone: timezoneSchema.optional().openapi({- description:- "IANA timezone. If not provided, times will be stored as UTC and no timezone will be set on the poll (indicating floating times).",- example: "Europe/London",- }),- times: z- .array(- z.union([- z.iso.datetime().openapi({- description: "ISO datetime start time",- example: "2025-01-15T09:00:00Z",- }),- slotGeneratorSchema,- ]),- )- .min(1)- .openapi({- description:- "Times to include. An array of ISO datetime strings and/or slot generators.",- }),- })- .openapi("SlotsInput");--const datesInputSchema = z- .array(z.iso.date())- .min(1)- .openapi({- description: "Array of ISO dates for all-day options",- example: ["2025-01-15", "2025-01-16", "2025-01-17"],- });--export const createPollInputSchema = z- .object({- title: z.string().trim().min(1).openapi({ example: "Team sync" }),- description: z- .string()- .trim()- .max(1000)- .optional()- .openapi({ example: "Pick a time that works for everyone" }),- location: z- .string()- .trim()- .max(255)- .optional()- .openapi({ example: "Zoom" }),- requireEmail: z.boolean().optional().openapi({- description: "Require participants to provide their email address",- example: true,- }),- hideParticipants: z.boolean().optional().openapi({- description: "Hide participant names from other participants",- example: false,- }),- hideScores: z.boolean().optional().openapi({- description: "Hide vote counts from participants",- example: false,- }),- disableComments: z.boolean().optional().openapi({- description: "Disable the comments section",- example: false,- }),- spaceId: z.string().optional().openapi({- description:- "ID of the space to create the poll in. Defaults to user's most recently used space.",- example: "space_abc123",- }),- organizer: z- .object({- email: z.email().openapi({- description: "Email address of the organizer",- example: "[email protected]",- }),- })- .optional()- .openapi({- description:- "Organizer of the poll. Defaults to the space owner if not provided. The organizer must be a member of the space.",- }),- dates: datesInputSchema.optional(),- slots: slotsInputSchema.optional(),- })- .refine((data) => data.dates || data.slots, {- message: "Either 'dates' or 'slots' must be provided",- })- .refine((data) => !(data.dates && data.slots), {- message: "Cannot provide both 'dates' and 'slots'",- })- .openapi("CreatePollInput");--export const errorResponseSchema = z- .object({- error: z.object({- code: z.string().openapi({ example: "TIMEZONE_REQUIRED" }),- message: z.string().openapi({- example:- "Timezone is required. Either provide a timezone in the request or set one in your profile.",- }),- }),- })- .openapi("ErrorResponse");--export const deletePollSuccessResponseSchema = z- .object({- data: z.object({- id: z.string().openapi({ example: "p_123abc" }),- deleted: z.literal(true).openapi({ example: true }),- }),- })- .openapi("DeletePollResponse");--export const pollStatusSchema = z- .enum(["open", "closed", "scheduled", "canceled"])- .openapi("PollStatus");--export const pollOptionSchema = z- .object({- id: z.string().openapi({ example: "opt_abc123" }),- startTime: z.iso.datetime().openapi({ example: "2025-01-15T09:00:00Z" }),- duration: z.number().int().openapi({- description: "Duration in minutes. 0 indicates an all-day option.",- example: 30,- }),- })- .openapi("PollOption");--export const pollUserSchema = z- .object({- name: z.string().openapi({ example: "John Doe" }),- image: z- .string()- .nullable()- .openapi({ example: "https://example.com/avatar.jpg" }),- })- .openapi("PollUser");--export const getPollSuccessResponseSchema = z- .object({- data: z.object({- id: z.string().openapi({ example: "p_123abc" }),- title: z.string().openapi({ example: "Team sync" }),- description: z.string().nullable().openapi({- example: "Pick a time that works for everyone",- }),- location: z.string().nullable().openapi({ example: "Zoom" }),- timezone: z.string().nullable().openapi({ example: "Europe/London" }),- status: pollStatusSchema,- createdAt: z- .string()- .datetime()- .openapi({ example: "2025-01-10T12:00:00Z" }),- user: pollUserSchema.nullable().openapi({- description: "The poll organizer",- }),- options: z.array(pollOptionSchema),- adminUrl: z- .string()- .openapi({ example: "https://example.com/poll/p_123abc" }),- inviteUrl: z- .string()- .openapi({ example: "https://example.com/invite/p_123abc" }),- }),- })- .openapi("GetPollResponse");--// Create poll returns the same shape as get poll-export const createPollSuccessResponseSchema =- getPollSuccessResponseSchema.openapi("CreatePollResponse");--export const voteCountSchema = z- .object({- type: z.string().openapi({- description: "The vote type (e.g., yes, ifNeedBe, no)",- example: "yes",- }),- count: z.int().nonnegative().openapi({- description: "Number of votes of this type",- example: 5,- }),- })- .openapi("VoteCount");--export const optionResultSchema = z- .object({- id: z.string().openapi({ example: "opt_abc123" }),- startTime: z.iso.datetime().openapi({ example: "2025-01-15T09:00:00Z" }),- duration: z.int().nonnegative().openapi({- description: "Duration in minutes. 0 indicates an all-day option.",- example: 30,- }),- votes: z.array(voteCountSchema).openapi({- description: "Array of vote counts by type",- }),- score: z.int().nonnegative().openapi({- description:- "Ranking score: (yes + ifNeedBe) * 1000 + yes. Total availability is primary, yes votes break ties.",- example: 5004,- }),- isTopChoice: z.boolean().openapi({- description: "Whether this option has the highest score",- example: true,- }),- })- .openapi("OptionResult");--export const getPollResultsSuccessResponseSchema = z- .object({- data: z.object({- pollId: z.string().openapi({ example: "p_123abc" }),- participantCount: z.int().nonnegative().openapi({- description: "Total number of participants",- example: 8,- }),- options: z.array(optionResultSchema),- highScore: z.int().nonnegative().openapi({- description: "Highest score across all options",- example: 7,- }),- }),- })- .openapi("GetPollResultsResponse");--export const participantSchema = z- .object({- id: z.string().openapi({ example: "participant_abc123" }),- name: z.string().openapi({ example: "Jane Smith" }),- email: z.string().nullable().openapi({ example: "[email protected]" }),- createdAt: z.iso.datetime().openapi({ example: "2025-01-10T12:00:00Z" }),- })- .openapi("Participant");--export const getPollParticipantsSuccessResponseSchema = z- .object({- data: z.object({- pollId: z.string().openapi({ example: "p_123abc" }),- participants: z.array(participantSchema),- }),- })- .openapi("GetPollParticipantsResponse");diff --git a/apps/api/src/utils/error.ts b/apps/api/src/utils/error.tsdeleted file mode 100644index 2c6ad8936..000000000--- a/apps/api/src/utils/error.ts+++ /dev/null@@ -1,3 +0,0 @@-export const apiError = (code: string, message: string) => ({- error: { code, message },-});diff --git a/apps/api/src/utils/time-slots.test.ts b/apps/api/src/utils/time-slots.test.tsdeleted file mode 100644index 60380af94..000000000--- a/apps/api/src/utils/time-slots.test.ts+++ /dev/null@@ -1,258 +0,0 @@-import { describe, expect, it } from "vitest";-import {- dedupeTimeSlots,- generateTimeSlots,- parseStartTime,-} from "./time-slots";--describe("time-slots utilities", () => {- describe("parseStartTime", () => {- it("should parse ISO datetime with timezone offset", () => {- const result = parseStartTime(- "2025-01-15T09:00:00Z",- "Europe/London",- 30,- );-- expect(result.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result.duration).toBe(30);- });-- it("should parse datetime without offset using provided timezone", () => {- const result = parseStartTime(- "2025-01-15T09:00:00",- "America/New_York",- 60,- );-- expect(result.startTime).toEqual(new Date("2025-01-15T14:00:00Z"));- expect(result.duration).toBe(60);- });-- it("should handle positive timezone offset", () => {- const result = parseStartTime(- "2025-01-15T09:00:00+05:30",- "Europe/London",- 30,- );-- expect(result.startTime).toEqual(new Date("2025-01-15T03:30:00Z"));- });-- it("should handle negative timezone offset", () => {- const result = parseStartTime(- "2025-01-15T09:00:00-08:00",- "Europe/London",- 30,- );-- expect(result.startTime).toEqual(new Date("2025-01-15T17:00:00Z"));- });-- it("should parse datetime without offset as UTC when timezone is undefined", () => {- const result = parseStartTime("2025-01-15T09:00:00", undefined, 30);-- expect(result.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result.duration).toBe(30);- });-- it("should parse ISO datetime with timezone offset as-is when timezone is undefined", () => {- const result = parseStartTime("2025-01-15T09:00:00Z", undefined, 30);-- expect(result.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result.duration).toBe(30);- });- });-- describe("dedupeTimeSlots", () => {- it("should remove duplicate time slots", () => {- const slots = [- { startTime: new Date("2025-01-15T09:00:00Z"), duration: 30 },- { startTime: new Date("2025-01-15T09:00:00Z"), duration: 30 },- { startTime: new Date("2025-01-15T10:00:00Z"), duration: 30 },- ];-- const result = dedupeTimeSlots(slots);-- expect(result).toHaveLength(2);- expect(result[0]?.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result[1]?.startTime).toEqual(new Date("2025-01-15T10:00:00Z"));- });-- it("should keep slots with same time but different duration", () => {- const slots = [- { startTime: new Date("2025-01-15T09:00:00Z"), duration: 30 },- { startTime: new Date("2025-01-15T09:00:00Z"), duration: 60 },- ];-- const result = dedupeTimeSlots(slots);-- expect(result).toHaveLength(2);- });-- it("should return empty array for empty input", () => {- const result = dedupeTimeSlots([]);- expect(result).toEqual([]);- });- });-- describe("generateTimeSlots", () => {- it("should generate slots for a single day", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "09:00",- toTime: "12:00",- },- "UTC",- 60,- );-- expect(result).toHaveLength(3);- expect(result[0]?.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result[1]?.startTime).toEqual(new Date("2025-01-15T10:00:00Z"));- expect(result[2]?.startTime).toEqual(new Date("2025-01-15T11:00:00Z"));- expect(result[0]?.duration).toBe(60);- });-- it("should generate slots across multiple days", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-13",- endDate: "2025-01-17",- daysOfWeek: ["mon", "wed", "fri"],- fromTime: "09:00",- toTime: "10:00",- },- "UTC",- 30,- );-- expect(result).toHaveLength(6);- });-- it("should respect custom interval", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "09:00",- toTime: "11:00",- interval: 30,- },- "UTC",- 30,- );-- expect(result).toHaveLength(4);- expect(result[0]?.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result[1]?.startTime).toEqual(new Date("2025-01-15T09:30:00Z"));- expect(result[2]?.startTime).toEqual(new Date("2025-01-15T10:00:00Z"));- expect(result[3]?.startTime).toEqual(new Date("2025-01-15T10:30:00Z"));- });-- it("should return empty array when no matching days in range", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["mon"],- fromTime: "09:00",- toTime: "10:00",- },- "UTC",- 30,- );-- expect(result).toEqual([]);- });-- it("should return empty array when end time is before start time", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "12:00",- toTime: "09:00",- },- "UTC",- 30,- );-- expect(result).toEqual([]);- });-- it("should handle timezone correctly", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "09:00",- toTime: "10:00",- },- "America/New_York",- 30,- );-- expect(result[0]?.startTime).toEqual(new Date("2025-01-15T14:00:00Z"));- expect(result[1]?.startTime).toEqual(new Date("2025-01-15T14:30:00Z"));- });-- it("should not generate slot if duration exceeds window", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "09:00",- toTime: "09:30",- },- "UTC",- 60,- );-- expect(result).toEqual([]);- });-- it("should deduplicate generated slots", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "09:00",- toTime: "10:00",- },- "UTC",- 30,- );-- const uniqueTimes = new Set(result.map((s) => s.startTime.toISOString()));- expect(result.length).toBe(uniqueTimes.size);- });-- it("should generate slots as UTC when timezone is undefined", () => {- const result = generateTimeSlots(- {- startDate: "2025-01-15",- endDate: "2025-01-15",- daysOfWeek: ["wed"],- fromTime: "09:00",- toTime: "10:00",- },- undefined,- 30,- );-- expect(result).toHaveLength(2);- expect(result[0]?.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));- expect(result[1]?.startTime).toEqual(new Date("2025-01-15T09:30:00Z"));- expect(result[0]?.duration).toBe(30);- });- });-});diff --git a/apps/api/src/utils/time-slots.ts b/apps/api/src/utils/time-slots.tsdeleted file mode 100644index c61726c10..000000000--- a/apps/api/src/utils/time-slots.ts+++ /dev/null@@ -1,126 +0,0 @@-import dayjs from "dayjs";-import isSameOrBefore from "dayjs/plugin/isSameOrBefore";-import timezone from "dayjs/plugin/timezone";-import utc from "dayjs/plugin/utc";--dayjs.extend(utc);-dayjs.extend(timezone);-dayjs.extend(isSameOrBefore);--export type SlotGeneratorInput = {- startDate: string;- endDate: string;- daysOfWeek: Array<"mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun">;- fromTime: string;- toTime: string;- interval?: number;-};--export type TimeSlot = {- startTime: Date;- duration: number;-};--export const dedupeTimeSlots = (slots: Array<TimeSlot>) => {- const unique = new Map<string, TimeSlot>();- for (const slot of slots) {- unique.set(`${slot.startTime.getTime()}:${slot.duration}`, slot);- }- return Array.from(unique.values());-};--const hasTzOffset = (value: string) =>- /[zZ]$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(value);--const parseDateTimeInTimeZone = (value: string, timeZone?: string) =>- hasTzOffset(value)- ? dayjs(value)- : timeZone- ? dayjs(value).tz(timeZone, true)- : dayjs(value).utc(true);--const parseLocalDateTimeInTimeZone = (- date: string,- time: string,- timeZone: string | undefined,-) =>- timeZone- ? dayjs(`${date}T${time}`).tz(timeZone, true)- : dayjs(`${date}T${time}`).utc(true);--export const parseStartTime = (- startTime: string,- timeZone: string | undefined,- duration: number,-): TimeSlot => ({- startTime: parseDateTimeInTimeZone(startTime, timeZone).toDate(),- duration,-});--export const generateTimeSlots = (- generator: SlotGeneratorInput,- timeZone: string | undefined,- durationMinutes: number,-): Array<TimeSlot> => {- const dayMap: Record<SlotGeneratorInput["daysOfWeek"][number], number> = {- sun: 0,- mon: 1,- tue: 2,- wed: 3,- thu: 4,- fri: 5,- sat: 6,- };-- const allowed = new Set(generator.daysOfWeek.map((d) => dayMap[d]));-- // Use UTC for date iteration to avoid local timezone interference- const startDay = dayjs.utc(generator.startDate).startOf("day");- const endDay = dayjs.utc(generator.endDate).startOf("day");-- const results: Array<TimeSlot> = [];-- for (- let cursor = startDay;- cursor.isSameOrBefore(endDay, "day");- cursor = cursor.add(1, "day")- ) {- const date = cursor.format("YYYY-MM-DD");- // Get day of week in the target timezone- const dayInTz = timeZone ? dayjs.tz(date, timeZone).day() : cursor.day();- if (!allowed.has(dayInTz)) {- continue;- }- const windowStart = parseLocalDateTimeInTimeZone(- date,- generator.fromTime,- timeZone,- );- const windowEnd = parseLocalDateTimeInTimeZone(- date,- generator.toTime,- timeZone,- );- if (!windowEnd.isAfter(windowStart)) {- continue;- }-- const duration = durationMinutes;- const interval = generator.interval ?? durationMinutes;- const totalMinutes = windowEnd.diff(windowStart, "minute");-- for (- let offset = 0;- offset + duration <= totalMinutes;- offset += interval- ) {- const t = windowStart.add(offset, "minute");- results.push({- startTime: t.toDate(),- duration,- });- }- }-- return results;-};diff --git a/apps/api/src/utils/timezone-schema.ts b/apps/api/src/utils/timezone-schema.tsdeleted file mode 100644index 8c8b7058e..000000000--- a/apps/api/src/utils/timezone-schema.ts+++ /dev/null@@ -1,56 +0,0 @@-import * as z from "zod";--// Override runtime canonicalization when ICU data lags behind IANA updates.-const ianaOverrides: Record<string, string> = {- "Europe/Kiev": "Europe/Kyiv",-};--export function normalizeLegacyIanaId(id: string): string {- return ianaOverrides[id] ?? id;-}--const fixedOffsetPrefixes = ["etc/", "gmt", "utc"];--function isGeographic(timeZone: string) {- const lower = timeZone.toLowerCase();- return !fixedOffsetPrefixes.some((prefix) => lower.startsWith(prefix));-}--/**- * Resolve timezone to its canonical IANA ID via the runtime,- * then apply manual overrides for cases where the runtime is outdated.- * Returns the canonical ID or null if the timezone is invalid.- */-function resolveTimezone(tz: string): string | null {- try {- const resolved = Intl.DateTimeFormat(undefined, {- timeZone: tz,- }).resolvedOptions().timeZone;- return normalizeLegacyIanaId(resolved);- } catch {- return null;- }-}--export const timezoneSchema = z.string().transform((tz, ctx) => {- const resolved = resolveTimezone(tz);- if (resolved === null) {- ctx.issues.push({- code: "custom",- message: "Must be a valid IANA timezone",- input: tz,- });- return z.NEVER;- }-- if (!isGeographic(resolved)) {- ctx.issues.push({- code: "custom",- message: "Must be a geographic timezone",- input: tz,- });- return z.NEVER;- }-- return resolved;-});diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.jsondeleted file mode 100644index 8c563dfca..000000000--- a/apps/api/tsconfig.json+++ /dev/null@@ -1,11 +0,0 @@-{- "extends": "@rallly/tsconfig/node.json",- "compilerOptions": {- "lib": ["es2023"],- "target": "es2023",- "types": ["node"],- "outDir": "dist",- "rootDir": "src"- },- "include": ["src/**/*"]-}diff --git a/apps/api/vitest.config.mts b/apps/api/vitest.config.mtsdeleted file mode 100644index de6eca2e9..000000000--- a/apps/api/vitest.config.mts+++ /dev/null@@ -1,8 +0,0 @@-import { defineConfig } from "vitest/config";--export default defineConfig({- test: {- include: ["**/*.test.ts"],- exclude: ["**/node_modules/**", "**/dist/**"],- },-});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f9a5977dd..913424611 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -42,70 +42,6 @@ importers:specifier: ^4.0.16version: 4.0.18(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- apps/api:- dependencies:- '@hono-rate-limiter/redis':- specifier: ^0.1.4- version: 0.1.4([email protected]([email protected]))- '@hono/node-server':- specifier: ^1.19.9- version: 1.19.9([email protected])- '@hono/zod-openapi':- specifier: ^1.2.0- version: 1.2.1([email protected])([email protected])- '@rallly/api-core':- specifier: workspace:*- version: link:../../packages/api-core- '@rallly/database':- specifier: workspace:*- version: link:../../packages/database- '@rallly/logger':- specifier: workspace:*- version: link:../../packages/logger- '@rallly/utils':- specifier: workspace:*- version: link:../../packages/utils- '@scalar/hono-api-reference':- specifier: ^0.9.30- version: 0.9.40([email protected])- '@t3-oss/env-core':- specifier: ^0.13.10- version: 0.13.10([email protected])([email protected])([email protected]([email protected]))([email protected])- '@upstash/redis':- specifier: ^1.36.2- version: 1.36.2- dayjs:- specifier: ^1.11.13- version: 1.11.19- hono:- specifier: ^4.11.1- version: 4.11.7- hono-openapi:- specifier: ^1.1.2- version: 1.2.0(@hono/[email protected](@standard-schema/[email protected])([email protected]))(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-community/[email protected](@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])- hono-rate-limiter:- specifier: ^0.2.1- version: 0.2.3([email protected])- zod:- specifier: ^4.3.6- version: 4.3.6- devDependencies:- '@rallly/tsconfig':- specifier: workspace:*- version: link:../../packages/tsconfig- '@types/node':- specifier: ^24.1.0- version: 24.10.11- tsx:- specifier: ^4.6.2- version: 4.21.0- typescript:- specifier: ^5.8.2- version: 5.9.3- vitest:- specifier: ^4.0.16- version: 4.0.18(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-apps/docs:dependencies:mint:@@ -13433,10 +13369,6 @@ snapshots:dependencies:hono: 4.11.4- '@hono/[email protected]([email protected])':- dependencies:- hono: 4.11.7-dependencies:'@standard-schema/spec': 1.1.0