The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Migrate Tinybird data to include projectId & linkId
Steven Tey38f26ead6270
diff --git a/apps/web/app/api/stats/[endpoint]/route.ts b/apps/web/app/api/stats/[endpoint]/route.tsindex 26c592f06a..dead24e68f 100644--- a/apps/web/app/api/stats/[endpoint]/route.ts+++ b/apps/web/app/api/stats/[endpoint]/route.ts@@ -1,25 +1,13 @@import { withAuth } from "@/lib/auth";+import { getDomainViaEdge, getLinkViaEdge } from "@/lib/planetscale";import { getStats } from "@/lib/stats";import { NextResponse } from "next/server";// GET /api/stats/[endpoint] – get stats for a specific endpointexport const GET = withAuth(- async ({ params, searchParams, project }) => {+ async ({ params, searchParams, project, link }) => {const { endpoint } = params;- const { domain, key, interval } = searchParams;-- const constructedDomain =- domain || project?.domains?.map((d) => d.slug).join(",");-- if (!constructedDomain) {- return new Response("Missing link domain.", { status: 400 });- }-- // if there's no key and it's not a project, return 400- // this is because projects can show stats for all links- if (!key && !project) {- return new Response("Missing link key.", { status: 400 });- }+ let { domain, key, interval } = searchParams;// return 403 if project is on the free plan and interval is 90d or allif (@@ -29,11 +17,18 @@ export const GET = withAuth(return new Response(`Require higher plan`, { status: 403 });}+ const linkId = link+ ? link.id+ : domain && key === "_root"+ ? await getDomainViaEdge(domain).then((d) => d?.id)+ : null;+const response = await getStats({- domain: constructedDomain,- key,+ projectId: project.id,+ domain,endpoint,interval,+ ...(linkId && { linkId }),...searchParams,});return NextResponse.json(response);diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 92526752a5..0a74274ddd 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -463,8 +463,8 @@ export async function addLink(link: LinkProps) {`${domain}:${key}`,{url: encodeURIComponent(url),- password: hasPassword,- proxy,+ ...(hasPassword && { password: true }),+ ...(proxy && { proxy: true }),...(rewrite && {rewrite: true,iframeable: await isIframeable({ url, requestDomain: domain }),@@ -508,7 +508,7 @@ export async function bulkCreateLinks(links: LinkProps[]) {`${domain}:${key}`,{url: encodeURIComponent(url),- password: hasPassword,+ ...(hasPassword && { password: true }),...(expiresAt && { expiresAt }),},{@@ -630,8 +630,8 @@ export async function editLink({}),redis.set(`${domain}:${key}`, {url: encodeURIComponent(url),- password: hasPassword,- proxy,+ ...(hasPassword && { password: true }),+ ...(proxy && { proxy: true }),...(rewrite && {rewrite: true,iframeable: await isIframeable({ url, requestDomain: domain }),diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex 1ba5d13489..470df374b7 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -49,7 +49,8 @@ export default async function LinkMiddleware();const {- url: target,+ id,+ url,password,proxy,rewrite,@@ -58,10 +59,11 @@ export default async function LinkMiddleware(ios,android,geo,+ projectId,banned,} = response || {};- if (target) {+ if (url) {// only show inspect modal if the link is not password protectedif (inspectMode && !password) {return NextResponse.rewrite(@@ -101,9 +103,26 @@ export default async function LinkMiddleware();}- // only track the click when there is no `dub-no-track` header- if (!req.headers.get("dub-no-track")) {- ev.waitUntil(recordClick({ req, domain, key }));+ const searchParams = req.nextUrl.searchParams;+ // only track the click when:+ // - the `dub-no-track` header is not set+ // - the `__dub_no_track` query param is not set+ if (+ !(+ req.headers.get("dub-no-track") ||+ searchParams.get("__dub_no_track") === "1"+ )+ ) {+ ev.waitUntil(+ recordClick({+ req,+ domain,+ key,+ url: getFinalUrl(url, { req }),+ id,+ projectId,+ }),+ );}const isBot = detectBot(req);@@ -117,16 +136,16 @@ export default async function LinkMiddleware(new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),);- // rewrite to target URL if link cloaking is enabled+ // rewrite to destination URL if link cloaking is enabled} else if (rewrite) {if (iframeable) {return NextResponse.rewrite(- new URL(`/rewrite/${target}`, req.url),+ new URL(`/rewrite/${url}`, req.url),DUB_HEADERS,);} else {// if link is not iframeable, use Next.js rewrite instead- return NextResponse.rewrite(decodeURIComponent(target), DUB_HEADERS);+ return NextResponse.rewrite(decodeURIComponent(url), DUB_HEADERS);}// redirect to iOS link if it is specified and the user is on an iOS device@@ -146,7 +165,7 @@ export default async function LinkMiddleware(// regular redirect} else {- return NextResponse.redirect(getFinalUrl(target, { req }), DUB_HEADERS);+ return NextResponse.redirect(getFinalUrl(url, { req }), DUB_HEADERS);}} else {// short link not found, redirect to rootdiff --git a/apps/web/lib/middleware/root.ts b/apps/web/lib/middleware/root.tsindex e0b42b0c9d..cc1c57fede 100644--- a/apps/web/lib/middleware/root.ts+++ b/apps/web/lib/middleware/root.ts@@ -2,7 +2,7 @@ import { recordClick } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { DUB_HEADERS } from "@dub/utils";import { NextFetchEvent, NextRequest, NextResponse } from "next/server";-import { parse } from "./utils";+import { getFinalUrl, parse } from "./utils";export default async function RootMiddleware(req: NextRequest,@@ -14,16 +14,36 @@ export default async function RootMiddleware(return NextResponse.next();}- // record clicks on root page- ev.waitUntil(recordClick({ req, domain }));-const response = await redis.get<{- target: string;+ id?: string;+ target?: string;rewrite?: boolean;iframeable?: boolean;+ projectId?: string;}>(`root:${domain}`);- const { target, rewrite, iframeable } = response || {};+ const { id, target, rewrite, iframeable, projectId } = response || {};++ const searchParams = req.nextUrl.searchParams;+ // only track the click when:+ // - the `dub-no-track` header is not set+ // - the `__dub_no_track` query param is not set+ if (+ !(+ req.headers.get("dub-no-track") ||+ searchParams.get("__dub_no_track") === "1"+ )+ ) {+ ev.waitUntil(+ recordClick({+ req,+ domain,+ url: target ? getFinalUrl(target, { req }) : undefined,+ id,+ projectId,+ }),+ );+ }if (target) {if (rewrite) {diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.tsindex 5554f204e5..6ad97a8324 100644--- a/apps/web/lib/planetscale.ts+++ b/apps/web/lib/planetscale.ts@@ -1,4 +1,5 @@import { connect } from "@planetscale/database";+import { DomainProps, LinkProps } from "./types";export const pscale_config = {url: process.env.DATABASE_URL,@@ -11,22 +12,22 @@ export const getLinkViaEdge = async (domain: string, key: string) => {const { rows } =(await conn.execute(- "SELECT `key`, url, password, proxy, title, description, image, clicks, userId, publicStats FROM Link WHERE domain = ? AND `key` = ?",+ "SELECT * FROM Link WHERE domain = ? AND `key` = ?",[domain, decodeURIComponent(key)], // we need to make sure that the key is always decoded (cause that's how we store it in MySQL))) || {};return rows && Array.isArray(rows) && rows.length > 0- ? (rows[0] as {- key: string;- url: string;- password: string | null;- proxy: number;- title: string;- description: string;- image: string;- clicks: number;- userId: number;- publicStats: number;- })+ ? (rows[0] as LinkProps)+ : null;+};++export const getDomainViaEdge = async (domain: string) => {+ if (!process.env.DATABASE_URL) return null;++ const { rows } =+ (await conn.execute("SELECT * FROM Domain WHERE slug = ?", [domain])) || {};++ return rows && Array.isArray(rows) && rows.length > 0+ ? (rows[0] as DomainProps): null;};diff --git a/apps/web/lib/stats.ts b/apps/web/lib/stats.tsindex 963e15b1b8..a39bc65251 100644--- a/apps/web/lib/stats.ts+++ b/apps/web/lib/stats.ts@@ -58,13 +58,15 @@ export const intervalData = {};export type LocationTabs = "country" | "city" | "region";-+export type TopLinksTabs = "link" | "url" | "alias";export type DeviceTabs = "device" | "browser" | "os" | "ua";const VALID_TINYBIRD_ENDPOINTS = ["timeseries","clicks","top_links",+ "top_urls",+ "top_aliases","country","city","device",@@ -76,6 +78,8 @@ const VALID_TINYBIRD_ENDPOINTS = [export const VALID_STATS_FILTERS = ["country","city",+ "url",+ "alias","device","browser","os",@@ -83,14 +87,16 @@ export const VALID_STATS_FILTERS = [];export const getStats = async ({+ projectId,+ linkId,domain,- key,endpoint,interval,...rest}: {- domain: string;- key?: string;+ projectId: string;+ linkId?: string;+ domain?: string;endpoint: string;interval?: string;} & {@@ -109,16 +115,12 @@ export const getStats = async ({// get all-time clicks count if:// 1. endpoint is /clicks// 2. interval is not defined- if (endpoint === "clicks" && key && !interval) {- const response =- key === "_root"- ? await conn.execute("SELECT clicks FROM Domain WHERE slug = ?", [- domain,- ])- : await conn.execute(- "SELECT clicks FROM Link WHERE domain = ? AND `key` = ?",- [domain, decodeURIComponent(key)],- );+ if (endpoint === "clicks" && !interval) {+ const response = linkId+ ? await conn.execute("SELECT clicks FROM Link WHERE `id` = ?", [linkId])+ : await conn.execute("SELECT clicks FROM Domain WHERE slug = ?", [+ domain,+ ]);try {const clicks = response.rows[0]["clicks"];return clicks || "0";@@ -128,11 +130,13 @@ export const getStats = async ({}let url = new URL(- `https://api.us-east.tinybird.co/v0/pipes/${endpoint}.json`,+ `https://api.us-east.tinybird.co/v0/pipes/${endpoint}_new.json`,);- url.searchParams.append("domain", domain);- if (key) {- url.searchParams.append("key", decodeURIComponent(key));+ url.searchParams.append("projectId", projectId);+ if (linkId) {+ url.searchParams.append("linkId", linkId);+ } else if (domain) {+ url.searchParams.append("domain", domain);}if (interval) {url.searchParams.append(@@ -161,7 +165,13 @@ export const getStats = async ({Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,},})- .then((res) => res.json())+ .then(async (res) => {+ if (res.ok) {+ return res.json();+ }+ const error = await res.text();+ console.error(error);+ }).then(({ data }) => {if (endpoint === "clicks") {try {diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.tsindex ae40e11583..093e400690 100644--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@ -6,8 +6,8 @@ import {} from "@dub/utils";import { ipAddress } from "@vercel/edge";import { NextRequest, userAgent } from "next/server";-import { conn } from "./planetscale";-import { ratelimit } from "./upstash";+import { conn, getDomainViaEdge, getLinkViaEdge } from "./planetscale";+import { ratelimit, updateRedisLink } from "./upstash";import { detectBot } from "./middleware/utils";/**@@ -18,10 +18,16 @@ export async function recordClick({req,domain,key,+ url,+ id,+ projectId,}: {req: NextRequest;domain: string;key?: string;+ url?: string;+ id?: string;+ projectId?: string;}) {const isBot = detectBot(req);if (isBot) {@@ -31,44 +37,66 @@ export async function recordClick({const ua = userAgent(req);const referer = req.headers.get("referer");const ip = ipAddress(req) || LOCALHOST_IP;- // deduplicate clicks from the same IP, domain and key – only record 1 click per hour- const { success } = await ratelimit(2, "1 h").limit(- `recordClick:${ip}:${domain.toLowerCase()}:${- key?.toLowerCase() || "_root"- }`,- );- if (!success) {- return null;+ // if in production / preview env, deduplicate clicks from the same IP, domain and key – only record 1 click per hour+ if (process.env.VERCEL === "1") {+ const { success } = await ratelimit(2, "1 h").limit(+ `recordClick:${ip}:${domain.toLowerCase()}:${+ key?.toLowerCase() || "_root"+ }`,+ );+ if (!success) {+ return null;+ }+ }+ let updateRedis = false;++ if (id || !projectId) {+ if (key) {+ const linkData = await getLinkViaEdge(domain, key);+ id = linkData?.id;+ projectId = linkData?.projectId || undefined;+ } else {+ const domainData = await getDomainViaEdge(domain);+ id = domainData?.id;+ projectId = domainData?.projectId || undefined;+ }+ updateRedis = true;}+ console.log({ id, projectId, domain, key, url });+return await Promise.allSettled([fetch(- "https://api.us-east.tinybird.co/v0/events?name=click_events&wait=true",+ "https://api.us-east.tinybird.co/v0/events?name=dub_click_events&wait=true",{method: "POST",headers: {Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,},body: JSON.stringify({- timestamp: new Date(Date.now()).toISOString(),+ link_id: id,+ project_id: projectId,domain,key: key || "_root",+ url,+ timestamp: new Date(Date.now()).toISOString(),+ alias: "", // "dub.sh/alias"country: geo?.country || "Unknown",city: geo?.city || "Unknown",region: geo?.region || "Unknown",latitude: geo?.latitude || "Unknown",longitude: geo?.longitude || "Unknown",- ua: ua.ua || "Unknown",+ device: ua.device.type ? capitalize(ua.device.type) : "Desktop",+ device_vendor: ua.device.vendor || "Unknown",+ device_model: ua.device.model || "Unknown",browser: ua.browser.name || "Unknown",browser_version: ua.browser.version || "Unknown",engine: ua.engine.name || "Unknown",engine_version: ua.engine.version || "Unknown",os: ua.os.name || "Unknown",os_version: ua.os.version || "Unknown",- device: ua.device.type ? capitalize(ua.device.type) : "Desktop",- device_vendor: ua.device.vendor || "Unknown",- device_model: ua.device.model || "Unknown",cpu_architecture: ua.cpu?.architecture || "Unknown",+ ua: ua.ua || "Unknown",bot: ua.isBot,referer: referer? getDomainWithoutWWW(referer) || "(direct)"@@ -78,6 +106,16 @@ export async function recordClick({},).then((res) => res.json()),+ updateRedis &&+ updateRedisLink({+ domain,+ key,+ data: {+ id,+ projectId,+ },+ }),+// increment the click count for the link if key is specified (not root click)// also increment the usage count for the project, and then we have a cron that will reset it at the start of new billing cyclekeydiff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 693638f327..5e3fcbe84e 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -14,6 +14,7 @@ export interface QRLinkProps {}export interface RedisLinkProps {+ id?: string;url: string;password?: boolean;proxy?: boolean;@@ -23,6 +24,7 @@ export interface RedisLinkProps {ios?: string;android?: string;geo?: object;+ projectId?: string;banned?: boolean;}@@ -86,6 +88,7 @@ export type DomainVerificationStatusProps =| "Unknown Error";export interface DomainProps {+ id: string;slug: string;verified: boolean;primary: boolean;@@ -93,6 +96,7 @@ export interface DomainProps {type: "redirect" | "rewrite";placeholder?: string;clicks: number;+ projectId: string;}export interface BitlyGroupProps {diff --git a/apps/web/lib/upstash.ts b/apps/web/lib/upstash.tsindex 88384dad6a..371cb11b0f 100644--- a/apps/web/lib/upstash.ts+++ b/apps/web/lib/upstash.ts@@ -1,6 +1,7 @@import { getDomainWithoutWWW, nanoid } from "@dub/utils";import { Ratelimit } from "@upstash/ratelimit";import { Redis } from "@upstash/redis";+import { RedisLinkProps } from "./types";// Initiate Redis instance by connecting to REST URLexport const redis = new Redis({@@ -78,3 +79,34 @@ export async function recordMetatags(url: string, error: boolean) {const domain = getDomainWithoutWWW(url);return await ratelimitRedis.zincrby("metatags-zset", 1, domain);}++/**+ * Update Redis data for a given link+ */++export const updateRedisLink = async ({+ domain,+ key,+ data,+}: {+ domain: string;+ key?: string;+ data: Partial<RedisLinkProps>;+}) => {+ const redisKey = key ? `${domain}:${key}` : `root:${domain}`;++ // RedisLinkProps is technically not the right type since+ // root:{domain} has a slightly different type, but it works+ const currentData = await redis.get<RedisLinkProps>(redisKey);+ if (!currentData) return null;++ // filter out properties that are false (e.g. password: false, proxy: false)+ Object.keys(currentData).forEach((key) => {+ if (!currentData[key as keyof RedisLinkProps]) {+ delete currentData[key as keyof RedisLinkProps];+ }+ });++ const newData = { ...currentData, ...data };+ return await redis.set<RedisLinkProps>(redisKey, newData);+};diff --git a/apps/web/package.json b/apps/web/package.jsonindex 47fdc07ffe..3639149d5b 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -52,7 +52,6 @@"he": "^1.2.0","html-escaper": "^3.0.3","js-cookie": "^3.0.5",- "linkify-react": "^4.1.3","lucide-react": "^0.299.0","nanoid": "^5.0.1","next": "14.0.5-canary.39",diff --git a/apps/web/scripts/format-clicks.ts b/apps/web/scripts/format-clicks.tsnew file mode 100644index 0000000000..1409681553--- /dev/null+++ b/apps/web/scripts/format-clicks.ts@@ -0,0 +1,94 @@+import "dotenv-flow/config";+import * as Papa from "papaparse";+import * as fs from "fs";+import prisma from "@/lib/prisma";++const projectId = "cl7wsy2836920mjrb352g5wfx";+const clicks: any[] = [];++async function main() {+ const links = await prisma.link.findMany({+ where: {+ projectId,+ },+ select: {+ id: true,+ domain: true,+ key: true,+ url: true,+ },+ });+ const domains = await prisma.domain.findMany({+ where: {+ projectId,+ },+ select: {+ id: true,+ slug: true,+ target: true,+ },+ });++ Papa.parse(fs.createReadStream("sql.csv", "utf-8"), {+ header: true,+ skipEmptyLines: true,+ step: ({ data }) => {+ const { id, projectId: pId, url, ...rest } = data;+ const link =+ data.key === "_root"+ ? domains.find(({ slug }) => slug === data.domain)+ : links.find(+ ({ domain, key }) =>+ domain === data.domain &&+ key.toLowerCase() === data.key.toLowerCase(),+ );++ if (!link) {+ console.log(+ `No link found for ${data.domain}/${data.key}. Probably deleted.`,+ );+ return;+ }++ clicks.push({+ ...rest,+ link_id: link.id,+ project_id: projectId,+ // @ts-ignore+ url: link.url || link.target || "",+ alias: "",+ bot: data.bot === "1" ? 1 : 0,+ });+ },+ complete: async () => {+ console.log(clicks.length);++ // chunk the clicks into period of 8 months, up until today's date+ const today = new Date();+ let start = new Date("2022-09-01");+ while (start < today) {+ const end = new Date(start);+ end.setMonth(end.getMonth() + 8);+ const clicksForPeriod = clicks.filter(+ ({ timestamp }) =>+ new Date(timestamp) >= start && new Date(timestamp) < end,+ );+ const file = fs.createWriteStream(+ `clicks-${start.getFullYear()}-${start.getMonth()}.ndjson`,+ );++ // Iterate over the array and write each object as a string+ clicksForPeriod.forEach((obj) => {+ file.write(JSON.stringify(obj) + "\n");+ });++ // Close the stream+ file.end();++ start = end;+ }+ },+ });+}++main();diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsxindex 4f83aad26b..995eac0504 100644--- a/apps/web/ui/links/link-card.tsx+++ b/apps/web/ui/links/link-card.tsx@@ -44,10 +44,10 @@ import {} from "lucide-react";import Link from "next/link";import { useParams } from "next/navigation";-import Linkify from "linkify-react";import punycode from "punycode/";import { useContext, useEffect, useMemo, useRef, useState } from "react";import useSWR from "swr";+import { LinkifyTooltipContent } from "@dub/ui/src/tooltip";export default function LinkCard({props,@@ -302,19 +302,7 @@ export default function LinkCard({{comments && (<Tooltipcontent={- <div className="block max-w-sm px-4 py-2 text-center text-sm text-gray-700">- <Linkify- as="p"- options={{- target: "_blank",- rel: "noopener noreferrer nofollow",- className:- "underline underline-offset-4 text-gray-400 hover:text-gray-700",- }}- >- {comments}- </Linkify>- </div>+ <LinkifyTooltipContent>{comments}</LinkifyTooltipContent>}><buttondiff --git a/apps/web/ui/modals/add-edit-domain-modal.tsx b/apps/web/ui/modals/add-edit-domain-modal.tsxindex 86ea361927..6f145cf4b2 100644--- a/apps/web/ui/modals/add-edit-domain-modal.tsx+++ b/apps/web/ui/modals/add-edit-domain-modal.tsx@@ -45,12 +45,14 @@ function AddEditDomainModal({const [data, setData] = useState<DomainProps>(props || {+ id: "",slug: "",verified: false,primary: false,target: "",type: "redirect",clicks: 0,+ projectId: "",},);diff --git a/apps/web/ui/stats/bar-list.tsx b/apps/web/ui/stats/bar-list.tsxindex 07d1fb2617..1ff6cce409 100644--- a/apps/web/ui/stats/bar-list.tsx+++ b/apps/web/ui/stats/bar-list.tsx@@ -1,12 +1,13 @@"use client";import { NumberTooltip, Tooltip } from "@dub/ui";-import { cn, nFormatter } from "@dub/utils";+import { cn, nFormatter, truncate } from "@dub/utils";import { motion } from "framer-motion";import { Search } from "lucide-react";import Link from "next/link";import { Dispatch, ReactNode, SetStateAction, useMemo, useState } from "react";import LinkPreviewTooltip from "./link-preview";+import { LinkifyTooltipContent } from "@dub/ui/src/tooltip";export default function BarList({tab,@@ -50,11 +51,11 @@ export default function BarList({{icon}<pclassName={cn(- "text-sm text-gray-800",+ "truncate text-sm text-gray-800",href && "underline-offset-4 group-hover:underline",)}>- {title}+ {truncate(title, 48)}</p></div>);@@ -68,10 +69,18 @@ export default function BarList({><div key={idx} className="group flex items-center justify-between"><div className="relative z-10 flex w-full max-w-[calc(100%-2rem)] items-center">- {tab === "Top Links" ? (+ {tab === "link" ? (<Tooltip content={<LinkPreviewTooltip link={title} />}>{lineItem}</Tooltip>+ ) : tab === "url" ? (+ <Tooltip+ content={+ <LinkifyTooltipContent>{title}</LinkifyTooltipContent>+ }+ >+ {lineItem}+ </Tooltip>) : (lineItem)}diff --git a/apps/web/ui/stats/clicks.tsx b/apps/web/ui/stats/clicks.tsxindex 928db26066..38ce96f0ed 100644--- a/apps/web/ui/stats/clicks.tsx+++ b/apps/web/ui/stats/clicks.tsx@@ -1,6 +1,12 @@import { Chart } from "@/ui/shared/icons";import { NumberTooltip, useRouterStuff } from "@dub/ui";-import { COUNTRIES, capitalize, linkConstructor, nFormatter } from "@dub/utils";+import {+ COUNTRIES,+ capitalize,+ linkConstructor,+ nFormatter,+ truncate,+} from "@dub/utils";import { useContext } from "react";import { StatsContext } from ".";import BarChart from "./bar-chart";@@ -37,8 +43,7 @@ export default function Clicks() {</p></div><div className="flex flex-wrap items-center justify-end gap-2">- {slug &&- domain &&+ {domain &&(key ? (<buttononClick={() => {@@ -82,7 +87,9 @@ export default function Clicks() {><p>{capitalize(filter)}</p><strong className="text-gray-800">- {filter === "country" ? COUNTRIES[value] : value}+ {filter === "country"+ ? COUNTRIES[value]+ : truncate(value, 24)}</strong><X className="h-4 w-4" /></button>diff --git a/apps/web/ui/stats/toggle.tsx b/apps/web/ui/stats/toggle.tsxindex 9c103d1c1a..ed642f3169 100644--- a/apps/web/ui/stats/toggle.tsx+++ b/apps/web/ui/stats/toggle.tsx@@ -157,7 +157,7 @@ export default function Toggle() {? `interval=${value}`: `${new URLSearchParams({...(domain && { domain }),- ...(key && key !== "_root" && { key }),+ ...(key && { key }),interval: value,}).toString()}`}`}@@ -198,7 +198,7 @@ export default function Toggle() {}const DomainsFilterTooltip = ({ domains }: { domains: DomainProps[] }) => {- const searchParams = useSearchParams()+ const searchParams = useSearchParams();const domain = searchParams?.get("domain");const key = searchParams?.get("key");const { queryParams } = useRouterStuff();diff --git a/apps/web/ui/stats/top-links.tsx b/apps/web/ui/stats/top-links.tsxindex c2090b7ec7..e9f7de11e6 100644--- a/apps/web/ui/stats/top-links.tsx+++ b/apps/web/ui/stats/top-links.tsx@@ -1,37 +1,49 @@-import { LoadingSpinner, Modal, useRouterStuff } from "@dub/ui";-import { fetcher, linkConstructor } from "@dub/utils";+import { LoadingSpinner, Modal, TabSelect, useRouterStuff } from "@dub/ui";+import { capitalize, fetcher, linkConstructor, truncate } from "@dub/utils";import { Maximize } from "lucide-react";import { useContext, useState } from "react";import useSWR from "swr";import { StatsContext } from ".";import BarList from "./bar-list";+import { TopLinksTabs } from "@/lib/stats";export default function TopLinks() {+ const [tab, setTab] = useState<TopLinksTabs>("link");+const { baseApiPath, queryString, modal } = useContext(StatsContext);- const { data } = useSWR<{ domain: string; key: string; clicks: number }[]>(- `${baseApiPath}/top_links?${queryString}`,- fetcher,- );+ const { data } = useSWR<+ ({ domain: string; key: string } & {+ [key in TopLinksTabs]: string;+ } & { clicks: number })[]+ >(`${baseApiPath}/top_${tab}s?${queryString}`, fetcher);const { queryParams } = useRouterStuff();const [showModal, setShowModal] = useState(false);const barList = (limit?: number) => (<BarList- tab="Top Links"+ tab={tab}data={data?.map((d) => ({- title: linkConstructor({- domain: d.domain,- key: d.key,- pretty: true,- }),+ title:+ tab === "link"+ ? linkConstructor({+ domain: d.domain,+ key: d.key,+ pretty: true,+ })+ : d[tab],href: queryParams({- set: {- domain: d.domain,- key: d.key,- },+ set:+ tab === "link"+ ? {+ domain: d.domain,+ key: d.key,+ }+ : {+ [tab]: d[tab],+ },getNewPath: true,}) as string,clicks: d.clicks,@@ -57,8 +69,14 @@ export default function TopLinks() {{barList()}</Modal><div className="scrollbar-hide relative z-0 h-[400px] overflow-scroll border border-gray-200 bg-white px-7 py-5 sm:rounded-lg sm:border-gray-100 sm:shadow-lg">- <div className="mb-5 flex">- <h1 className="text-lg font-semibold">Top Links</h1>+ <div className="mb-5 flex justify-between">+ <h1 className="text-lg font-semibold capitalize">Top Links</h1>+ <TabSelect+ options={["link", "url", "alias"]}+ selected={tab}+ // @ts-ignore+ selectAction={setTab}+ /></div>{data ? (data.length > 0 ? (diff --git a/packages/tinybird/datasources/click_events.datasource b/packages/tinybird/datasources/dub_click_events.datasourcesimilarity index 83%rename from packages/tinybird/datasources/click_events.datasourcerename to packages/tinybird/datasources/dub_click_events.datasourceindex d526bae1db..5a37aee2c1 100644--- a/packages/tinybird/datasources/click_events.datasource+++ b/packages/tinybird/datasources/dub_click_events.datasource@@ -1,28 +1,32 @@SCHEMA >- `timestamp` DateTime64(3) `json:$.timestamp`,+ `link_id` String `json:$.link_id`,+ `project_id` String `json:$.project_id`,`domain` String `json:$.domain`,`key` String `json:$.key`,+ `url` String `json:$.url`,+ `timestamp` DateTime64(3) `json:$.timestamp`,+ `alias` String `json:$.alias`,`country` LowCardinality(String) `json:$.country`,`city` String `json:$.city`,+ `region` String `json:$.region`,+ `latitude` String `json:$.latitude`,+ `longitude` String `json:$.longitude`,`device` LowCardinality(String) `json:$.device`,+ `device_model` LowCardinality(String) `json:$.device_model`,+ `device_vendor` LowCardinality(String) `json:$.device_vendor`,`browser` LowCardinality(String) `json:$.browser`,- `os` LowCardinality(String) `json:$.os`,- `bot` UInt8 `json:$.bot`,- `referer` String `json:$.referer`,`browser_version` String `json:$.browser_version`,+ `os` LowCardinality(String) `json:$.os`,+ `os_version` String `json:$.os_version`,`engine` LowCardinality(String) `json:$.engine`,`engine_version` String `json:$.engine_version`,- `latitude` String `json:$.latitude`,- `longitude` String `json:$.longitude`,- `os_version` String `json:$.os_version`,- `region` String `json:$.region`,- `ua` String `json:$.ua`,- `device_model` LowCardinality(String) `json:$.device_model`,- `device_vendor` LowCardinality(String) `json:$.device_vendor`,`cpu_architecture` LowCardinality(String) `json:$.cpu_architecture`,+ `ua` String `json:$.ua`,+ `bot` UInt8 `json:$.bot`,+ `referer` String `json:$.referer`,`referer_url` String `json:$.referer_url`ENGINE "MergeTree"ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"-ENGINE_SORTING_KEY "domain, key, timestamp"\ No newline at end of file+ENGINE_SORTING_KEY "project_id, link_id, domain, key, timestamp"\ No newline at end of filediff --git a/packages/ui/package.json b/packages/ui/package.jsonindex e9ce92aa18..e0786564b2 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -43,6 +43,7 @@"@radix-ui/react-tooltip": "^1.0.7","class-variance-authority": "^0.7.0","js-cookie": "^3.0.5",+ "linkify-react": "^4.1.3","lucide-react": "^0.284.0","sonner": "^0.5.0","swr": "^2.1.5",diff --git a/packages/ui/src/tooltip.tsx b/packages/ui/src/tooltip.tsxindex 127dc9e1a0..0d25310cc7 100644--- a/packages/ui/src/tooltip.tsx+++ b/packages/ui/src/tooltip.tsx@@ -2,6 +2,7 @@import { nFormatter, timeAgo } from "@dub/utils";import * as TooltipPrimitive from "@radix-ui/react-tooltip";+import Linkify from "linkify-react";import { HelpCircle } from "lucide-react";import Link from "next/link";import { ReactNode, useState } from "react";@@ -111,6 +112,7 @@ export function SimpleTooltipContent({href={href}target="_blank"rel="noopener noreferrer"+ onClick={(e) => e.stopPropagation()}className="inline-flex text-gray-500 underline underline-offset-4 hover:text-gray-800">{cta}@@ -119,6 +121,24 @@ export function SimpleTooltipContent({);}+export function LinkifyTooltipContent({ children }: { children: ReactNode }) {+ return (+ <div className="block max-w-md whitespace-pre-wrap px-4 py-2 text-center text-sm text-gray-700">+ <Linkify+ as="p"+ options={{+ target: "_blank",+ rel: "noopener noreferrer nofollow",+ className:+ "underline underline-offset-4 text-gray-400 hover:text-gray-700",+ }}+ >+ {children}+ </Linkify>+ </div>+ );+}+export function InfoTooltip({ content }: { content: ReactNode | string }) {return (<Tooltip content={content}>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dd04b5b176..4060ab4a56 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -154,9 +154,6 @@ importers:js-cookie:specifier: ^3.0.5version: 3.0.5- linkify-react:- specifier: ^4.1.3- version: 4.1.3([email protected])([email protected])lucide-react:specifier: ^0.299.0version: 0.299.0([email protected])@@ -650,7 +647,7 @@ importers:version: 1.0.1([email protected])([email protected])'@radix-ui/react-dialog':specifier: 1.0.5- version: 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-navigation-menu':specifier: ^1.1.2version: 1.1.2([email protected])([email protected])@@ -672,6 +669,9 @@ importers:js-cookie:specifier: ^3.0.5version: 3.0.5+ linkify-react:+ specifier: ^4.1.3+ version: 4.1.3([email protected])([email protected])lucide-react:specifier: ^0.284.0version: 0.284.0([email protected])@@ -763,7 +763,7 @@ importers:version: link:../tsconfigtsup:specifier: ^6.1.3- version: 6.1.3([email protected])([email protected])+ version: 6.1.3([email protected])typescript:specifier: ^5.1.6version: 5.1.6@@ -5503,11 +5503,11 @@ packages:'@radix-ui/primitive': 1.0.1'@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])'@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])([email protected])([email protected])'@radix-ui/react-focus-guards': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-focus-scope': 1.0.4(@types/[email protected])([email protected])([email protected])'@radix-ui/react-id': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-portal': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-slot': 1.0.2(@types/[email protected])([email protected])@@ -5626,6 +5626,30 @@ packages:react-dom: 18.2.0([email protected])dev: false+ resolution: {integrity: sha512-aJeDjQhywg9LBu2t/At58hCvr7pEm0o2Ke1x33B+MhjNmmZ17sy4KImo0KPLgsnc/zN7GPdce8Cnn0SWvwZO7g==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.23.2+ '@radix-ui/primitive': 1.0.1+ '@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-use-callback-ref': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-use-escape-keydown': 1.0.3(@types/[email protected])([email protected])+ '@types/react': 18.2.14+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+/@radix-ui/[email protected]([email protected]):resolution: {integrity: sha512-UagjDk4ijOAnGu4WMUPj9ahi7/zJJqNZ9ZAiGPp7waUWJO0O1aWXi/udPphI0IUjvrhBsZJGSN66dR2dsueLWQ==}peerDependencies:@@ -5737,6 +5761,28 @@ packages:react-dom: 18.2.0([email protected])dev: false+ resolution: {integrity: sha512-sL04Mgvf+FmyvZeYfNu1EPAaaxD+aw7cYeIB9L9Fvq8+urhltTRaEo5ysKOpHuKPclsZcSUMKlN05x4u+CINpA==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.23.2+ '@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-use-callback-ref': 1.0.1(@types/[email protected])([email protected])+ '@types/react': 18.2.14+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+/@radix-ui/[email protected]([email protected]):resolution: {integrity: sha512-Q6iAB/U7Tq3NTolBBQbHTgclPmGWE3OlktGGqrClPozSw4vkQ1DfQAOtzgRPecKsMdJINE05iaoDUG8tRzCBjw==}peerDependencies:@@ -5847,12 +5893,12 @@ packages:'@radix-ui/primitive': 1.0.1'@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])'@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])([email protected])([email protected])'@radix-ui/react-focus-guards': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-focus-scope': 1.0.4(@types/[email protected])([email protected])([email protected])'@radix-ui/react-id': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-portal': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-slot': 1.0.2(@types/[email protected])([email protected])@@ -5981,6 +6027,26 @@ packages:react-dom: 18.2.0([email protected])dev: false+ resolution: {integrity: sha512-Qki+C/EuGUVCQTOTD5vzJzJuMUlewbzuKyUy+/iHM2uwGiru9gZeBJtHAPKAEkB5KWGi9mP/CHKcY0wt1aW45Q==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.23.2+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@types/react': 18.2.14+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+resolution: {integrity: sha512-A+6XEvN01NfVWiKu38ybawfHsBjWum42MRPnEuqPsBZ4eV7e/7K321B5VgYMPv3Xx5An6o1/l9ZuDBgmcmWK3w==}peerDependencies:@@ -6278,10 +6344,10 @@ packages:'@radix-ui/primitive': 1.0.1'@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])'@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-dismissable-layer': 1.0.5(@types/[email protected])([email protected])([email protected])'@radix-ui/react-id': 1.0.1(@types/[email protected])([email protected])- '@radix-ui/react-portal': 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-slot': 1.0.2(@types/[email protected])([email protected])@@ -16559,6 +16625,42 @@ packages:- ts-nodedev: true+ resolution: {integrity: sha512-eRpBnbfpDFng+EJNTQ90N7QAf4HAGGC7O3buHIjroKWK7D1ibk9/YnR/3cS8HsMU5T+6Oi+cnF+yU5WmCnB//Q==}+ engines: {node: '>=14'}+ hasBin: true+ peerDependencies:+ '@swc/core': ^1+ postcss: ^8.4.12+ typescript: ^4.1.0+ peerDependenciesMeta:+ '@swc/core':+ optional: true+ postcss:+ optional: true+ typescript:+ optional: true+ dependencies:+ bundle-require: 3.1.2([email protected])+ cac: 6.7.14+ chokidar: 3.5.3+ debug: 4.3.4+ esbuild: 0.14.54+ execa: 5.1.1+ globby: 11.1.0+ joycon: 3.1.1+ postcss-load-config: 3.1.4([email protected])+ resolve-from: 5.0.0+ rollup: 2.79.1+ source-map: 0.8.0-beta.0+ sucrase: 3.34.0+ tree-kill: 1.2.2+ typescript: 5.1.6+ transitivePeerDependencies:+ - supports-color+ - ts-node+ dev: true+resolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==}engines: {node: '>= 6'}