Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add /api/v1 alongside the frozen /api/private route (#3201)
Luke Vellab531c3a812c9
diff --git a/apps/web/biome.json b/apps/web/biome.jsonindex dec500abf..0b056f36e 100644--- a/apps/web/biome.json+++ b/apps/web/biome.json@@ -184,7 +184,8 @@"src/app/api/legacy/**","src/app/api/status/**","src/app/api/updates/**",- "src/app/api/private/**"+ "src/app/api/private/**",+ "src/app/api/middleware/**"],"linter": {"rules": {diff --git a/apps/web/src/app/api/private/utils/poll.ts b/apps/web/src/app/api/middleware/api-error.tssimilarity index 100%rename from apps/web/src/app/api/private/utils/poll.tsrename to apps/web/src/app/api/middleware/api-error.tsdiff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/middleware/api-key.tssimilarity index 99%rename from apps/web/src/app/api/private/utils/api-key.tsrename to apps/web/src/app/api/middleware/api-key.tsindex adb4d69e0..6ca7a7fa2 100644--- a/apps/web/src/app/api/private/utils/api-key.ts+++ b/apps/web/src/app/api/middleware/api-key.ts@@ -13,7 +13,7 @@ import {} from "@/features/api-keys/utils";import { resolveSpaceTier } from "@/features/billing/utils";import type { AuthorizedSpaceId } from "@/features/space/types";-import { apiError } from "./poll";+import { apiError } from "./api-error";const LAST_USED_AT_WRITE_INTERVAL_MS = 60_000;diff --git a/apps/web/src/app/api/private/utils/fake-redis.ts b/apps/web/src/app/api/middleware/fake-redis.tssimilarity index 100%rename from apps/web/src/app/api/private/utils/fake-redis.tsrename to apps/web/src/app/api/middleware/fake-redis.tsdiff --git a/apps/web/src/app/api/private/utils/rate-limit-in-process.test.ts b/apps/web/src/app/api/middleware/rate-limit-in-process.test.tssimilarity index 100%rename from apps/web/src/app/api/private/utils/rate-limit-in-process.test.tsrename to apps/web/src/app/api/middleware/rate-limit-in-process.test.tsdiff --git a/apps/web/src/app/api/private/utils/rate-limit-unconfigured.test.ts b/apps/web/src/app/api/middleware/rate-limit-unconfigured.test.tssimilarity index 100%rename from apps/web/src/app/api/private/utils/rate-limit-unconfigured.test.tsrename to apps/web/src/app/api/middleware/rate-limit-unconfigured.test.tsdiff --git a/apps/web/src/app/api/private/utils/rate-limit.test.ts b/apps/web/src/app/api/middleware/rate-limit.test.tssimilarity index 100%rename from apps/web/src/app/api/private/utils/rate-limit.test.tsrename to apps/web/src/app/api/middleware/rate-limit.test.tsdiff --git a/apps/web/src/app/api/private/utils/rate-limit.ts b/apps/web/src/app/api/middleware/rate-limit.tssimilarity index 99%rename from apps/web/src/app/api/private/utils/rate-limit.tsrename to apps/web/src/app/api/middleware/rate-limit.tsindex 03ac80e06..f8b4837f8 100644--- a/apps/web/src/app/api/private/utils/rate-limit.ts+++ b/apps/web/src/app/api/middleware/rate-limit.ts@@ -6,7 +6,7 @@ import {} from "@/features/api-keys/constants";import { isFeatureEnabled } from "@/lib/feature-flags/server";import { redis } from "@/lib/kv";-import { apiError } from "./poll";+import { apiError } from "./api-error";/*** Re-exported for the OpenAPI docs and tests. The values live in thediff --git a/apps/web/src/app/api/private/utils/wide-event.test.ts b/apps/web/src/app/api/middleware/wide-event.test.tssimilarity index 98%rename from apps/web/src/app/api/private/utils/wide-event.test.tsrename to apps/web/src/app/api/middleware/wide-event.test.tsindex ddbbf6423..3c8a467cb 100644--- a/apps/web/src/app/api/private/utils/wide-event.test.ts+++ b/apps/web/src/app/api/middleware/wide-event.test.ts@@ -38,7 +38,7 @@ const window = (limit: number, used: number) => ({const buildApp = () => {const app = new Hono<TestEnv>();- app.use("*", wideEvent);+ app.use("*", wideEvent({ service: "api-test" }));app.get("/ok",@@ -93,7 +93,7 @@ describe("wideEvent middleware", () => {const event = info.mock.calls[0][0];expect(event).toMatchObject({- service: "private-api",+ service: "api-test",method: "GET",path: "/ok",statusCode: 200,diff --git a/apps/web/src/app/api/middleware/wide-event.ts b/apps/web/src/app/api/middleware/wide-event.tsnew file mode 100644index 000000000..8862d65ae--- /dev/null+++ b/apps/web/src/app/api/middleware/wide-event.ts@@ -0,0 +1,95 @@+import { createWideEvent, logger } from "@rallly/logger";+import { createMiddleware } from "hono/factory";+import type { RateLimitFailure, RateLimitInfo } from "./rate-limit";++type WideEventEnv = {+ Variables: {+ apiAuth?: {+ spaceId: string;+ apiKeyId: string;+ };+ rateLimit?: RateLimitInfo;+ rateLimitFailure?: RateLimitFailure;+ };+};++/**+ * Emits a single wide event per request, following the "one event per request"+ * pattern in `packages/logger/src/wide-event.ts`. Registered first so it wraps+ * every outcome, including maintenance (503), auth (401/403), and rate limit+ * (429) short-circuits from downstream middleware.+ *+ * `service` labels the route that handled the request (`api-private`,+ * `api-v1`), so migration between versions is a single `group_by` in the+ * logs.+ */+export const wideEvent = ({ service }: { service: string }) =>+ createMiddleware<WideEventEnv>(async (c, next) => {+ const startTime = Date.now();+ const event = createWideEvent({+ service,+ requestId:+ c.req.header("x-vercel-id") ??+ c.req.header("x-request-id") ??+ undefined,+ method: c.req.method,+ path: c.req.path,+ ip: c.req.header("x-vercel-forwarded-for") ?? undefined,+ ja4Digest: c.req.header("x-vercel-ja4-digest") ?? undefined,+ });++ try {+ await next();++ // `c.res.status` is authoritative: Hono's error handler has already+ // resolved thrown HTTPExceptions (e.g. the 401 from bearer auth) into the+ // correct status. `c.error` is still set for those, so enrich error fields+ // from it but never let it override the resolved status.+ event.statusCode = c.res.status;++ if (c.error) {+ event.errorType = c.error.name;+ event.errorMessage = c.error.message;+ }+ } finally {+ // `apiAuth` and `rateLimit` are populated by downstream middleware, so they+ // are only available once `next()` has run — and stay absent when the+ // request is rejected before they run (401 unauthenticated, 403 non-pro).+ const apiAuth = c.get("apiAuth");+ if (apiAuth) {+ event.spaceId = apiAuth.spaceId;+ event.apiKeyId = apiAuth.apiKeyId;+ }++ const rateLimit = c.get("rateLimit");+ if (rateLimit) {+ event.rateLimiter = "private-api";+ event.rateLimiterConsumedPoints = rateLimit.minute.used;+ event.rateLimiterRemainingPoints = rateLimit.minute.remaining;+ event.rateLimiterDailyConsumedPoints = rateLimit.day.used;+ event.rateLimiterDailyRemainingPoints = rateLimit.day.remaining;+ }++ // A fail-closed 503 from the rate limiter is returned, not thrown, so+ // `c.error` is empty; carry its cause so an outage is queryable.+ const rateLimitFailure = c.get("rateLimitFailure");+ if (rateLimitFailure) {+ event.rateLimiter = "private-api";+ event.rateLimiterError = rateLimitFailure.reason;+ event.errorType = "RateLimitStoreError";+ event.errorCode = "SERVICE_UNAVAILABLE";+ event.errorMessage = rateLimitFailure.message;+ event.isRetriable = true;+ }++ event.durationMs = Date.now() - startTime;++ if (event.statusCode && event.statusCode >= 500) {+ logger.error(event);+ } else if (event.statusCode && event.statusCode >= 400) {+ logger.warn(event);+ } else {+ logger.info(event);+ }+ }+ });diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex ac9178310..d30cba900 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -62,7 +62,7 @@ vi.mock("@/lib/feature-flags/server", () => ({}));vi.mock("@/lib/kv", async () => ({- redis: (await import("../utils/fake-redis")).createFakeRedis(),+ redis: (await import("../../middleware/fake-redis")).createFakeRedis(),}));vi.mock("@/lib/posthog", () => ({@@ -76,6 +76,8 @@ import { after } from "next/server";import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";import { redis } from "@/lib/kv";+import type { FakeRedis } from "../../middleware/fake-redis";+import { RATE_LIMIT_PER_MINUTE } from "../../middleware/rate-limit";import {createPollRequestExamples,patchPollRequestExamples,@@ -90,8 +92,6 @@ import {listPollsSuccessResponseSchema,patchPollSuccessResponseSchema,} from "../schemas";-import type { FakeRedis } from "../utils/fake-redis";-import { RATE_LIMIT_PER_MINUTE } from "../utils/rate-limit";import { app } from "./route";const expectMatchesContract = (diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.tsindex f291a0519..cdfe62e42 100644--- a/apps/web/src/app/api/private/[...route]/route.ts+++ b/apps/web/src/app/api/private/[...route]/route.ts@@ -27,6 +27,14 @@ import {} from "@/lib/datetime/slot-generator";import { isMaintenanceModeEnabled } from "@/lib/maintenance";import { flushPostHog, identifyGroup, track } from "@/lib/posthog";+import { apiError } from "../../middleware/api-error";+import { spaceApiKeyAuth } from "../../middleware/api-key";+import {+ RATE_LIMIT_PER_DAY,+ RATE_LIMIT_PER_MINUTE,+ rateLimit,+} from "../../middleware/rate-limit";+import { wideEvent } from "../../middleware/wide-event";import {createPollRequestExamples,patchPollRequestExamples,@@ -44,14 +52,6 @@ import {patchPollInputSchema,patchPollSuccessResponseSchema,} from "../schemas";-import { spaceApiKeyAuth } from "../utils/api-key";-import { apiError } from "../utils/poll";-import {- RATE_LIMIT_PER_DAY,- RATE_LIMIT_PER_MINUTE,- rateLimit,-} from "../utils/rate-limit";-import { wideEvent } from "../utils/wide-event";type Env = {Variables: {@@ -103,7 +103,7 @@ function toPollResponseBody(poll: {};}-app.use("*", wideEvent);+app.use("*", wideEvent({ service: "api-private" }));app.use("*", async (c, next) => {if (isMaintenanceModeEnabled()) {diff --git a/apps/web/src/app/api/private/utils/wide-event.ts b/apps/web/src/app/api/private/utils/wide-event.tsdeleted file mode 100644index d2fa473f9..000000000--- a/apps/web/src/app/api/private/utils/wide-event.ts+++ /dev/null@@ -1,88 +0,0 @@-import { createWideEvent, logger } from "@rallly/logger";-import { createMiddleware } from "hono/factory";-import type { RateLimitFailure, RateLimitInfo } from "./rate-limit";--type WideEventEnv = {- Variables: {- apiAuth?: {- spaceId: string;- apiKeyId: string;- };- rateLimit?: RateLimitInfo;- rateLimitFailure?: RateLimitFailure;- };-};--/**- * Emits a single wide event per request, following the "one event per request"- * pattern in `packages/logger/src/wide-event.ts`. Registered first so it wraps- * every outcome, including maintenance (503), auth (401/403), and rate limit- * (429) short-circuits from downstream middleware.- */-export const wideEvent = createMiddleware<WideEventEnv>(async (c, next) => {- const startTime = Date.now();- const event = createWideEvent({- service: "private-api",- requestId:- c.req.header("x-vercel-id") ?? c.req.header("x-request-id") ?? undefined,- method: c.req.method,- path: c.req.path,- ip: c.req.header("x-vercel-forwarded-for") ?? undefined,- ja4Digest: c.req.header("x-vercel-ja4-digest") ?? undefined,- });-- try {- await next();-- // `c.res.status` is authoritative: Hono's error handler has already- // resolved thrown HTTPExceptions (e.g. the 401 from bearer auth) into the- // correct status. `c.error` is still set for those, so enrich error fields- // from it but never let it override the resolved status.- event.statusCode = c.res.status;-- if (c.error) {- event.errorType = c.error.name;- event.errorMessage = c.error.message;- }- } finally {- // `apiAuth` and `rateLimit` are populated by downstream middleware, so they- // are only available once `next()` has run — and stay absent when the- // request is rejected before they run (401 unauthenticated, 403 non-pro).- const apiAuth = c.get("apiAuth");- if (apiAuth) {- event.spaceId = apiAuth.spaceId;- event.apiKeyId = apiAuth.apiKeyId;- }-- const rateLimit = c.get("rateLimit");- if (rateLimit) {- event.rateLimiter = "private-api";- event.rateLimiterConsumedPoints = rateLimit.minute.used;- event.rateLimiterRemainingPoints = rateLimit.minute.remaining;- event.rateLimiterDailyConsumedPoints = rateLimit.day.used;- event.rateLimiterDailyRemainingPoints = rateLimit.day.remaining;- }-- // A fail-closed 503 from the rate limiter is returned, not thrown, so- // `c.error` is empty; carry its cause so an outage is queryable.- const rateLimitFailure = c.get("rateLimitFailure");- if (rateLimitFailure) {- event.rateLimiter = "private-api";- event.rateLimiterError = rateLimitFailure.reason;- event.errorType = "RateLimitStoreError";- event.errorCode = "SERVICE_UNAVAILABLE";- event.errorMessage = rateLimitFailure.message;- event.isRetriable = true;- }-- event.durationMs = Date.now() - startTime;-- if (event.statusCode && event.statusCode >= 500) {- logger.error(event);- } else if (event.statusCode && event.statusCode >= 400) {- logger.warn(event);- } else {- logger.info(event);- }- }-});diff --git a/apps/web/src/app/api/v1/[...route]/route.test.ts b/apps/web/src/app/api/v1/[...route]/route.test.tsnew file mode 100644index 000000000..0356fa70a--- /dev/null+++ b/apps/web/src/app/api/v1/[...route]/route.test.ts@@ -0,0 +1,1890 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// Mock server-only before any imports that might need it+vi.mock("server-only", () => ({}));++const mockDeletePoll = vi.fn();+const mockCreatePoll = vi.fn();+const mockClosePoll = vi.fn();+const mockGetPollResults = vi.fn();+const mockGetPollParticipants = vi.fn();+const mockListPolls = vi.fn();+const mockGetPollWithOptions = vi.fn();+const mockGetSpaceMemberByEmail = vi.fn();+const mockTrack = vi.fn();+const mockIdentifyGroup = vi.fn();++vi.mock("@/features/poll/mutations", () => ({+ deletePoll: (...args: unknown[]) => mockDeletePoll(...args),+ createPoll: (...args: unknown[]) => mockCreatePoll(...args),+ closePoll: (...args: unknown[]) => mockClosePoll(...args),+}));++vi.mock("@/features/poll/data", () => ({+ getPollResults: (...args: unknown[]) => mockGetPollResults(...args),+ getPollParticipants: (...args: unknown[]) => mockGetPollParticipants(...args),+ listPolls: (...args: unknown[]) => mockListPolls(...args),+ getPollWithOptions: (...args: unknown[]) => mockGetPollWithOptions(...args),+}));++vi.mock("@/features/space/member/data", () => ({+ getSpaceMemberByEmail: (...args: unknown[]) =>+ mockGetSpaceMemberByEmail(...args),+}));++// Hoisted so the tests can drive the api-key middleware's lookups without+// importing @rallly/database, which the DAL lint bans outside data/mutations.+const prisma = vi.hoisted(() => ({+ spaceApiKey: {+ findUnique: vi.fn(),+ findMany: vi.fn(),+ update: vi.fn(),+ },+ user: {+ findUnique: vi.fn(),+ },+}));++vi.mock("@rallly/database", () => ({ prisma }));++vi.mock("@rallly/utils/absolute-url", () => ({+ absoluteUrl: (path = "") => `https://example.com${path}`,+ shortUrl: (path: string) => `https://example.com${path}`,+}));++vi.mock("@rallly/utils/nanoid", () => ({+ nanoid: () => "test-poll-id",+}));++vi.mock("next/server", () => ({+ after: vi.fn(),+}));++vi.mock("@/lib/feature-flags/server", () => ({+ isFeatureEnabled: () => false,+}));++vi.mock("@/lib/kv", async () => ({+ redis: (await import("../../middleware/fake-redis")).createFakeRedis(),+}));++vi.mock("@/lib/posthog", () => ({+ track: (...args: unknown[]) => mockTrack(...args),+ identifyGroup: (...args: unknown[]) => mockIdentifyGroup(...args),+ flushPostHog: vi.fn(),+}));++import { after } from "next/server";+import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";+import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";+import { redis } from "@/lib/kv";+import type { FakeRedis } from "../../middleware/fake-redis";+import { RATE_LIMIT_PER_MINUTE } from "../../middleware/rate-limit";+import {+ createPollRequestExamples,+ patchPollRequestExamples,+} from "../examples";+import {+ createPollInputSchema,+ createPollSuccessResponseSchema,+ deletePollSuccessResponseSchema,+ getPollParticipantsSuccessResponseSchema,+ getPollResultsSuccessResponseSchema,+ getPollSuccessResponseSchema,+ listPollsSuccessResponseSchema,+ patchPollSuccessResponseSchema,+} from "../schemas";+import { app } from "./route";++const expectMatchesContract = (+ schema: {+ safeParse: (data: unknown) => { success: boolean; error?: unknown };+ },+ body: unknown,+) => {+ const result = schema.safeParse(body);+ expect(result.error).toBeUndefined();+ expect(result.success).toBe(true);+};++// Pre-generated test API key fixture. The stored hash deliberately uses the+// deprecated scrypt format so every test in this file exercises the legacy+// verification path that existing production keys depend on.+const testApiKey = "sk_eXzkd84Y_bN24KFwZ_UyiQ0b6zckpNfL2pSdng3r3";+const mockApiKey = {+ id: "api-key-id",+ name: "Test API Key",+ prefix: "eXzkd84Y",+ spaceId: "test-space-id",+ hashedKey:+ "scrypt$16384$8$1$AvCRsm3--6zUOTmMdmM5Jg$4fe1f6de88b70ed9f78aa89752e632cc6ff628194dd42bd34a8cf8e71b23e19ba23ceb9c6371f6eed9129a8afee81bdad8b5b31351162178e2a8b68381102940",+ lastUsedAt: null,+ expiresAt: null,+ revokedAt: null,+ createdAt: new Date("2025-01-01"),+ updatedAt: new Date("2025-01-01"),+ space: {+ ownerId: "test-user-id",+ tier: "pro",+ },+};++describe("API v1 - /polls", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (redis as unknown as FakeRedis).reset();++ // Mock findMany for the timing-safe lookup+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([mockApiKey]);+ vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue(mockApiKey);+ vi.mocked(prisma.spaceApiKey.update).mockResolvedValue({} as never);+ vi.mocked(prisma.user.findUnique).mockResolvedValue({+ id: "test-user-id",+ } as never);+ mockGetSpaceMemberByEmail.mockResolvedValue(null);++ // Mock createPoll mutation+ mockCreatePoll.mockResolvedValue({+ id: "test-poll-id",+ title: "Test Poll",+ description: null,+ location: null,+ timeZone: null,+ status: "open",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ user: {+ name: "Test User",+ image: null,+ },+ options: [],+ adminUrl: "https://example.com/poll/test-poll-id",+ inviteUrl: "https://example.com/invite/test-poll-id",+ });+ });++ describe("Authentication", () => {+ it("should return 401 without authorization header", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(401);+ });++ it("should return 401 with invalid API key", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: "Bearer invalid_key",+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(401);+ });++ it("should return 401 with revoked API key", async () => {+ // Revoked keys are filtered out by the database query+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(401);+ });++ it("should return 401 with expired API key", async () => {+ // Expired keys are filtered out by the database query+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(401);+ });+ });++ describe("Pro tier enforcement", () => {+ it("should return 403 with SPACE_NOT_PRO when the space is not pro", async () => {+ const hobbyApiKey = {+ ...mockApiKey,+ space: { ...mockApiKey.space, tier: "hobby" },+ };+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([hobbyApiKey]);++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(403);+ const json = await res.json();+ expect(json.error.code).toBe("SPACE_NOT_PRO");+ });++ it("should not schedule a lastUsedAt write when the space is not pro", async () => {+ const hobbyApiKey = {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: null,+ space: { ...mockApiKey.space, tier: "hobby" },+ };+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([hobbyApiKey]);++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(403);+ expect(after).not.toHaveBeenCalled();+ });++ it("should return 200 with a valid key when the space is pro", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(200);+ });+ });++ describe("lastUsedAt throttling", () => {+ it("should not schedule a write when lastUsedAt is recent", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: new Date(Date.now() - 30_000),+ },+ ]);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).not.toHaveBeenCalled();+ });++ it("should schedule a write when lastUsedAt is stale", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: new Date(Date.now() - 120_000),+ },+ ]);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).toHaveBeenCalledTimes(1);+ });++ it("should schedule a write when lastUsedAt is null", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: null,+ },+ ]);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).toHaveBeenCalledTimes(1);+ });++ it("should still re-hash a legacy key when lastUsedAt is recent", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ lastUsedAt: new Date(Date.now() - 30_000),+ },+ ]);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).toHaveBeenCalledTimes(1);+ });+ });++ describe("Hash migration (scrypt -> sha256)", () => {+ // The lastUsedAt/re-hash update runs in an after() callback; invoke the+ // captured callbacks to simulate the post-response phase+ const flushAfterCallbacks = async () => {+ for (const [callback] of vi.mocked(after).mock.calls) {+ await (callback as () => Promise<unknown>)();+ }+ };++ it("should authenticate a legacy scrypt-hashed key and re-hash it to sha256", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(200);+ await flushAfterCallbacks();++ expect(prisma.spaceApiKey.update).toHaveBeenCalledWith({+ where: { id: mockApiKey.id },+ data: expect.objectContaining({+ hashedKey: expect.stringMatching(/^sha256\$/),+ }),+ });++ // The re-hashed value must still verify the original key+ const updateCall = vi.mocked(prisma.spaceApiKey.update).mock.calls[0];+ const newHash = updateCall?.[0]?.data?.hashedKey as string;+ expect(await verifyApiKey(testApiKey, newHash)).toBe(true);+ });++ it("should authenticate a sha256-hashed key without re-hashing", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ { ...mockApiKey, hashedKey: hashApiKey(testApiKey) },+ ]);++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(200);+ await flushAfterCallbacks();++ expect(prisma.spaceApiKey.update).toHaveBeenCalledWith({+ where: { id: mockApiKey.id },+ data: { lastUsedAt: expect.any(Date) },+ });+ });+ });++ describe("Create poll with dates", () => {+ it("should create a poll with date options", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team offsite",+ dates: ["2025-01-15", "2025-01-16", "2025-01-17"],+ }),+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(createPollSuccessResponseSchema, json);+ expect(json.data.id).toBe("test-poll-id");+ expect(json.data.adminUrl).toBe("https://example.com/poll/test-poll-id");+ expect(json.data.inviteUrl).toBe(+ "https://example.com/invite/test-poll-id",+ );++ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Team offsite",+ options: [+ {+ startTime: new Date("2025-01-15T00:00:00.000Z"),+ duration: 0,+ },+ {+ startTime: new Date("2025-01-16T00:00:00.000Z"),+ duration: 0,+ },+ {+ startTime: new Date("2025-01-17T00:00:00.000Z"),+ duration: 0,+ },+ ],+ }),+ );+ });++ it("should track poll creation with source api and kind date", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team offsite",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(200);+ expect(mockTrack).toHaveBeenCalledWith(+ { id: "test-user-id", isGuest: false },+ expect.objectContaining({+ event: "poll_create",+ properties: expect.objectContaining({+ kind: "date",+ source: "api",+ }),+ groups: { poll: "test-poll-id", space: "test-space-id" },+ }),+ );+ expect(mockIdentifyGroup).toHaveBeenCalledWith(+ expect.objectContaining({+ groupType: "poll",+ groupKey: "test-poll-id",+ properties: expect.objectContaining({ kind: "date" }),+ }),+ );+ });++ it("should save location when provided", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team offsite",+ location: "Conference Room A",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(200);+ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Team offsite",+ location: "Conference Room A",+ }),+ );+ });++ it("should return error when too many date options", async () => {+ const dates = Array.from({ length: 101 }, (_, i) => {+ const date = new Date(2025, 0, 1 + i);+ return date.toISOString().split("T")[0];+ });++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates,+ }),+ });++ expect(res.status).toBe(400);+ const json = await res.json();+ expect(json.error.code).toBe("TOO_MANY_OPTIONS");+ });++ it("should return error when duplicate dates are provided", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15", "2025-01-16", "2025-01-15", "2025-01-17"],+ }),+ });++ expect(res.status).toBe(400);+ const json = await res.json();+ expect(json.error.code).toBe("DUPLICATE_DATES");+ expect(json.error.message).toContain("Duplicate dates found");+ });+ });++ describe("Create poll with slots", () => {+ it("should create a poll with time slot options", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: ["2025-01-15T09:00:00Z", "2025-01-15T10:00:00Z"],+ },+ }),+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(createPollSuccessResponseSchema, json);+ expect(json.data.id).toBe("test-poll-id");++ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Team sync",+ timeZone: "Europe/London",+ }),+ );+ });++ it("should track poll creation with source api and kind time", async () => {+ mockCreatePoll.mockResolvedValueOnce({+ id: "test-poll-id",+ title: "Team sync",+ description: null,+ location: null,+ timeZone: "Europe/London",+ status: "open",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ user: { name: "Test User", image: null },+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ },+ ],+ });++ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: ["2025-01-15T09:00:00Z"],+ },+ }),+ });++ expect(res.status).toBe(200);+ expect(mockTrack).toHaveBeenCalledWith(+ { id: "test-user-id", isGuest: false },+ expect.objectContaining({+ event: "poll_create",+ properties: expect.objectContaining({+ kind: "time",+ source: "api",+ }),+ }),+ );+ expect(mockIdentifyGroup).toHaveBeenCalledWith(+ expect.objectContaining({+ properties: expect.objectContaining({ kind: "time" }),+ }),+ );+ });++ it("should create poll without timezone when not provided in request", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ slots: {+ duration: 30,+ times: ["2025-01-15T09:00:00Z"],+ },+ }),+ });++ expect(res.status).toBe(200);+ expect(mockCreatePoll).toHaveBeenCalledWith(+ expect.objectContaining({+ timeZone: undefined,+ }),+ );+ });++ it("should return error for invalid timezone", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Team sync",+ slots: {+ duration: 30,+ timezone: "Invalid/Timezone",+ times: ["2025-01-15T09:00:00Z"],+ },+ }),+ });++ expect(res.status).toBe(400);+ });++ it("should create poll with slot generator", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Weekly standup",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: "2025-01-20",+ endDate: "2025-01-22",+ days: ["mon", "tue", "wed"],+ startTime: "09:00",+ endTime: "10:00",+ },+ ],+ },+ }),+ });++ expect(res.status).toBe(200);+ expect(mockCreatePoll).toHaveBeenCalled();+ });++ it("should reject a slot generator range longer than the supported limit", async () => {+ // A 516-day range, one Sunday slot each week (~74 slots). Deliberately+ // under MAX_POLL_OPTIONS so TOO_MANY_OPTIONS can't mask it: only the+ // range check rejects this. The old code silently truncated to ~52 slots+ // and returned them as a successful poll.+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Way too long",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: "2025-01-01",+ endDate: "2026-06-01",+ days: ["sun"],+ startTime: "09:00",+ endTime: "09:30",+ },+ ],+ },+ }),+ });++ // Rejected up front by validation, not silently truncated into a poll.+ // Assert the error targets endDate + names the limit so an unrelated 400+ // (e.g. TOO_MANY_OPTIONS) can't mask a regression.+ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ const json = await res.json();+ const issue = json.error.find((e: { path: (string | number)[] }) =>+ e.path.includes("endDate"),+ );+ expect(issue).toBeDefined();+ expect(issue.message).toContain(String(MAX_SLOT_GENERATION_DAYS));+ });++ it("should reject a slot generator range where endDate precedes startDate", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Reversed range",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: "2025-06-01",+ endDate: "2025-01-01",+ days: ["mon"],+ startTime: "09:00",+ endTime: "10:00",+ },+ ],+ },+ }),+ });++ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ const json = await res.json();+ const issue = json.error.find((e: { path: (string | number)[] }) =>+ e.path.includes("endDate"),+ );+ expect(issue).toBeDefined();+ });++ it("should reject a range spanning exactly MAX_SLOT_GENERATION_DAYS", async () => {+ // The generator processes days inclusively, so a span equal to the cap is+ // one day too many — the boundary must reject, not truncate.+ const start = new Date(Date.UTC(2025, 0, 1));+ const end = new Date(start);+ end.setUTCDate(end.getUTCDate() + MAX_SLOT_GENERATION_DAYS);+ const toIsoDate = (d: Date) => d.toISOString().slice(0, 10);+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Boundary range",+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: [+ {+ startDate: toIsoDate(start),+ endDate: toIsoDate(end),+ days: ["sun"],+ startTime: "09:00",+ endTime: "09:30",+ },+ ],+ },+ }),+ });++ expect(res.status).toBe(400);+ expect(mockCreatePoll).not.toHaveBeenCalled();+ });+ });++ describe("Validation", () => {+ it("should return error when neither dates nor slots provided", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ }),+ });++ expect(res.status).toBe(400);+ });++ it("should return error when both dates and slots provided", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ slots: {+ duration: 30,+ timezone: "Europe/London",+ times: ["2025-01-15T09:00:00Z"],+ },+ }),+ });++ expect(res.status).toBe(400);+ });++ it("should return error when title is missing", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(400);+ });++ it("should return error when dates array is empty", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: [],+ }),+ });++ expect(res.status).toBe(400);+ });+ });++ describe("OpenAPI endpoints", () => {+ it("should return OpenAPI spec", async () => {+ const res = await app.request("/api/v1/openapi");++ expect(res.status).toBe(200);+ const json = await res.json();+ expect(json.info.title).toBe("Rallly API");+ expect(json.info.version).toBe("1.0.0");+ });++ it("should state the versioning policy and point the playground at this origin", async () => {+ const res = await app.request("/api/v1/openapi");++ expect(res.status).toBe(200);+ const json = await res.json();+ expect(json.info.description).toContain("## Versioning");+ expect(json.info.description).toContain("new version prefix");+ expect(json.servers).toEqual([{ url: "https://example.com" }]);+ });++ it("should include create poll request examples that match the input schema", async () => {+ const res = await app.request("/api/v1/openapi");++ expect(res.status).toBe(200);+ const json = await res.json();+ const media =+ json.paths["/api/v1/polls"].post.requestBody.content[+ "application/json"+ ];+ expect(Object.keys(media.examples)).toEqual(+ Object.keys(createPollRequestExamples),+ );++ for (const example of Object.values(createPollRequestExamples)) {+ const result = createPollInputSchema.safeParse(example.value);+ expect(result.error).toBeUndefined();+ expect(result.success).toBe(true);+ }+ });++ it("should document the close poll transition on PATCH /polls/{pollId}", async () => {+ const res = await app.request("/api/v1/openapi");++ expect(res.status).toBe(200);+ const json = await res.json();+ const operation = json.paths["/api/v1/polls/{pollId}"].patch;++ expect(operation.summary).toBeDefined();+ expect(operation.description).toContain("closed");+ expect(Object.keys(operation.responses)).toEqual(+ expect.arrayContaining(["200", "403", "404", "422", "429"]),+ );++ const media = operation.requestBody.content["application/json"];+ expect(Object.keys(media.examples)).toEqual(+ Object.keys(patchPollRequestExamples),+ );+ });++ it("should not serve a docs page (the reference lives in the docs site)", async () => {+ const res = await app.request("/api/v1/docs");++ expect(res.status).toBe(404);+ });+ });++ describe("Patch poll (close)", () => {+ const closedPoll = {+ id: "test-poll-id",+ title: "Test Poll",+ description: null,+ location: null,+ timeZone: null,+ status: "closed",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ user: { name: "Test User", image: null },+ options: [],+ };++ it("should close an open poll", async () => {+ mockClosePoll.mockResolvedValue(closedPoll);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(patchPollSuccessResponseSchema, json);+ expect(json.data.id).toBe("test-poll-id");+ expect(json.data.status).toBe("closed");++ expect(mockClosePoll).toHaveBeenCalledWith({+ pollId: "test-poll-id",+ spaceId: "test-space-id",+ });+ });++ it("should be idempotent when the poll is already closed", async () => {+ mockClosePoll.mockResolvedValue(closedPoll);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expect(json.data.status).toBe("closed");+ });++ it("should return 404 when the poll is not found", async () => {+ mockClosePoll.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/nonexistent-poll", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ expect(mockClosePoll).toHaveBeenCalled();+ });++ it.each([+ "open",+ "scheduled",+ "canceled",+ ])("should return 422 when transitioning to %s", async (status) => {+ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status }),+ });++ expect(res.status).toBe(422);+ const json = await res.json();+ expect(json.error.code).toBe("TRANSITION_NOT_AVAILABLE");+ expect(mockClosePoll).not.toHaveBeenCalled();+ });++ it("should return 400 for an unknown status value", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "archived" }),+ });++ expect(res.status).toBe(400);+ expect(mockClosePoll).not.toHaveBeenCalled();+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ status: "closed" }),+ });++ expect(res.status).toBe(401);+ expect(mockClosePoll).not.toHaveBeenCalled();+ });+ });++ describe("Delete poll", () => {+ it("should delete a poll", async () => {+ mockDeletePoll.mockResolvedValue({ id: "test-poll-id" });++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(deletePollSuccessResponseSchema, json);+ expect(json.data.id).toBe("test-poll-id");+ expect(json.data.deleted).toBe(true);++ expect(mockDeletePoll).toHaveBeenCalledWith(+ "test-poll-id",+ "test-space-id",+ );+ });++ it("should return 404 when poll not found", async () => {+ mockDeletePoll.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/nonexistent-poll", {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return 404 when poll belongs to different space", async () => {+ mockDeletePoll.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/other-space-poll", {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "DELETE",+ });++ expect(res.status).toBe(401);+ });++ it("should return 404 when poll is already deleted", async () => {+ mockDeletePoll.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/deleted-poll-id", {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });+ });++ describe("Get poll", () => {+ const mockPoll = {+ id: "test-poll-id",+ title: "Team sync",+ description: "Weekly team meeting",+ location: "Zoom",+ timeZone: "Europe/London",+ status: "open",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ user: {+ name: "John Doe",+ image: "https://example.com/avatar.jpg",+ },+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ },+ {+ id: "opt-2",+ startTime: new Date("2025-01-15T10:00:00Z"),+ duration: 30,+ },+ ],+ };++ it("should return poll data", async () => {+ mockGetPollWithOptions.mockResolvedValue(mockPoll);++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(getPollSuccessResponseSchema, json);+ expect(json.data.id).toBe("test-poll-id");+ expect(json.data.title).toBe("Team sync");+ expect(json.data.description).toBe("Weekly team meeting");+ expect(json.data.location).toBe("Zoom");+ expect(json.data.timezone).toBe("Europe/London");+ expect(json.data.status).toBe("open");+ expect(json.data.createdAt).toBe("2025-01-10T12:00:00.000Z");+ expect(json.data.user).toEqual({+ name: "John Doe",+ image: "https://example.com/avatar.jpg",+ });+ expect(json.data.options).toHaveLength(2);+ expect(json.data.options[0]).toEqual({+ id: "opt-1",+ startTime: "2025-01-15T09:00:00.000Z",+ duration: 30,+ });+ expect(json.data.adminUrl).toBe("https://example.com/poll/test-poll-id");+ expect(json.data.inviteUrl).toBe(+ "https://example.com/invite/test-poll-id",+ );++ expect(mockGetPollWithOptions).toHaveBeenCalledWith({+ pollId: "test-poll-id",+ spaceId: "test-space-id",+ });+ });++ it("should return poll without user when user is null", async () => {+ mockGetPollWithOptions.mockResolvedValue({+ ...mockPoll,+ user: null,+ });++ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expect(json.data.user).toBeNull();+ });++ it("should return 404 when poll not found", async () => {+ mockGetPollWithOptions.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/nonexistent-poll", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return 404 when poll belongs to different space", async () => {+ mockGetPollWithOptions.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/other-space-poll", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id", {+ method: "GET",+ });++ expect(res.status).toBe(401);+ });+ });++ describe("List polls", () => {+ const mockListedPoll = {+ id: "test-poll-id",+ title: "Team sync",+ description: "Weekly team meeting",+ location: "Zoom",+ timeZone: "Europe/London",+ status: "open",+ createdAt: new Date("2025-01-10T12:00:00Z"),+ user: {+ name: "John Doe",+ image: null,+ },+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ },+ ],+ participantCount: 3,+ };++ it("should return a list of polls", async () => {+ mockListPolls.mockResolvedValue({+ polls: [mockListedPoll],+ nextCursor: null,+ });++ const res = await app.request("/api/v1/polls", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(listPollsSuccessResponseSchema, json);++ expect(json.data).toHaveLength(1);+ expect(json.data[0].id).toBe("test-poll-id");+ expect(json.data[0].title).toBe("Team sync");+ expect(json.data[0].status).toBe("open");+ expect(json.data[0].participantCount).toBe(3);+ expect(json.data[0].createdAt).toBe("2025-01-10T12:00:00.000Z");+ expect(json.data[0].options).toEqual([+ {+ id: "opt-1",+ startTime: "2025-01-15T09:00:00.000Z",+ duration: 30,+ },+ ]);+ expect(json.data[0].adminUrl).toBe(+ "https://example.com/poll/test-poll-id",+ );+ expect(json.data[0].inviteUrl).toBe(+ "https://example.com/invite/test-poll-id",+ );+ expect(json.nextCursor).toBeNull();++ expect(mockListPolls).toHaveBeenCalledWith({+ spaceId: "test-space-id",+ status: undefined,+ cursor: undefined,+ limit: 20,+ });+ });++ it("should return an empty list when the space has no polls", async () => {+ mockListPolls.mockResolvedValue({+ polls: [],+ nextCursor: null,+ });++ const res = await app.request("/api/v1/polls", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(listPollsSuccessResponseSchema, json);+ expect(json.data).toEqual([]);+ expect(json.nextCursor).toBeNull();+ });++ it("should pass the status filter to the query", async () => {+ mockListPolls.mockResolvedValue({+ polls: [],+ nextCursor: null,+ });++ const res = await app.request("/api/v1/polls?status=open", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ expect(mockListPolls).toHaveBeenCalledWith(+ expect.objectContaining({+ spaceId: "test-space-id",+ status: "open",+ }),+ );+ });++ it("should return 400 for an invalid status", async () => {+ const res = await app.request("/api/v1/polls?status=finalized", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(400);+ expect(mockListPolls).not.toHaveBeenCalled();+ });++ it("should pass cursor and limit to the query and return nextCursor", async () => {+ mockListPolls.mockResolvedValue({+ polls: [mockListedPoll],+ nextCursor: "test-poll-id",+ });++ const res = await app.request(+ "/api/v1/polls?cursor=prev-poll-id&limit=1",+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ },+ );++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(listPollsSuccessResponseSchema, json);+ expect(json.nextCursor).toBe("test-poll-id");++ expect(mockListPolls).toHaveBeenCalledWith(+ expect.objectContaining({+ cursor: "prev-poll-id",+ limit: 1,+ }),+ );+ });++ it("should return 400 when limit exceeds the maximum", async () => {+ const res = await app.request("/api/v1/polls?limit=101", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(400);+ expect(mockListPolls).not.toHaveBeenCalled();+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/v1/polls", {+ method: "GET",+ });++ expect(res.status).toBe(401);+ });+ });++ describe("Get poll results", () => {+ it("should return aggregated vote results", async () => {+ mockGetPollResults.mockResolvedValue({+ pollId: "test-poll-id",+ status: "open",+ participantCount: 5,+ highScore: 4003,+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ votes: [+ { type: "yes", count: 3 },+ { type: "ifNeedBe", count: 1 },+ { type: "no", count: 1 },+ ],+ score: 4003,+ isTopChoice: true,+ },+ {+ id: "opt-2",+ startTime: new Date("2025-01-15T10:00:00Z"),+ duration: 30,+ votes: [+ { type: "yes", count: 1 },+ { type: "no", count: 2 },+ ],+ score: 1001,+ isTopChoice: false,+ },+ {+ id: "opt-3",+ startTime: new Date("2025-01-15T11:00:00Z"),+ duration: 30,+ votes: [],+ score: 0,+ isTopChoice: false,+ },+ ],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/results", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(getPollResultsSuccessResponseSchema, json);++ expect(json.data.pollId).toBe("test-poll-id");+ expect(json.data.status).toBe("open");+ expect(json.data.participantCount).toBe(5);+ expect(json.data.highScore).toBe(4003);+ expect(json.data.options).toHaveLength(3);++ expect(mockGetPollResults).toHaveBeenCalledWith({+ pollId: "test-poll-id",+ spaceId: "test-space-id",+ });+ });++ it("should return the poll status for closed polls", async () => {+ mockGetPollResults.mockResolvedValue({+ pollId: "test-poll-id",+ status: "closed",+ participantCount: 1,+ highScore: 1001,+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ votes: [{ type: "yes", count: 1 }],+ score: 1001,+ isTopChoice: true,+ },+ ],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/results", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(getPollResultsSuccessResponseSchema, json);+ expect(json.data.status).toBe("closed");+ });++ it("should handle ties for top choice", async () => {+ mockGetPollResults.mockResolvedValue({+ pollId: "test-poll-id",+ status: "open",+ participantCount: 2,+ highScore: 2002,+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ votes: [{ type: "yes", count: 2 }],+ score: 2002,+ isTopChoice: true,+ },+ {+ id: "opt-2",+ startTime: new Date("2025-01-15T10:00:00Z"),+ duration: 30,+ votes: [{ type: "yes", count: 2 }],+ score: 2002,+ isTopChoice: true,+ },+ ],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/results", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();++ // Both options have score 2002, both should be top choice+ expect(json.data.options[0].isTopChoice).toBe(true);+ expect(json.data.options[1].isTopChoice).toBe(true);+ expect(json.data.highScore).toBe(2002);+ });++ it("should prioritize total availability over yes votes", async () => {+ mockGetPollResults.mockResolvedValue({+ pollId: "test-poll-id",+ status: "open",+ participantCount: 5,+ highScore: 5003,+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ votes: [{ type: "yes", count: 4 }],+ score: 4004,+ isTopChoice: false,+ },+ {+ id: "opt-2",+ startTime: new Date("2025-01-15T10:00:00Z"),+ duration: 30,+ votes: [+ { type: "yes", count: 3 },+ { type: "ifNeedBe", count: 2 },+ ],+ score: 5003,+ isTopChoice: true,+ },+ ],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/results", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();++ // 5 available (5003) beats 4 available (4004) even though opt-1 has more yes votes+ expect(json.data.options[0].score).toBe(4004);+ expect(json.data.options[0].isTopChoice).toBe(false);+ expect(json.data.options[1].score).toBe(5003);+ expect(json.data.options[1].isTopChoice).toBe(true);+ });++ it("should use yes votes as tiebreaker when availability is equal", async () => {+ mockGetPollResults.mockResolvedValue({+ pollId: "test-poll-id",+ status: "open",+ participantCount: 4,+ highScore: 4004,+ options: [+ {+ id: "opt-1",+ startTime: new Date("2025-01-15T09:00:00Z"),+ duration: 30,+ votes: [+ { type: "yes", count: 3 },+ { type: "ifNeedBe", count: 1 },+ ],+ score: 4003,+ isTopChoice: false,+ },+ {+ id: "opt-2",+ startTime: new Date("2025-01-15T10:00:00Z"),+ duration: 30,+ votes: [{ type: "yes", count: 4 }],+ score: 4004,+ isTopChoice: true,+ },+ ],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/results", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();++ // Same availability (4), but opt-2 has more yes votes+ expect(json.data.options[0].score).toBe(4003);+ expect(json.data.options[0].isTopChoice).toBe(false);+ expect(json.data.options[1].score).toBe(4004);+ expect(json.data.options[1].isTopChoice).toBe(true);+ });++ it("should return 404 when poll not found", async () => {+ mockGetPollResults.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/nonexistent-poll/results", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id/results", {+ method: "GET",+ });++ expect(res.status).toBe(401);+ });+ });++ describe("Rate limiting", () => {+ // The rate limiter is keyed per space. Use a dedicated space id here so+ // the requests below don't count against (or get counted by) other tests.+ const rateLimitSpaceId = "rate-limit-space-id";++ beforeEach(() => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ spaceId: rateLimitSpaceId,+ lastUsedAt: new Date(),+ },+ ]);+ });++ it("should include standard RateLimit headers on successful responses", async () => {+ mockGetPollWithOptions.mockResolvedValue(null);++ const res = await app.request("/api/v1/polls/some-poll", {+ method: "GET",+ headers: { Authorization: `Bearer ${testApiKey}` },+ });++ expect(res.headers.get("RateLimit-Limit")).toBe(+ String(RATE_LIMIT_PER_MINUTE),+ );+ expect(res.headers.get("RateLimit-Remaining")).not.toBeNull();+ });++ it("should return 429 with RATE_LIMIT_EXCEEDED once the per-space limit is exceeded", async () => {+ mockGetPollWithOptions.mockResolvedValue(null);++ const request = () =>+ app.request("/api/v1/polls/some-poll", {+ method: "GET",+ headers: { Authorization: `Bearer ${testApiKey}` },+ });++ // The limit is RATE_LIMIT_PER_MINUTE requests/minute per space; one more trips it.+ let limited: Response | undefined;+ for (let i = 0; i < RATE_LIMIT_PER_MINUTE + 1; i++) {+ const res = await request();+ if (res.status === 429) {+ limited = res;+ break;+ }+ }++ expect(limited).toBeDefined();+ expect(limited?.status).toBe(429);+ expect(limited?.headers.get("Retry-After")).not.toBeNull();++ const json = await limited?.json();+ expect(json.error.code).toBe("RATE_LIMIT_EXCEEDED");+ });+ });++ describe("Get poll participants", () => {+ it("should return participants", async () => {+ mockGetPollParticipants.mockResolvedValue({+ pollId: "test-poll-id",+ participants: [+ {+ id: "participant-1",+ name: "Alice",+ email: "[email protected]",+ createdAt: new Date("2025-01-10T10:00:00Z"),+ },+ {+ id: "participant-2",+ name: "Bob",+ email: null,+ createdAt: new Date("2025-01-10T11:00:00Z"),+ },+ ],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/participants", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();+ expectMatchesContract(getPollParticipantsSuccessResponseSchema, json);++ expect(json.data.pollId).toBe("test-poll-id");+ expect(json.data.participants).toHaveLength(2);++ expect(mockGetPollParticipants).toHaveBeenCalledWith({+ pollId: "test-poll-id",+ spaceId: "test-space-id",+ });+ });++ it("should return empty array when no participants", async () => {+ mockGetPollParticipants.mockResolvedValue({+ pollId: "test-poll-id",+ participants: [],+ });++ const res = await app.request("/api/v1/polls/test-poll-id/participants", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).toBe(200);+ const json = await res.json();++ expect(json.data.pollId).toBe("test-poll-id");+ expect(json.data.participants).toEqual([]);+ });++ it("should return 404 when poll not found", async () => {+ mockGetPollParticipants.mockResolvedValue(null);++ const res = await app.request(+ "/api/v1/polls/nonexistent-poll/participants",+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ },+ );++ expect(res.status).toBe(404);+ const json = await res.json();+ expect(json.error.code).toBe("POLL_NOT_FOUND");+ });++ it("should return 401 without authorization", async () => {+ const res = await app.request("/api/v1/polls/test-poll-id/participants", {+ method: "GET",+ });++ expect(res.status).toBe(401);+ });+ });+});diff --git a/apps/web/src/app/api/v1/[...route]/route.ts b/apps/web/src/app/api/v1/[...route]/route.tsnew file mode 100644index 000000000..71330c4c2--- /dev/null+++ b/apps/web/src/app/api/v1/[...route]/route.ts@@ -0,0 +1,833 @@+import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";+import { Hono } from "hono";+import { handle } from "hono/vercel";+import {+ describeRoute,+ generateSpecs,+ resolver,+ validator,+} from "hono-openapi";+import { after } from "next/server";+import { MAX_POLL_OPTIONS } from "@/features/poll/constants";+import {+ getPollParticipants,+ getPollResults,+ getPollWithOptions,+ listPolls,+} from "@/features/poll/data";+import { closePoll, createPoll, deletePoll } from "@/features/poll/mutations";+import { getSpaceMemberByEmail } from "@/features/space/member/data";+import type { SpaceTier } from "@/features/space/schema";+import type { AuthorizedSpaceId } from "@/features/space/types";+import type { SlotGeneratorInput } from "@/lib/datetime/slot-generator";+import {+ dedupeTimeSlots,+ generateTimeSlots,+ parseStartTime,+} from "@/lib/datetime/slot-generator";+import { isMaintenanceModeEnabled } from "@/lib/maintenance";+import { flushPostHog, identifyGroup, track } from "@/lib/posthog";+import { apiError } from "../../middleware/api-error";+import { spaceApiKeyAuth } from "../../middleware/api-key";+import {+ RATE_LIMIT_PER_DAY,+ RATE_LIMIT_PER_MINUTE,+ rateLimit,+} from "../../middleware/rate-limit";+import { wideEvent } from "../../middleware/wide-event";+import {+ createPollRequestExamples,+ patchPollRequestExamples,+} from "../examples";+import {+ createPollInputSchema,+ createPollSuccessResponseSchema,+ deletePollSuccessResponseSchema,+ errorResponseSchema,+ getPollParticipantsSuccessResponseSchema,+ getPollResultsSuccessResponseSchema,+ getPollSuccessResponseSchema,+ listPollsQuerySchema,+ listPollsSuccessResponseSchema,+ patchPollInputSchema,+ patchPollSuccessResponseSchema,+} from "../schemas";++type Env = {+ Variables: {+ apiAuth: {+ spaceId: AuthorizedSpaceId;+ spaceOwnerId: string;+ spaceTier: SpaceTier;+ apiKeyId: string;+ };+ };+};++const app = new Hono<Env>().basePath("/api/v1");++function toPollResponseBody(poll: {+ id: string;+ title: string;+ description: string | null;+ location: string | null;+ timeZone: string | null;+ status: string;+ createdAt: Date;+ user: { name: string; image: string | null } | null;+ options: { id: string; startTime: Date; duration: number }[];+}) {+ return {+ 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: absoluteUrl(`/poll/${poll.id}`),+ inviteUrl: shortUrl(`/invite/${poll.id}`),+ },+ };+}++app.use("*", wideEvent({ service: "api-v1" }));++app.use("*", async (c, next) => {+ if (isMaintenanceModeEnabled()) {+ return c.json(+ apiError("SERVICE_UNAVAILABLE", "The app is down for maintenance"),+ 503,+ { "Retry-After": "300" },+ );+ }+ await next();+});++const spaceNotProResponse = {+ description:+ "The space associated with the API key does not have a Pro subscription",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+};++const retryAfterHeader = {+ "Retry-After": {+ description: "Seconds to wait before retrying the request.",+ schema: { type: "integer" as const },+ },+};++const rateLimitExceededResponse = {+ description:+ "Rate limit exceeded. Includes a `Retry-After` header indicating how many seconds to wait before retrying.",+ headers: retryAfterHeader,+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+};++const serviceUnavailableResponse = {+ description:+ "The API is temporarily unavailable, for maintenance or because the rate limit store cannot be reached. Includes a `Retry-After` header. Maintenance responses are sent before the rate limiter runs and carry no `RateLimit-*` headers.",+ headers: retryAfterHeader,+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+};++async function buildOpenApiSpec() {+ const spec = await generateSpecs(app, {+ documentation: {+ info: {+ title: "Rallly API",+ version: "1.0.0",+ description: [+ "## Versioning",+ "",+ "`v1` is stable. Additive changes (new endpoints, new optional fields) may land on this path at any time; breaking changes only arrive under a new version prefix.",+ "",+ "## Rate limits",+ "",+ `All endpoints share two limits per space: **${RATE_LIMIT_PER_MINUTE} requests per minute** and **${RATE_LIMIT_PER_DAY} requests per day**. Both are fixed windows that open with the first request and reset when they expire. Both limits are per space, not per API key, so creating additional keys does not increase throughput.`,+ "",+ "Every response from an authenticated request includes the standard `RateLimit-*` headers. Responses sent before the limiter runs (`401`, `403`, and the maintenance `503`) do not. `RateLimit-Policy` lists both limits; `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` describe whichever limit is closest to being exhausted. When either limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.",+ "",+ "If the rate limit store cannot be reached the API fails closed and responds with `503 Service Unavailable`, a `SERVICE_UNAVAILABLE` error body, and a `Retry-After` header.",+ ].join("\n"),+ },+ servers: [{ url: absoluteUrl() }],+ components: {+ securitySchemes: {+ bearerAuth: {+ type: "http",+ scheme: "bearer",+ },+ },+ },+ },+ });++ // hono-openapi's validator middleware owns the request body schema and+ // overwrites any content set via describeRoute, so named examples have to+ // be attached to the generated spec instead.+ const createPollRequestBody = spec.paths["/api/v1/polls"]?.post?.requestBody;+ if (createPollRequestBody && "content" in createPollRequestBody) {+ const media = createPollRequestBody.content?.["application/json"];+ if (media) {+ media.examples = createPollRequestExamples;+ }+ }++ const patchPollRequestBody =+ spec.paths["/api/v1/polls/{pollId}"]?.patch?.requestBody;+ if (patchPollRequestBody && "content" in patchPollRequestBody) {+ const media = patchPollRequestBody.content?.["application/json"];+ if (media) {+ media.examples = patchPollRequestExamples;+ }+ }++ return spec;+}++let openApiSpec: Awaited<ReturnType<typeof buildOpenApiSpec>> | undefined;++app.get("/openapi", async (c) => {+ openApiSpec ??= await buildOpenApiSpec();+ return c.json(openApiSpec);+});++app.post(+ "/polls",+ spaceApiKeyAuth,+ rateLimit,+ describeRoute({+ tags: ["Polls"],+ summary: "Create a poll",+ description: [+ "Creates a new poll. Provide the poll options in one of two ways:",+ "",+ "- `dates` — a list of calendar dates. Each date becomes an all-day option (date poll).",+ "- `slots` — time-based options that share a fixed `duration` in minutes. Each entry in `slots.times` is either an ISO datetime for an explicit slot, or a slot generator that expands into recurring slots within a time window across a date range. Generated slots start every `interval` minutes (defaults to `duration`) and must fit entirely between `startTime` and `endTime`.",+ "",+ "`dates` and `slots` are mutually exclusive, and a poll can have at most 100 options. See the request examples for common scenarios.",+ ].join("\n"),+ 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),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ },+ }),+ 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 getSpaceMemberByEmail({+ spaceId,+ email: input.organizer.email,+ });++ if (!spaceMember) {+ return c.json(+ apiError(+ "ORGANIZER_NOT_MEMBER",+ "The specified organizer is not a member of this space.",+ ),+ 400,+ );+ }++ organizerUserId = spaceMember.userId;+ }++ const trackPollCreated = (poll: Awaited<ReturnType<typeof createPoll>>) => {+ const kind = poll.options.some((o) => o.duration > 0) ? "time" : "date";++ identifyGroup({+ groupType: "poll",+ groupKey: poll.id,+ properties: {+ name: poll.title,+ status: poll.status,+ kind,+ created_at: poll.createdAt,+ comment_count: 0,+ option_count: poll.options.length,+ has_location: !!poll.location,+ has_description: !!poll.description,+ timezone: poll.timeZone,+ muted: false,+ },+ });++ track(+ { id: organizerUserId, isGuest: false },+ {+ event: "poll_create",+ properties: {+ title: poll.title,+ kind,+ source: "api",+ optionCount: poll.options.length,+ hasLocation: !!poll.location,+ hasDescription: !!poll.description,+ timezone: poll.timeZone,+ requireParticipantEmail: input.requireEmail,+ hideParticipants: input.hideParticipants,+ hideScores: input.hideScores,+ disableComments: poll.disableComments,+ isGuest: false,+ },+ groups: {+ poll: poll.id,+ space: spaceId,+ },+ },+ );++ after(() => flushPostHog());+ };++ // Process dates (all-day options)+ if (input.dates) {+ if (input.dates.length > MAX_POLL_OPTIONS) {+ return c.json(+ apiError(+ "TOO_MANY_OPTIONS",+ `Too many options (${input.dates.length}). Maximum allowed is ${MAX_POLL_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,+ });++ trackPollCreated(poll);++ return c.json(+ createPollSuccessResponseSchema.parse(toPollResponseBody(poll)),+ );+ }++ // 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_POLL_OPTIONS) {+ return c.json(+ apiError(+ "TOO_MANY_OPTIONS",+ `Too many options generated (${options.length}). Maximum allowed is ${MAX_POLL_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,+ });++ trackPollCreated(poll);++ return c.json(+ createPollSuccessResponseSchema.parse(toPollResponseBody(poll)),+ );+ },+);++app.get(+ "/polls",+ spaceApiKeyAuth,+ rateLimit,+ describeRoute({+ tags: ["Polls"],+ summary: "List polls",+ description: [+ "Lists the polls in the space associated with the API key, sorted by creation date (newest first).",+ "",+ "Use the `status` query parameter to only return polls in a given state — for example `status=open` to sweep polls that are still collecting responses. Results are paginated with a cursor: pass the `nextCursor` value from the previous response to fetch the next page.",+ ].join("\n"),+ security: [{ bearerAuth: [] }],+ responses: {+ 200: {+ description: "Successful response",+ content: {+ "application/json": {+ schema: resolver(listPollsSuccessResponseSchema),+ },+ },+ },+ 400: {+ description: "Invalid query parameters",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ },+ }),+ validator("query", listPollsQuerySchema),+ async (c) => {+ const { status, cursor, limit } = c.req.valid("query");+ const { spaceId } = c.get("apiAuth");++ const { polls, nextCursor } = await listPolls({+ spaceId,+ status,+ cursor,+ limit,+ });++ return c.json(+ listPollsSuccessResponseSchema.parse({+ data: polls.map((poll) => ({+ ...toPollResponseBody(poll).data,+ participantCount: poll.participantCount,+ })),+ nextCursor,+ }),+ );+ },+);++app.get(+ "/polls/:pollId",+ spaceApiKeyAuth,+ rateLimit,+ 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),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ 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 getPollWithOptions({ pollId, spaceId });++ if (!poll) {+ return c.json(+ apiError(+ "POLL_NOT_FOUND",+ "Poll not found or does not belong to this space.",+ ),+ 404,+ );+ }++ return c.json(getPollSuccessResponseSchema.parse(toPollResponseBody(poll)));+ },+);++app.patch(+ "/polls/:pollId",+ spaceApiKeyAuth,+ rateLimit,+ describeRoute({+ tags: ["Polls"],+ summary: "Update a poll",+ description: [+ 'Updates a poll\'s status. Currently the only supported transition is closing a poll by sending `{ "status": "closed" }`.',+ "",+ "Close a poll once you have picked a date or the poll is no longer needed. Closing is non-destructive — the poll and its responses are preserved — but the results become final and participants can no longer vote. Consumers polling `GET /polls/:pollId/results` should remove closed polls from their queues.",+ "",+ "Closing is idempotent: closing an already-closed poll returns a `200` with the poll unchanged. The other statuses (`open`, `scheduled`, `canceled`) are not available via the API and return `422`.",+ ].join("\n"),+ security: [{ bearerAuth: [] }],+ responses: {+ 200: {+ description: "Poll updated successfully",+ content: {+ "application/json": {+ schema: resolver(patchPollSuccessResponseSchema),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ 404: {+ description: "Poll not found",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+ },+ 422: {+ description: "The requested status transition is not available",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+ },+ },+ }),+ validator("json", patchPollInputSchema),+ async (c) => {+ const { pollId } = c.req.param();+ const { status } = c.req.valid("json");+ const { spaceId } = c.get("apiAuth");++ if (status !== "closed") {+ return c.json(+ apiError(+ "TRANSITION_NOT_AVAILABLE",+ `Transitioning a poll to "${status}" is not available via the API. Only "closed" is supported.`,+ ),+ 422,+ );+ }++ const poll = await closePoll({ pollId, spaceId });++ if (!poll) {+ return c.json(+ apiError(+ "POLL_NOT_FOUND",+ "Poll not found or does not belong to this space.",+ ),+ 404,+ );+ }++ return c.json(+ patchPollSuccessResponseSchema.parse(toPollResponseBody(poll)),+ );+ },+);++app.get(+ "/polls/:pollId/results",+ spaceApiKeyAuth,+ rateLimit,+ 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),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ 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(+ getPollResultsSuccessResponseSchema.parse({+ data: {+ ...data,+ options: data.options.map((option) => ({+ ...option,+ startTime: option.startTime.toISOString(),+ })),+ },+ }),+ );+ },+);++app.get(+ "/polls/:pollId/participants",+ spaceApiKeyAuth,+ rateLimit,+ 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),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ 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(+ getPollParticipantsSuccessResponseSchema.parse({+ data: {+ pollId: data.pollId,+ participants: data.participants.map((participant) => ({+ ...participant,+ createdAt: participant.createdAt.toISOString(),+ })),+ },+ }),+ );+ },+);++app.delete(+ "/polls/:pollId",+ spaceApiKeyAuth,+ rateLimit,+ 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),+ },+ },+ },+ 403: spaceNotProResponse,+ 429: rateLimitExceededResponse,+ 503: serviceUnavailableResponse,+ 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(+ deletePollSuccessResponseSchema.parse({+ data: {+ id: result.id,+ deleted: true,+ },+ }),+ );+ },+);++export { app };++export const GET = handle(app);+export const POST = handle(app);+export const PATCH = handle(app);+export const DELETE = handle(app);diff --git a/apps/web/src/app/api/v1/examples.ts b/apps/web/src/app/api/v1/examples.tsnew file mode 100644index 000000000..873585f69--- /dev/null+++ b/apps/web/src/app/api/v1/examples.ts@@ -0,0 +1,91 @@+import type * as z from "zod";+import type { createPollInputSchema, patchPollInputSchema } from "./schemas";++type CreatePollInput = z.input<typeof createPollInputSchema>;+type PatchPollInput = z.input<typeof patchPollInputSchema>;++export const createPollRequestExamples = {+ datePoll: {+ summary: "Date poll (all-day options)",+ description:+ "Use `dates` to let participants pick between calendar days. Each date becomes an all-day option.",+ value: {+ title: "Team offsite",+ description: "Which days work for a two day offsite?",+ dates: ["2026-08-03", "2026-08-04", "2026-08-05"],+ } satisfies CreatePollInput,+ },+ timePoll: {+ summary: "Time poll (explicit times)",+ description:+ "Use `slots` with ISO datetime strings to offer specific time slots. Datetimes without an offset are interpreted as wall-clock in the poll's `timezone` — the example below offers 09:00 and 14:00 in London. Append `Z` or an offset to specify an absolute instant instead.",+ value: {+ title: "Project kickoff",+ location: "Zoom",+ slots: {+ duration: 60,+ timezone: "Europe/London",+ times: [+ "2026-08-03T09:00:00",+ "2026-08-03T14:00:00",+ "2026-08-04T09:00:00",+ ],+ },+ } satisfies CreatePollInput,+ },+ slotGenerator: {+ summary: "Time poll (slot generator)",+ description:+ "Use a slot generator to expand recurring slots across a date range. This example generates 30 minute slots at 09:00, 10:00 and 11:00 (New York time) every weekday between 3-7 August.",+ value: {+ title: "Interview availability",+ slots: {+ duration: 30,+ timezone: "America/New_York",+ times: [+ {+ startDate: "2026-08-03",+ endDate: "2026-08-07",+ days: ["mon", "tue", "wed", "thu", "fri"],+ startTime: "09:00",+ endTime: "12:00",+ interval: 60,+ },+ ],+ },+ } satisfies CreatePollInput,+ },+ mixedTimes: {+ summary: "Time poll (explicit times + generator)",+ description:+ "`slots.times` can mix ISO datetime strings and slot generators. When `interval` is omitted it defaults to `duration`, so this generator produces back to back 90 minute slots at 14:00 and 15:30 on Monday and Wednesday.",+ value: {+ title: "Product workshop",+ slots: {+ duration: 90,+ timezone: "Europe/Berlin",+ times: [+ "2026-08-01T10:00:00",+ {+ startDate: "2026-08-03",+ endDate: "2026-08-05",+ days: ["mon", "wed"],+ startTime: "14:00",+ endTime: "17:00",+ },+ ],+ },+ } satisfies CreatePollInput,+ },+};++export const patchPollRequestExamples = {+ close: {+ summary: "Close a poll",+ description:+ "Set `status` to `closed` once you have picked a date or no longer need the poll. Closing is idempotent and makes the results final.",+ value: {+ status: "closed",+ } satisfies PatchPollInput,+ },+};diff --git a/apps/web/src/app/api/v1/schemas.ts b/apps/web/src/app/api/v1/schemas.tsnew file mode 100644index 000000000..f622d2693--- /dev/null+++ b/apps/web/src/app/api/v1/schemas.ts@@ -0,0 +1,348 @@+import { z } from "@hono/zod-openapi";+import { MAX_SLOT_GENERATION_DAYS } from "@/lib/datetime/slot-generator";+import { timezoneSchema } from "@/lib/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,+ }),+ })+ // Reject over-long ranges up front rather than silently truncating at the+ // generator's MAX_SLOT_GENERATION_DAYS cap.+ .refine(+ (data) => {+ const start = Date.parse(data.startDate);+ const end = Date.parse(data.endDate);+ const spanDays = (end - start) / (1000 * 60 * 60 * 24);+ return spanDays >= 0 && spanDays < MAX_SLOT_GENERATION_DAYS;+ },+ {+ message: `The date range must span fewer than ${MAX_SLOT_GENERATION_DAYS} days, with endDate on or after startDate.`,+ path: ["endDate"],+ },+ )+ .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. Datetime strings without an offset are interpreted in this timezone. If omitted, offset-less datetimes are treated as floating times (no timezone conversion) and the poll has no timezone set.",+ example: "Europe/London",+ }),+ times: z+ .array(+ z.union([+ z.iso.datetime({ local: true, offset: true }).openapi({+ description:+ "ISO datetime start time. Strings without an offset are interpreted as wall-clock in `timezone` (e.g. `2025-01-15T09:00:00` with `timezone: Europe/London` means 09:00 in London). Strings with an offset or `Z` are treated as absolute instants.",+ example: "2025-01-15T09:00:00",+ }),+ 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. Defaults to true: new polls have comments disabled unless this is set to false.",+ 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");++const pollSchema = 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("Poll");++export const getPollSuccessResponseSchema = z+ .object({+ data: pollSchema,+ })+ .openapi("GetPollResponse");++export const patchPollInputSchema = z+ .object({+ status: pollStatusSchema.openapi({+ description:+ "The status to transition the poll to. Only `closed` is currently accepted; the other statuses are reserved for future transitions.",+ example: "closed",+ }),+ })+ .openapi("PatchPollInput");++// Updating a poll returns the same shape as get poll+export const patchPollSuccessResponseSchema =+ getPollSuccessResponseSchema.openapi("PatchPollResponse");++// Create poll returns the same shape as get poll+export const createPollSuccessResponseSchema =+ getPollSuccessResponseSchema.openapi("CreatePollResponse");++export const listPollsQuerySchema = z.object({+ status: pollStatusSchema.optional().openapi({+ description: "Filter polls by status. Omit to include all statuses.",+ example: "open",+ }),+ cursor: z.string().optional().openapi({+ description:+ "Cursor for pagination. Pass the `nextCursor` value from the previous response to fetch the next page.",+ example: "p_123abc",+ }),+ limit: z.coerce.number().int().min(1).max(100).default(20).openapi({+ description: "Number of polls to return per page (1-100).",+ example: 20,+ }),+});++export const listPollItemSchema = pollSchema+ .extend({+ participantCount: z.int().nonnegative().openapi({+ description: "Number of participants who have responded to the poll",+ example: 3,+ }),+ })+ .openapi("ListPollItem");++export const listPollsSuccessResponseSchema = z+ .object({+ data: z.array(listPollItemSchema),+ nextCursor: z.string().nullable().openapi({+ description:+ "Cursor to fetch the next page. `null` when there are no more results.",+ example: "p_123abc",+ }),+ })+ .openapi("ListPollsResponse");++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" }),+ status: pollStatusSchema.openapi({+ description:+ "Current poll status. Polls close automatically when all options are in the past.",+ example: "open",+ }),+ 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/web/src/features/api-keys/constants.ts b/apps/web/src/features/api-keys/constants.tsindex 77efa8eb3..bd07f05f5 100644--- a/apps/web/src/features/api-keys/constants.ts+++ b/apps/web/src/features/api-keys/constants.ts@@ -20,15 +20,8 @@ export const API_RATE_LIMIT_PER_MINUTE = 60;export const API_RATE_LIMIT_PER_DAY = 5000;/**- * Path segment for the current version of the public API. Keeping it here- * means moving between versions (e.g. `private` → `v1`) only touches one- * place, and every link stays pointed at the latest docs.+ * Link to the API reference. Still the private route's Scalar page: v1 has+ * no in-app docs page, its reference is generated from `/api/v1/openapi`+ * into the docs site, and this link moves there when that ships.*/-const CURRENT_API_VERSION_PATH = "private";--/**- * Link to the interactive API reference for the current version. Callers- * should use this rather than hardcoding the path so version moves don't- * leave stale links behind.- */-export const getApiDocsPath = () => `/api/${CURRENT_API_VERSION_PATH}/docs`;+export const getApiDocsPath = () => "/api/private/docs";diff --git a/apps/web/src/features/poll/data.ts b/apps/web/src/features/poll/data.tsindex ee9c311b4..30f69ea69 100644--- a/apps/web/src/features/poll/data.ts+++ b/apps/web/src/features/poll/data.ts@@ -498,3 +498,44 @@ export async function listParticipantIdsByToken({});return participant ? [participant.id] : [];}++export async function getPollWithOptions({+ pollId,+ spaceId,+}: {+ pollId: string;+ spaceId: AuthorizedSpaceId;+}) {+ return 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",+ },+ },+ },+ });+}diff --git a/apps/web/src/features/space/member/data.ts b/apps/web/src/features/space/member/data.tsindex 2aedd22d7..74a2f3d5c 100644--- a/apps/web/src/features/space/member/data.ts+++ b/apps/web/src/features/space/member/data.ts@@ -95,3 +95,21 @@ export async function listSpaceInvites({}) satisfies MemberInviteDTO,);}++export async function getSpaceMemberByEmail({+ spaceId,+ email,+}: {+ spaceId: AuthorizedSpaceId;+ email: string;+}) {+ return prisma.spaceMember.findFirst({+ where: {+ spaceId,+ user: { email },+ },+ select: {+ userId: true,+ },+ });+}