Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Port private API polls routes, schemas and middleware to apps/api (#2370)
Luke Vella7d5f55ac26e3
diff --git a/apps/api/.env.sample b/apps/api/.env.samplenew file mode 100644index 000000000..7a90150be--- /dev/null+++ b/apps/api/.env.sample@@ -0,0 +1,16 @@+# 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/package.json b/apps/api/package.jsonindex e28301209..ed3351d69 100644--- a/apps/api/package.json+++ b/apps/api/package.json@@ -4,9 +4,10 @@"private": true,"main": "dist/index.js","scripts": {- "dev": "portless api.local.rallly tsx watch src/index.ts",+ "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 dist/index.js",+ "start": "node --env-file-if-exists=.env dist/index.js",+ "test:unit": "vitest run","type-check": "tsc --noEmit"},"dependencies": {@@ -18,15 +19,19 @@"@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"+ "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"+ "typescript": "^5.8.2",+ "vitest": "^4.0.16"}}diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex cf0ccb0ad..d1af0cd71 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -1,11 +1,14 @@import { Scalar } from "@scalar/hono-api-reference";import { Hono } from "hono";import { openAPIRouteHandler } from "hono-openapi";+import { polls } from "./routes/polls";export const app = new Hono();app.get("/health", (c) => c.json({ ok: true }));+app.route("/v1/polls", polls);+app.get("/openapi",openAPIRouteHandler(app, {@@ -14,6 +17,14 @@ app.get(title: "Rallly API",version: "0.0.1",},+ components: {+ securitySchemes: {+ bearerAuth: {+ type: "http",+ scheme: "bearer",+ },+ },+ },},}),);diff --git a/apps/api/src/env.ts b/apps/api/src/env.tsnew file mode 100644index 000000000..27239a83d--- /dev/null+++ b/apps/api/src/env.ts@@ -0,0 +1,15 @@+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.tsindex 95e8c0bf8..c38ad9c7d 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -1,4 +1,5 @@import { serve } from "@hono/node-server";import { app } from "./app";+import { env } from "./env";-serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 4000) });+serve({ fetch: app.fetch, port: env.PORT });diff --git a/apps/api/src/lib/redis.ts b/apps/api/src/lib/redis.tsindex 0772c2b9c..095c47081 100644--- a/apps/api/src/lib/redis.ts+++ b/apps/api/src/lib/redis.ts@@ -1,17 +1,18 @@import { createLogger } from "@rallly/logger";import { Redis } from "@upstash/redis";+import { env } from "../env";const logger = createLogger("api/lib/redis");function createRedis() {- if (!process.env.KV_REST_API_URL || !process.env.KV_REST_API_TOKEN) {+ if (!env.KV_REST_API_URL || !env.KV_REST_API_TOKEN) {return null;}try {return new Redis({- url: process.env.KV_REST_API_URL,- token: process.env.KV_REST_API_TOKEN,+ url: env.KV_REST_API_URL,+ token: env.KV_REST_API_TOKEN,});} catch (error) {logger.error(diff --git a/apps/api/src/middleware/api-key.ts b/apps/api/src/middleware/api-key.tsnew file mode 100644index 000000000..587828ddd--- /dev/null+++ b/apps/api/src/middleware/api-key.ts@@ -0,0 +1,84 @@+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.tsnew file mode 100644index 000000000..f68287ec5--- /dev/null+++ b/apps/api/src/routes/polls.ts@@ -0,0 +1,568 @@+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/schemas.ts b/apps/api/src/schemas.tsnew file mode 100644index 000000000..d14312791--- /dev/null+++ b/apps/api/src/schemas.ts@@ -0,0 +1,272 @@+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.tsnew file mode 100644index 000000000..2c6ad8936--- /dev/null+++ b/apps/api/src/utils/error.ts@@ -0,0 +1,3 @@+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.tsnew file mode 100644index 000000000..60380af94--- /dev/null+++ b/apps/api/src/utils/time-slots.test.ts@@ -0,0 +1,258 @@+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.tsnew file mode 100644index 000000000..c61726c10--- /dev/null+++ b/apps/api/src/utils/time-slots.ts@@ -0,0 +1,126 @@+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.tsnew file mode 100644index 000000000..fdc0d1142--- /dev/null+++ b/apps/api/src/utils/timezone-schema.ts@@ -0,0 +1,56 @@+import { 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/vitest.config.mts b/apps/api/vitest.config.mtsnew file mode 100644index 000000000..de6eca2e9--- /dev/null+++ b/apps/api/vitest.config.mts@@ -0,0 +1,8 @@+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 bb40b33dc..df2ac71de 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -68,9 +68,15 @@ importers:'@scalar/hono-api-reference':specifier: ^0.9.30version: 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.2version: 1.36.2+ dayjs:+ specifier: ^1.11.13+ version: 1.11.19hono:specifier: ^4.11.1version: 4.11.7@@ -80,6 +86,9 @@ importers:hono-rate-limiter:specifier: ^0.2.1version: 0.2.3([email protected])+ zod:+ specifier: ^4.3.6+ version: 4.3.6devDependencies:'@rallly/tsconfig':specifier: workspace:*@@ -93,6 +102,9 @@ importers:typescript:specifier: ^5.8.2version: 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:@@ -144,7 +156,7 @@ importers:version: 8.1.0([email protected])'@vercel/analytics':specifier: ^1.5.0- version: 1.6.1([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])dayjs:specifier: ^1.11.13version: 1.11.19@@ -183,7 +195,7 @@ importers:version: 6.0.0(@types/[email protected])([email protected])next-seo:specifier: ^6.1.0- version: 6.8.0([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ version: 6.8.0([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])pg:specifier: ^8.17.1version: 8.18.0@@ -17891,7 +17903,7 @@ snapshots:dependencies:uncrypto: 0.1.3- '@vercel/[email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':+ '@vercel/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])':optionalDependencies:next: 16.2.1(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 19.2.4@@ -21663,7 +21675,7 @@ snapshots:react: 19.2.4react-dom: 19.2.4([email protected])- [email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):+ [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:next: 16.2.1(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])react: 19.2.4