diff --git a/app/api/accounts/[id]/route.ts b/app/api/accounts/[id]/route.ts index b272465ae..5bef4541e 100644 --- a/app/api/accounts/[id]/route.ts +++ b/app/api/accounts/[id]/route.ts @@ -3,9 +3,9 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getAccountHandler } from "@/lib/accounts/getAccountHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. * - * @returns A NextResponse with CORS headers. + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { @@ -15,18 +15,12 @@ export async function OPTIONS() { } /** - * GET /api/accounts/[id] + * Handles GET requests. * - * Retrieves account details by ID including profile info, emails, and wallets. - * Requires authentication via `x-api-key` or `Authorization: Bearer`; the caller must be - * allowed to access the requested account (same account, org delegation, or Recoup admin). - * - * Path parameters: - * - id (required): The unique identifier of the account (UUID) - * - * @param request - The request object - * @param params - Route params containing the account ID - * @returns A NextResponse with account data + * @param request - Incoming HTTP request. + * @param root1 - Input object. + * @param root1.params - Dynamic route parameters. + * @returns - Computed result. */ export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { return getAccountHandler(request, params); diff --git a/app/api/admins/coding/pr/route.ts b/app/api/admins/coding/pr/route.ts index 33aef3f91..0d3e5db53 100644 --- a/app/api/admins/coding/pr/route.ts +++ b/app/api/admins/coding/pr/route.ts @@ -3,20 +3,20 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getPrStatusHandler } from "@/lib/admins/pr/getPrStatusHandler"; /** - * GET /api/admins/coding/pr + * Handles GET requests. * - * Returns the status (open, closed, or merged) for each provided GitHub PR URL. - * Accepts one or more `pull_requests` query parameters (GitHub PR URLs). - * Uses the GitHub REST API to check each PR's state. - * Requires admin authentication. - * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function GET(request: NextRequest): Promise { return getPrStatusHandler(request); } -/** CORS preflight handler. */ +/** + * Handles OPTIONS requests. + * + * @returns - Computed result. + */ export async function OPTIONS(): Promise { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } diff --git a/app/api/admins/coding/slack/route.ts b/app/api/admins/coding/slack/route.ts index ea880d306..9975ccb65 100644 --- a/app/api/admins/coding/slack/route.ts +++ b/app/api/admins/coding/slack/route.ts @@ -3,18 +3,20 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getSlackTagsHandler } from "@/lib/admins/slack/getSlackTagsHandler"; /** - * GET /api/admins/coding/slack + * Handles GET requests. * - * Returns Slack tagging analytics for the Recoup Coding Agent bot. - * Pulls directly from the Slack API as the source of truth. - * Supports period filtering: all (default), daily, weekly, monthly. - * Requires admin authentication. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function GET(request: NextRequest): Promise { return getSlackTagsHandler(request); } -/** CORS preflight handler. */ +/** + * Handles OPTIONS requests. + * + * @returns - Computed result. + */ export async function OPTIONS(): Promise { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } diff --git a/app/api/admins/content/slack/route.ts b/app/api/admins/content/slack/route.ts index 35ba38f7e..d6b73aec7 100644 --- a/app/api/admins/content/slack/route.ts +++ b/app/api/admins/content/slack/route.ts @@ -3,20 +3,20 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getContentSlackTagsHandler } from "@/lib/admins/content/getContentSlackTagsHandler"; /** - * GET /api/admins/content/slack + * Handles GET requests. * - * Returns Slack tagging analytics for the Recoup Content Agent bot. - * Pulls directly from the Slack API as the source of truth. - * Supports period filtering: all (default), daily, weekly, monthly. - * Requires admin authentication. - * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function GET(request: NextRequest): Promise { return getContentSlackTagsHandler(request); } -/** CORS preflight handler. */ +/** + * Handles OPTIONS requests. + * + * @returns - Computed result. + */ export async function OPTIONS(): Promise { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } diff --git a/app/api/admins/privy/route.ts b/app/api/admins/privy/route.ts index 073bac603..20aef331a 100644 --- a/app/api/admins/privy/route.ts +++ b/app/api/admins/privy/route.ts @@ -3,16 +3,20 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getPrivyLoginsHandler } from "@/lib/admins/privy/getPrivyLoginsHandler"; /** - * GET /api/admins/privy + * Handles GET requests. * - * Returns Privy login statistics for the requested time period. - * Supports daily (last 24h), weekly (last 7 days), and monthly (last 30 days) periods. - * Requires admin authentication. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function GET(request: NextRequest): Promise { return getPrivyLoginsHandler(request); } +/** + * Handles OPTIONS requests. + * + * @returns - Computed result. + */ export async function OPTIONS(): Promise { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } diff --git a/app/api/chats/[id]/messages/trailing/route.ts b/app/api/chats/[id]/messages/trailing/route.ts index afe9b6737..32b87f04f 100644 --- a/app/api/chats/[id]/messages/trailing/route.ts +++ b/app/api/chats/[id]/messages/trailing/route.ts @@ -4,7 +4,9 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { deleteTrailingChatMessagesHandler } from "@/lib/chats/deleteTrailingChatMessagesHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { @@ -14,9 +16,12 @@ export async function OPTIONS() { } /** - * DELETE /api/chats/[id]/messages/trailing + * Handles DELETE requests. * - * Deletes all messages in chat `id` from `from_message_id` onward. + * @param request - Incoming HTTP request. + * @param root1 - Input object. + * @param root1.params - Dynamic route parameters. + * @returns - Computed result. */ export async function DELETE( request: NextRequest, diff --git a/app/api/coding-agent/callback/route.ts b/app/api/coding-agent/callback/route.ts index 2582611f1..fc784f2c2 100644 --- a/app/api/coding-agent/callback/route.ts +++ b/app/api/coding-agent/callback/route.ts @@ -3,12 +3,10 @@ import { codingAgentBot } from "@/lib/coding-agent/bot"; import { handleCodingAgentCallback } from "@/lib/coding-agent/handleCodingAgentCallback"; /** - * POST /api/coding-agent/callback + * Handles POST requests. * - * Callback endpoint for the coding agent Trigger.dev task. - * Receives task results and posts them back to the Slack thread. - * - * @param request - The incoming callback request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest) { await codingAgentBot.initialize(); diff --git a/app/api/coding-agent/github/route.ts b/app/api/coding-agent/github/route.ts index f1d615a78..a348aa29e 100644 --- a/app/api/coding-agent/github/route.ts +++ b/app/api/coding-agent/github/route.ts @@ -2,12 +2,10 @@ import type { NextRequest } from "next/server"; import { handleGitHubWebhook } from "@/lib/coding-agent/handleGitHubWebhook"; /** - * POST /api/coding-agent/github + * Handles POST requests. * - * Webhook endpoint for GitHub PR comment feedback. - * Receives issue_comment events and triggers update-pr when the bot is mentioned. - * - * @param request - The incoming GitHub webhook request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest) { return handleGitHubWebhook(request); diff --git a/app/api/connectors/route.ts b/app/api/connectors/route.ts index 9a20d83a9..24b1060dc 100644 --- a/app/api/connectors/route.ts +++ b/app/api/connectors/route.ts @@ -6,7 +6,9 @@ import { authorizeConnectorHandler } from "@/lib/composio/connectors/authorizeCo import { disconnectConnectorHandler } from "@/lib/composio/connectors/disconnectConnectorHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { @@ -16,53 +18,30 @@ export async function OPTIONS() { } /** - * GET /api/connectors - * - * List all available connectors and their connection status. - * - * Query params: - * - account_id (optional): Entity ID for entity-specific connections (e.g., artist ID) + * Handles GET requests. * - * Authentication: x-api-key OR Authorization Bearer token required. - * - * @param request - * @returns List of connectors with connection status + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function GET(request: NextRequest) { return getConnectorsHandler(request); } /** - * POST /api/connectors - * - * Generate an OAuth authorization URL for a specific connector. + * Handles POST requests. * - * Authentication: x-api-key OR Authorization Bearer token required. - * - * Request body: - * - connector: The connector slug, e.g., "googlesheets" or "tiktok" (required) - * - callback_url: Optional custom callback URL after OAuth - * - account_id: Optional account ID for account-specific connections - * - * @param request - * @returns The redirect URL for OAuth authorization + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest) { return authorizeConnectorHandler(request); } /** - * DELETE /api/connectors - * - * Disconnect a connected account from Composio. - * - * Body: - * - connected_account_id (required): The connected account ID to disconnect - * - account_id (optional): Entity ID for ownership verification (e.g., artist ID) - * - * Authentication: x-api-key OR Authorization Bearer token required. + * Handles DELETE requests. * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function DELETE(request: NextRequest) { return disconnectConnectorHandler(request); diff --git a/app/api/content/analyze/route.ts b/app/api/content/analyze/route.ts index 2679338b5..75e626ecd 100644 --- a/app/api/content/analyze/route.ts +++ b/app/api/content/analyze/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { createAnalyzeHandler } from "@/lib/content/analyze/createAnalyzeHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * POST /api/content/analyze + * Handles POST requests. * - * Analyze a video with AI — describe scenes, check quality, evaluate content. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest): Promise { return createAnalyzeHandler(request); diff --git a/app/api/content/caption/route.ts b/app/api/content/caption/route.ts index 59b1a9ae1..e84e62d7e 100644 --- a/app/api/content/caption/route.ts +++ b/app/api/content/caption/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { createTextHandler } from "@/lib/content/caption/createTextHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * POST /api/content/caption + * Handles POST requests. * - * Generate on-screen caption text for a social video. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest): Promise { return createTextHandler(request); diff --git a/app/api/content/image/route.ts b/app/api/content/image/route.ts index 06c7bc9f3..61867868c 100644 --- a/app/api/content/image/route.ts +++ b/app/api/content/image/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { createImageHandler } from "@/lib/content/image/createImageHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * POST /api/content/image + * Handles POST requests. * - * Generate an image from a prompt and optional reference image. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest): Promise { return createImageHandler(request); diff --git a/app/api/content/route.ts b/app/api/content/route.ts index f5703b378..c42eed4d7 100644 --- a/app/api/content/route.ts +++ b/app/api/content/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { editHandler } from "@/lib/content/edit/editHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * PATCH /api/content + * Handles PATCH requests. * - * Edit media with operations or a template preset. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function PATCH(request: NextRequest): Promise { return editHandler(request); diff --git a/app/api/content/templates/[id]/route.ts b/app/api/content/templates/[id]/route.ts index e4c272512..1a3c5d6f0 100644 --- a/app/api/content/templates/[id]/route.ts +++ b/app/api/content/templates/[id]/route.ts @@ -3,16 +3,21 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getContentTemplateDetailHandler } from "@/lib/content/getContentTemplateDetailHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * GET /api/content/templates/[id] + * Handles GET requests. * - * Returns the full template configuration for a given template id. + * @param request - Incoming HTTP request. + * @param context - Route handler context. + * @param context.params - Dynamic route parameters. + * @returns - Computed result. */ export async function GET( request: NextRequest, diff --git a/app/api/content/transcribe/route.ts b/app/api/content/transcribe/route.ts index 75f7be638..f11cc59ae 100644 --- a/app/api/content/transcribe/route.ts +++ b/app/api/content/transcribe/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { createAudioHandler } from "@/lib/content/transcribe/createAudioHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * POST /api/content/transcribe + * Handles POST requests. * - * Transcribe audio into text with word-level timestamps. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest): Promise { return createAudioHandler(request); diff --git a/app/api/content/upscale/route.ts b/app/api/content/upscale/route.ts index 63739f5d1..d7a7c18bf 100644 --- a/app/api/content/upscale/route.ts +++ b/app/api/content/upscale/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { createUpscaleHandler } from "@/lib/content/upscale/createUpscaleHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * POST /api/content/upscale + * Handles POST requests. * - * Upscale an image or video to higher resolution. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest): Promise { return createUpscaleHandler(request); diff --git a/app/api/content/video/route.ts b/app/api/content/video/route.ts index fde60b30c..f03ce4b78 100644 --- a/app/api/content/video/route.ts +++ b/app/api/content/video/route.ts @@ -3,16 +3,19 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { createVideoHandler } from "@/lib/content/video/createVideoHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. + * + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { status: 204, headers: getCorsHeaders() }); } /** - * POST /api/content/video + * Handles POST requests. * - * Generate a video from a prompt, image, or existing video. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function POST(request: NextRequest): Promise { return createVideoHandler(request); diff --git a/app/api/songs/analyze/presets/route.ts b/app/api/songs/analyze/presets/route.ts index 8baccd38d..515a9ca4b 100644 --- a/app/api/songs/analyze/presets/route.ts +++ b/app/api/songs/analyze/presets/route.ts @@ -4,9 +4,9 @@ import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { getFlamingoPresetsHandler } from "@/lib/flamingo/getFlamingoPresetsHandler"; /** - * OPTIONS handler for CORS preflight requests. + * Handles OPTIONS requests. * - * @returns A NextResponse with CORS headers. + * @returns - Computed result. */ export async function OPTIONS() { return new NextResponse(null, { @@ -16,19 +16,10 @@ export async function OPTIONS() { } /** - * GET /api/songs/analyze/presets + * Handles GET requests. * - * Lists all available music analysis presets. Each preset is a curated - * prompt with optimized generation parameters for a specific use case - * (e.g. catalog metadata, sync licensing, audience profiling). - * - * Authentication: x-api-key header or Authorization Bearer token required. - * - * Response (200): - * - status: "success" - * - presets: Array of { name, label, description, requiresAudio, responseFormat } - * - * @returns A NextResponse with the list of available presets + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function GET(request: NextRequest): Promise { return getFlamingoPresetsHandler(request); diff --git a/app/api/transcribe/route.ts b/app/api/transcribe/route.ts index 28cf4261d..bdd152cdc 100644 --- a/app/api/transcribe/route.ts +++ b/app/api/transcribe/route.ts @@ -2,6 +2,12 @@ import { NextRequest, NextResponse } from "next/server"; import { processAudioTranscription } from "@/lib/transcribe/processAudioTranscription"; import { formatTranscriptionError } from "@/lib/transcribe/types"; +/** + * Handles POST requests. + * + * @param req - Incoming HTTP request. + * @returns - Computed result. + */ export async function POST(req: NextRequest) { try { const body = await req.json(); diff --git a/lib/accounts/__tests__/resolveAccountIdByEmail.test.ts b/lib/accounts/__tests__/resolveAccountIdByEmail.test.ts index 593192a90..48c921285 100644 --- a/lib/accounts/__tests__/resolveAccountIdByEmail.test.ts +++ b/lib/accounts/__tests__/resolveAccountIdByEmail.test.ts @@ -20,7 +20,7 @@ describe("resolveAccountIdByEmail", () => { vi.mocked(selectAccountByEmail).mockResolvedValue({ account_id: "customer-456", email: "test@example.com", - } as any); + } as unknown); const result = await resolveAccountIdByEmail("test@example.com"); @@ -41,7 +41,7 @@ describe("resolveAccountIdByEmail", () => { vi.mocked(selectAccountByEmail).mockResolvedValue({ account_id: null, email: "test@example.com", - } as any); + } as unknown); const result = await resolveAccountIdByEmail("test@example.com"); diff --git a/lib/accounts/__tests__/validateUpdateAccountRequest.test.ts b/lib/accounts/__tests__/validateUpdateAccountRequest.test.ts index 17f350aad..d21391614 100644 --- a/lib/accounts/__tests__/validateUpdateAccountRequest.test.ts +++ b/lib/accounts/__tests__/validateUpdateAccountRequest.test.ts @@ -16,6 +16,12 @@ vi.mock("@/lib/networking/safeParseJson", () => ({ safeParseJson: vi.fn(async (req: Request) => req.json()), })); +/** + * Create Request. + * + * @param body - Request payload. + * @returns - Computed result. + */ function createRequest(body: unknown): NextRequest { return new NextRequest("http://localhost/api/accounts", { method: "PATCH", diff --git a/lib/accounts/validateOverrideAccountId.ts b/lib/accounts/validateOverrideAccountId.ts index 8f52cde0e..653b1a26b 100644 --- a/lib/accounts/validateOverrideAccountId.ts +++ b/lib/accounts/validateOverrideAccountId.ts @@ -13,17 +13,12 @@ export type ValidateOverrideAccountIdResult = { }; /** - * Validates that an API key has permission to override to a target accountId. + * Validate Override Account Id. * - * Used when an org API key wants to create resources on behalf of another account. - * Checks that the API key belongs to an org with access to the target account. - * - * @param params.apiKey - The x-api-key header value - * @param params.targetAccountId - The accountId to override to - * @param root0 - * @param root0.apiKey - * @param root0.targetAccountId - * @returns The validated accountId or a NextResponse error + * @param root0 - Input object. + * @param root0.apiKey - Value for root0.apiKey. + * @param root0.targetAccountId - Value for root0.targetAccountId. + * @returns - Computed result. */ export async function validateOverrideAccountId({ apiKey, diff --git a/lib/accounts/validateUpdateAccountRequest.ts b/lib/accounts/validateUpdateAccountRequest.ts index 78e667674..63425ea81 100644 --- a/lib/accounts/validateUpdateAccountRequest.ts +++ b/lib/accounts/validateUpdateAccountRequest.ts @@ -24,8 +24,16 @@ export const updateAccountBodySchema = z }) .refine( data => { - const { accountId: _, ...fields } = data; - return Object.values(fields).some(v => v !== undefined); + return [ + data.name, + data.instruction, + data.organization, + data.image, + data.jobTitle, + data.roleType, + data.companyName, + data.knowledges, + ].some(value => value !== undefined); }, { message: "At least one field to update must be provided" }, ); @@ -38,7 +46,10 @@ export type ValidatedUpdateAccountRequest = Omit< }; /** - * Validates PATCH /api/accounts including auth, account override access, and body schema. + * Validate Update Account Request. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateUpdateAccountRequest( request: NextRequest, diff --git a/lib/admins/content/__tests__/getContentSlackTagsHandler.test.ts b/lib/admins/content/__tests__/getContentSlackTagsHandler.test.ts index 16dba6930..54a4ce1e4 100644 --- a/lib/admins/content/__tests__/getContentSlackTagsHandler.test.ts +++ b/lib/admins/content/__tests__/getContentSlackTagsHandler.test.ts @@ -40,8 +40,10 @@ const mockTags = [ ]; /** + * Make Request. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ function makeRequest(period = "all") { return new NextRequest(`https://example.com/api/admins/content/slack?period=${period}`); diff --git a/lib/admins/emails/__tests__/validateGetAdminEmailsQuery.test.ts b/lib/admins/emails/__tests__/validateGetAdminEmailsQuery.test.ts index 90e1a3d08..baed33298 100644 --- a/lib/admins/emails/__tests__/validateGetAdminEmailsQuery.test.ts +++ b/lib/admins/emails/__tests__/validateGetAdminEmailsQuery.test.ts @@ -12,6 +12,12 @@ vi.mock("@/lib/admins/validateAdminAuth", () => ({ validateAdminAuth: vi.fn(), })); +/** + * Create Mock Request. + * + * @param url - URL to process. + * @returns - Computed result. + */ function createMockRequest(url: string): NextRequest { return { url, diff --git a/lib/admins/pr/__tests__/getPrMergedStatusHandler.test.ts b/lib/admins/pr/__tests__/getPrMergedStatusHandler.test.ts index e007e9c85..34039471b 100644 --- a/lib/admins/pr/__tests__/getPrMergedStatusHandler.test.ts +++ b/lib/admins/pr/__tests__/getPrMergedStatusHandler.test.ts @@ -19,6 +19,12 @@ vi.mock("@/lib/github/fetchGithubPrStatus", () => ({ const PR_URL_1 = "https://github.com/recoupable/api/pull/42"; const PR_URL_2 = "https://github.com/recoupable/chat/pull/100"; +/** + * Make Request. + * + * @param urls - List of URLs to process. + * @returns - Computed result. + */ function makeRequest(urls: string[] = [PR_URL_1]) { const params = new URLSearchParams(); urls.forEach(url => params.append("pull_requests", url)); diff --git a/lib/admins/pr/getPrStatusHandler.ts b/lib/admins/pr/getPrStatusHandler.ts index 270817184..4a640e17d 100644 --- a/lib/admins/pr/getPrStatusHandler.ts +++ b/lib/admins/pr/getPrStatusHandler.ts @@ -4,12 +4,10 @@ import { validateGetCodingPrQuery } from "./validateGetCodingPrQuery"; import { fetchGithubPrStatus } from "@/lib/github/fetchGithubPrStatus"; /** - * Handler for GET /api/admins/coding/pr + * Get Pr Status Handler. * - * Returns the status (open, closed, or merged) for each provided GitHub PR URL. - * Uses the GitHub REST API to check each PR's state. - * - * Requires admin authentication. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function getPrStatusHandler(request: NextRequest): Promise { try { diff --git a/lib/admins/privy/__tests__/getPrivyLoginsHandler.test.ts b/lib/admins/privy/__tests__/getPrivyLoginsHandler.test.ts index 87730ae6d..d380219d2 100644 --- a/lib/admins/privy/__tests__/getPrivyLoginsHandler.test.ts +++ b/lib/admins/privy/__tests__/getPrivyLoginsHandler.test.ts @@ -49,8 +49,10 @@ const mockLogins = [ ]; /** + * Make Request. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ function makeRequest(period = "daily") { return new NextRequest(`https://example.com/api/admins/privy?period=${period}`); diff --git a/lib/admins/privy/__tests__/validateGetPrivyLoginsQuery.test.ts b/lib/admins/privy/__tests__/validateGetPrivyLoginsQuery.test.ts index 009aa0b93..930d4c10f 100644 --- a/lib/admins/privy/__tests__/validateGetPrivyLoginsQuery.test.ts +++ b/lib/admins/privy/__tests__/validateGetPrivyLoginsQuery.test.ts @@ -15,8 +15,10 @@ vi.mock("@/lib/admins/validateAdminAuth", () => ({ const mockAuth = { accountId: "test-account", orgId: null, authToken: "token" }; /** + * Make Request. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ function makeRequest(period?: string) { const url = period diff --git a/lib/admins/privy/countNewAccounts.ts b/lib/admins/privy/countNewAccounts.ts index 012ced532..63c2f3d1d 100644 --- a/lib/admins/privy/countNewAccounts.ts +++ b/lib/admins/privy/countNewAccounts.ts @@ -4,7 +4,11 @@ import type { User } from "@privy-io/node"; import { getCutoffMs } from "./getCutoffMs"; /** - * Counts how many users in the list were created within the cutoff period. + * Count New Accounts. + * + * @param users - Value for users. + * @param period - Time range filter. + * @returns - Computed result. */ export function countNewAccounts(users: User[], period: PrivyLoginsPeriod): number { const cutoffMs = getCutoffMs(period); diff --git a/lib/admins/privy/fetchPrivyLogins.ts b/lib/admins/privy/fetchPrivyLogins.ts index ae4d4dd03..d9a54c6ef 100644 --- a/lib/admins/privy/fetchPrivyLogins.ts +++ b/lib/admins/privy/fetchPrivyLogins.ts @@ -20,6 +20,12 @@ export type FetchPrivyLoginsResult = { totalPrivyUsers: number; }; +/** + * Fetch Privy Logins. + * + * @param period - Time range filter. + * @returns - Computed result. + */ export async function fetchPrivyLogins(period: PrivyLoginsPeriod): Promise { const isAll = period === "all"; const cutoffMs = getCutoffMs(period); diff --git a/lib/admins/privy/getCutoffMs.ts b/lib/admins/privy/getCutoffMs.ts index 8b80ec6aa..06b32b810 100644 --- a/lib/admins/privy/getCutoffMs.ts +++ b/lib/admins/privy/getCutoffMs.ts @@ -2,9 +2,10 @@ import type { PrivyLoginsPeriod } from "./privyLoginsPeriod"; import { PERIOD_DAYS } from "./periodDays"; /** - * Returns the cutoff timestamp in milliseconds for a given period. - * Uses midnight UTC calendar day boundaries to match Privy dashboard behavior. - * Returns 0 for "all" (no cutoff). + * Get Cutoff Ms. + * + * @param period - Time range filter. + * @returns - Computed result. */ export function getCutoffMs(period: PrivyLoginsPeriod): number { if (period === "all") return 0; diff --git a/lib/admins/privy/getLatestVerifiedAt.ts b/lib/admins/privy/getLatestVerifiedAt.ts index 465ea8762..9e42f1ec5 100644 --- a/lib/admins/privy/getLatestVerifiedAt.ts +++ b/lib/admins/privy/getLatestVerifiedAt.ts @@ -2,8 +2,10 @@ import { toMs } from "./toMs"; import type { User } from "@privy-io/node"; /** - * Returns the most recent latest_verified_at (in ms) across all linked_accounts for a Privy user. - * Returns null if no linked account has a latest_verified_at. + * Get Latest Verified At. + * + * @param user - Value for user. + * @returns - Computed result. */ export function getLatestVerifiedAt(user: User): number | null { const linkedAccounts = user.linked_accounts; diff --git a/lib/admins/privy/toMs.ts b/lib/admins/privy/toMs.ts index 472ff9ebc..e047e2765 100644 --- a/lib/admins/privy/toMs.ts +++ b/lib/admins/privy/toMs.ts @@ -1,6 +1,8 @@ /** - * Normalizes a Privy timestamp to milliseconds. - * Privy docs say milliseconds but examples show seconds (10 digits). + * To Ms. + * + * @param timestamp - Value for timestamp. + * @returns - Computed result. */ export function toMs(timestamp: number): number { return timestamp > 1e12 ? timestamp : timestamp * 1000; diff --git a/lib/admins/slack/__tests__/createSlackTagsHandler.test.ts b/lib/admins/slack/__tests__/createSlackTagsHandler.test.ts index fb2fe6672..5c4091b28 100644 --- a/lib/admins/slack/__tests__/createSlackTagsHandler.test.ts +++ b/lib/admins/slack/__tests__/createSlackTagsHandler.test.ts @@ -18,8 +18,10 @@ const handler = createSlackTagsHandler({ }); /** + * Make Request. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ function makeRequest(period = "all") { return new NextRequest(`https://example.com/api/admins/coding/slack?period=${period}`); diff --git a/lib/admins/slack/__tests__/fetchBotMentions.test.ts b/lib/admins/slack/__tests__/fetchBotMentions.test.ts index f97bf3190..6904d6760 100644 --- a/lib/admins/slack/__tests__/fetchBotMentions.test.ts +++ b/lib/admins/slack/__tests__/fetchBotMentions.test.ts @@ -118,8 +118,7 @@ describe("fetchBotMentions", () => { // conversations.history returns a thread parent with reply_count > 0 but no bot mention // conversations.replies returns a reply that mentions the bot vi.mocked(slackGet).mockImplementation( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (endpoint: string, _token: string, params?: Record): Promise => { + (endpoint: string, _token: string, params?: Record): Promise => { if (endpoint === "conversations.history") { return Promise.resolve({ ok: true, @@ -202,8 +201,7 @@ describe("fetchBotMentions", () => { vi.mocked(getCutoffTs).mockReturnValue(null); vi.mocked(slackGet).mockImplementation( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (endpoint: string, _token: string, params?: Record): Promise => { + (endpoint: string, _token: string, params?: Record): Promise => { if (endpoint === "conversations.history") { return Promise.resolve({ ok: true, @@ -277,8 +275,7 @@ describe("fetchBotMentions", () => { vi.mocked(getCutoffTs).mockReturnValue(1705312400); vi.mocked(slackGet).mockImplementation( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (endpoint: string, _token: string, params?: Record): Promise => { + (endpoint: string, _token: string, params?: Record): Promise => { if (endpoint === "conversations.history") { return Promise.resolve({ ok: true, diff --git a/lib/admins/slack/__tests__/getSlackTagsHandler.test.ts b/lib/admins/slack/__tests__/getSlackTagsHandler.test.ts index 6b5563bde..eceb720d5 100644 --- a/lib/admins/slack/__tests__/getSlackTagsHandler.test.ts +++ b/lib/admins/slack/__tests__/getSlackTagsHandler.test.ts @@ -40,8 +40,10 @@ const mockTags = [ ]; /** + * Make Request. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ function makeRequest(period = "all") { return new NextRequest(`https://example.com/api/admins/coding/slack?period=${period}`); diff --git a/lib/admins/slack/__tests__/validateGetSlackTagsQuery.test.ts b/lib/admins/slack/__tests__/validateGetSlackTagsQuery.test.ts index 56a4d7a40..438e0e832 100644 --- a/lib/admins/slack/__tests__/validateGetSlackTagsQuery.test.ts +++ b/lib/admins/slack/__tests__/validateGetSlackTagsQuery.test.ts @@ -14,8 +14,10 @@ vi.mock("@/lib/admins/validateAdminAuth", () => ({ const mockAuth = { accountId: "test-account", orgId: null, authToken: "token" }; /** + * Make Request. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ function makeRequest(period?: string) { const url = period diff --git a/lib/admins/slack/createSlackTagsHandler.ts b/lib/admins/slack/createSlackTagsHandler.ts index dcbbb0ca5..93c71c33d 100644 --- a/lib/admins/slack/createSlackTagsHandler.ts +++ b/lib/admins/slack/createSlackTagsHandler.ts @@ -12,10 +12,10 @@ interface SlackTagsHandlerConfig { } /** - * Factory that creates a handler for admin slack tags endpoints. - * Parameterized by validation, fetching, and response field naming. + * Create Slack Tags Handler. * - * @param config + * @param config - Configuration options. + * @returns - Computed result. */ export function createSlackTagsHandler( config: SlackTagsHandlerConfig, diff --git a/lib/admins/slack/extractGithubPrUrls.ts b/lib/admins/slack/extractGithubPrUrls.ts index 0b534e208..c48655e5e 100644 --- a/lib/admins/slack/extractGithubPrUrls.ts +++ b/lib/admins/slack/extractGithubPrUrls.ts @@ -22,12 +22,12 @@ const PR_URL_PATTERN = /https:\/\/github\.com\/[^\s>|]+\/pull\/\d+/g; const PR_URL_EXACT = /^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/; /** - * Extracts GitHub pull request URLs from a Slack message's text, attachments, and blocks. - * Handles plain URLs, Slack-formatted links, action button URLs, and Block Kit element URLs. + * Extract Github Pr Urls. * - * @param text - * @param attachments - * @param blocks + * @param text - Text content. + * @param attachments - Value for attachments. + * @param blocks - Value for blocks. + * @returns - Computed result. */ export function extractGithubPrUrls( text: string, diff --git a/lib/admins/slack/fetchThreadPullRequests.ts b/lib/admins/slack/fetchThreadPullRequests.ts index c49fed8ba..1afd99f5e 100644 --- a/lib/admins/slack/fetchThreadPullRequests.ts +++ b/lib/admins/slack/fetchThreadPullRequests.ts @@ -16,12 +16,12 @@ interface ConversationsRepliesResponse { } /** - * Fetches bot replies in a Slack thread and returns any GitHub PR URLs found. - * Extracts URLs from message text, attachment action buttons, and Block Kit blocks. + * Fetch Thread Pull Requests. * - * @param token - * @param channel - * @param threadTs + * @param token - Authentication token. + * @param channel - Slack channel identifier. + * @param threadTs - Slack thread timestamp. + * @returns - Computed result. */ export async function fetchThreadPullRequests( token: string, diff --git a/lib/admins/slack/fetchThreadReplyMentions.ts b/lib/admins/slack/fetchThreadReplyMentions.ts index ceec53422..a31217799 100644 --- a/lib/admins/slack/fetchThreadReplyMentions.ts +++ b/lib/admins/slack/fetchThreadReplyMentions.ts @@ -42,8 +42,16 @@ const THREAD_BATCH_SIZE = 5; const THREAD_BATCH_DELAY_MS = 1100; /** - * Scans Slack thread replies for messages that mention the bot. - * Returns the mentions (with parent thread ts) while caching user info. + * Fetch Thread Reply Mentions. + * + * @param root0 - Input object. + * @param root0.token - Authentication token. + * @param root0.threadsToScan - Value for root0.threadsToScan. + * @param root0.mentionPattern - Value for root0.mentionPattern. + * @param root0.mentionRegex - Value for root0.mentionRegex. + * @param root0.cutoffTs - Value for root0.cutoffTs. + * @param root0.userCache - Value for root0.userCache. + * @returns - Computed result. */ export async function fetchThreadReplyMentions({ token, diff --git a/lib/admins/slack/getCutoffTs.ts b/lib/admins/slack/getCutoffTs.ts index 2aeec98d9..84655dba8 100644 --- a/lib/admins/slack/getCutoffTs.ts +++ b/lib/admins/slack/getCutoffTs.ts @@ -2,10 +2,10 @@ import type { AdminPeriod } from "@/lib/admins/adminPeriod"; import { PERIOD_DAYS } from "@/lib/admins/privy/periodDays"; /** - * Returns the cutoff timestamp in seconds for a given period, or null for "all". - * Used by the Slack API which expects timestamps in seconds. + * Get Cutoff Ts. * - * @param period + * @param period - Time range filter. + * @returns - Computed result. */ export function getCutoffTs(period: AdminPeriod): number | null { if (period === "all") return null; diff --git a/lib/agents/content/__tests__/handleContentAgentCallback.test.ts b/lib/agents/content/__tests__/handleContentAgentCallback.test.ts index 36fa4ea1c..e39e921bf 100644 --- a/lib/agents/content/__tests__/handleContentAgentCallback.test.ts +++ b/lib/agents/content/__tests__/handleContentAgentCallback.test.ts @@ -84,6 +84,12 @@ describe("handleContentAgentCallback", () => { }); describe("completed callback with videos", () => { + /** + * Make Auth Request. + * + * @param body - Request payload. + * @returns - Computed result. + */ function makeAuthRequest(body: object) { return new Request("http://localhost/api/content-agent/callback", { method: "POST", @@ -92,6 +98,11 @@ describe("handleContentAgentCallback", () => { }); } + /** + * Mock Thread. + * + * @returns - Computed result. + */ function mockThread() { const thread = { post: vi.fn().mockResolvedValue(undefined), diff --git a/lib/agents/content/__tests__/registerOnNewMention.test.ts b/lib/agents/content/__tests__/registerOnNewMention.test.ts index 7e50cfc7e..75e27b8ba 100644 --- a/lib/agents/content/__tests__/registerOnNewMention.test.ts +++ b/lib/agents/content/__tests__/registerOnNewMention.test.ts @@ -34,7 +34,7 @@ vi.mock("../extractMessageAttachments", () => ({ })); vi.mock("@/lib/agents/buildTaskCard", () => ({ - buildTaskCard: vi.fn((_title: string, _message: string, _runId: string) => ({ + buildTaskCard: vi.fn((..._: [string, string, string]) => ({ mockCard: true, })), })); diff --git a/lib/agents/content/extractMessageAttachments.ts b/lib/agents/content/extractMessageAttachments.ts index 7aceede98..ad81ffbf2 100644 --- a/lib/agents/content/extractMessageAttachments.ts +++ b/lib/agents/content/extractMessageAttachments.ts @@ -19,10 +19,10 @@ export interface ExtractedAttachments { } /** - * Extracts audio and image attachments from a Slack message and returns - * public URLs for the content pipeline. + * Extract Message Attachments. * - * @param message + * @param message - Value for message. + * @returns - Computed result. */ export async function extractMessageAttachments( message: MessageWithAttachments, diff --git a/lib/agents/content/resolveAttachmentUrl.ts b/lib/agents/content/resolveAttachmentUrl.ts index 6293342f8..1286384d2 100644 --- a/lib/agents/content/resolveAttachmentUrl.ts +++ b/lib/agents/content/resolveAttachmentUrl.ts @@ -12,14 +12,11 @@ interface Attachment { } /** - * Downloads a Slack file and uploads to Vercel Blob. + * Resolve Attachment Url. * - * Uses Slack's files.info API to get the url_private_download URL, - * then downloads with Bearer token auth. The attachment.url from the - * Chat SDK is a thumbnail URL that doesn't serve actual file content. - * - * @param attachment - * @param prefix + * @param attachment - Value for attachment. + * @param prefix - Value for prefix. + * @returns - Computed result. */ export async function resolveAttachmentUrl( attachment: Attachment, diff --git a/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts b/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts index d29ed8c58..b4ccc6f5b 100644 --- a/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts +++ b/lib/agents/generalAgent/__tests__/getGeneralAgent.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { ChatRequestBody } from "@/lib/chat/validateChatRequest"; -import { ToolLoopAgent, stepCountIs } from "ai"; +import { ToolLoopAgent } from "ai"; // Import after mocks import getGeneralAgent from "../getGeneralAgent"; @@ -65,14 +65,14 @@ describe("getGeneralAgent", () => { // Set up default mock returns mockSelectAccountEmails.mockResolvedValue([ - { email: "user@example.com", account_id: "account-123" } as any, + { email: "user@example.com", account_id: "account-123" } as unknown, ]); mockSelectAccountInfo.mockResolvedValue(null); mockGetAccountWithDetails.mockResolvedValue({ id: "account-123", name: "Test User", email: "user@example.com", - } as any); + } as unknown); mockGetKnowledgeBaseText.mockResolvedValue(undefined); mockSetupToolsForRequest.mockResolvedValue(mockTools); mockGetSystemPrompt.mockReturnValue(baseSystemPrompt); @@ -165,8 +165,8 @@ describe("getGeneralAgent", () => { it("uses first email from account emails list", async () => { mockSelectAccountEmails.mockResolvedValue([ - { email: "first@example.com", account_id: "account-123" } as any, - { email: "second@example.com", account_id: "account-123" } as any, + { email: "first@example.com", account_id: "account-123" } as unknown, + { email: "second@example.com", account_id: "account-123" } as unknown, ]); const body: ChatRequestBody = { @@ -229,7 +229,7 @@ describe("getGeneralAgent", () => { mockSelectAccountInfo.mockResolvedValue({ instruction: "Always be formal with this artist", knowledges: [], - } as any); + } as unknown); const body: ChatRequestBody = { accountId: "account-123", @@ -254,7 +254,7 @@ describe("getGeneralAgent", () => { mockSelectAccountInfo.mockResolvedValue({ instruction: null, knowledges: mockKnowledges, - } as any); + } as unknown); mockGetKnowledgeBaseText.mockResolvedValue("FAQ content here"); const body: ChatRequestBody = { @@ -304,7 +304,7 @@ describe("getGeneralAgent", () => { email: "user@example.com", job_title: "Music Manager", }; - mockGetAccountWithDetails.mockResolvedValue(mockAccountDetails as any); + mockGetAccountWithDetails.mockResolvedValue(mockAccountDetails as unknown); const body: ChatRequestBody = { accountId: "account-123", @@ -476,7 +476,7 @@ describe("getGeneralAgent", () => { const result = await getGeneralAgent(body); // providerOptions should be baked into the agent constructor (stored in settings) - const settings = (result.agent as any).settings; + const settings = (result.agent as unknown).settings; expect(settings.providerOptions).toBeDefined(); expect(settings.providerOptions.anthropic).toEqual( expect.objectContaining({ @@ -509,7 +509,7 @@ describe("getGeneralAgent", () => { const result = await getGeneralAgent(body); // prepareStep should be baked into the agent constructor (stored in settings) - const settings = (result.agent as any).settings; + const settings = (result.agent as unknown).settings; expect(settings.prepareStep).toBeInstanceOf(Function); }); }); diff --git a/lib/ai/__tests__/getAvailableModels.test.ts b/lib/ai/__tests__/getAvailableModels.test.ts index 271752bc7..b097db438 100644 --- a/lib/ai/__tests__/getAvailableModels.test.ts +++ b/lib/ai/__tests__/getAvailableModels.test.ts @@ -29,7 +29,7 @@ describe("getAvailableModels", () => { { id: "text-embedding-ada-002", pricing: { input: "0.0001", output: "0" } }, { id: "claude-3-opus", pricing: { input: "0.00001", output: "0.00003" } }, ], - } as any); + } as unknown); const models = await getAvailableModels(); @@ -39,7 +39,7 @@ describe("getAvailableModels", () => { }); it("returns empty array when gateway returns no models", async () => { - mockGatewayGetAvailableModels.mockResolvedValue({ models: [] } as any); + mockGatewayGetAvailableModels.mockResolvedValue({ models: [] } as unknown); const models = await getAvailableModels(); diff --git a/lib/ai/__tests__/getModel.test.ts b/lib/ai/__tests__/getModel.test.ts index 367fa40cb..24c4d26fa 100644 --- a/lib/ai/__tests__/getModel.test.ts +++ b/lib/ai/__tests__/getModel.test.ts @@ -24,7 +24,7 @@ describe("getModel", () => { { id: "gpt-4", pricing: { input: "0.00003", output: "0.00006" } }, { id: "claude-3-opus", pricing: { input: "0.00001", output: "0.00003" } }, ]; - mockGetAvailableModels.mockResolvedValue(models as any); + mockGetAvailableModels.mockResolvedValue(models as unknown); const model = await getModel("gpt-4"); @@ -36,7 +36,7 @@ describe("getModel", () => { it("returns undefined when model is not found", async () => { const models = [{ id: "gpt-4", pricing: { input: "0.00003", output: "0.00006" } }]; - mockGetAvailableModels.mockResolvedValue(models as any); + mockGetAvailableModels.mockResolvedValue(models as unknown); const model = await getModel("unknown-model"); diff --git a/lib/ai/getAvailableModels.ts b/lib/ai/getAvailableModels.ts index a46fd79ee..27251cfcd 100644 --- a/lib/ai/getAvailableModels.ts +++ b/lib/ai/getAvailableModels.ts @@ -1,10 +1,6 @@ import { gateway, GatewayLanguageModelEntry } from "@ai-sdk/gateway"; import isEmbedModel from "./isEmbedModel"; -/** - * Returns the list of available LLMs from the Vercel AI Gateway. - * Filters out embed models that are not suitable for chat. - */ export const getAvailableModels = async (): Promise => { try { const apiResponse = await gateway.getAvailableModels(); diff --git a/lib/ai/getModel.ts b/lib/ai/getModel.ts index edf4d4259..264fd65f8 100644 --- a/lib/ai/getModel.ts +++ b/lib/ai/getModel.ts @@ -1,11 +1,6 @@ import { getAvailableModels } from "./getAvailableModels"; import { GatewayLanguageModelEntry } from "@ai-sdk/gateway"; -/** - * Returns a specific model by its ID from the list of available models. - * @param modelId - The ID of the model to find - * @returns The matching model or undefined if not found - */ export const getModel = async (modelId: string): Promise => { try { const availableModels = await getAvailableModels(); diff --git a/lib/ai/isEmbedModel.ts b/lib/ai/isEmbedModel.ts index 7c5fbbfb4..d71966bfb 100644 --- a/lib/ai/isEmbedModel.ts +++ b/lib/ai/isEmbedModel.ts @@ -1,9 +1,5 @@ import { GatewayLanguageModelEntry } from "@ai-sdk/gateway"; -/** - * Determines if a model is an embedding model (not suitable for chat). - * Embed models typically have 0 output pricing since they only produce embeddings. - */ export const isEmbedModel = (m: GatewayLanguageModelEntry): boolean => { const pricing = m.pricing; if (!pricing) return false; diff --git a/lib/artist/__tests__/updateArtistSocials.test.ts b/lib/artist/__tests__/updateArtistSocials.test.ts index 8c5f7b1c9..c30888215 100644 --- a/lib/artist/__tests__/updateArtistSocials.test.ts +++ b/lib/artist/__tests__/updateArtistSocials.test.ts @@ -183,9 +183,7 @@ describe("updateArtistSocials", () => { mockSelectSocials.mockResolvedValue([]); // Mock insertSocials to return different IDs for each call - let insertCallCount = 0; mockInsertSocials.mockImplementation(socials => { - insertCallCount++; const social = socials[0]; if (social.profile_url.includes("instagram")) { return Promise.resolve([ diff --git a/lib/artists/__tests__/createArtistPostHandler.test.ts b/lib/artists/__tests__/createArtistPostHandler.test.ts index e63d244dc..656533ec9 100644 --- a/lib/artists/__tests__/createArtistPostHandler.test.ts +++ b/lib/artists/__tests__/createArtistPostHandler.test.ts @@ -14,6 +14,13 @@ vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: (...args: unknown[]) => mockValidateAuthContext(...args), })); +/** + * Create Request. + * + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. + */ function createRequest(body: unknown, headers: Record = {}): NextRequest { const defaultHeaders: Record = { "Content-Type": "application/json", diff --git a/lib/artists/__tests__/validateCreateArtistBody.test.ts b/lib/artists/__tests__/validateCreateArtistBody.test.ts index 4de5562b1..b38a1e1bf 100644 --- a/lib/artists/__tests__/validateCreateArtistBody.test.ts +++ b/lib/artists/__tests__/validateCreateArtistBody.test.ts @@ -9,6 +9,13 @@ vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: (...args: unknown[]) => mockValidateAuthContext(...args), })); +/** + * Create Request. + * + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. + */ function createRequest(body: unknown, headers: Record = {}): NextRequest { const defaultHeaders: Record = { "Content-Type": "application/json" }; return new NextRequest("http://localhost/api/artists", { diff --git a/lib/artists/createArtistInDb.ts b/lib/artists/createArtistInDb.ts index e1eeceb9c..47a71a030 100644 --- a/lib/artists/createArtistInDb.ts +++ b/lib/artists/createArtistInDb.ts @@ -51,7 +51,7 @@ export async function createArtistInDb( ...artist, account_id: artist.id, }; - } catch (error) { + } catch { return null; } } diff --git a/lib/auth/__tests__/validateAuthContext.test.ts b/lib/auth/__tests__/validateAuthContext.test.ts index 31dda345a..d37037b3b 100644 --- a/lib/auth/__tests__/validateAuthContext.test.ts +++ b/lib/auth/__tests__/validateAuthContext.test.ts @@ -33,6 +33,12 @@ const mockGetAuthenticatedAccountId = vi.mocked(getAuthenticatedAccountId); const mockValidateOrganizationAccess = vi.mocked(validateOrganizationAccess); const mockCanAccessAccount = vi.mocked(canAccessAccount); +/** + * Create Mock Request. + * + * @param headers - Headers for the request. + * @returns - Computed result. + */ function createMockRequest(headers: Record = {}): Request { return { headers: { diff --git a/lib/catalog/formatCatalogSongsAsCSV.ts b/lib/catalog/formatCatalogSongsAsCSV.ts index 5115eecee..11dd4d4fe 100644 --- a/lib/catalog/formatCatalogSongsAsCSV.ts +++ b/lib/catalog/formatCatalogSongsAsCSV.ts @@ -1,7 +1,10 @@ import { CatalogSong } from "./getCatalogSongs"; /** - * Formats catalog songs into the CSV-like format expected by the scorer + * Format Catalog Songs As CSV. + * + * @param songs - Value for songs. + * @returns - Computed result. */ export function formatCatalogSongsAsCSV(songs: CatalogSong[]): string { const csvLines = songs.map(song => { diff --git a/lib/catalog/getCatalogDataAsCSV.ts b/lib/catalog/getCatalogDataAsCSV.ts index ea529c37e..e3b869b13 100644 --- a/lib/catalog/getCatalogDataAsCSV.ts +++ b/lib/catalog/getCatalogDataAsCSV.ts @@ -2,7 +2,10 @@ import { getCatalogSongs, CatalogSong } from "./getCatalogSongs"; import { formatCatalogSongsAsCSV } from "./formatCatalogSongsAsCSV"; /** - * Gets all catalog songs and formats them as CSV for the scorer + * Get Catalog Data As CSV. + * + * @param catalogId - Value for catalogId. + * @returns - Computed result. */ export async function getCatalogDataAsCSV(catalogId: string): Promise { const allSongs: CatalogSong[] = []; diff --git a/lib/catalog/getCatalogSongs.ts b/lib/catalog/getCatalogSongs.ts index c58c33bee..4fd4a3e7b 100644 --- a/lib/catalog/getCatalogSongs.ts +++ b/lib/catalog/getCatalogSongs.ts @@ -25,6 +25,15 @@ export interface CatalogSongsResponse { error?: string; } +/** + * Get Catalog Songs. + * + * @param catalogId - Value for catalogId. + * @param pageSize - Value for pageSize. + * @param page - Value for page. + * @param artistName - Value for artistName. + * @returns - Computed result. + */ export async function getCatalogSongs( catalogId: string, pageSize: number = 100, diff --git a/lib/catalog/getCatalogs.ts b/lib/catalog/getCatalogs.ts index 9533183ba..6db258d6c 100644 --- a/lib/catalog/getCatalogs.ts +++ b/lib/catalog/getCatalogs.ts @@ -8,6 +8,12 @@ export interface CatalogsResponse { error?: string; } +/** + * Get Catalogs. + * + * @param accountId - Account identifier. + * @returns - Computed result. + */ export async function getCatalogs(accountId: string): Promise { try { const response = await fetch( diff --git a/lib/chat/__tests__/handleChatCompletion.test.ts b/lib/chat/__tests__/handleChatCompletion.test.ts index aab50328f..4ea61f547 100644 --- a/lib/chat/__tests__/handleChatCompletion.test.ts +++ b/lib/chat/__tests__/handleChatCompletion.test.ts @@ -56,10 +56,12 @@ const mockSendErrorNotification = vi.mocked(sendErrorNotification); // Helper to create mock UIMessage /** + * Create Mock UIMessage. * - * @param id - * @param role - * @param text + * @param id - Identifier value. + * @param role - Value for role. + * @param text - Text content. + * @returns - Computed result. */ function createMockUIMessage(id: string, role: "user" | "assistant", text: string): UIMessage { return { @@ -72,8 +74,10 @@ function createMockUIMessage(id: string, role: "user" | "assistant", text: strin // Helper to create mock ChatRequestBody /** + * Create Mock Body. * - * @param overrides + * @param overrides - Optional override values. + * @returns - Computed result. */ function createMockBody(overrides: Partial = {}): ChatRequestBody { return { @@ -165,7 +169,7 @@ describe("handleChatCompletion", () => { it("sends notification for new conversation", async () => { mockSelectRoom.mockResolvedValue(null); mockGenerateChatTitle.mockResolvedValue("Test Topic"); - mockSelectAccountEmails.mockResolvedValue([{ email: "test@example.com" } as any]); + mockSelectAccountEmails.mockResolvedValue([{ email: "test@example.com" } as unknown]); const body = createMockBody({ roomId: "new-room-123" }); const responseMessages = [createMockUIMessage("resp-1", "assistant", "Hi!")]; @@ -222,8 +226,8 @@ describe("handleChatCompletion", () => { mockSelectRoom.mockResolvedValue(null); mockGenerateChatTitle.mockResolvedValue("Topic"); mockSelectAccountEmails.mockResolvedValue([ - { email: "first@example.com" } as any, - { email: "second@example.com" } as any, + { email: "first@example.com" } as unknown, + { email: "second@example.com" } as unknown, ]); const body = createMockBody(); diff --git a/lib/chat/__tests__/handleChatGenerate.test.ts b/lib/chat/__tests__/handleChatGenerate.test.ts index c1d3ede82..806d58d1a 100644 --- a/lib/chat/__tests__/handleChatGenerate.test.ts +++ b/lib/chat/__tests__/handleChatGenerate.test.ts @@ -51,8 +51,10 @@ const mockSetupConversation = vi.mocked(setupConversation); // Helper to create a mock agent with .generate() /** + * Create Mock Agent. * - * @param generateResult + * @param generateResult - Value for generateResult. + * @returns - Computed result. */ function createMockAgent(generateResult: Record) { return { @@ -64,9 +66,11 @@ function createMockAgent(generateResult: Record) { // Helper to create mock NextRequest /** + * Create Mock Request. * - * @param body - * @param headers + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. */ function createMockRequest(body: unknown, headers: Record = {}): Request { return { @@ -102,7 +106,7 @@ describe("handleChatGenerate", () => { const request = createMockRequest({ roomId: "room-123" }, { "x-api-key": "test-key" }); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(400); @@ -116,7 +120,7 @@ describe("handleChatGenerate", () => { ); const request = createMockRequest({ prompt: "Hello" }, {}); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(401); @@ -147,11 +151,11 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const request = createMockRequest({ prompt: "Hello, world!" }, { "x-api-key": "valid-key" }); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(mockAgent.generate).toHaveBeenCalled(); expect(result.status).toBe(200); @@ -178,12 +182,12 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const messages = [{ role: "user", content: "Hello" }]; const request = createMockRequest({ messages }, { "x-api-key": "valid-key" }); - await handleChatGenerate(request as any); + await handleChatGenerate(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalledWith( expect.objectContaining({ @@ -214,7 +218,7 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const request = createMockRequest( { @@ -227,7 +231,7 @@ describe("handleChatGenerate", () => { { "x-api-key": "valid-key" }, ); - await handleChatGenerate(request as any); + await handleChatGenerate(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalledWith( expect.objectContaining({ @@ -258,11 +262,11 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result.status).toBe(200); const json = await result.json(); @@ -282,7 +286,7 @@ describe("handleChatGenerate", () => { const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(500); @@ -306,11 +310,11 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(500); @@ -337,14 +341,14 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const request = createMockRequest( { prompt: "Hello", accountId: "target-account-456" }, { "x-api-key": "org-api-key" }, ); - await handleChatGenerate(request as any); + await handleChatGenerate(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalledWith( expect.objectContaining({ @@ -376,7 +380,7 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); mockSaveChatCompletion.mockResolvedValue(null); @@ -385,7 +389,7 @@ describe("handleChatGenerate", () => { { "x-api-key": "valid-key" }, ); - await handleChatGenerate(request as any); + await handleChatGenerate(request as unknown); expect(mockSaveChatCompletion).toHaveBeenCalledWith({ text: "Hello! How can I help you?", @@ -414,13 +418,13 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); mockSaveChatCompletion.mockResolvedValue(null); const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - await handleChatGenerate(request as any); + await handleChatGenerate(request as unknown); // Since roomId is auto-created, saveChatCompletion should be called expect(mockSaveChatCompletion).toHaveBeenCalledWith({ @@ -450,7 +454,7 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); mockSaveChatCompletion.mockResolvedValue(null); @@ -459,7 +463,7 @@ describe("handleChatGenerate", () => { { "x-api-key": "valid-key" }, ); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result.status).toBe(200); const json = await result.json(); @@ -487,13 +491,13 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); mockSaveChatCompletion.mockResolvedValue(null); const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result.status).toBe(200); const json = await result.json(); @@ -521,7 +525,7 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); mockSaveChatCompletion.mockResolvedValue(null); @@ -530,7 +534,7 @@ describe("handleChatGenerate", () => { { "x-api-key": "valid-key" }, ); - await handleChatGenerate(request as any); + await handleChatGenerate(request as unknown); expect(mockSaveChatCompletion).toHaveBeenCalledWith({ text: "This is the assistant response text", @@ -559,7 +563,7 @@ describe("handleChatGenerate", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); mockSaveChatCompletion.mockRejectedValue(new Error("Database error")); @@ -568,7 +572,7 @@ describe("handleChatGenerate", () => { { "x-api-key": "valid-key" }, ); - const result = await handleChatGenerate(request as any); + const result = await handleChatGenerate(request as unknown); expect(result.status).toBe(200); const json = await result.json(); diff --git a/lib/chat/__tests__/handleChatStream.test.ts b/lib/chat/__tests__/handleChatStream.test.ts index c670b1ef1..09b4a0455 100644 --- a/lib/chat/__tests__/handleChatStream.test.ts +++ b/lib/chat/__tests__/handleChatStream.test.ts @@ -58,9 +58,11 @@ const mockCreateUIMessageStreamResponse = vi.mocked(createUIMessageStreamRespons // Helper to create mock NextRequest /** + * Create Mock Request. * - * @param body - * @param headers + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. */ function createMockRequest(body: unknown, headers: Record = {}): Request { return { @@ -97,7 +99,7 @@ describe("handleChatStream", () => { const request = createMockRequest({ roomId: "room-123" }, { "x-api-key": "test-key" }); - const result = await handleChatStream(request as any); + const result = await handleChatStream(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(400); @@ -111,7 +113,7 @@ describe("handleChatStream", () => { ); const request = createMockRequest({ prompt: "Hello" }, {}); - const result = await handleChatStream(request as any); + const result = await handleChatStream(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(401); @@ -137,7 +139,7 @@ describe("handleChatStream", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const mockStream = new ReadableStream(); mockCreateUIMessageStream.mockReturnValue(mockStream); @@ -147,7 +149,7 @@ describe("handleChatStream", () => { const request = createMockRequest({ prompt: "Hello, world!" }, { "x-api-key": "valid-key" }); - const result = await handleChatStream(request as any); + const result = await handleChatStream(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalled(); expect(mockCreateUIMessageStream).toHaveBeenCalled(); @@ -181,7 +183,7 @@ describe("handleChatStream", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const mockStream = new ReadableStream(); mockCreateUIMessageStream.mockReturnValue(mockStream); @@ -190,7 +192,7 @@ describe("handleChatStream", () => { const messages = [{ role: "user", content: "Hello" }]; const request = createMockRequest({ messages }, { "x-api-key": "valid-key" }); - await handleChatStream(request as any); + await handleChatStream(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalledWith( expect.objectContaining({ @@ -218,7 +220,7 @@ describe("handleChatStream", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const mockStream = new ReadableStream(); mockCreateUIMessageStream.mockReturnValue(mockStream); @@ -235,7 +237,7 @@ describe("handleChatStream", () => { { "x-api-key": "valid-key" }, ); - await handleChatStream(request as any); + await handleChatStream(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalledWith( expect.objectContaining({ @@ -259,7 +261,7 @@ describe("handleChatStream", () => { const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await handleChatStream(request as any); + const result = await handleChatStream(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect(result.status).toBe(500); @@ -287,7 +289,7 @@ describe("handleChatStream", () => { mockSetupChatRequest.mockResolvedValue({ agent: mockAgent, messages: [], - } as any); + } as unknown); const mockStream = new ReadableStream(); mockCreateUIMessageStream.mockReturnValue(mockStream); @@ -298,7 +300,7 @@ describe("handleChatStream", () => { { "x-api-key": "org-api-key" }, ); - await handleChatStream(request as any); + await handleChatStream(request as unknown); expect(mockSetupChatRequest).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/lib/chat/__tests__/integration/chatEndToEnd.test.ts b/lib/chat/__tests__/integration/chatEndToEnd.test.ts index b54e51f5b..6a9380890 100644 --- a/lib/chat/__tests__/integration/chatEndToEnd.test.ts +++ b/lib/chat/__tests__/integration/chatEndToEnd.test.ts @@ -154,6 +154,13 @@ const mockDeductCredits = vi.mocked(deductCredits); const mockGenerateChatTitle = vi.mocked(generateChatTitle); // Helper to create mock NextRequest +/** + * Create Mock Request. + * + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. + */ function createMockRequest(body: unknown, headers: Record = {}): Request { return { json: () => Promise.resolve(body), @@ -169,7 +176,7 @@ describe("Chat Integration Tests", () => { vi.clearAllMocks(); // Set up default mocks for Supabase operations - mockSelectAccountEmails.mockResolvedValue([{ email: "test@example.com" }] as any); + mockSelectAccountEmails.mockResolvedValue([{ email: "test@example.com" }] as unknown); mockSelectAccountInfo.mockResolvedValue(null); mockGetAccountWithDetails.mockResolvedValue(null); mockGetKnowledgeBaseText.mockResolvedValue(""); @@ -197,12 +204,12 @@ describe("Chat Integration Tests", () => { const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); // Should not be a NextResponse error expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).accountId).toBe("account-123"); - expect((result as any).prompt).toBe("Hello"); + expect((result as unknown).accountId).toBe("account-123"); + expect((result as unknown).prompt).toBe("Hello"); }); it("validates and returns body for valid request with messages", async () => { @@ -219,10 +226,10 @@ describe("Chat Integration Tests", () => { { "x-api-key": "valid-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).messages).toHaveLength(1); + expect((result as unknown).messages).toHaveLength(1); }); it("returns 401 when auth fails", async () => { @@ -231,7 +238,7 @@ describe("Chat Integration Tests", () => { ); const request = createMockRequest({ prompt: "Hello" }, {}); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(401); @@ -246,7 +253,7 @@ describe("Chat Integration Tests", () => { const request = createMockRequest({ roomId: "room-123" }, { "x-api-key": "valid-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); @@ -267,7 +274,7 @@ describe("Chat Integration Tests", () => { { "x-api-key": "valid-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); @@ -291,26 +298,26 @@ describe("Chat Integration Tests", () => { { "x-api-key": "valid-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).roomId).toBe("room-123"); - expect((result as any).artistId).toBe("artist-456"); - expect((result as any).model).toBe("gpt-4"); - expect((result as any).excludeTools).toEqual(["tool1", "tool2"]); + expect((result as unknown).roomId).toBe("room-123"); + expect((result as unknown).artistId).toBe("artist-456"); + expect((result as unknown).model).toBe("gpt-4"); + expect((result as unknown).excludeTools).toEqual(["tool1", "tool2"]); }); }); describe("setupChatRequest integration", () => { it("correctly retrieves account email for system prompt", async () => { - mockSelectAccountEmails.mockResolvedValue([{ email: "user@test.com" }] as any); + mockSelectAccountEmails.mockResolvedValue([{ email: "user@test.com" }] as unknown); const body = { accountId: "account-123", messages: [{ id: "msg-1", role: "user", content: "Hello" }], }; - await setupChatRequest(body as any); + await setupChatRequest(body as unknown); expect(mockSelectAccountEmails).toHaveBeenCalledWith({ accountIds: "account-123", @@ -321,7 +328,7 @@ describe("Chat Integration Tests", () => { mockSelectAccountInfo.mockResolvedValue({ instruction: "Be helpful for this artist", knowledges: [{ id: "kb-1" }], - } as any); + } as unknown); mockGetKnowledgeBaseText.mockResolvedValue("Artist knowledge base content"); const body = { @@ -330,7 +337,7 @@ describe("Chat Integration Tests", () => { messages: [{ id: "msg-1", role: "user", content: "Hello" }], }; - await setupChatRequest(body as any); + await setupChatRequest(body as unknown); expect(mockSelectAccountInfo).toHaveBeenCalledWith("artist-456"); expect(mockGetKnowledgeBaseText).toHaveBeenCalled(); @@ -342,7 +349,7 @@ describe("Chat Integration Tests", () => { messages: [{ id: "msg-1", role: "user", content: "Hello" }], }; - await setupChatRequest(body as any); + await setupChatRequest(body as unknown); expect(mockSelectAccountInfo).not.toHaveBeenCalled(); expect(mockGetKnowledgeBaseText).not.toHaveBeenCalled(); @@ -354,7 +361,7 @@ describe("Chat Integration Tests", () => { messages: [{ id: "msg-1", role: "user", content: "Hello" }], }; - const result = await setupChatRequest(body as any); + const result = await setupChatRequest(body as unknown); expect(result).toHaveProperty("agent"); expect(result).toHaveProperty("messages"); @@ -365,14 +372,14 @@ describe("Chat Integration Tests", () => { mockGetAccountWithDetails.mockResolvedValue({ name: "Test User", professional_context: "Music producer", - } as any); + } as unknown); const body = { accountId: "account-123", messages: [{ id: "msg-1", role: "user", content: "Hello" }], }; - await setupChatRequest(body as any); + await setupChatRequest(body as unknown); expect(mockGetAccountWithDetails).toHaveBeenCalledWith("account-123"); }); @@ -393,7 +400,7 @@ describe("Chat Integration Tests", () => { { id: "response-1", role: "assistant", parts: [{ type: "text", text: "Hi there!" }] }, ]; - await handleChatCompletion(body as any, responseMessages as any); + await handleChatCompletion(body as unknown, responseMessages as unknown); expect(mockUpsertRoom).toHaveBeenCalledWith( expect.objectContaining({ @@ -406,7 +413,7 @@ describe("Chat Integration Tests", () => { }); it("skips room creation for existing rooms", async () => { - mockSelectRoom.mockResolvedValue({ id: "existing-room" } as any); + mockSelectRoom.mockResolvedValue({ id: "existing-room" } as unknown); const body = { messages: [{ id: "msg-1", role: "user", parts: [{ type: "text", text: "Hello" }] }], @@ -418,14 +425,14 @@ describe("Chat Integration Tests", () => { { id: "response-1", role: "assistant", parts: [{ type: "text", text: "Hi!" }] }, ]; - await handleChatCompletion(body as any, responseMessages as any); + await handleChatCompletion(body as unknown, responseMessages as unknown); expect(mockUpsertRoom).not.toHaveBeenCalled(); expect(mockSendNewConversationNotification).not.toHaveBeenCalled(); }); it("stores both user and assistant messages to memories", async () => { - mockSelectRoom.mockResolvedValue({ id: "room-123" } as any); + mockSelectRoom.mockResolvedValue({ id: "room-123" } as unknown); const body = { messages: [{ id: "msg-1", role: "user", parts: [{ type: "text", text: "Hello" }] }], @@ -437,7 +444,7 @@ describe("Chat Integration Tests", () => { { id: "response-1", role: "assistant", parts: [{ type: "text", text: "Hi!" }] }, ]; - await handleChatCompletion(body as any, responseMessages as any); + await handleChatCompletion(body as unknown, responseMessages as unknown); expect(mockUpsertMemory).toHaveBeenCalledTimes(2); expect(mockUpsertMemory).toHaveBeenCalledWith( @@ -455,7 +462,7 @@ describe("Chat Integration Tests", () => { }); it("processes email tool outputs", async () => { - mockSelectRoom.mockResolvedValue({ id: "room-123" } as any); + mockSelectRoom.mockResolvedValue({ id: "room-123" } as unknown); const body = { messages: [{ id: "msg-1", role: "user", parts: [{ type: "text", text: "Send an email" }] }], @@ -477,7 +484,7 @@ describe("Chat Integration Tests", () => { }, ]; - await handleChatCompletion(body as any, responseMessages as any); + await handleChatCompletion(body as unknown, responseMessages as unknown); expect(mockHandleSendEmailToolOutputs).toHaveBeenCalledWith(responseMessages); }); @@ -497,7 +504,7 @@ describe("Chat Integration Tests", () => { // Should not throw await expect( - handleChatCompletion(body as any, responseMessages as any), + handleChatCompletion(body as unknown, responseMessages as unknown), ).resolves.toBeUndefined(); }); @@ -512,7 +519,7 @@ describe("Chat Integration Tests", () => { { id: "response-1", role: "assistant", parts: [{ type: "text", text: "Hi!" }] }, ]; - await handleChatCompletion(body as any, responseMessages as any); + await handleChatCompletion(body as unknown, responseMessages as unknown); expect(mockSelectRoom).toHaveBeenCalledWith(""); }); @@ -605,10 +612,10 @@ describe("Chat Integration Tests", () => { const request = createMockRequest({ prompt: "What is 2+2?" }, { "x-api-key": "valid-key" }); - const validationResult = await validateChatRequest(request as any); + const validationResult = await validateChatRequest(request as unknown); expect(validationResult).not.toBeInstanceOf(NextResponse); - const chatConfig = await setupChatRequest(validationResult as any); + const chatConfig = await setupChatRequest(validationResult as unknown); expect(chatConfig.agent).toBeDefined(); expect(chatConfig.messages).toBeDefined(); }); @@ -631,10 +638,10 @@ describe("Chat Integration Tests", () => { { "x-api-key": "valid-key" }, ); - const validationResult = await validateChatRequest(request as any); + const validationResult = await validateChatRequest(request as unknown); expect(validationResult).not.toBeInstanceOf(NextResponse); - const chatConfig = await setupChatRequest(validationResult as any); + const chatConfig = await setupChatRequest(validationResult as unknown); expect(chatConfig.agent).toBeDefined(); expect(chatConfig.messages.length).toBeLessThanOrEqual(100); // MAX_MESSAGES }); @@ -657,11 +664,11 @@ describe("Chat Integration Tests", () => { { "x-api-key": "valid-key" }, ); - const body = await validateChatRequest(request as any); + const body = await validateChatRequest(request as unknown); expect(body).not.toBeInstanceOf(NextResponse); // 2. Setup chat request - const chatConfig = await setupChatRequest(body as any); + const chatConfig = await setupChatRequest(body as unknown); expect(chatConfig.agent).toBeDefined(); // 3. Handle post-completion (simulating what would happen after agent response) @@ -673,7 +680,7 @@ describe("Chat Integration Tests", () => { }, ]; - await handleChatCompletion(body as any, responseMessages as any); + await handleChatCompletion(body as unknown, responseMessages as unknown); expect(mockUpsertRoom).toHaveBeenCalled(); expect(mockUpsertMemory).toHaveBeenCalledTimes(2); @@ -681,8 +688,8 @@ describe("Chat Integration Tests", () => { // 4. Handle credits await handleChatCredits({ usage: { promptTokens: 100, completionTokens: 50 }, - model: (body as any).model || "openai/gpt-5-mini", - accountId: (body as any).accountId, + model: (body as unknown).model || "openai/gpt-5-mini", + accountId: (body as unknown).accountId, }); expect(mockGetCreditUsage).toHaveBeenCalled(); diff --git a/lib/chat/__tests__/saveChatCompletion.test.ts b/lib/chat/__tests__/saveChatCompletion.test.ts index 8704ae73b..d74dcf9c3 100644 --- a/lib/chat/__tests__/saveChatCompletion.test.ts +++ b/lib/chat/__tests__/saveChatCompletion.test.ts @@ -148,7 +148,7 @@ describe("saveChatCompletion", () => { }; mockGetMessages.mockReturnValue([mockMessage]); mockFilterMessageContentForMemories.mockReturnValue(mockFilteredContent); - mockInsertMemories.mockResolvedValue(mockInsertedMemory as any); + mockInsertMemories.mockResolvedValue(mockInsertedMemory as unknown); const result = await saveChatCompletion({ text: "Return test", diff --git a/lib/chat/__tests__/setupChatRequest.test.ts b/lib/chat/__tests__/setupChatRequest.test.ts index bd2ac4e14..e3ca72d8e 100644 --- a/lib/chat/__tests__/setupChatRequest.test.ts +++ b/lib/chat/__tests__/setupChatRequest.test.ts @@ -40,8 +40,8 @@ describe("setupChatRequest", () => { beforeEach(() => { vi.clearAllMocks(); - mockGetGeneralAgent.mockResolvedValue(mockRoutingDecision as any); - mockConvertToModelMessages.mockImplementation(messages => messages as any); + mockGetGeneralAgent.mockResolvedValue(mockRoutingDecision as unknown); + mockConvertToModelMessages.mockImplementation(messages => messages as unknown); }); describe("basic functionality", () => { @@ -126,7 +126,7 @@ describe("setupChatRequest", () => { ...mockAgent, tools: mockTools, }, - } as any); + } as unknown); const body: ChatRequestBody = { accountId: "account-123", diff --git a/lib/chat/__tests__/validateChatRequest.test.ts b/lib/chat/__tests__/validateChatRequest.test.ts index 0fd081fac..3afc3669c 100644 --- a/lib/chat/__tests__/validateChatRequest.test.ts +++ b/lib/chat/__tests__/validateChatRequest.test.ts @@ -3,10 +3,6 @@ import { NextResponse } from "next/server"; import { validateChatRequest, chatRequestSchema } from "../validateChatRequest"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; -import { generateUUID } from "@/lib/uuid/generateUUID"; -import { createNewRoom } from "@/lib/chat/createNewRoom"; -import insertMemories from "@/lib/supabase/memories/insertMemories"; -import filterMessageContentForMemories from "@/lib/messages/filterMessageContentForMemories"; import { setupConversation } from "@/lib/chat/setupConversation"; // Mock dependencies @@ -39,17 +35,15 @@ vi.mock("@/lib/chat/setupConversation", () => ({ })); const mockValidateAuthContext = vi.mocked(validateAuthContext); -const mockGenerateUUID = vi.mocked(generateUUID); -const mockCreateNewRoom = vi.mocked(createNewRoom); -const mockInsertMemories = vi.mocked(insertMemories); -const mockFilterMessageContentForMemories = vi.mocked(filterMessageContentForMemories); const mockSetupConversation = vi.mocked(setupConversation); // Helper to create mock NextRequest /** + * Create Mock Request. * - * @param body - * @param headers + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. */ function createMockRequest(body: unknown, headers: Record = {}): Request { return { @@ -81,7 +75,7 @@ describe("validateChatRequest", () => { const request = createMockRequest({ roomId: "room-123" }, { "x-api-key": "test-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); const json = await (result as NextResponse).json(); @@ -104,7 +98,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); const json = await (result as NextResponse).json(); @@ -124,10 +118,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).accountId).toBe("account-123"); + expect((result as unknown).accountId).toBe("account-123"); }); it("accepts valid prompt string", async () => { @@ -139,10 +133,10 @@ describe("validateChatRequest", () => { const request = createMockRequest({ prompt: "Hello, world!" }, { "x-api-key": "test-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).accountId).toBe("account-123"); + expect((result as unknown).accountId).toBe("account-123"); }); }); @@ -156,7 +150,7 @@ describe("validateChatRequest", () => { ); const request = createMockRequest({ prompt: "Hello" }, {}); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); const json = await (result as NextResponse).json(); @@ -170,7 +164,7 @@ describe("validateChatRequest", () => { ); const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "invalid-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(401); @@ -184,10 +178,10 @@ describe("validateChatRequest", () => { }); const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "valid-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).accountId).toBe("resolved-account-123"); + expect((result as unknown).accountId).toBe("resolved-account-123"); }); it("passes accountId and organizationId to validateAuthContext", async () => { @@ -201,7 +195,7 @@ describe("validateChatRequest", () => { { prompt: "Hello", accountId: "target-456", organizationId: "org-789" }, { "x-api-key": "valid-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); expect(mockValidateAuthContext).toHaveBeenCalledWith(expect.anything(), { accountId: "target-456", @@ -220,12 +214,12 @@ describe("validateChatRequest", () => { const request = createMockRequest({ prompt: "Hello, world!" }, { "x-api-key": "test-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).messages).toHaveLength(1); - expect((result as any).messages[0].role).toBe("user"); - expect((result as any).messages[0].parts[0].text).toBe("Hello, world!"); + expect((result as unknown).messages).toHaveLength(1); + expect((result as unknown).messages[0].role).toBe("user"); + expect((result as unknown).messages[0].parts[0].text).toBe("Hello, world!"); }); it("preserves original messages when provided", async () => { @@ -244,10 +238,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).messages).toEqual(originalMessages); + expect((result as unknown).messages).toEqual(originalMessages); }); }); @@ -268,10 +262,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).roomId).toBe("room-xyz"); + expect((result as unknown).roomId).toBe("room-xyz"); }); it("passes through artistId", async () => { @@ -286,10 +280,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).artistId).toBe("artist-abc"); + expect((result as unknown).artistId).toBe("artist-abc"); }); it("passes through model selection", async () => { @@ -304,10 +298,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).model).toBe("gpt-4"); + expect((result as unknown).model).toBe("gpt-4"); }); it("passes through excludeTools array", async () => { @@ -322,10 +316,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).excludeTools).toEqual(["tool1", "tool2"]); + expect((result as unknown).excludeTools).toEqual(["tool1", "tool2"]); }); it("passes through topic", async () => { @@ -340,10 +334,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).topic).toBe("Pulse Feb 2"); + expect((result as unknown).topic).toBe("Pulse Feb 2"); }); }); @@ -399,10 +393,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).orgId).toBe("org-456"); + expect((result as unknown).orgId).toBe("org-456"); }); it("returns null orgId when no organizationId provided", async () => { @@ -414,10 +408,10 @@ describe("validateChatRequest", () => { const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "test-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).orgId).toBeNull(); + expect((result as unknown).orgId).toBeNull(); }); }); @@ -435,10 +429,10 @@ describe("validateChatRequest", () => { const request = createMockRequest({ prompt: "Hello" }, { "x-api-key": "test-key" }); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).roomId).toBe("generated-uuid-456"); + expect((result as unknown).roomId).toBe("generated-uuid-456"); }); it("calls setupConversation with correct params when roomId is not provided", async () => { @@ -457,7 +451,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); expect(mockSetupConversation).toHaveBeenCalledWith({ accountId: "account-123", @@ -487,7 +481,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); expect(mockSetupConversation).toHaveBeenCalledWith( expect.objectContaining({ @@ -512,7 +506,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); expect(mockSetupConversation).toHaveBeenCalledWith( expect.objectContaining({ @@ -537,10 +531,10 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).roomId).toBe("existing-room-123"); + expect((result as unknown).roomId).toBe("existing-room-123"); }); it("passes roomId to setupConversation when provided", async () => { @@ -559,7 +553,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); expect(mockSetupConversation).toHaveBeenCalledWith( expect.objectContaining({ @@ -584,10 +578,10 @@ describe("validateChatRequest", () => { { authorization: "Bearer valid-jwt" }, ); - const result = await validateChatRequest(request as any); + const result = await validateChatRequest(request as unknown); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).roomId).toBe("jwt-generated-uuid"); + expect((result as unknown).roomId).toBe("jwt-generated-uuid"); expect(mockSetupConversation).toHaveBeenCalledWith( expect.objectContaining({ accountId: "jwt-account-123", @@ -611,7 +605,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); expect(mockSetupConversation).toHaveBeenCalledWith({ accountId: "account-123", @@ -643,7 +637,7 @@ describe("validateChatRequest", () => { { "x-api-key": "test-key" }, ); - await validateChatRequest(request as any); + await validateChatRequest(request as unknown); // setupConversation handles both new and existing rooms expect(mockSetupConversation).toHaveBeenCalledWith({ diff --git a/lib/chat/toolChains/__tests__/getExecutedToolTimeline.test.ts b/lib/chat/toolChains/__tests__/getExecutedToolTimeline.test.ts index 4e7085c9f..44f703aa4 100644 --- a/lib/chat/toolChains/__tests__/getExecutedToolTimeline.test.ts +++ b/lib/chat/toolChains/__tests__/getExecutedToolTimeline.test.ts @@ -21,7 +21,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual(["get_spotify_search"]); }); @@ -43,7 +43,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual(["tool_a", "tool_b"]); }); @@ -78,7 +78,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual(["create_new_artist", "get_spotify_search", "update_account_info"]); }); }); @@ -98,7 +98,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual(["tool_a"]); }); @@ -116,7 +116,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual(["tool_a"]); }); @@ -141,7 +141,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual([ "step1_tool1", "step1_tool2", @@ -163,7 +163,7 @@ describe("getExecutedToolTimeline", () => { }, ]; - const result = getExecutedToolTimeline(steps as any); + const result = getExecutedToolTimeline(steps as unknown); expect(result).toEqual(["tool_without_id"]); }); }); diff --git a/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts b/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts index df582c015..a4d641ea8 100644 --- a/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts +++ b/lib/chat/toolChains/__tests__/getPrepareStepResult.test.ts @@ -37,7 +37,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toBeUndefined(); }); @@ -59,7 +59,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toBeUndefined(); }); }); @@ -83,7 +83,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toEqual({ toolChoice: { type: "tool", toolName: "step_one" }, }); @@ -112,7 +112,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toEqual({ toolChoice: { type: "tool", toolName: "step_two" }, model: "gemini-2.5-pro", // From TOOL_MODEL_MAP @@ -152,7 +152,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toBeUndefined(); }); @@ -188,7 +188,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); // Should return step_two since step_one has been executed expect(result).toEqual({ toolChoice: { type: "tool", toolName: "step_two" }, @@ -216,7 +216,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toEqual({ toolChoice: { type: "tool", toolName: "custom_step_one" }, system: "Custom system prompt for step one", @@ -252,7 +252,7 @@ describe("getPrepareStepResult", () => { messages: existingMessages, }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result).toEqual({ toolChoice: { type: "tool", toolName: "custom_step_two" }, messages: [ @@ -287,7 +287,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result?.model).toBe("gemini-2.5-pro"); }); @@ -309,7 +309,7 @@ describe("getPrepareStepResult", () => { messages: [], }; - const result = getPrepareStepResult(options as any); + const result = getPrepareStepResult(options as unknown); expect(result?.model).toBeUndefined(); }); }); diff --git a/lib/chat/toolChains/__tests__/toolChains.test.ts b/lib/chat/toolChains/__tests__/toolChains.test.ts index fdd5782f6..932b64a57 100644 --- a/lib/chat/toolChains/__tests__/toolChains.test.ts +++ b/lib/chat/toolChains/__tests__/toolChains.test.ts @@ -38,7 +38,7 @@ describe("toolChains", () => { it("allows result with model override", () => { const result: PrepareStepResult = { toolChoice: { type: "tool", toolName: "test_tool" }, - model: "gemini-2.5-pro" as any, + model: "gemini-2.5-pro" as unknown, }; expect(result.model).toBe("gemini-2.5-pro"); }); @@ -46,7 +46,7 @@ describe("toolChains", () => { it("allows result with all properties", () => { const result: PrepareStepResult = { toolChoice: { type: "tool", toolName: "test_tool" }, - model: "gemini-2.5-pro" as any, + model: "gemini-2.5-pro" as unknown, system: "Custom prompt", messages: [{ role: "user", content: "Test" }], }; diff --git a/lib/chat/toolChains/create_release_report/getReleaseReportReferenceMessage.ts b/lib/chat/toolChains/create_release_report/getReleaseReportReferenceMessage.ts index 40507d7bc..911e87823 100644 --- a/lib/chat/toolChains/create_release_report/getReleaseReportReferenceMessage.ts +++ b/lib/chat/toolChains/create_release_report/getReleaseReportReferenceMessage.ts @@ -1,9 +1,6 @@ import { ModelMessage } from "ai"; import { referenceReleaseReport } from "./referenceReleaseReport"; -/** - * Creates a reference message with the release report example - */ const getReleaseReportReferenceMessage = (): ModelMessage => { return { role: "user", diff --git a/lib/chat/toolChains/getPrepareStepResult.ts b/lib/chat/toolChains/getPrepareStepResult.ts index 4362ea489..caf4fcbea 100644 --- a/lib/chat/toolChains/getPrepareStepResult.ts +++ b/lib/chat/toolChains/getPrepareStepResult.ts @@ -9,10 +9,6 @@ type PrepareStepOptions = { messages: Array; }; -/** - * Returns the next tool to run based on timeline progression through tool chains. - * Uses toolCallsContent to track exact execution order and position in sequence. - */ const getPrepareStepResult = (options: PrepareStepOptions): PrepareStepResult | undefined => { const { steps } = options; // Extract tool calls timeline (history) from steps diff --git a/lib/chats/__tests__/createChatHandler.test.ts b/lib/chats/__tests__/createChatHandler.test.ts index 6d5091471..4c0bb60c0 100644 --- a/lib/chats/__tests__/createChatHandler.test.ts +++ b/lib/chats/__tests__/createChatHandler.test.ts @@ -41,6 +41,12 @@ vi.mock("../generateChatTitle", () => ({ generateChatTitle: vi.fn(), })); +/** + * Create Mock Request. + * + * @param headers - Headers for the request. + * @returns - Computed result. + */ function createMockRequest( headers: Record = { "x-api-key": "test-api-key" }, ): NextRequest { diff --git a/lib/chats/__tests__/generateChatTitle.test.ts b/lib/chats/__tests__/generateChatTitle.test.ts index e1bb8a8bf..97b4ee235 100644 --- a/lib/chats/__tests__/generateChatTitle.test.ts +++ b/lib/chats/__tests__/generateChatTitle.test.ts @@ -18,7 +18,7 @@ describe("generateChatTitle", () => { it("generates a title from the input text", async () => { mockGenerateText.mockResolvedValue({ text: "Marketing Plan", - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies should I use?"); @@ -28,7 +28,7 @@ describe("generateChatTitle", () => { it("calls generateText with correct prompt structure", async () => { mockGenerateText.mockResolvedValue({ text: "Test Title", - } as any); + } as unknown); await generateChatTitle("Test input"); @@ -43,7 +43,7 @@ describe("generateChatTitle", () => { it("uses LIGHTWEIGHT_MODEL for efficiency", async () => { mockGenerateText.mockResolvedValue({ text: "Test Title", - } as any); + } as unknown); await generateChatTitle("Test input"); @@ -59,7 +59,7 @@ describe("generateChatTitle", () => { it("removes leading double quotes from generated title", async () => { mockGenerateText.mockResolvedValue({ text: '"Marketing Plan', - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies?"); @@ -69,7 +69,7 @@ describe("generateChatTitle", () => { it("removes trailing double quotes from generated title", async () => { mockGenerateText.mockResolvedValue({ text: 'Marketing Plan"', - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies?"); @@ -79,7 +79,7 @@ describe("generateChatTitle", () => { it("removes both leading and trailing double quotes", async () => { mockGenerateText.mockResolvedValue({ text: '"Marketing Plan"', - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies?"); @@ -89,7 +89,7 @@ describe("generateChatTitle", () => { it("removes leading single quotes", async () => { mockGenerateText.mockResolvedValue({ text: "'Marketing Plan", - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies?"); @@ -99,7 +99,7 @@ describe("generateChatTitle", () => { it("removes trailing single quotes", async () => { mockGenerateText.mockResolvedValue({ text: "Marketing Plan'", - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies?"); @@ -109,7 +109,7 @@ describe("generateChatTitle", () => { it("removes both leading and trailing single quotes", async () => { mockGenerateText.mockResolvedValue({ text: "'Marketing Plan'", - } as any); + } as unknown); const result = await generateChatTitle("What marketing strategies?"); @@ -119,7 +119,7 @@ describe("generateChatTitle", () => { it("does not remove quotes in the middle of the title", async () => { mockGenerateText.mockResolvedValue({ text: "User's Plan", - } as any); + } as unknown); const result = await generateChatTitle("Help me with the user's plan"); @@ -131,7 +131,7 @@ describe("generateChatTitle", () => { it("instructs model to generate title under 20 characters", async () => { mockGenerateText.mockResolvedValue({ text: "Short Title", - } as any); + } as unknown); await generateChatTitle("A very long question about many things"); @@ -145,7 +145,7 @@ describe("generateChatTitle", () => { it("instructs model to highlight segment names if present", async () => { mockGenerateText.mockResolvedValue({ text: "Active Fans", - } as any); + } as unknown); await generateChatTitle("Show me the Active Fans segment"); @@ -159,7 +159,7 @@ describe("generateChatTitle", () => { it("instructs model not to wrap title in quotes", async () => { mockGenerateText.mockResolvedValue({ text: "Clean Title", - } as any); + } as unknown); await generateChatTitle("Some question"); @@ -175,7 +175,7 @@ describe("generateChatTitle", () => { it("handles empty input gracefully", async () => { mockGenerateText.mockResolvedValue({ text: "New Chat", - } as any); + } as unknown); const result = await generateChatTitle(""); @@ -185,7 +185,7 @@ describe("generateChatTitle", () => { it("handles very long input", async () => { mockGenerateText.mockResolvedValue({ text: "Long Discussion", - } as any); + } as unknown); const longInput = "a".repeat(1000); const result = await generateChatTitle(longInput); diff --git a/lib/chats/__tests__/getChatsHandler.test.ts b/lib/chats/__tests__/getChatsHandler.test.ts index 5a85935e1..2b2256854 100644 --- a/lib/chats/__tests__/getChatsHandler.test.ts +++ b/lib/chats/__tests__/getChatsHandler.test.ts @@ -4,7 +4,6 @@ import { getChatsHandler } from "../getChatsHandler"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; import { canAccessAccount } from "@/lib/organizations/canAccessAccount"; -import { getAccountOrganizations } from "@/lib/supabase/account_organization_ids/getAccountOrganizations"; import { selectRooms } from "@/lib/supabase/rooms/selectRooms"; vi.mock("@/lib/auth/validateAuthContext", () => ({ @@ -15,10 +14,6 @@ vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn(), })); -vi.mock("@/lib/supabase/account_organization_ids/getAccountOrganizations", () => ({ - getAccountOrganizations: vi.fn(), -})); - vi.mock("@/lib/supabase/rooms/selectRooms", () => ({ selectRooms: vi.fn(), })); diff --git a/lib/chats/__tests__/validateCreateChatBody.test.ts b/lib/chats/__tests__/validateCreateChatBody.test.ts index 0ec4fbe2c..ba5d193ff 100644 --- a/lib/chats/__tests__/validateCreateChatBody.test.ts +++ b/lib/chats/__tests__/validateCreateChatBody.test.ts @@ -10,7 +10,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).artistId).toBe("123e4567-e89b-12d3-a456-426614174000"); + expect((result as unknown).artistId).toBe("123e4567-e89b-12d3-a456-426614174000"); }); it("rejects invalid UUID for artistId", () => { @@ -35,7 +35,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).chatId).toBe("123e4567-e89b-12d3-a456-426614174000"); + expect((result as unknown).chatId).toBe("123e4567-e89b-12d3-a456-426614174000"); }); it("rejects invalid UUID for chatId", () => { @@ -54,7 +54,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).accountId).toBe("123e4567-e89b-12d3-a456-426614174000"); + expect((result as unknown).accountId).toBe("123e4567-e89b-12d3-a456-426614174000"); }); it("rejects invalid UUID for accountId", () => { @@ -71,7 +71,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).accountId).toBeUndefined(); + expect((result as unknown).accountId).toBeUndefined(); }); }); @@ -99,7 +99,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).firstMessage).toBe("What marketing strategies should I use?"); + expect((result as unknown).firstMessage).toBe("What marketing strategies should I use?"); }); it("accepts missing firstMessage (optional)", () => { @@ -108,7 +108,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).firstMessage).toBeUndefined(); + expect((result as unknown).firstMessage).toBeUndefined(); }); it("accepts empty string for firstMessage", () => { @@ -118,7 +118,7 @@ describe("validateCreateChatBody", () => { }); expect(result).not.toBeInstanceOf(NextResponse); - expect((result as any).firstMessage).toBe(""); + expect((result as unknown).firstMessage).toBe(""); }); }); }); diff --git a/lib/chats/__tests__/validateGetChatsRequest.test.ts b/lib/chats/__tests__/validateGetChatsRequest.test.ts index ea86c5abd..e9e9bf85b 100644 --- a/lib/chats/__tests__/validateGetChatsRequest.test.ts +++ b/lib/chats/__tests__/validateGetChatsRequest.test.ts @@ -4,7 +4,6 @@ import { validateGetChatsRequest } from "../validateGetChatsRequest"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; import { canAccessAccount } from "@/lib/organizations/canAccessAccount"; -import { getAccountOrganizations } from "@/lib/supabase/account_organization_ids/getAccountOrganizations"; // Mock dependencies vi.mock("@/lib/auth/validateAuthContext", () => ({ @@ -15,10 +14,6 @@ vi.mock("@/lib/organizations/canAccessAccount", () => ({ canAccessAccount: vi.fn(), })); -vi.mock("@/lib/supabase/account_organization_ids/getAccountOrganizations", () => ({ - getAccountOrganizations: vi.fn(), -})); - vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => new Headers()), })); diff --git a/lib/chats/compactChatsHandler.ts b/lib/chats/compactChatsHandler.ts index 1bacaa565..ef5491f4a 100644 --- a/lib/chats/compactChatsHandler.ts +++ b/lib/chats/compactChatsHandler.ts @@ -21,7 +21,7 @@ export async function compactChatsHandler(request: NextRequest): Promise { describe("handleCodingAgentCallback", () => { /** + * Make Request. * - * @param body - * @param secret + * @param body - Request payload. + * @param secret - Value for secret. + * @returns - Computed result. */ function makeRequest(body: unknown, secret = "test-secret") { return { diff --git a/lib/coding-agent/__tests__/handleGitHubWebhook.test.ts b/lib/coding-agent/__tests__/handleGitHubWebhook.test.ts index 5e059f4e7..22766678c 100644 --- a/lib/coding-agent/__tests__/handleGitHubWebhook.test.ts +++ b/lib/coding-agent/__tests__/handleGitHubWebhook.test.ts @@ -45,6 +45,14 @@ const BASE_PAYLOAD = { }, }; +/** + * Make Request. + * + * @param body - Request payload. + * @param event - Value for event. + * @param signature - Value for signature. + * @returns - Computed result. + */ function makeRequest(body: unknown, event = "issue_comment", signature = "valid") { return { text: () => Promise.resolve(JSON.stringify(body)), diff --git a/lib/coding-agent/__tests__/handlers.test.ts b/lib/coding-agent/__tests__/handlers.test.ts index b21ebfe24..8aba15229 100644 --- a/lib/coding-agent/__tests__/handlers.test.ts +++ b/lib/coding-agent/__tests__/handlers.test.ts @@ -30,12 +30,14 @@ beforeEach(() => { }); /** + * Create Mock Bot. * + * @returns - Computed result. */ function createMockBot() { return { onNewMention: vi.fn(), - } as any; + } as unknown; } describe("registerOnNewMention", () => { diff --git a/lib/coding-agent/__tests__/mergeGithubBranch.test.ts b/lib/coding-agent/__tests__/mergeGithubBranch.test.ts index a31b44d1a..c89f9334c 100644 --- a/lib/coding-agent/__tests__/mergeGithubBranch.test.ts +++ b/lib/coding-agent/__tests__/mergeGithubBranch.test.ts @@ -41,7 +41,7 @@ describe("mergeGithubBranch", () => { ok: false, status: 409, text: () => Promise.resolve(JSON.stringify({ message: "Merge conflict" })), - } as any); + } as unknown); const result = await mergeGithubBranch("recoupable/api", "test", "main", "ghp_test"); diff --git a/lib/coding-agent/__tests__/mergeGithubPR.test.ts b/lib/coding-agent/__tests__/mergeGithubPR.test.ts index 889f23f6e..87a894a60 100644 --- a/lib/coding-agent/__tests__/mergeGithubPR.test.ts +++ b/lib/coding-agent/__tests__/mergeGithubPR.test.ts @@ -29,7 +29,7 @@ describe("mergeGithubPR", () => { ok: false, status: 405, text: () => Promise.resolve(JSON.stringify({ message: "Not allowed" })), - } as any); + } as unknown); const result = await mergeGithubPR("recoupable/api", 42, "ghp_test"); diff --git a/lib/coding-agent/__tests__/onMergeAction.test.ts b/lib/coding-agent/__tests__/onMergeAction.test.ts index 56f25c326..d311e2518 100644 --- a/lib/coding-agent/__tests__/onMergeAction.test.ts +++ b/lib/coding-agent/__tests__/onMergeAction.test.ts @@ -30,12 +30,14 @@ beforeEach(() => { }); /** + * Create Mock Bot. * + * @returns - Computed result. */ function createMockBot() { return { onAction: vi.fn(), - } as any; + } as unknown; } describe("registerOnMergeAction", () => { diff --git a/lib/coding-agent/__tests__/onMergeTestToMainAction.test.ts b/lib/coding-agent/__tests__/onMergeTestToMainAction.test.ts index 8af470e18..e704286e0 100644 --- a/lib/coding-agent/__tests__/onMergeTestToMainAction.test.ts +++ b/lib/coding-agent/__tests__/onMergeTestToMainAction.test.ts @@ -12,8 +12,13 @@ beforeEach(() => { process.env.GITHUB_TOKEN = "ghp_test"; }); +/** + * Create Mock Bot. + * + * @returns - Computed result. + */ function createMockBot() { - return { onAction: vi.fn() } as any; + return { onAction: vi.fn() } as unknown; } describe("registerOnMergeTestToMainAction", () => { diff --git a/lib/coding-agent/__tests__/onSubscribedMessage.test.ts b/lib/coding-agent/__tests__/onSubscribedMessage.test.ts index 78a772e98..dd4d84423 100644 --- a/lib/coding-agent/__tests__/onSubscribedMessage.test.ts +++ b/lib/coding-agent/__tests__/onSubscribedMessage.test.ts @@ -15,12 +15,14 @@ beforeEach(() => { }); /** + * Create Mock Bot. * + * @returns - Computed result. */ function createMockBot() { return { onSubscribedMessage: vi.fn(), - } as any; + } as unknown; } describe("registerOnSubscribedMessage", () => { diff --git a/lib/coding-agent/__tests__/resolvePRState.test.ts b/lib/coding-agent/__tests__/resolvePRState.test.ts index 308ef700b..11ceecdba 100644 --- a/lib/coding-agent/__tests__/resolvePRState.test.ts +++ b/lib/coding-agent/__tests__/resolvePRState.test.ts @@ -13,8 +13,10 @@ beforeEach(() => { }); /** + * Create Mock Thread. * - * @param state + * @param state - Value for state. + * @returns - Computed result. */ function createMockThread(state: unknown) { return { @@ -22,7 +24,7 @@ function createMockThread(state: unknown) { get state() { return Promise.resolve(state); }, - } as any; + } as unknown; } describe("resolvePRState", () => { diff --git a/lib/coding-agent/buildMergeTestToMainCard.ts b/lib/coding-agent/buildMergeTestToMainCard.ts index 258cc431d..5ecf0571a 100644 --- a/lib/coding-agent/buildMergeTestToMainCard.ts +++ b/lib/coding-agent/buildMergeTestToMainCard.ts @@ -1,9 +1,10 @@ import { Card, CardText, Actions, Button } from "chat"; /** - * Builds a Card with a "Merge test to main" button for a specific repo. + * Build Merge Test To Main Card. * - * @param repo - Full repo identifier (e.g. "recoupable/chat") + * @param repo - Value for repo. + * @returns - Computed result. */ export function buildMergeTestToMainCard(repo: string) { return Card({ diff --git a/lib/coding-agent/buildPRCard.ts b/lib/coding-agent/buildPRCard.ts index 61ca0a870..b5229c692 100644 --- a/lib/coding-agent/buildPRCard.ts +++ b/lib/coding-agent/buildPRCard.ts @@ -2,10 +2,11 @@ import { Card, CardText, Actions, Button, LinkButton } from "chat"; import type { CodingAgentPR } from "./types"; /** - * Builds a Card with PR review links and individual Merge buttons per PR. + * Build PRCard. * - * @param title - Card title (e.g. "PRs Created", "PRs Updated") - * @param prs - Array of PRs to build review links for + * @param title - Value for title. + * @param prs - Value for prs. + * @returns - Computed result. */ export function buildPRCard(title: string, prs: CodingAgentPR[]) { return Card({ diff --git a/lib/coding-agent/encodeGitHubThreadId.ts b/lib/coding-agent/encodeGitHubThreadId.ts index 1cfff2fe4..e12314ef2 100644 --- a/lib/coding-agent/encodeGitHubThreadId.ts +++ b/lib/coding-agent/encodeGitHubThreadId.ts @@ -1,11 +1,10 @@ import type { GitHubThreadId } from "@chat-adapter/github"; /** - * Encodes a GitHubThreadId into the Chat SDK thread ID string format. - * Mirrors GitHubAdapter.encodeThreadId without needing an adapter instance. + * Encode Git Hub Thread Id. * - * - PR-level: `github:{owner}/{repo}:{prNumber}` - * - Review comment: `github:{owner}/{repo}:{prNumber}:rc:{reviewCommentId}` + * @param thread - Value for thread. + * @returns - Computed result. */ export function encodeGitHubThreadId(thread: GitHubThreadId): string { const { owner, repo, prNumber, reviewCommentId } = thread; diff --git a/lib/coding-agent/extractPRComment.ts b/lib/coding-agent/extractPRComment.ts index d5e7d5679..be17d14e8 100644 --- a/lib/coding-agent/extractPRComment.ts +++ b/lib/coding-agent/extractPRComment.ts @@ -10,11 +10,11 @@ export interface PRComment { } /** - * Extracts GitHub thread ID, branch, and comment body from a GitHub webhook payload. - * Returns null if the event is not actionable. + * Extract PRComment. * - * @param event - The x-github-event header value - * @param payload - The parsed webhook payload + * @param event - Value for event. + * @param payload - Value for payload. + * @returns - Computed result. */ export function extractPRComment( event: string, diff --git a/lib/coding-agent/handleGitHubWebhook.ts b/lib/coding-agent/handleGitHubWebhook.ts index fd6e5fc93..f5785a0f8 100644 --- a/lib/coding-agent/handleGitHubWebhook.ts +++ b/lib/coding-agent/handleGitHubWebhook.ts @@ -10,11 +10,10 @@ import { postGitHubComment } from "./postGitHubComment"; const BOT_MENTION = "@recoup-coding-agent"; /** - * Handles incoming GitHub webhook requests for PR comment feedback. - * Supports both issue_comment and pull_request_review_comment events. - * Verifies signature, extracts PR context, and triggers update-pr when the bot is mentioned. + * Handle Git Hub Webhook. * - * @param request - The incoming webhook request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function handleGitHubWebhook(request: Request): Promise { const body = await request.text(); diff --git a/lib/coding-agent/handleMergeSuccess.ts b/lib/coding-agent/handleMergeSuccess.ts index f026f48d4..de37d396d 100644 --- a/lib/coding-agent/handleMergeSuccess.ts +++ b/lib/coding-agent/handleMergeSuccess.ts @@ -4,9 +4,10 @@ import { RECOUP_ORG_ID, SNAPSHOT_EXPIRY_MS } from "@/lib/const"; import type { CodingAgentThreadState } from "./types"; /** - * Handles post-merge cleanup after all PRs merged successfully. - * Deletes the shared PR state keys for all repos and persists the latest - * snapshot via upsertAccountSnapshot. + * Handle Merge Success. + * + * @param state - Value for state. + * @returns - Computed result. */ export async function handleMergeSuccess(state: CodingAgentThreadState): Promise { try { diff --git a/lib/coding-agent/handlePRCreated.ts b/lib/coding-agent/handlePRCreated.ts index 52bee2687..518e4ff4f 100644 --- a/lib/coding-agent/handlePRCreated.ts +++ b/lib/coding-agent/handlePRCreated.ts @@ -5,11 +5,11 @@ import type { CodingAgentCallbackBody } from "./validateCodingAgentCallback"; import type { CodingAgentThreadState } from "./types"; /** - * Handles the pr_created callback status. - * Writes to both thread state and shared PR state key. + * Handle PRCreated. * - * @param threadId - * @param body + * @param threadId - Value for threadId. + * @param body - Request payload. + * @returns - Computed result. */ export async function handlePRCreated(threadId: string, body: CodingAgentCallbackBody) { const thread = getThread(threadId); diff --git a/lib/coding-agent/handlers/handleFeedback.ts b/lib/coding-agent/handlers/handleFeedback.ts index 2290a0bf1..2d3c77f7e 100644 --- a/lib/coding-agent/handlers/handleFeedback.ts +++ b/lib/coding-agent/handlers/handleFeedback.ts @@ -5,12 +5,12 @@ import { setCodingAgentPRState } from "../prState"; import type { CodingAgentThreadState } from "../types"; /** - * Handles a message in a thread that already has state. - * Returns true if the message was handled (busy or feedback), false otherwise. + * Handle Feedback. * - * @param thread - The chat thread - * @param messageText - The user's message text - * @param state - The current thread state + * @param thread - Value for thread. + * @param messageText - Value for messageText. + * @param state - Value for state. + * @returns - Computed result. */ export async function handleFeedback( thread: Thread, diff --git a/lib/coding-agent/handlers/onMergeAction.ts b/lib/coding-agent/handlers/onMergeAction.ts index 887e35254..5f06e7a56 100644 --- a/lib/coding-agent/handlers/onMergeAction.ts +++ b/lib/coding-agent/handlers/onMergeAction.ts @@ -6,16 +6,10 @@ import { mergeGithubPR } from "../mergeGithubPR"; import { buildMergeTestToMainCard } from "../buildMergeTestToMainCard"; /** - * Registers individual per-PR merge button action handlers on the bot. - * Each button has an ID like "merge_pr:#" and squash-merges - * that single PR via the GitHub API. + * Register On Merge Action. * - * When a PR targeting the "test" branch is merged, a follow-up - * "Merge test to main" button is presented. - * - * Uses a prefix pattern so a single handler covers all merge_pr:* actions. - * - * @param bot + * @param bot - Value for bot. + * @returns - Computed result. */ export function registerOnMergeAction(bot: CodingAgentBot) { bot.onAction(async event => { diff --git a/lib/coding-agent/handlers/onMergeTestToMainAction.ts b/lib/coding-agent/handlers/onMergeTestToMainAction.ts index 57932baab..78b627dca 100644 --- a/lib/coding-agent/handlers/onMergeTestToMainAction.ts +++ b/lib/coding-agent/handlers/onMergeTestToMainAction.ts @@ -3,10 +3,10 @@ import { mergeGithubBranch } from "../mergeGithubBranch"; import { parseMergeTestToMainActionId } from "../parseMergeTestToMainActionId"; /** - * Registers the "Merge test to main" button action handler on the bot. - * Merges the test branch into main for the specified repo via the GitHub API. + * Register On Merge Test To Main Action. * - * @param bot + * @param bot - Value for bot. + * @returns - Computed result. */ export function registerOnMergeTestToMainAction(bot: CodingAgentBot) { bot.onAction(async event => { diff --git a/lib/coding-agent/handlers/onNewMention.ts b/lib/coding-agent/handlers/onNewMention.ts index bb399f02b..f362d4763 100644 --- a/lib/coding-agent/handlers/onNewMention.ts +++ b/lib/coding-agent/handlers/onNewMention.ts @@ -5,15 +5,10 @@ import { resolvePRState } from "../resolvePRState"; import { handleFeedback } from "./handleFeedback"; /** - * Registers the onNewMention handler on the bot. - * If the thread already has PRs (via thread state or shared PR state key), - * treats the mention as feedback and triggers the update-pr task. - * Otherwise, starts a new coding agent task. + * Register On New Mention. * - * For GitHub PR comments, message.meta may contain { repo, branch } to look up - * the shared PR state key when thread state is empty. - * - * @param bot + * @param bot - Value for bot. + * @returns - Computed result. */ export function registerOnNewMention(bot: CodingAgentBot) { bot.onNewMention(async (thread, message) => { diff --git a/lib/coding-agent/handlers/onSubscribedMessage.ts b/lib/coding-agent/handlers/onSubscribedMessage.ts index 7b769706b..e5631e38f 100644 --- a/lib/coding-agent/handlers/onSubscribedMessage.ts +++ b/lib/coding-agent/handlers/onSubscribedMessage.ts @@ -2,10 +2,10 @@ import type { CodingAgentBot } from "../bot"; import { handleFeedback } from "./handleFeedback"; /** - * Registers the onSubscribedMessage handler on the bot. - * Delegates to handleFeedback for busy/update-pr logic. + * Register On Subscribed Message. * - * @param bot + * @param bot - Value for bot. + * @returns - Computed result. */ export function registerOnSubscribedMessage(bot: CodingAgentBot) { bot.onSubscribedMessage(async (thread, message) => { diff --git a/lib/coding-agent/mergeGithubBranch.ts b/lib/coding-agent/mergeGithubBranch.ts index 74024a0f8..989d612e8 100644 --- a/lib/coding-agent/mergeGithubBranch.ts +++ b/lib/coding-agent/mergeGithubBranch.ts @@ -10,12 +10,13 @@ export interface MergeGithubBranchFailure { export type MergeGithubBranchResult = MergeGithubBranchSuccess | MergeGithubBranchFailure; /** - * Merges one branch into another via the GitHub API. + * Merge Github Branch. * - * @param repo - Full repo identifier (e.g. "recoupable/api") - * @param head - Branch to merge from (e.g. "test") - * @param base - Branch to merge into (e.g. "main") - * @param token - GitHub API token + * @param repo - Value for repo. + * @param head - Value for head. + * @param base - Value for base. + * @param token - Authentication token. + * @returns - Computed result. */ export async function mergeGithubBranch( repo: string, diff --git a/lib/coding-agent/mergeGithubPR.ts b/lib/coding-agent/mergeGithubPR.ts index cfe70fce2..e93077eb4 100644 --- a/lib/coding-agent/mergeGithubPR.ts +++ b/lib/coding-agent/mergeGithubPR.ts @@ -10,11 +10,12 @@ export interface MergeGithubPRFailure { export type MergeGithubPRResult = MergeGithubPRSuccess | MergeGithubPRFailure; /** - * Squash-merges a GitHub pull request via the API. + * Merge Github PR. * - * @param repo - Full repo identifier (e.g. "recoupable/api") - * @param prNumber - PR number to merge - * @param token - GitHub API token + * @param repo - Value for repo. + * @param prNumber - Value for prNumber. + * @param token - Authentication token. + * @returns - Computed result. */ export async function mergeGithubPR( repo: string, diff --git a/lib/coding-agent/parseMergeActionId.ts b/lib/coding-agent/parseMergeActionId.ts index 5118249eb..b18fc5e20 100644 --- a/lib/coding-agent/parseMergeActionId.ts +++ b/lib/coding-agent/parseMergeActionId.ts @@ -1,6 +1,8 @@ /** - * Parses a merge action ID like "merge_pr:recoupable/api#42" - * into { repo, number } or null if the format doesn't match. + * Parse Merge Action Id. + * + * @param actionId - Value for actionId. + * @returns - Computed result. */ export function parseMergeActionId(actionId: string) { const match = actionId.match(/^merge_pr:(.+)#(\d+)$/); diff --git a/lib/coding-agent/parseMergeTestToMainActionId.ts b/lib/coding-agent/parseMergeTestToMainActionId.ts index 1228615fa..382003133 100644 --- a/lib/coding-agent/parseMergeTestToMainActionId.ts +++ b/lib/coding-agent/parseMergeTestToMainActionId.ts @@ -1,6 +1,8 @@ /** - * Parses a merge_test_to_main action ID like "merge_test_to_main:recoupable/api" - * into the repo string, or null if the format doesn't match. + * Parse Merge Test To Main Action Id. + * + * @param actionId - Value for actionId. + * @returns - Computed result. */ export function parseMergeTestToMainActionId(actionId: string): string | null { const prefix = "merge_test_to_main:"; diff --git a/lib/coding-agent/prState/buildPRStateKey.ts b/lib/coding-agent/prState/buildPRStateKey.ts index 570a44ab5..d5845e490 100644 --- a/lib/coding-agent/prState/buildPRStateKey.ts +++ b/lib/coding-agent/prState/buildPRStateKey.ts @@ -1,10 +1,11 @@ const KEY_PREFIX = "coding-agent:pr"; /** - * Builds the Redis key for a given repo and branch. + * Build PRState Key. * - * @param repo - * @param branch + * @param repo - Value for repo. + * @param branch - Value for branch. + * @returns - Computed result. */ export function buildPRStateKey(repo: string, branch: string): string { return `${KEY_PREFIX}:${repo}:${branch}`; diff --git a/lib/coding-agent/prState/deleteCodingAgentPRState.ts b/lib/coding-agent/prState/deleteCodingAgentPRState.ts index 87cf0eef0..20bb0b9ed 100644 --- a/lib/coding-agent/prState/deleteCodingAgentPRState.ts +++ b/lib/coding-agent/prState/deleteCodingAgentPRState.ts @@ -2,10 +2,11 @@ import redis from "@/lib/redis/connection"; import { buildPRStateKey } from "./buildPRStateKey"; /** - * Deletes the shared PR state for a repo/branch from Redis. + * Delete Coding Agent PRState. * - * @param repo - * @param branch + * @param repo - Value for repo. + * @param branch - Value for branch. + * @returns - Computed result. */ export async function deleteCodingAgentPRState(repo: string, branch: string): Promise { const key = buildPRStateKey(repo, branch); diff --git a/lib/coding-agent/prState/getCodingAgentPRState.ts b/lib/coding-agent/prState/getCodingAgentPRState.ts index 69e68753d..0ec0bb011 100644 --- a/lib/coding-agent/prState/getCodingAgentPRState.ts +++ b/lib/coding-agent/prState/getCodingAgentPRState.ts @@ -3,10 +3,11 @@ import { buildPRStateKey } from "./buildPRStateKey"; import type { CodingAgentPRState } from "./types"; /** - * Gets the shared PR state for a repo/branch from Redis. + * Get Coding Agent PRState. * - * @param repo - * @param branch + * @param repo - Value for repo. + * @param branch - Value for branch. + * @returns - Computed result. */ export async function getCodingAgentPRState( repo: string, diff --git a/lib/coding-agent/prState/setCodingAgentPRState.ts b/lib/coding-agent/prState/setCodingAgentPRState.ts index f7ffaac6a..42acbb726 100644 --- a/lib/coding-agent/prState/setCodingAgentPRState.ts +++ b/lib/coding-agent/prState/setCodingAgentPRState.ts @@ -3,11 +3,12 @@ import { buildPRStateKey } from "./buildPRStateKey"; import type { CodingAgentPRState } from "./types"; /** - * Sets the shared PR state for a repo/branch in Redis. + * Set Coding Agent PRState. * - * @param repo - * @param branch - * @param state + * @param repo - Value for repo. + * @param branch - Value for branch. + * @param state - Value for state. + * @returns - Computed result. */ export async function setCodingAgentPRState( repo: string, diff --git a/lib/coding-agent/resolvePRState.ts b/lib/coding-agent/resolvePRState.ts index 78f8bb2d8..6611d6b97 100644 --- a/lib/coding-agent/resolvePRState.ts +++ b/lib/coding-agent/resolvePRState.ts @@ -1,5 +1,5 @@ import type { Thread } from "chat"; -import { getCodingAgentPRState, type CodingAgentPRState } from "./prState"; +import { getCodingAgentPRState } from "./prState"; import type { CodingAgentThreadState } from "./types"; export interface PRContext { diff --git a/lib/coding-agent/verifyGitHubWebhook.ts b/lib/coding-agent/verifyGitHubWebhook.ts index 330ebfd49..dca1b2bbe 100644 --- a/lib/coding-agent/verifyGitHubWebhook.ts +++ b/lib/coding-agent/verifyGitHubWebhook.ts @@ -1,12 +1,12 @@ import { timingSafeEqual } from "crypto"; /** - * Verifies a GitHub webhook signature using HMAC SHA-256. - * Uses constant-time comparison to prevent timing attacks. + * Verify Git Hub Webhook. * - * @param body - Raw request body string - * @param signature - The x-hub-signature-256 header value - * @param secret - The webhook secret + * @param body - Request payload. + * @param signature - Value for signature. + * @param secret - Value for secret. + * @returns - Computed result. */ export async function verifyGitHubWebhook( body: string, diff --git a/lib/coding-agent/whatsApp/isWhatsAppConfigured.ts b/lib/coding-agent/whatsApp/isWhatsAppConfigured.ts index 8d9702662..b841d9b0f 100644 --- a/lib/coding-agent/whatsApp/isWhatsAppConfigured.ts +++ b/lib/coding-agent/whatsApp/isWhatsAppConfigured.ts @@ -6,7 +6,9 @@ export const WHATSAPP_ENV_VARS = [ ] as const; /** - * Returns true when all WhatsApp environment variables are configured. + * Is Whats App Configured. + * + * @returns - Computed result. */ export function isWhatsAppConfigured(): boolean { return WHATSAPP_ENV_VARS.every(name => !!process.env[name]); diff --git a/lib/composio/client.ts b/lib/composio/client.ts index 055540af6..e4fa404e8 100644 --- a/lib/composio/client.ts +++ b/lib/composio/client.ts @@ -1,10 +1,5 @@ import { getComposioApiKey } from "./getComposioApiKey"; -/** - * Lazily imports and creates a Composio client. - * Uses dynamic imports to avoid bundler issues with @composio/core's - * use of createRequire(import.meta.url). - */ export const getComposioClient = async () => { const { Composio } = await import("@composio/core"); const { VercelProvider } = await import("@composio/vercel"); diff --git a/lib/composio/connectors/buildAuthConfigs.ts b/lib/composio/connectors/buildAuthConfigs.ts index 7bac8d276..860c13488 100644 --- a/lib/composio/connectors/buildAuthConfigs.ts +++ b/lib/composio/connectors/buildAuthConfigs.ts @@ -1,7 +1,7 @@ /** - * Build auth configs from environment variables. - * Must match the configs used during authorization so Composio - * can find connections created with custom OAuth credentials. + * Build Auth Configs. + * + * @returns - Computed result. */ export function buildAuthConfigs(): Record | undefined { const configs: Record = {}; diff --git a/lib/composio/connectors/isAllowedArtistConnector.ts b/lib/composio/connectors/isAllowedArtistConnector.ts index 9acfa63e3..cde7a5dc0 100644 --- a/lib/composio/connectors/isAllowedArtistConnector.ts +++ b/lib/composio/connectors/isAllowedArtistConnector.ts @@ -7,9 +7,10 @@ export const ALLOWED_ARTIST_CONNECTORS = ["tiktok", "instagram"] as const; export type AllowedArtistConnector = (typeof ALLOWED_ARTIST_CONNECTORS)[number]; /** - * Check if a connector slug is an allowed artist connector. + * Is Allowed Artist Connector. * - * @param slug + * @param slug - Value for slug. + * @returns - Computed result. */ export function isAllowedArtistConnector(slug: string): slug is AllowedArtistConnector { return (ALLOWED_ARTIST_CONNECTORS as readonly string[]).includes(slug); diff --git a/lib/composio/getCallbackUrl.ts b/lib/composio/getCallbackUrl.ts index 570c92516..3b1e48a15 100644 --- a/lib/composio/getCallbackUrl.ts +++ b/lib/composio/getCallbackUrl.ts @@ -15,11 +15,10 @@ interface CallbackOptions { } /** - * Build callback URL for OAuth redirects. + * Get Callback Url. * - * @param options.destination - Where to redirect: "chat" or "connectors" - * @param options.roomId - For chat destination, the room ID to return to - * @returns Full callback URL with success indicator + * @param options - Options for this operation. + * @returns - Computed result. */ export function getCallbackUrl(options: CallbackOptions): string { const baseUrl = getFrontendBaseUrl(); diff --git a/lib/composio/getFrontendBaseUrl.ts b/lib/composio/getFrontendBaseUrl.ts index 7a5dbe18e..2adef133a 100644 --- a/lib/composio/getFrontendBaseUrl.ts +++ b/lib/composio/getFrontendBaseUrl.ts @@ -1,7 +1,9 @@ const TEST_FRONTEND_URL = "https://test-recoup-chat.vercel.app"; /** - * Get the frontend base URL based on environment. + * Get Frontend Base Url. + * + * @returns - Computed result. */ export function getFrontendBaseUrl(): string { if (process.env.VERCEL_ENV === "production") { diff --git a/lib/composio/toolRouter/createToolRouterSession.ts b/lib/composio/toolRouter/createToolRouterSession.ts index deb86406f..32375dc29 100644 --- a/lib/composio/toolRouter/createToolRouterSession.ts +++ b/lib/composio/toolRouter/createToolRouterSession.ts @@ -9,18 +9,12 @@ import { getConnectors } from "../connectors/getConnectors"; const ENABLED_TOOLKITS = ["googlesheets", "googledrive", "googledocs", "tiktok"]; /** - * Create a Composio Tool Router session for an account. + * Create Tool Router Session. * - * This is the opinionated layer — it decides which connections the AI agent uses. - * When both the account and artist have the same toolkit connected, the account's - * connection is kept and the artist's is dropped to prevent tool collision - * (the AI wouldn't know which credentials to use). - * - * Artist connections only fill gaps where the account has no connection. - * - * @param accountId - Unique identifier for the account - * @param roomId - Optional chat room ID for OAuth redirect - * @param artistConnections - Optional mapping of toolkit slug to connected account ID for artist-specific connections + * @param accountId - Account identifier. + * @param roomId - Room identifier. + * @param artistConnections - Value for artistConnections. + * @returns - Computed result. */ export async function createToolRouterSession( accountId: string, diff --git a/lib/content/__tests__/validateCreateContentBody.test.ts b/lib/content/__tests__/validateCreateContentBody.test.ts index 658ef8d7c..289babbe5 100644 --- a/lib/content/__tests__/validateCreateContentBody.test.ts +++ b/lib/content/__tests__/validateCreateContentBody.test.ts @@ -21,8 +21,10 @@ vi.mock("@/lib/content/resolveArtistSlug", () => ({ })); /** + * Create Request. * - * @param body + * @param body - Request payload. + * @returns - Computed result. */ function createRequest(body: unknown): NextRequest { return new NextRequest("http://localhost/api/content/create", { diff --git a/lib/content/analyze/validateAnalyzeVideoBody.ts b/lib/content/analyze/validateAnalyzeVideoBody.ts index ee8d221b2..1cce89279 100644 --- a/lib/content/analyze/validateAnalyzeVideoBody.ts +++ b/lib/content/analyze/validateAnalyzeVideoBody.ts @@ -17,7 +17,10 @@ export type ValidatedAnalyzeVideoBody = { accountId: string } & z.infer< >; /** - * Validates auth and request body for POST /api/content/analyze. + * Validate Analyze Video Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateAnalyzeVideoBody( request: NextRequest, diff --git a/lib/content/caption/validateCreateCaptionBody.ts b/lib/content/caption/validateCreateCaptionBody.ts index 9eb2faf90..4d0724ad2 100644 --- a/lib/content/caption/validateCreateCaptionBody.ts +++ b/lib/content/caption/validateCreateCaptionBody.ts @@ -18,7 +18,10 @@ export type ValidatedCreateCaptionBody = { accountId: string } & z.infer< >; /** - * Validates auth and request body for POST /api/content/caption. + * Validate Create Caption Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateCreateCaptionBody( request: NextRequest, diff --git a/lib/content/createContentHandler.ts b/lib/content/createContentHandler.ts index 577e81327..093e070c0 100644 --- a/lib/content/createContentHandler.ts +++ b/lib/content/createContentHandler.ts @@ -7,10 +7,10 @@ import { getArtistContentReadiness } from "@/lib/content/getArtistContentReadine import { selectAccountSnapshots } from "@/lib/supabase/account_snapshots/selectAccountSnapshots"; /** - * Handler for POST /api/content/create. - * Always returns runIds array (KISS — one response shape for single and batch). + * Create Content Handler. * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function createContentHandler(request: NextRequest): Promise { const validated = await validateCreateContentBody(request); diff --git a/lib/content/edit/validateEditContentBody.ts b/lib/content/edit/validateEditContentBody.ts index b10406360..d0d5afb06 100644 --- a/lib/content/edit/validateEditContentBody.ts +++ b/lib/content/edit/validateEditContentBody.ts @@ -48,7 +48,10 @@ export const editBodySchema = z export type ValidatedEditContentBody = { accountId: string } & z.infer; /** - * Validates auth and request body for PATCH /api/content. + * Validate Edit Content Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateEditContentBody( request: NextRequest, diff --git a/lib/content/getArtistContentReadiness.ts b/lib/content/getArtistContentReadiness.ts index a902ce0f8..aa0d0cd7b 100644 --- a/lib/content/getArtistContentReadiness.ts +++ b/lib/content/getArtistContentReadiness.ts @@ -20,8 +20,13 @@ export interface ArtistContentReadiness { } /** - * Checks whether an artist has the expected files for content creation. - * Searches the main repo and org submodule repos. + * Get Artist Content Readiness. + * + * @param root0 - Input object. + * @param root0.accountId - Account identifier. + * @param root0.artistAccountId - Value for root0.artistAccountId. + * @param root0.artistSlug - Value for root0.artistSlug. + * @returns - Computed result. */ export async function getArtistContentReadiness({ accountId, diff --git a/lib/content/getArtistFileTree.ts b/lib/content/getArtistFileTree.ts index 908855a00..210d3f56c 100644 --- a/lib/content/getArtistFileTree.ts +++ b/lib/content/getArtistFileTree.ts @@ -2,8 +2,11 @@ import { getRepoFileTree, type FileTreeEntry } from "@/lib/github/getRepoFileTre import { getOrgRepoUrls } from "@/lib/github/getOrgRepoUrls"; /** - * Gets the file tree that contains the artist, checking the main repo - * first, then falling back to org submodule repos. + * Get Artist File Tree. + * + * @param githubRepo - Value for githubRepo. + * @param artistSlug - Value for artistSlug. + * @returns - Computed result. */ export async function getArtistFileTree( githubRepo: string, diff --git a/lib/content/getArtistRootPrefix.ts b/lib/content/getArtistRootPrefix.ts index 5a777abe9..b317719c7 100644 --- a/lib/content/getArtistRootPrefix.ts +++ b/lib/content/getArtistRootPrefix.ts @@ -1,3 +1,10 @@ +/** + * Get Artist Root Prefix. + * + * @param paths - Value for paths. + * @param artistSlug - Value for artistSlug. + * @returns - Computed result. + */ export function getArtistRootPrefix(paths: string[], artistSlug: string): string { const preferredPrefix = `artists/${artistSlug}/`; if (paths.some(path => path.startsWith(preferredPrefix))) { diff --git a/lib/content/getContentEstimateHandler.ts b/lib/content/getContentEstimateHandler.ts index 3d4d3a38d..9ee279395 100644 --- a/lib/content/getContentEstimateHandler.ts +++ b/lib/content/getContentEstimateHandler.ts @@ -7,9 +7,10 @@ const BASE_IMAGE_TO_VIDEO_COST = 0.82; const BASE_AUDIO_TO_VIDEO_COST = 0.95; /** - * Handler for GET /api/content/estimate. + * Get Content Estimate Handler. * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function getContentEstimateHandler(request: NextRequest): Promise { const validated = await validateGetContentEstimateQuery(request); diff --git a/lib/content/getContentTemplateDetailHandler.ts b/lib/content/getContentTemplateDetailHandler.ts index 6051b4c9b..49497046d 100644 --- a/lib/content/getContentTemplateDetailHandler.ts +++ b/lib/content/getContentTemplateDetailHandler.ts @@ -5,11 +5,12 @@ import { validateAuthContext } from "@/lib/auth/validateAuthContext"; import { loadTemplate } from "@/lib/content/templates"; /** - * Handler for GET /api/content/templates/{id}. + * Get Content Template Detail Handler. * - * @param request - Incoming API request. - * @param params - Route params containing the template id. - * @returns The full template object, or 404 if not found. + * @param request - Incoming HTTP request. + * @param root1 - Input object. + * @param root1.params - Dynamic route parameters. + * @returns - Computed result. */ export async function getContentTemplateDetailHandler( request: NextRequest, diff --git a/lib/content/getContentTemplatesHandler.ts b/lib/content/getContentTemplatesHandler.ts index 2bf6552dd..212c71297 100644 --- a/lib/content/getContentTemplatesHandler.ts +++ b/lib/content/getContentTemplatesHandler.ts @@ -5,9 +5,10 @@ import { validateAuthContext } from "@/lib/auth/validateAuthContext"; import { listTemplates } from "@/lib/content/templates"; /** - * Handler for GET /api/content/templates. + * Get Content Templates Handler. * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function getContentTemplatesHandler(request: NextRequest): Promise { const authResult = await validateAuthContext(request); diff --git a/lib/content/getContentValidateHandler.ts b/lib/content/getContentValidateHandler.ts index e0c758b83..8acd6806f 100644 --- a/lib/content/getContentValidateHandler.ts +++ b/lib/content/getContentValidateHandler.ts @@ -5,9 +5,10 @@ import { validateGetContentValidateQuery } from "@/lib/content/validateGetConten import { getArtistContentReadiness } from "@/lib/content/getArtistContentReadiness"; /** - * Handler for GET /api/content/validate. - * NOTE: Phase 1 returns structural readiness scaffolding. Deep filesystem checks - * are performed in the background task before spend-heavy steps. + * Get Content Validate Handler. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function getContentValidateHandler(request: NextRequest): Promise { const validated = await validateGetContentValidateQuery(request); @@ -22,7 +23,8 @@ export async function getContentValidateHandler(request: NextRequest): Promise; /** - * Validates auth and request body for POST /api/content/image. + * Validate Create Image Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateCreateImageBody( request: NextRequest, diff --git a/lib/content/isCompletedRun.ts b/lib/content/isCompletedRun.ts index 855ea0683..196e2ddb8 100644 --- a/lib/content/isCompletedRun.ts +++ b/lib/content/isCompletedRun.ts @@ -5,6 +5,12 @@ export type TriggerRunLike = { output?: unknown; }; +/** + * Is Completed Run. + * + * @param run - Value for run. + * @returns - Computed result. + */ export function isCompletedRun(run: TriggerRunLike): boolean { return run.status === "COMPLETED"; } diff --git a/lib/content/persistCreateContentRunVideo.ts b/lib/content/persistCreateContentRunVideo.ts index 25a77eed8..4d3124c1f 100644 --- a/lib/content/persistCreateContentRunVideo.ts +++ b/lib/content/persistCreateContentRunVideo.ts @@ -23,10 +23,10 @@ type CreateContentOutput = { }; /** - * Persists create-content task video output to Supabase storage + files table - * and returns the run with normalized output. + * Persist Create Content Run Video. * - * This keeps Supabase writes in API only. + * @param run - Value for run. + * @returns - Computed result. */ export async function persistCreateContentRunVideo(run: T): Promise { if (run.taskIdentifier !== CREATE_CONTENT_TASK_ID || !isCompletedRun(run)) { diff --git a/lib/content/templates/types.ts b/lib/content/templates/types.ts index f275b7363..fed221e5e 100644 --- a/lib/content/templates/types.ts +++ b/lib/content/templates/types.ts @@ -1,6 +1,6 @@ export interface TemplateEditOperation { - type: string; [key: string]: unknown; + type: string; } export interface Template { diff --git a/lib/content/transcribe/validateTranscribeAudioBody.ts b/lib/content/transcribe/validateTranscribeAudioBody.ts index df34a56c5..7c8b24991 100644 --- a/lib/content/transcribe/validateTranscribeAudioBody.ts +++ b/lib/content/transcribe/validateTranscribeAudioBody.ts @@ -18,7 +18,10 @@ export type ValidatedTranscribeAudioBody = { accountId: string } & z.infer< >; /** - * Validates auth and request body for POST /api/content/transcribe. + * Validate Transcribe Audio Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateTranscribeAudioBody( request: NextRequest, diff --git a/lib/content/upscale/validateUpscaleBody.ts b/lib/content/upscale/validateUpscaleBody.ts index 496ecf1d4..da5612b7b 100644 --- a/lib/content/upscale/validateUpscaleBody.ts +++ b/lib/content/upscale/validateUpscaleBody.ts @@ -15,7 +15,10 @@ export const createUpscaleBodySchema = z.object({ export type ValidatedUpscaleBody = { accountId: string } & z.infer; /** - * Validates auth and request body for POST /api/content/upscale. + * Validate Upscale Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateUpscaleBody( request: NextRequest, diff --git a/lib/content/validateCreateContentBody.ts b/lib/content/validateCreateContentBody.ts index 7e02a543c..7f39e4a6f 100644 --- a/lib/content/validateCreateContentBody.ts +++ b/lib/content/validateCreateContentBody.ts @@ -37,9 +37,10 @@ export type ValidatedCreateContentBody = { }; /** - * Validates auth and request body for POST /api/content/create. + * Validate Create Content Body. * - * @param request + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateCreateContentBody( request: NextRequest, diff --git a/lib/content/validateGetContentEstimateQuery.ts b/lib/content/validateGetContentEstimateQuery.ts index 5828e7cc2..e98dde850 100644 --- a/lib/content/validateGetContentEstimateQuery.ts +++ b/lib/content/validateGetContentEstimateQuery.ts @@ -14,7 +14,10 @@ export const getContentEstimateQuerySchema = z.object({ export type ValidatedGetContentEstimateQuery = z.infer; /** - * Validates auth and query params for GET /api/content/estimate. + * Validate Get Content Estimate Query. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateGetContentEstimateQuery( request: NextRequest, diff --git a/lib/content/validateGetContentValidateQuery.ts b/lib/content/validateGetContentValidateQuery.ts index c8084fa6b..703125050 100644 --- a/lib/content/validateGetContentValidateQuery.ts +++ b/lib/content/validateGetContentValidateQuery.ts @@ -11,8 +11,10 @@ export type ValidatedGetContentValidateQuery = { }; /** - * Validates auth and query params for GET /api/content/validate. - * Requires artist_account_id query parameter. + * Validate Get Content Validate Query. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateGetContentValidateQuery( request: NextRequest, diff --git a/lib/content/video/buildFalInput.ts b/lib/content/video/buildFalInput.ts index 8f5805f63..3bcc279ad 100644 --- a/lib/content/video/buildFalInput.ts +++ b/lib/content/video/buildFalInput.ts @@ -1,10 +1,19 @@ /** - * Maps user-facing fields to the fal input format for each video mode. - * Different fal models expect different field names for the same concept. + * Build Fal Input. * - * @param mode - The resolved video generation mode. - * @param v - Validated request body fields. - * @returns The fal input object with mode-specific field mappings. + * @param mode - Value for mode. + * @param v - Value for v. + * @param v.prompt - Value for v.prompt. + * @param v.negative_prompt - Value for v.negative_prompt. + * @param v.image_url - Value for v.image_url. + * @param v.end_image_url - Value for v.end_image_url. + * @param v.video_url - Value for v.video_url. + * @param v.audio_url - Value for v.audio_url. + * @param v.aspect_ratio - Value for v.aspect_ratio. + * @param v.duration - Value for v.duration. + * @param v.resolution - Value for v.resolution. + * @param v.generate_audio - Value for v.generate_audio. + * @returns - Computed result. */ export function buildFalInput( mode: string, diff --git a/lib/content/video/inferMode.ts b/lib/content/video/inferMode.ts index 3b25cbdc8..fed3ab71c 100644 --- a/lib/content/video/inferMode.ts +++ b/lib/content/video/inferMode.ts @@ -1,8 +1,12 @@ /** - * Infers the video generation mode from the inputs when the caller doesn't specify one. + * Infer Mode. * - * @param v - Object with optional media URL fields. - * @returns The inferred mode string. + * @param v - Value for v. + * @param v.audio_url - Value for v.audio_url. + * @param v.video_url - Value for v.video_url. + * @param v.image_url - Value for v.image_url. + * @param v.end_image_url - Value for v.end_image_url. + * @returns - Computed result. */ export function inferMode(v: { audio_url?: string; diff --git a/lib/content/video/validateCreateVideoBody.ts b/lib/content/video/validateCreateVideoBody.ts index f84603c87..0c39a1692 100644 --- a/lib/content/video/validateCreateVideoBody.ts +++ b/lib/content/video/validateCreateVideoBody.ts @@ -27,7 +27,10 @@ export type ValidatedCreateVideoBody = { accountId: string } & z.infer< >; /** - * Validates auth and request body for POST /api/content/video. + * Validate Create Video Body. + * + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function validateCreateVideoBody( request: NextRequest, diff --git a/lib/credits/__tests__/getCreditUsage.test.ts b/lib/credits/__tests__/getCreditUsage.test.ts index 8aa291909..ed567fc97 100644 --- a/lib/credits/__tests__/getCreditUsage.test.ts +++ b/lib/credits/__tests__/getCreditUsage.test.ts @@ -26,7 +26,7 @@ describe("getCreditUsage", () => { input: "0.00003", // $0.03 per 1K tokens output: "0.00006", // $0.06 per 1K tokens }, - } as any); + } as unknown); const usage = { promptTokens: 1000, @@ -59,7 +59,7 @@ describe("getCreditUsage", () => { input: "0.00003", output: "0.00006", }, - } as any); + } as unknown); const usage = { promptTokens: undefined as unknown as number, @@ -78,7 +78,7 @@ describe("getCreditUsage", () => { input: "0.00003", output: "0.00006", }, - } as any); + } as unknown); const usage = { promptTokens: 1000, @@ -94,7 +94,7 @@ describe("getCreditUsage", () => { mockGetModel.mockResolvedValue({ id: "gpt-4", // No pricing property - } as any); + } as unknown); const usage = { promptTokens: 1000, @@ -114,7 +114,7 @@ describe("getCreditUsage", () => { input: "0.00003", output: "0.00006", }, - } as any); + } as unknown); const usage = { promptTokens: 0, diff --git a/lib/credits/getCreditUsage.ts b/lib/credits/getCreditUsage.ts index 7cd29c9fc..b923fbf97 100644 --- a/lib/credits/getCreditUsage.ts +++ b/lib/credits/getCreditUsage.ts @@ -1,12 +1,11 @@ import { getModel } from "@/lib/ai/getModel"; import { LanguageModelUsage } from "ai"; -/** - * Calculates the total spend in USD for a given language model usage. - * @param usage - The language model usage data - * @param modelId - The ID of the model used - * @returns The total spend in USD or 0 if calculation fails - */ +type CompatibleLanguageModelUsage = LanguageModelUsage & { + promptTokens?: number; + completionTokens?: number; +}; + export const getCreditUsage = async ( usage: LanguageModelUsage, modelId: string, @@ -20,8 +19,9 @@ export const getCreditUsage = async ( // LanguageModelUsage uses inputTokens/outputTokens (SDK v3) // or promptTokens/completionTokens (SDK v2 compatibility) - const inputTokens = (usage as any).inputTokens ?? (usage as any).promptTokens; - const outputTokens = (usage as any).outputTokens ?? (usage as any).completionTokens; + const usageWithCompatibility = usage as CompatibleLanguageModelUsage; + const inputTokens = usage.inputTokens ?? usageWithCompatibility.promptTokens; + const outputTokens = usage.outputTokens ?? usageWithCompatibility.completionTokens; if (!inputTokens || !outputTokens) { console.error("No tokens found in usage"); diff --git a/lib/credits/handleChatCredits.ts b/lib/credits/handleChatCredits.ts index b0d884383..eb946331d 100644 --- a/lib/credits/handleChatCredits.ts +++ b/lib/credits/handleChatCredits.ts @@ -8,13 +8,6 @@ interface HandleChatCreditsParams { accountId?: string; } -/** - * Handles credit deduction after chat completion. - * Always deducts at least 1 credit when accountId is present (round up from usage cost). - * @param usage - The language model usage data - * @param model - The model ID used for the chat - * @param accountId - The account ID to deduct credits from (optional) - */ export const handleChatCredits = async ({ usage, model, diff --git a/lib/emails/inbound/__tests__/validateNewEmailMemory.test.ts b/lib/emails/inbound/__tests__/validateNewEmailMemory.test.ts index 17c164d41..58f4cdbd9 100644 --- a/lib/emails/inbound/__tests__/validateNewEmailMemory.test.ts +++ b/lib/emails/inbound/__tests__/validateNewEmailMemory.test.ts @@ -56,8 +56,10 @@ const MOCK_EMAIL_ID = "email-123"; const MOCK_MESSAGE_ID = "msg-456"; /** + * Create Mock Event. * - * @param overrides + * @param overrides - Optional override values. + * @returns - Computed result. */ function createMockEvent( overrides?: Partial, diff --git a/lib/emails/processAndSendEmail.ts b/lib/emails/processAndSendEmail.ts index 934939ca6..ef02601c9 100644 --- a/lib/emails/processAndSendEmail.ts +++ b/lib/emails/processAndSendEmail.ts @@ -29,11 +29,10 @@ export interface ProcessAndSendEmailError { export type ProcessAndSendEmailResult = ProcessAndSendEmailSuccess | ProcessAndSendEmailError; /** - * Shared email processing and sending logic used by both the - * POST /api/notifications handler and the send_email MCP tool. + * Process And Send Email. * - * Handles room lookup, footer generation, markdown-to-HTML conversion, - * and the Resend API call. + * @param input - Value for input. + * @returns - Computed result. */ export async function processAndSendEmail( input: ProcessAndSendEmailInput, diff --git a/lib/evals/callChatFunctions.ts b/lib/evals/callChatFunctions.ts index ef770a2b5..864edb152 100644 --- a/lib/evals/callChatFunctions.ts +++ b/lib/evals/callChatFunctions.ts @@ -2,11 +2,10 @@ import { callChatFunctionsWithResult } from "./callChatFunctionsWithResult"; import { extractTextFromResult } from "./extractTextFromResult"; /** - * Call the chat functions directly instead of making HTTP requests - * This function encapsulates the logic for calling the chat system - * and can be reused across different evaluations. + * Call Chat Functions. * - * @deprecated Use callChatFunctionsWithResult for access to tool calls + * @param input - Value for input. + * @returns - Computed result. */ export async function callChatFunctions(input: string): Promise { try { diff --git a/lib/evals/callChatFunctionsWithResult.ts b/lib/evals/callChatFunctionsWithResult.ts index a792248b3..6a0e290f3 100644 --- a/lib/evals/callChatFunctionsWithResult.ts +++ b/lib/evals/callChatFunctionsWithResult.ts @@ -4,10 +4,10 @@ import { setupChatRequest } from "@/lib/chat/setupChatRequest"; import { ChatRequestBody } from "@/lib/chat/validateChatRequest"; /** - * Call the chat functions and return the full result including tool calls from ALL steps. + * Call Chat Functions With Result. * - * Note: result.toolCalls only contains calls from the LAST step. When using multi-step - * tool chains, we need to collect toolCalls from result.steps to capture all tool usage. + * @param input - Value for input. + * @returns - Computed result. */ export async function callChatFunctionsWithResult(input: string) { const messages: UIMessage[] = [ diff --git a/lib/evals/createToolsCalledScorer.ts b/lib/evals/createToolsCalledScorer.ts index 1d838ee31..73f401586 100644 --- a/lib/evals/createToolsCalledScorer.ts +++ b/lib/evals/createToolsCalledScorer.ts @@ -1,9 +1,5 @@ import { ToolsCalled } from "./scorers/ToolsCalled"; -/** - * Creates a scorer that checks if required tools were called. - * Handles extracting output text and toolCalls from the task result. - */ export const createToolsCalledScorer = (requiredTools: string[], penalizedTools: string[] = []) => { return async (args: { output: unknown; expected?: string; input: string }) => { // Extract output text and toolCalls diff --git a/lib/evals/extractTextFromResult.ts b/lib/evals/extractTextFromResult.ts index fac24cf6c..8c52ac488 100644 --- a/lib/evals/extractTextFromResult.ts +++ b/lib/evals/extractTextFromResult.ts @@ -2,7 +2,10 @@ import { generateText } from "ai"; import { extractTextResultFromSteps } from "./extractTextResultFromSteps"; /** - * Extract text from a GenerateTextResult + * Extract Text From Result. + * + * @param result - Value for result. + * @returns - Computed result. */ export function extractTextFromResult(result: Awaited>): string { // Handle multi-step responses (when maxSteps > 1) diff --git a/lib/evals/extractTextResultFromSteps.ts b/lib/evals/extractTextResultFromSteps.ts index 44c0ae0d6..69dff9bb8 100644 --- a/lib/evals/extractTextResultFromSteps.ts +++ b/lib/evals/extractTextResultFromSteps.ts @@ -2,8 +2,10 @@ import { generateText } from "ai"; import type { TextPart } from "ai"; /** - * Extract text from multi-step GenerateTextResult - * Handles responses where maxSteps > 1 + * Extract Text Result From Steps. + * + * @param result - Value for result. + * @returns - Computed result. */ export function extractTextResultFromSteps( result: Awaited>, diff --git a/lib/evals/getCatalogSongsCountExpected.ts b/lib/evals/getCatalogSongsCountExpected.ts index 6f04e59ca..aa0d42b41 100644 --- a/lib/evals/getCatalogSongsCountExpected.ts +++ b/lib/evals/getCatalogSongsCountExpected.ts @@ -2,6 +2,11 @@ import { getCatalogs } from "@/lib/catalog/getCatalogs"; import { getCatalogSongs } from "@/lib/catalog/getCatalogSongs"; import { EVAL_ACCOUNT_ID } from "@/lib/consts"; +/** + * Get Catalog Songs Count Expected. + * + * @returns - Computed result. + */ async function getCatalogSongsCountExpected() { try { const catalogsData = await getCatalogs(EVAL_ACCOUNT_ID); diff --git a/lib/evals/getSpotifyFollowersExpected.ts b/lib/evals/getSpotifyFollowersExpected.ts index ef96e2487..169ea9bc1 100644 --- a/lib/evals/getSpotifyFollowersExpected.ts +++ b/lib/evals/getSpotifyFollowersExpected.ts @@ -1,5 +1,11 @@ import { getSpotifyFollowers } from "@/lib/spotify/getSpotifyFollowers"; +/** + * Get Spotify Followers Expected. + * + * @param artist - Value for artist. + * @returns - Computed result. + */ async function getSpotifyFollowersExpected(artist: string) { try { const followerCount = await getSpotifyFollowers(artist); diff --git a/lib/evals/scorers/CatalogAvailability.ts b/lib/evals/scorers/CatalogAvailability.ts index f4829ea41..109b40a1d 100644 --- a/lib/evals/scorers/CatalogAvailability.ts +++ b/lib/evals/scorers/CatalogAvailability.ts @@ -3,9 +3,6 @@ import { generateObject } from "ai"; import { getCatalogDataAsCSV } from "@/lib/catalog/getCatalogDataAsCSV"; import { z } from "zod"; -/** - * Custom scorer that uses AI to check if recommended songs are actually in the catalog - */ export const CatalogAvailability = async ({ output, }: { diff --git a/lib/evals/scorers/QuestionAnswered.ts b/lib/evals/scorers/QuestionAnswered.ts index abe0222cb..a07e3ceca 100644 --- a/lib/evals/scorers/QuestionAnswered.ts +++ b/lib/evals/scorers/QuestionAnswered.ts @@ -2,10 +2,6 @@ import { DEFAULT_MODEL } from "@/lib/consts"; import { generateObject } from "ai"; import { z } from "zod"; -/** - * Custom scorer that checks if the AI actually answered the customer's question - * with a specific answer, or if it deflected/explained why it couldn't answer - */ export const QuestionAnswered = async ({ output, expected, diff --git a/lib/evals/scorers/ToolsCalled.ts b/lib/evals/scorers/ToolsCalled.ts index 2d901ec34..343d12558 100644 --- a/lib/evals/scorers/ToolsCalled.ts +++ b/lib/evals/scorers/ToolsCalled.ts @@ -1,6 +1,3 @@ -/** - * Generic scorer that checks if specific tools were called - */ export const ToolsCalled = async ({ toolCalls, requiredTools = [], diff --git a/lib/flamingo/__tests__/getFlamingoPresetsHandler.test.ts b/lib/flamingo/__tests__/getFlamingoPresetsHandler.test.ts index 19109b2d6..cdb98347b 100644 --- a/lib/flamingo/__tests__/getFlamingoPresetsHandler.test.ts +++ b/lib/flamingo/__tests__/getFlamingoPresetsHandler.test.ts @@ -17,6 +17,11 @@ vi.mock("../presets", () => ({ getPresetSummaries: vi.fn(), })); +/** + * Create Mock Request. + * + * @returns - Computed result. + */ function createMockRequest(): NextRequest { return { headers: new Headers({ "x-api-key": "test-key" }), diff --git a/lib/flamingo/getFlamingoPresetsHandler.ts b/lib/flamingo/getFlamingoPresetsHandler.ts index e35b58999..32602120d 100644 --- a/lib/flamingo/getFlamingoPresetsHandler.ts +++ b/lib/flamingo/getFlamingoPresetsHandler.ts @@ -5,12 +5,10 @@ import { getPresetSummaries } from "@/lib/flamingo/presets"; import { validateAuthContext } from "@/lib/auth/validateAuthContext"; /** - * Handler for GET /api/songs/analyze/presets. + * Get Flamingo Presets Handler. * - * Returns a list of all available analysis presets. - * Requires authentication via x-api-key header or Authorization bearer token. - * - * @returns A NextResponse with the list of available presets. + * @param request - Incoming HTTP request. + * @returns - Computed result. */ export async function getFlamingoPresetsHandler(request: NextRequest): Promise { const authResult = await validateAuthContext(request); diff --git a/lib/flamingo/postFlamingoGenerateHandler.ts b/lib/flamingo/postFlamingoGenerateHandler.ts index a971a3612..45ad37da5 100644 --- a/lib/flamingo/postFlamingoGenerateHandler.ts +++ b/lib/flamingo/postFlamingoGenerateHandler.ts @@ -57,7 +57,8 @@ export async function postFlamingoGenerateHandler(request: NextRequest): Promise } // 4. Return flat response - const { type: _, ...data } = result; + const data = { ...result }; + delete data.type; return NextResponse.json( { status: "success", ...data }, { status: 200, headers: getCorsHeaders() }, diff --git a/lib/github/__tests__/createOrUpdateFileContent.test.ts b/lib/github/__tests__/createOrUpdateFileContent.test.ts index 8e2a19a15..f8fee1a1a 100644 --- a/lib/github/__tests__/createOrUpdateFileContent.test.ts +++ b/lib/github/__tests__/createOrUpdateFileContent.test.ts @@ -1,12 +1,12 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { createOrUpdateFileContent } from "../createOrUpdateFileContent"; +import { parseGitHubRepoUrl } from "../parseGitHubRepoUrl"; + vi.mock("../parseGitHubRepoUrl", () => ({ parseGitHubRepoUrl: vi.fn(), })); -import { parseGitHubRepoUrl } from "../parseGitHubRepoUrl"; - const mockFetch = vi.fn(); global.fetch = mockFetch; diff --git a/lib/github/__tests__/expandSubmoduleEntries.test.ts b/lib/github/__tests__/expandSubmoduleEntries.test.ts index aa7fdfb8a..6703f9a93 100644 --- a/lib/github/__tests__/expandSubmoduleEntries.test.ts +++ b/lib/github/__tests__/expandSubmoduleEntries.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; import { expandSubmoduleEntries } from "../expandSubmoduleEntries"; import { getRepoGitModules } from "../getRepoGitModules"; import { getRepoFileTree } from "../getRepoFileTree"; diff --git a/lib/github/expandSubmoduleEntries.ts b/lib/github/expandSubmoduleEntries.ts index 9531bee1a..5fcf6f14a 100644 --- a/lib/github/expandSubmoduleEntries.ts +++ b/lib/github/expandSubmoduleEntries.ts @@ -7,14 +7,16 @@ interface SubmoduleRef { } /** - * Expands git submodule references into full directory trees. - * Resolves submodule URLs from .gitmodules, fetches each submodule's tree, - * and merges the results into the regular entries with correct path prefixes. + * Expand Submodule Entries. * - * @param regularEntries - Non-submodule file tree entries - * @param submoduleEntries - Submodule references (type "commit" from GitHub Trees API) - * @param repo - Repository context for fetching .gitmodules - * @returns Combined file tree entries with submodules expanded as directories + * @param root0 - Input object. + * @param root0.regularEntries - Value for root0.regularEntries. + * @param root0.submoduleEntries - Value for root0.submoduleEntries. + * @param root0.repo - Value for root0.repo. + * @param root0.repo.owner - Value for root0.repo.owner. + * @param root0.repo.repo - Value for root0.repo.repo. + * @param root0.repo.branch - Value for root0.repo.branch. + * @returns - Computed result. */ export async function expandSubmoduleEntries({ regularEntries, diff --git a/lib/github/getRepoGitModules.ts b/lib/github/getRepoGitModules.ts index caa0304e3..ab1671623 100644 --- a/lib/github/getRepoGitModules.ts +++ b/lib/github/getRepoGitModules.ts @@ -1,13 +1,13 @@ import { parseGitModules, type SubmoduleEntry } from "./parseGitModules"; /** - * Fetches and parses .gitmodules from a GitHub repository. - * Uses the GitHub Contents API (works for both public and private repos). + * Get Repo Git Modules. * - * @param owner - The GitHub repository owner - * @param repo - The GitHub repository name - * @param branch - The branch to fetch from - * @returns Array of submodule entries, or null if .gitmodules doesn't exist or fetch fails + * @param root0 - Input object. + * @param root0.owner - Value for root0.owner. + * @param root0.repo - Value for root0.repo. + * @param root0.branch - Value for root0.branch. + * @returns - Computed result. */ export async function getRepoGitModules({ owner, diff --git a/lib/github/resolveSubmodulePath.ts b/lib/github/resolveSubmodulePath.ts index 7c3f60edd..881bea44d 100644 --- a/lib/github/resolveSubmodulePath.ts +++ b/lib/github/resolveSubmodulePath.ts @@ -2,13 +2,12 @@ import { parseGitHubRepoUrl } from "./parseGitHubRepoUrl"; import { getRepoGitModules } from "./getRepoGitModules"; /** - * Resolves a file path that may be inside a git submodule. - * If the path falls within a submodule, returns the submodule's repo URL - * and the relative path within it. Otherwise returns the original values. + * Resolve Submodule Path. * - * @param githubRepo - The parent GitHub repository URL - * @param path - The file path to resolve - * @returns The resolved repo URL and path + * @param root0 - Input object. + * @param root0.githubRepo - Value for root0.githubRepo. + * @param root0.path - Value for root0.path. + * @returns - Computed result. */ export async function resolveSubmodulePath({ githubRepo, diff --git a/lib/mcp/__tests__/getMcpTools.test.ts b/lib/mcp/__tests__/getMcpTools.test.ts index 860c575ef..5d2709b9a 100644 --- a/lib/mcp/__tests__/getMcpTools.test.ts +++ b/lib/mcp/__tests__/getMcpTools.test.ts @@ -24,7 +24,7 @@ describe("getMcpTools", () => { mockCreateMCPClient.mockResolvedValue({ tools: vi.fn().mockResolvedValue(mockTools), - } as any); + } as unknown); }); it("creates MCP client with HTTP transport config", async () => { diff --git a/lib/mcp/resolveAccountId.ts b/lib/mcp/resolveAccountId.ts index 03d1d0d8a..c7ef147d3 100644 --- a/lib/mcp/resolveAccountId.ts +++ b/lib/mcp/resolveAccountId.ts @@ -12,11 +12,12 @@ export interface ResolveAccountIdResult { } /** - * Resolves the accountId from MCP auth info or an override parameter. - * Validates access when an org API key attempts to use an account_id override. + * Resolve Account Id. * - * @param params - The auth info and optional account_id override. - * @returns The resolved accountId or an error message. + * @param root0 - Input object. + * @param root0.authInfo - Value for root0.authInfo. + * @param root0.accountIdOverride - Value for root0.accountIdOverride. + * @returns - Computed result. */ export async function resolveAccountId({ authInfo, diff --git a/lib/mcp/tools/artists/__tests__/registerCreateNewArtistTool.test.ts b/lib/mcp/tools/artists/__tests__/registerCreateNewArtistTool.test.ts index 47e912afe..b716ff925 100644 --- a/lib/mcp/tools/artists/__tests__/registerCreateNewArtistTool.test.ts +++ b/lib/mcp/tools/artists/__tests__/registerCreateNewArtistTool.test.ts @@ -24,11 +24,12 @@ vi.mock("@/lib/organizations/canAccessAccount", () => ({ type ServerRequestHandlerExtra = RequestHandlerExtra; /** - * Creates a mock extra object with optional authInfo. + * Create Mock Extra. * - * @param authInfo - * @param authInfo.accountId - * @param authInfo.orgId + * @param authInfo - Value for authInfo. + * @param authInfo.accountId - Account identifier. + * @param authInfo.orgId - Organization identifier. + * @returns - Computed result. */ function createMockExtra(authInfo?: { accountId?: string; diff --git a/lib/mcp/tools/flamingo/registerAnalyzeMusicTool.ts b/lib/mcp/tools/flamingo/registerAnalyzeMusicTool.ts index 70ce56efd..1912b84b7 100644 --- a/lib/mcp/tools/flamingo/registerAnalyzeMusicTool.ts +++ b/lib/mcp/tools/flamingo/registerAnalyzeMusicTool.ts @@ -58,7 +58,8 @@ export function registerAnalyzeMusicTool(server: McpServer): void { return getToolResultError(result.error); } - const { type: _, ...data } = result; + const data = { ...result }; + delete data.type; return getToolResultSuccess(data); }, ); diff --git a/lib/mcp/tools/pulse/__tests__/registerGetPulsesTool.test.ts b/lib/mcp/tools/pulse/__tests__/registerGetPulsesTool.test.ts index a0c80c8a9..a3e301630 100644 --- a/lib/mcp/tools/pulse/__tests__/registerGetPulsesTool.test.ts +++ b/lib/mcp/tools/pulse/__tests__/registerGetPulsesTool.test.ts @@ -18,10 +18,11 @@ vi.mock("@/lib/organizations/canAccessAccount", () => ({ type ServerRequestHandlerExtra = RequestHandlerExtra; /** - * Creates a mock extra object with optional authInfo. + * Create Mock Extra. * - * @param authInfo - * @param authInfo.accountId + * @param authInfo - Value for authInfo. + * @param authInfo.accountId - Account identifier. + * @returns - Computed result. */ function createMockExtra(authInfo?: { accountId?: string }): ServerRequestHandlerExtra { return { diff --git a/lib/mcp/tools/pulse/__tests__/registerUpdatePulseTool.test.ts b/lib/mcp/tools/pulse/__tests__/registerUpdatePulseTool.test.ts index 151b18d78..b631f4196 100644 --- a/lib/mcp/tools/pulse/__tests__/registerUpdatePulseTool.test.ts +++ b/lib/mcp/tools/pulse/__tests__/registerUpdatePulseTool.test.ts @@ -18,11 +18,12 @@ vi.mock("@/lib/organizations/canAccessAccount", () => ({ type ServerRequestHandlerExtra = RequestHandlerExtra; /** - * Creates a mock extra object with optional authInfo. + * Create Mock Extra. * - * @param authInfo - * @param authInfo.accountId - * @param authInfo.orgId + * @param authInfo - Value for authInfo. + * @param authInfo.accountId - Account identifier. + * @param authInfo.orgId - Organization identifier. + * @returns - Computed result. */ function createMockExtra(authInfo?: { accountId?: string; diff --git a/lib/mcp/tools/sandbox/__tests__/registerPromptSandboxTool.test.ts b/lib/mcp/tools/sandbox/__tests__/registerPromptSandboxTool.test.ts index 054b08073..716724b8d 100644 --- a/lib/mcp/tools/sandbox/__tests__/registerPromptSandboxTool.test.ts +++ b/lib/mcp/tools/sandbox/__tests__/registerPromptSandboxTool.test.ts @@ -19,11 +19,12 @@ vi.mock("@/lib/mcp/resolveAccountId", () => ({ type ServerRequestHandlerExtra = RequestHandlerExtra; /** - * Creates a mock extra object with optional authInfo. + * Create Mock Extra. * - * @param authInfo - * @param authInfo.accountId - * @param authInfo.orgId + * @param authInfo - Value for authInfo. + * @param authInfo.accountId - Account identifier. + * @param authInfo.orgId - Organization identifier. + * @returns - Computed result. */ function createMockExtra(authInfo?: { accountId?: string; diff --git a/lib/mcp/tools/tasks/__tests__/registerGetTaskRunStatusTool.test.ts b/lib/mcp/tools/tasks/__tests__/registerGetTaskRunStatusTool.test.ts index f98472657..4e92c1abb 100644 --- a/lib/mcp/tools/tasks/__tests__/registerGetTaskRunStatusTool.test.ts +++ b/lib/mcp/tools/tasks/__tests__/registerGetTaskRunStatusTool.test.ts @@ -19,11 +19,12 @@ vi.mock("@/lib/mcp/resolveAccountId", () => ({ type ServerRequestHandlerExtra = RequestHandlerExtra; /** - * Creates a mock extra object with optional authInfo. + * Create Mock Extra. * - * @param authInfo - * @param authInfo.accountId - * @param authInfo.orgId + * @param authInfo - Value for authInfo. + * @param authInfo.accountId - Account identifier. + * @param authInfo.orgId - Organization identifier. + * @returns - Computed result. */ function createMockExtra(authInfo?: { accountId?: string; diff --git a/lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts b/lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts index 4942fdfb4..2cd9eee78 100644 --- a/lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts +++ b/lib/mcp/tools/transcribe/registerTranscribeAudioTool.ts @@ -15,6 +15,12 @@ const transcribeAudioSchema = z.object({ type TranscribeAudioArgs = z.infer; +/** + * Register Transcribe Audio Tool. + * + * @param server - Value for server. + * @returns - Computed result. + */ export function registerTranscribeAudioTool(server: McpServer): void { server.registerTool( "transcribe_audio", diff --git a/lib/messages/__tests__/convertToUiMessages.test.ts b/lib/messages/__tests__/convertToUiMessages.test.ts index a54104306..35a1c6f12 100644 --- a/lib/messages/__tests__/convertToUiMessages.test.ts +++ b/lib/messages/__tests__/convertToUiMessages.test.ts @@ -144,7 +144,7 @@ describe("convertToUiMessages", () => { }, ]; - const result = convertToUiMessages(messages as any); + const result = convertToUiMessages(messages as unknown); expect(result[0].parts[0].text).toBe("Hello world!"); }); diff --git a/lib/messages/__tests__/getTextContent.test.ts b/lib/messages/__tests__/getTextContent.test.ts index 1822bb4a3..310a29484 100644 --- a/lib/messages/__tests__/getTextContent.test.ts +++ b/lib/messages/__tests__/getTextContent.test.ts @@ -31,7 +31,7 @@ describe("getTextContent", () => { { type: "text" as const, text: "Hello" }, { type: "image" as const, image: "data:image/png;base64,..." }, { type: "text" as const, text: " world" }, - ] as any; + ] as unknown; expect(getTextContent(content)).toBe("Hello world"); }); @@ -40,7 +40,7 @@ describe("getTextContent", () => { }); it("returns empty string when no text parts exist", () => { - const content = [{ type: "image" as const, image: "data:image/png;base64,..." }] as any; + const content = [{ type: "image" as const, image: "data:image/png;base64,..." }] as unknown; expect(getTextContent(content)).toBe(""); }); }); diff --git a/lib/notifications/__tests__/createNotificationHandler.test.ts b/lib/notifications/__tests__/createNotificationHandler.test.ts index ca7fb677f..a0735dfe9 100644 --- a/lib/notifications/__tests__/createNotificationHandler.test.ts +++ b/lib/notifications/__tests__/createNotificationHandler.test.ts @@ -26,6 +26,12 @@ vi.mock("@/lib/networking/safeParseJson", () => ({ safeParseJson: vi.fn(async (req: Request) => req.json()), })); +/** + * Create Request. + * + * @param body - Request payload. + * @returns - Computed result. + */ function createRequest(body: unknown): NextRequest { return new NextRequest("https://recoup-api.vercel.app/api/notifications", { method: "POST", diff --git a/lib/notifications/__tests__/validateCreateNotificationBody.test.ts b/lib/notifications/__tests__/validateCreateNotificationBody.test.ts index 10390b15d..76e98ed38 100644 --- a/lib/notifications/__tests__/validateCreateNotificationBody.test.ts +++ b/lib/notifications/__tests__/validateCreateNotificationBody.test.ts @@ -16,6 +16,13 @@ vi.mock("@/lib/networking/safeParseJson", () => ({ safeParseJson: vi.fn(async (req: Request) => req.json()), })); +/** + * Create Request. + * + * @param body - Request payload. + * @param headers - Headers for the request. + * @returns - Computed result. + */ function createRequest(body: unknown, headers: Record = {}): NextRequest { const defaultHeaders: Record = { "Content-Type": "application/json" }; return new NextRequest("http://localhost/api/notifications", { diff --git a/lib/prompts/__tests__/getSystemPrompt.test.ts b/lib/prompts/__tests__/getSystemPrompt.test.ts index 942608af1..d772a3c6d 100644 --- a/lib/prompts/__tests__/getSystemPrompt.test.ts +++ b/lib/prompts/__tests__/getSystemPrompt.test.ts @@ -91,7 +91,7 @@ describe("getSystemPrompt", () => { id: "acc-1", name: "John Doe", email: "john@example.com", - } as any, + } as unknown, }); expect(result).toContain("-----CURRENT USER CONTEXT-----"); expect(result).toContain("Name: John Doe"); @@ -103,7 +103,7 @@ describe("getSystemPrompt", () => { accountId: "acc-1", accountWithDetails: { id: "acc-1", - } as any, + } as unknown, }); expect(result).toContain("Name: Not provided"); }); @@ -117,7 +117,7 @@ describe("getSystemPrompt", () => { role_type: "Manager", company_name: "Warner Music", organization: "Warner Records", - } as any, + } as unknown, }); expect(result).toContain("Professional Context:"); expect(result).toContain("Job Title: Music Manager"); @@ -132,7 +132,7 @@ describe("getSystemPrompt", () => { accountWithDetails: { id: "acc-1", name: "John", - } as any, + } as unknown, }); expect(result).not.toContain("Professional Context:"); }); @@ -143,7 +143,7 @@ describe("getSystemPrompt", () => { accountWithDetails: { id: "acc-1", instruction: "Always respond in formal English", - } as any, + } as unknown, }); expect(result).toContain("User's Custom Instructions & Preferences:"); expect(result).toContain("Always respond in formal English"); @@ -152,7 +152,7 @@ describe("getSystemPrompt", () => { it("includes end marker for user context", () => { const result = getSystemPrompt({ accountId: "acc-1", - accountWithDetails: { id: "acc-1" } as any, + accountWithDetails: { id: "acc-1" } as unknown, }); expect(result).toContain("-----END USER CONTEXT-----"); }); @@ -164,7 +164,7 @@ describe("getSystemPrompt", () => { accountWithDetails: { id: "acc-1", email: "details@example.com", - } as any, + } as unknown, }); expect(result).toContain("Email: details@example.com"); }); @@ -175,7 +175,7 @@ describe("getSystemPrompt", () => { email: "fallback@example.com", accountWithDetails: { id: "acc-1", - } as any, + } as unknown, }); expect(result).toContain("Email: fallback@example.com"); }); @@ -233,7 +233,7 @@ describe("getSystemPrompt", () => { it("places user context before artist context", () => { const result = getSystemPrompt({ accountId: "acc-1", - accountWithDetails: { id: "acc-1", name: "User" } as any, + accountWithDetails: { id: "acc-1", name: "User" } as unknown, artistInstruction: "Artist instructions", }); diff --git a/lib/prompts/getSystemPrompt.ts b/lib/prompts/getSystemPrompt.ts index 549646701..6525e22d2 100644 --- a/lib/prompts/getSystemPrompt.ts +++ b/lib/prompts/getSystemPrompt.ts @@ -2,18 +2,19 @@ import { SYSTEM_PROMPT } from "@/lib/chat/const"; import { AccountWithDetails } from "@/lib/supabase/accounts/getAccountWithDetails"; /** - * Generates a system prompt for the chat + * Get System Prompt. * - * @param params - The parameters for the system prompt - * @param params.roomId - The ID of the room - * @param params.artistId - The ID of the artist - * @param params.accountId - The ID of the account - * @param params.email - The email of the account - * @param params.knowledgeBaseText - The knowledge base text - * @param params.artistInstruction - The artist instruction - * @param params.conversationName - The name of the conversation - * @param params.accountWithDetails - The account with details - * @returns The system prompt + * @param root0 - Input object. + * @param root0.roomId - Room identifier. + * @param root0.artistId - Artist identifier. + * @param root0.accountId - Account identifier. + * @param root0.orgId - Organization identifier. + * @param root0.email - Email address. + * @param root0.knowledgeBaseText - Value for root0.knowledgeBaseText. + * @param root0.artistInstruction - Value for root0.artistInstruction. + * @param root0.conversationName - Value for root0.conversationName. + * @param root0.accountWithDetails - Value for root0.accountWithDetails. + * @returns - Computed result. */ export function getSystemPrompt({ roomId, diff --git a/lib/sandbox/__tests__/deleteSandboxHandler.test.ts b/lib/sandbox/__tests__/deleteSandboxHandler.test.ts index 4a84eebcb..780428505 100644 --- a/lib/sandbox/__tests__/deleteSandboxHandler.test.ts +++ b/lib/sandbox/__tests__/deleteSandboxHandler.test.ts @@ -28,7 +28,9 @@ vi.mock("@/lib/github/deleteAccountGithubRepos", () => ({ })); /** + * Create Mock Request. * + * @returns - Computed result. */ function createMockRequest(): Request { return new Request("https://example.com/api/sandboxes", { diff --git a/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts b/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts index 9c5f2fd10..e6307b99d 100644 --- a/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts +++ b/lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts @@ -133,7 +133,6 @@ describe("postSandboxesFilesHandler", () => { const result = await postSandboxesFilesHandler(mockRequest); const body = await result.json(); - expect(result.status).toBe(500); expect(body.error).toContain("All uploads failed"); // Blobs are always cleaned up, even on failure, to allow retries @@ -205,8 +204,6 @@ describe("postSandboxesFilesHandler", () => { }); const result = await postSandboxesFilesHandler(mockRequest); - const body = await result.json(); - expect(result.status).toBe(500); // Blobs are always cleaned up to allow retries expect(del).toHaveBeenCalledWith("https://blob.example.com/f.txt"); diff --git a/lib/sandbox/__tests__/validateDeleteSandboxBody.test.ts b/lib/sandbox/__tests__/validateDeleteSandboxBody.test.ts index f309950fa..142f298e6 100644 --- a/lib/sandbox/__tests__/validateDeleteSandboxBody.test.ts +++ b/lib/sandbox/__tests__/validateDeleteSandboxBody.test.ts @@ -18,7 +18,9 @@ vi.mock("@/lib/auth/validateAuthContext", () => ({ })); /** + * Create Mock Request. * + * @returns - Computed result. */ function createMockRequest(): Request { return new Request("https://example.com/api/sandboxes", { diff --git a/lib/slack/downloadSlackFile.ts b/lib/slack/downloadSlackFile.ts index dbc0ee27f..e1c9bd03d 100644 --- a/lib/slack/downloadSlackFile.ts +++ b/lib/slack/downloadSlackFile.ts @@ -1,9 +1,9 @@ /** - * Downloads a file from Slack using the files.info API to get - * url_private_download, then fetches the actual file content. + * Download Slack File. * - * @param fileId - * @param token + * @param fileId - Value for fileId. + * @param token - Authentication token. + * @returns - Computed result. */ export async function downloadSlackFile(fileId: string, token: string): Promise { const infoResponse = await fetch(`https://slack.com/api/files.info?file=${fileId}`, { diff --git a/lib/slack/extractSlackFileId.ts b/lib/slack/extractSlackFileId.ts index 0c840d988..fad9f7d60 100644 --- a/lib/slack/extractSlackFileId.ts +++ b/lib/slack/extractSlackFileId.ts @@ -1,8 +1,8 @@ /** - * Extracts the Slack file ID (e.g. F0APMKTKG9M) from a Slack file URL. - * URL format: files-tmb/TEAMID-FILEID-HASH/name or files-pri/TEAMID-FILEID/name + * Extract Slack File Id. * - * @param url + * @param url - URL to process. + * @returns - Computed result. */ export function extractSlackFileId(url: string): string | null { try { diff --git a/lib/slack/getBotChannels.ts b/lib/slack/getBotChannels.ts index 01fb47ff3..27149e67f 100644 --- a/lib/slack/getBotChannels.ts +++ b/lib/slack/getBotChannels.ts @@ -8,7 +8,10 @@ interface ConversationsListResponse { } /** - * Returns all channels the bot is a member of, paginating through all results. + * Get Bot Channels. + * + * @param token - Authentication token. + * @returns - Computed result. */ export async function getBotChannels(token: string): Promise> { const channels: Array<{ id: string; name: string }> = []; diff --git a/lib/slack/getBotUserId.ts b/lib/slack/getBotUserId.ts index 1c3e0924e..d59206d17 100644 --- a/lib/slack/getBotUserId.ts +++ b/lib/slack/getBotUserId.ts @@ -7,7 +7,10 @@ interface AuthTestResponse { } /** - * Returns the authenticated bot's Slack user ID via auth.test. + * Get Bot User Id. + * + * @param token - Authentication token. + * @returns - Computed result. */ export async function getBotUserId(token: string): Promise { const authTest = await slackGet("auth.test", token); diff --git a/lib/slack/getSlackUserInfo.ts b/lib/slack/getSlackUserInfo.ts index eb144e45a..4c2aa9342 100644 --- a/lib/slack/getSlackUserInfo.ts +++ b/lib/slack/getSlackUserInfo.ts @@ -15,7 +15,11 @@ interface UsersInfoResponse { } /** - * Fetches a Slack account's display name and avatar by their Slack ID. + * Get Slack User Info. + * + * @param token - Authentication token. + * @param userId - Value for userId. + * @returns - Computed result. */ export async function getSlackUserInfo( token: string, diff --git a/lib/spotify/getSpotifyFollowers.ts b/lib/spotify/getSpotifyFollowers.ts index 235de41e8..d7671ab18 100644 --- a/lib/spotify/getSpotifyFollowers.ts +++ b/lib/spotify/getSpotifyFollowers.ts @@ -36,9 +36,10 @@ interface SpotifySearchResponse { } /** - * Get Spotify follower count for an artist - * @param artistName - The name of the artist to search for - * @returns Promise - The follower count of the first matching artist + * Get Spotify Followers. + * + * @param artistName - Value for artistName. + * @returns - Computed result. */ export async function getSpotifyFollowers(artistName: string): Promise { try { diff --git a/lib/supabase/account_artist_ids/getAccountArtistIds.ts b/lib/supabase/account_artist_ids/getAccountArtistIds.ts index e4e6b8099..afaaebee1 100644 --- a/lib/supabase/account_artist_ids/getAccountArtistIds.ts +++ b/lib/supabase/account_artist_ids/getAccountArtistIds.ts @@ -5,11 +5,12 @@ import type { ArtistQueryRow } from "@/lib/artists/getFormattedArtist"; export type AccountArtistRow = ArtistQueryRow & { artist_id: string; pinned: boolean }; /** - * Get all artists for an array of artist IDs or account IDs, with full info. - * Returns raw data - formatting should be done by caller. + * Get Account Artist Ids. * - * @param params Object with artistIds or accountIds array - * @returns Array of raw artist rows from database + * @param params - Dynamic route parameters. + * @param params.artistIds - Value for params.artistIds. + * @param params.accountIds - Value for params.accountIds. + * @returns - Computed result. */ export async function getAccountArtistIds(params: { artistIds?: string[]; diff --git a/lib/supabase/account_sandboxes/__tests__/selectAccountSandboxes.test.ts b/lib/supabase/account_sandboxes/__tests__/selectAccountSandboxes.test.ts index be02e5655..0edb640fd 100644 --- a/lib/supabase/account_sandboxes/__tests__/selectAccountSandboxes.test.ts +++ b/lib/supabase/account_sandboxes/__tests__/selectAccountSandboxes.test.ts @@ -105,12 +105,10 @@ describe("selectAccountSandboxes", () => { }); // First call is for account_sandboxes, second is for account_organization_ids - let callCount = 0; mockFrom.mockImplementation((table: string) => { if (table === "account_organization_ids") { return { select: mockOrgSelect }; } - callCount++; return { select: mockSelect }; }); diff --git a/lib/supabase/account_workspace_ids/getAccountWorkspaceIds.ts b/lib/supabase/account_workspace_ids/getAccountWorkspaceIds.ts index ae121fdd6..3f5b747be 100644 --- a/lib/supabase/account_workspace_ids/getAccountWorkspaceIds.ts +++ b/lib/supabase/account_workspace_ids/getAccountWorkspaceIds.ts @@ -7,11 +7,10 @@ export type AccountWorkspaceRow = Omit & { }; /** - * Get all workspaces for an account, with full info. - * Returns raw data - formatting should be done by caller. + * Get Account Workspace Ids. * - * @param accountId The owner's account ID - * @returns Array of raw workspace rows from database + * @param accountId - Account identifier. + * @returns - Computed result. */ export async function getAccountWorkspaceIds(accountId: string): Promise { if (!accountId) return []; diff --git a/lib/supabase/files/createFileRecord.ts b/lib/supabase/files/createFileRecord.ts index 6f836f3cd..9ccb1cb86 100644 --- a/lib/supabase/files/createFileRecord.ts +++ b/lib/supabase/files/createFileRecord.ts @@ -24,7 +24,10 @@ export interface CreateFileRecordParams { } /** - * Create a file record in the database + * Create File Record. + * + * @param params - Dynamic route parameters. + * @returns - Computed result. */ export async function createFileRecord(params: CreateFileRecordParams): Promise { const { diff --git a/lib/supabase/files/selectFileByStorageKey.ts b/lib/supabase/files/selectFileByStorageKey.ts index 78598c3cd..9ba4752a6 100644 --- a/lib/supabase/files/selectFileByStorageKey.ts +++ b/lib/supabase/files/selectFileByStorageKey.ts @@ -2,11 +2,12 @@ import supabase from "@/lib/supabase/serverClient"; import type { FileRecord } from "@/lib/supabase/files/createFileRecord"; /** - * Select a file record by storage key for an owner account. + * Select File By Storage Key. * - * @param root0 - * @param root0.ownerAccountId - * @param root0.storageKey + * @param root0 - Input object. + * @param root0.ownerAccountId - Value for root0.ownerAccountId. + * @param root0.storageKey - Value for root0.storageKey. + * @returns - Computed result. */ export async function selectFileByStorageKey({ ownerAccountId, diff --git a/lib/supabase/song_artists/insertSongArtists.ts b/lib/supabase/song_artists/insertSongArtists.ts index b81879e38..a61c73edf 100644 --- a/lib/supabase/song_artists/insertSongArtists.ts +++ b/lib/supabase/song_artists/insertSongArtists.ts @@ -4,7 +4,10 @@ import supabase from "../serverClient"; export type SongArtistInsert = TablesInsert<"song_artists">; /** - * Inserts song-artist relationships, skipping duplicates. + * Insert Song Artists. + * + * @param songArtists - Value for songArtists. + * @returns - Computed result. */ export async function insertSongArtists(songArtists: SongArtistInsert[]): Promise { const records = songArtists.filter( diff --git a/lib/supabase/storage/createSignedFileUrlByKey.ts b/lib/supabase/storage/createSignedFileUrlByKey.ts index 30625b7ad..a990d0872 100644 --- a/lib/supabase/storage/createSignedFileUrlByKey.ts +++ b/lib/supabase/storage/createSignedFileUrlByKey.ts @@ -2,11 +2,12 @@ import supabase from "@/lib/supabase/serverClient"; import { SUPABASE_STORAGE_BUCKET } from "@/lib/const"; /** - * Creates a signed URL for a file in Supabase storage. + * Create Signed File Url By Key. * - * @param root0 - * @param root0.key - * @param root0.expiresInSeconds + * @param root0 - Input object. + * @param root0.key - Value for root0.key. + * @param root0.expiresInSeconds - Value for root0.expiresInSeconds. + * @returns - Computed result. */ export async function createSignedFileUrlByKey({ key, diff --git a/lib/supabase/storage/uploadFileByKey.ts b/lib/supabase/storage/uploadFileByKey.ts index ba146fa35..a9d42bc1a 100644 --- a/lib/supabase/storage/uploadFileByKey.ts +++ b/lib/supabase/storage/uploadFileByKey.ts @@ -2,7 +2,14 @@ import supabase from "@/lib/supabase/serverClient"; import { SUPABASE_STORAGE_BUCKET } from "@/lib/const"; /** - * Upload file to Supabase storage by key + * Upload File By Key. + * + * @param key - Value for key. + * @param file - Value for file. + * @param options - Options for this operation. + * @param options.contentType - Value for options.contentType. + * @param options.upsert - Value for options.upsert. + * @returns - Computed result. */ export async function uploadFileByKey( key: string, diff --git a/lib/tasks/__tests__/enrichTasks.test.ts b/lib/tasks/__tests__/enrichTasks.test.ts index fde0daade..3330cda88 100644 --- a/lib/tasks/__tests__/enrichTasks.test.ts +++ b/lib/tasks/__tests__/enrichTasks.test.ts @@ -1,6 +1,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { enrichTasks } from "../enrichTasks"; +import { fetchTriggerRuns } from "@/lib/trigger/fetchTriggerRuns"; +import { retrieveTaskRun } from "@/lib/trigger/retrieveTaskRun"; +import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails"; + vi.mock("@/lib/trigger/fetchTriggerRuns", () => ({ fetchTriggerRuns: vi.fn(), })); @@ -13,10 +17,6 @@ vi.mock("@/lib/supabase/account_emails/selectAccountEmails", () => ({ default: vi.fn(), })); -import { fetchTriggerRuns } from "@/lib/trigger/fetchTriggerRuns"; -import { retrieveTaskRun } from "@/lib/trigger/retrieveTaskRun"; -import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails"; - const mockTask = { id: "task-123", title: "Test Task", diff --git a/lib/tasks/__tests__/fixtures/createTaskRequestTestFixtures.ts b/lib/tasks/__tests__/fixtures/createTaskRequestTestFixtures.ts index 07aaca55c..5b5b13a47 100644 --- a/lib/tasks/__tests__/fixtures/createTaskRequestTestFixtures.ts +++ b/lib/tasks/__tests__/fixtures/createTaskRequestTestFixtures.ts @@ -2,7 +2,12 @@ export const ACCOUNT_A = "123e4567-e89b-12d3-a456-426614174000"; export const ACCOUNT_B = "223e4567-e89b-12d3-a456-426614174000"; export const ARTIST_ID = "323e4567-e89b-12d3-a456-426614174000"; -/** Request JSON; optional `account_id` per OpenAPI `CreateTaskRequest`. */ +/** + * Valid Create Body. + * + * @param overrides - Optional override values. + * @returns - Computed result. + */ export function validCreateBody(overrides: Record = {}) { return { title: "Daily report", diff --git a/lib/tasks/__tests__/getTaskRunHandler.test.ts b/lib/tasks/__tests__/getTaskRunHandler.test.ts index 9f17fffce..909553cca 100644 --- a/lib/tasks/__tests__/getTaskRunHandler.test.ts +++ b/lib/tasks/__tests__/getTaskRunHandler.test.ts @@ -23,6 +23,11 @@ vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), })); +/** + * Create Mock Request. + * + * @returns - Computed result. + */ function createMockRequest(): NextRequest { return { url: "http://localhost:3000/api/tasks/runs", diff --git a/lib/tasks/__tests__/validateGetTaskRunQuery.test.ts b/lib/tasks/__tests__/validateGetTaskRunQuery.test.ts index f7126175d..118eb9df6 100644 --- a/lib/tasks/__tests__/validateGetTaskRunQuery.test.ts +++ b/lib/tasks/__tests__/validateGetTaskRunQuery.test.ts @@ -23,7 +23,10 @@ vi.mock("@/lib/admins/checkIsAdmin", () => ({ })); /** - * Creates a mock NextRequest with the given URL. + * Create Mock Request. + * + * @param url - URL to process. + * @returns - Computed result. */ function createMockRequest(url: string): NextRequest { return { diff --git a/lib/tasks/__tests__/validateGetTasksQuery.test.ts b/lib/tasks/__tests__/validateGetTasksQuery.test.ts index b9d0dda71..6f0695a1a 100644 --- a/lib/tasks/__tests__/validateGetTasksQuery.test.ts +++ b/lib/tasks/__tests__/validateGetTasksQuery.test.ts @@ -22,6 +22,12 @@ vi.mock("@/lib/admins/checkIsAdmin", () => ({ checkIsAdmin: vi.fn(), })); +/** + * Create Mock Request. + * + * @param url - URL to process. + * @returns - Computed result. + */ function createMockRequest(url: string): NextRequest { return { url, diff --git a/lib/transcribe/processAudioTranscription.ts b/lib/transcribe/processAudioTranscription.ts index 351eee347..27a996297 100644 --- a/lib/transcribe/processAudioTranscription.ts +++ b/lib/transcribe/processAudioTranscription.ts @@ -5,8 +5,10 @@ import { saveTranscriptToFiles } from "./saveTranscriptToFiles"; import { ProcessTranscriptionParams, ProcessTranscriptionResult } from "./types"; /** - * Fetches audio from URL, transcribes it with OpenAI Whisper, and saves both - * the original audio and transcript markdown to the customer's files. + * Process Audio Transcription. + * + * @param params - Dynamic route parameters. + * @returns - Computed result. */ export async function processAudioTranscription( params: ProcessTranscriptionParams, @@ -64,6 +66,12 @@ export async function processAudioTranscription( }; } +/** + * Get Extension From Content Type. + * + * @param contentType - Value for contentType. + * @returns - Computed result. + */ function getExtensionFromContentType(contentType: string): string { if (contentType.includes("wav")) return "wav"; if (contentType.includes("m4a") || contentType.includes("mp4")) return "m4a"; diff --git a/lib/transcribe/saveAudioToFiles.ts b/lib/transcribe/saveAudioToFiles.ts index 12bda1efd..5e5a3be8c 100644 --- a/lib/transcribe/saveAudioToFiles.ts +++ b/lib/transcribe/saveAudioToFiles.ts @@ -2,6 +2,12 @@ import { uploadFileByKey } from "@/lib/supabase/storage/uploadFileByKey"; import { createFileRecord } from "@/lib/supabase/files/createFileRecord"; import { SaveAudioParams, FileRecord } from "./types"; +/** + * Save Audio To Files. + * + * @param params - Dynamic route parameters. + * @returns - Computed result. + */ export async function saveAudioToFiles(params: SaveAudioParams): Promise { const { audioBlob, diff --git a/lib/transcribe/saveTranscriptToFiles.ts b/lib/transcribe/saveTranscriptToFiles.ts index 627feb6dc..3f9e06958 100644 --- a/lib/transcribe/saveTranscriptToFiles.ts +++ b/lib/transcribe/saveTranscriptToFiles.ts @@ -2,6 +2,12 @@ import { uploadFileByKey } from "@/lib/supabase/storage/uploadFileByKey"; import { createFileRecord } from "@/lib/supabase/files/createFileRecord"; import { SaveTranscriptParams, FileRecord } from "./types"; +/** + * Save Transcript To Files. + * + * @param params - Dynamic route parameters. + * @returns - Computed result. + */ export async function saveTranscriptToFiles(params: SaveTranscriptParams): Promise { const { markdown, ownerAccountId, artistAccountId, title = "Transcription" } = params; diff --git a/lib/transcribe/types.ts b/lib/transcribe/types.ts index 91c0ac106..3525bdf77 100644 --- a/lib/transcribe/types.ts +++ b/lib/transcribe/types.ts @@ -54,8 +54,10 @@ export interface ProcessTranscriptionResult { } /** - * Formats transcription errors into user-friendly messages. - * Centralizes error message logic to avoid duplication. + * Format Transcription Error. + * + * @param error - Value for error. + * @returns - Computed result. */ export function formatTranscriptionError(error: unknown): { message: string; status: number } { const rawMessage = error instanceof Error ? error.message : "Transcription failed"; diff --git a/lib/trigger/fetchTriggerRuns.ts b/lib/trigger/fetchTriggerRuns.ts index d19d518f2..2fd11e6b5 100644 --- a/lib/trigger/fetchTriggerRuns.ts +++ b/lib/trigger/fetchTriggerRuns.ts @@ -1,11 +1,11 @@ export interface TriggerRun { + [key: string]: unknown; id: string; status: string; createdAt: string; startedAt: string | null; finishedAt: string | null; durationMs: number | null; - [key: string]: unknown; } export type TriggerRunFilter = { "filter[tag]": string } | { "filter[schedule]": string }; diff --git a/lib/trigger/triggerCreateContent.ts b/lib/trigger/triggerCreateContent.ts index eb41fb3ce..d836ef6a1 100644 --- a/lib/trigger/triggerCreateContent.ts +++ b/lib/trigger/triggerCreateContent.ts @@ -19,9 +19,10 @@ export interface TriggerCreateContentPayload { } /** - * Triggers the create-content task in Trigger.dev. + * Trigger Create Content. * - * @param payload + * @param payload - Value for payload. + * @returns - Computed result. */ export async function triggerCreateContent(payload: TriggerCreateContentPayload) { const handle = await tasks.trigger(CREATE_CONTENT_TASK_ID, payload); diff --git a/lib/twelvelabs/analyzeVideo.ts b/lib/twelvelabs/analyzeVideo.ts index 3b0af44ee..900399a0f 100644 --- a/lib/twelvelabs/analyzeVideo.ts +++ b/lib/twelvelabs/analyzeVideo.ts @@ -7,11 +7,14 @@ export interface AnalyzeVideoResult { } /** - * Call the Twelve Labs video analysis API. + * Analyze Video. * - * @param validated - Validated request body with video_url, prompt, temperature, and optional max_tokens. - * @returns Analysis result with text, finish reason, and usage. - * @throws Error if TWELVELABS_API_KEY is missing or API call fails. + * @param validated - Value for validated. + * @param validated.video_url - Value for validated.video_url. + * @param validated.prompt - Value for validated.prompt. + * @param validated.temperature - Value for validated.temperature. + * @param validated.max_tokens - Value for validated.max_tokens. + * @returns - Computed result. */ export async function analyzeVideo(validated: { video_url: string; diff --git a/lib/workspaces/createWorkspaceInDb.ts b/lib/workspaces/createWorkspaceInDb.ts index d7684c5b2..712db62ae 100644 --- a/lib/workspaces/createWorkspaceInDb.ts +++ b/lib/workspaces/createWorkspaceInDb.ts @@ -49,7 +49,7 @@ export async function createWorkspaceInDb( account_id: workspace.id, isWorkspace: true, }; - } catch (error) { + } catch { return null; } }