The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
some cleanups
Kiran Kd863e9af82b4
diff --git a/apps/web/lib/api/links/complete-ab-tests.ts b/apps/web/lib/api/links/complete-ab-tests.tsindex 61ef1676fd..e286d1096d 100644--- a/apps/web/lib/api/links/complete-ab-tests.ts+++ b/apps/web/lib/api/links/complete-ab-tests.ts@@ -1,7 +1,7 @@import { getAnalytics } from "@/lib/analytics/get-analytics";import { NewLinkProps, WorkspaceProps } from "@/lib/types";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";-import { linkEventSchema, LinkTestsSchema } from "@/lib/zod/schemas/links";+import { ABTestVariantsSchema, linkEventSchema } from "@/lib/zod/schemas/links";import { Link, Project } from "@prisma/client";import { waitUntil } from "@vercel/functions";import { DubApiError, ErrorCodes } from "../errors";@@ -9,11 +9,13 @@ import { processLink } from "./process-link";import { updateLink } from "./update-link";export async function completeABTests(link: Link & { project: Project }) {- if (!link.testVariants || !link.testCompletedAt || !link.projectId) return;+ if (!link.testVariants || !link.testCompletedAt || !link.projectId) {+ return;+ }- const testVariants = LinkTestsSchema.parse(link.testVariants);+ const testVariants = ABTestVariantsSchema.parse(link.testVariants);- const analytics = (await getAnalytics({+ const analytics: { url: string; leads: number }[] = await getAnalytics({event: "leads",groupBy: "top_urls",linkId: link.id,@@ -21,7 +23,7 @@ export async function completeABTests(link: Link & { project: Project }) {dataAvailableFrom: link.project.createdAt,start: link.testStartedAt ? new Date(link.testStartedAt) : undefined,end: link.testCompletedAt,- })) as { url: string; leads: number }[];+ });const max = Math.max(...testVariants.map(@@ -29,11 +31,12 @@ export async function completeABTests(link: Link & { project: Project }) {),);+ // All results are zero, do nothingif (max === 0) {- // All results are zero, do nothingconsole.log(- `completeTests: All results are zero for ${link.id}, doing nothing`,+ `AB Test completed but all results are zero for ${link.id}, doing nothing.`,);+return;}@@ -42,21 +45,19 @@ export async function completeABTests(link: Link & { project: Project }) {(analytics.find(({ url }) => url === test.url)?.leads || 0) === max,);- if (winners.length === 0)+ if (winners.length === 0) {throw new Error(- `completeTests: Failed to find winners based on max leads for link ${link.id}`,+ `AB Test completed but failed to find winners based on max leads for link ${link.id}.`,);+ }const winner = winners[Math.floor(Math.random() * winners.length)];- console.log(- `completeTests: Determined A/B testVariants winner for ${link.id}: ${winner.url}${winners.length > 1 ? ` (${winners.length} tied)` : ""}`,- );- if (winner.url === link.url) return;+ if (winner.url === link.url) {+ return;+ }// Update the link's URL to the winner-- // Add body onto existing link but maintain NewLinkProps form for processLinkconst { project, ...originalLink } = link;const updatedLink = {@@ -77,10 +78,8 @@ export async function completeABTests(link: Link & { project: Project }) {? link.testStartedAt.toISOString(): link.testStartedAt,- // Update URLurl: winner.url,- // When root domain...(link.key === "_root" && {domain: link.domain,key: link.key,diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.tsindex b6b80706cf..4978f393b6 100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@ -34,6 +34,7 @@ export async function createLink(link: ProcessedLinkProps) {geo,publicStats,testVariants,+ testStartedAt,testCompletedAt,} = link;@@ -69,7 +70,7 @@ export async function createLink(link: ProcessedLinkProps) {testVariants: testVariants || Prisma.JsonNull,testCompletedAt: testCompletedAt ? new Date(testCompletedAt) : null,- testStartedAt: testVariants && testCompletedAt ? new Date() : null,+ testStartedAt: testStartedAt ? new Date(testStartedAt) : null,// Associate tags by tagNames...(tagNames?.length &&diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.tsindex 4c33d76f24..18386f0a9b 100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@ -4,7 +4,7 @@ import { getPangeaDomainIntel } from "@/lib/pangea";import { checkIfUserExists, getRandomKey } from "@/lib/planetscale";import { isStored } from "@/lib/storage";import { NewLinkProps, ProcessedLinkProps, WorkspaceProps } from "@/lib/types";-import { LinkTestsSchema } from "@/lib/zod/schemas/links";+import { ABTestVariantsSchema } from "@/lib/zod/schemas/links";import { prisma } from "@dub/prisma";import {DUB_DOMAINS,@@ -564,7 +564,7 @@ export async function processLink<T extends Record<string, any>>({}testCompletedAt = datetime;- const parsedTests = LinkTestsSchema.safeParse(testVariants);+ const parsedTests = ABTestVariantsSchema.safeParse(testVariants);if (!parsedTests.success) {return {link: payload,diff --git a/apps/web/lib/middleware/utils/get-test-destination-url.ts b/apps/web/lib/middleware/utils/get-test-destination-url.tsindex fe61438c45..d0bfb014cd 100644--- a/apps/web/lib/middleware/utils/get-test-destination-url.ts+++ b/apps/web/lib/middleware/utils/get-test-destination-url.ts@@ -1,4 +1,4 @@-import { LinkTestsSchema, MAX_TEST_COUNT } from "@/lib/zod/schemas/links";+import { ABTestVariantsSchema, MAX_TEST_COUNT } from "@/lib/zod/schemas/links";import { cookies } from "next/headers";import { z } from "zod";@@ -9,7 +9,7 @@ export const getTestDestinationURL = ({testVariants,testCompletedAt,}: {- testVariants?: z.infer<typeof LinkTestsSchema>;+ testVariants?: z.infer<typeof ABTestVariantsSchema>;testCompletedAt?: Date;}) => {try {diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 035b8c92f1..fcf6409187 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -39,7 +39,7 @@ import {leadEventResponseSchema,trackLeadResponseSchema,} from "./zod/schemas/leads";-import { createLinkBodySchema, LinkTestsSchema } from "./zod/schemas/links";+import { createLinkBodySchema, ABTestVariantsSchema } from "./zod/schemas/links";import { createOAuthAppSchema, oAuthAppSchema } from "./zod/schemas/oauth";import {createPartnerSchema,@@ -113,7 +113,7 @@ export interface RedisLinkProps {doIndex?: boolean;projectId?: string;webhookIds?: string[];- testVariants?: z.infer<typeof LinkTestsSchema>;+ testVariants?: z.infer<typeof ABTestVariantsSchema>;testCompletedAt?: Date;}diff --git a/apps/web/lib/upstash/format-redis-link.ts b/apps/web/lib/upstash/format-redis-link.tsindex bdd5e5d06c..1beb964e5f 100644--- a/apps/web/lib/upstash/format-redis-link.ts+++ b/apps/web/lib/upstash/format-redis-link.ts@@ -1,7 +1,7 @@import { z } from "zod";import { ExpandedLink } from "../api/links/utils/transform-link";import { RedisLinkProps } from "../types";-import { LinkTestsSchema } from "../zod/schemas/links";+import { ABTestVariantsSchema } from "../zod/schemas/links";export function formatRedisLink(link: ExpandedLink): RedisLinkProps {const {@@ -46,7 +46,7 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {...(Boolean(testVariants && testCompletedAt && new Date(testCompletedAt) > new Date(),) && {- testVariants: testVariants as z.infer<typeof LinkTestsSchema>,+ testVariants: testVariants as z.infer<typeof ABTestVariantsSchema>,testCompletedAt: new Date(testCompletedAt!),}),};diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex b8213f33fa..ff50b5cb85 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -28,7 +28,7 @@ export const getDomainQuerySchema = z.object({export const MIN_TEST_PERCENTAGE = 10;export const MAX_TEST_COUNT = 4;-export const LinkTestsSchema = z+export const ABTestVariantsSchema = z.array(z.object({url: z.string(),@@ -40,7 +40,21 @@ export const LinkTestsSchema = z).min(2).max(MAX_TEST_COUNT)- .describe("An array of A/B test URLs and their percentages");+ .describe(+ "An array of A/B test URLs and the percentage of traffic to send to each URL.",+ )+ .openapi({+ example: [+ {+ url: "https://example.com/variant-1",+ percentage: 50,+ },+ {+ url: "https://example.com/variant-2",+ percentage: 50,+ },+ ],+ });const LinksQuerySchema = z.object({domain: z@@ -401,7 +415,7 @@ export const createLinkBodySchema = z.object({.describe("An array of webhook IDs to trigger when the link is clicked. These webhooks will receive click event data.",),- testVariants: LinkTestsSchema.nullish(),+ testVariants: ABTestVariantsSchema.nullish(),testStartedAt: z.string().nullish()@@ -626,7 +640,7 @@ export const LinkSchema = z.string().nullable().describe("The UTM content of the short link."),- testVariants: LinkTestsSchema.nullish(),+ testVariants: ABTestVariantsSchema.nullish(),testStartedAt: z.string().nullish()diff --git a/apps/web/ui/links/link-tests.tsx b/apps/web/ui/links/link-tests.tsxindex d08261cf99..235ff05a84 100644--- a/apps/web/ui/links/link-tests.tsx+++ b/apps/web/ui/links/link-tests.tsx@@ -1,5 +1,5 @@import useWorkspace from "@/lib/swr/use-workspace";-import { LinkTestsSchema } from "@/lib/zod/schemas/links";+import { ABTestVariantsSchema } from "@/lib/zod/schemas/links";import { fetcher } from "@dub/utils";import { motion } from "framer-motion";import { memo, useMemo } from "react";@@ -21,7 +21,7 @@ export const LinkTests = memo(({ link }: { link: ResponseLink }) => {return null;try {- return LinkTestsSchema.parse(link.testVariants);+ return ABTestVariantsSchema.parse(link.testVariants);} catch (e) {console.error(`Failed to parse link testVariants for link ${link.id}`, e);}@@ -52,7 +52,6 @@ export const LinkTests = memo(({ link }: { link: ResponseLink }) => {revalidateOnFocus: false,},);- console.log(data);if (!testVariants || !testVariants.length) return null;diff --git a/apps/web/ui/modals/link-builder/ab-testing-modal.tsx b/apps/web/ui/modals/link-builder/ab-testing-modal.tsxindex 5d5ad2171b..a3aaf2f765 100644--- a/apps/web/ui/modals/link-builder/ab-testing-modal.tsx+++ b/apps/web/ui/modals/link-builder/ab-testing-modal.tsx@@ -1,5 +1,5 @@import {- LinkTestsSchema,+ ABTestVariantsSchema,MAX_TEST_COUNT,MIN_TEST_PERCENTAGE,} from "@/lib/zod/schemas/links";@@ -42,7 +42,7 @@ import { z } from "zod";import { LinkFormData } from ".";const parseTests = (testVariants: LinkFormData["testVariants"]) =>- Array.isArray(testVariants) ? LinkTestsSchema.parse(testVariants) : null;+ Array.isArray(testVariants) ? ABTestVariantsSchema.parse(testVariants) : null;const inTwoWeeks = new Date(Date.now() + 2 * 7 * 24 * 60 * 60 * 1000);@@ -79,7 +79,7 @@ function ABTestingModal({formState: { isDirty, isValid },handleSubmit,} = useForm<- { testVariants: z.infer<typeof LinkTestsSchema> } & Pick<+ { testVariants: z.infer<typeof ABTestVariantsSchema> } & Pick<LinkFormData,"testCompletedAt">diff --git a/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsx b/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsxindex 621e96e2a5..1c93247b16 100644--- a/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsx+++ b/apps/web/ui/modals/link-builder/ab-testing/ab-testing-modal.tsx@@ -1,5 +1,5 @@import {- LinkTestsSchema,+ ABTestVariantsSchema,MAX_TEST_COUNT,MIN_TEST_PERCENTAGE,} from "@/lib/zod/schemas/links";@@ -42,7 +42,7 @@ import { LinkFormData } from "..";import { TrafficSplitSlider } from "./traffic-split-slider";const parseTests = (testVariants: LinkFormData["testVariants"]) =>- Array.isArray(testVariants) ? LinkTestsSchema.parse(testVariants) : null;+ Array.isArray(testVariants) ? ABTestVariantsSchema.parse(testVariants) : null;const inTwoWeeks = new Date(Date.now() + 2 * 7 * 24 * 60 * 60 * 1000);@@ -116,7 +116,7 @@ function ABTestingEdit({formState: { isDirty, isValid },handleSubmit,} = useForm<- { testVariants: z.infer<typeof LinkTestsSchema> } & Pick<+ { testVariants: z.infer<typeof ABTestVariantsSchema> } & Pick<LinkFormData,"testCompletedAt">