Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Update client dependencies and enhance subscription flow (#698)

Bill Yangc1ad55428421
diff --git a/client/package-lock.json b/client/package-lock.json
index 42acad91e..b06e35cc1 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "client",
- "version": "2.1.0",
+ "version": "2.1.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "client",
- "version": "2.1.0",
+ "version": "2.1.2",
"dependencies": {
"@hookform/resolvers": "5.0.1",
"@icons-pack/react-simple-icons": "^13.6.0",
@@ -61,6 +61,7 @@
"mapbox-gl": "^3.15.0",
"next": "15.3.2",
"next-themes": "0.4.6",
+ "nuqs": "^2.7.3",
"ol": "^10.6.1",
"react": "19.1.0",
"react-day-picker": "^8.10.1",
@@ -6238,6 +6239,12 @@
"node": ">=20.0.0"
}
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",
+ "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",
+ "license": "MIT"
+ },
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
@@ -9368,6 +9375,43 @@
"esm-env": "^1.1.4"
}
},
+ "node_modules/nuqs": {
+ "version": "2.7.3",
+ "resolved": "https://registry.npmjs.org/nuqs/-/nuqs-2.7.3.tgz",
+ "integrity": "sha512-lQzSYLsXUYftc0cerww64yevjMeYOX8thkcqI25XtyyTEJFTk3LE+i2hcY2h0Jwvp1+owCb+KJ0GMaKQwfmq3g==",
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/franky47"
+ },
+ "peerDependencies": {
+ "@remix-run/react": ">=2",
+ "@tanstack/react-router": "^1",
+ "next": ">=14.2.0",
+ "react": ">=18.2.0 || ^19.0.0-0",
+ "react-router": "^6 || ^7",
+ "react-router-dom": "^6 || ^7"
+ },
+ "peerDependenciesMeta": {
+ "@remix-run/react": {
+ "optional": true
+ },
+ "@tanstack/react-router": {
+ "optional": true
+ },
+ "next": {
+ "optional": true
+ },
+ "react-router": {
+ "optional": true
+ },
+ "react-router-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
diff --git a/client/package.json b/client/package.json
index 57ce54ff0..8fb22554d 100644
--- a/client/package.json
+++ b/client/package.json
@@ -65,6 +65,7 @@
"mapbox-gl": "^3.15.0",
"next": "15.3.2",
"next-themes": "0.4.6",
+ "nuqs": "^2.7.3",
"ol": "^10.6.1",
"react": "19.1.0",
"react-day-picker": "^8.10.1",
diff --git a/client/src/app/layout.tsx b/client/src/app/layout.tsx
index 7bc05da2a..04e23845f 100644
--- a/client/src/app/layout.tsx
+++ b/client/src/app/layout.tsx
@@ -13,6 +13,7 @@ import { ReactScan } from "./ReactScan";
import { OrganizationInitializer } from "../components/OrganizationInitializer";
import { AuthenticationGuard } from "../components/AuthenticationGuard";
import { ThemeProvider } from "next-themes";
+import { NuqsAdapter } from "nuqs/adapters/next/app";
const inter = Inter({ subsets: ["latin"] });
@@ -25,30 +26,32 @@ export default function RootLayout({ children }: { children: React.ReactNode })
return (
<html lang="en" suppressHydrationWarning>
<ReactScan />
- <body className={cn("bg-background text-foreground h-full", inter.className)} suppressHydrationWarning>
- <ThemeProvider attribute="class" enableSystem={true} disableTransitionOnChange>
- <TooltipProvider>
- <QueryProvider>
- <OrganizationInitializer />
- <AuthenticationGuard />
- {children}
- </QueryProvider>
- <Toaster />
- </TooltipProvider>
- </ThemeProvider>
- {isAppProduction && (
- <>
- <Script
- src="https://demo.rybbit.com/api/script.js"
- data-site-id="21"
- strategy="afterInteractive"
- data-web-vitals="true"
- data-track-errors="true"
- data-session-replay="true"
- />
- </>
- )}
- </body>
+ <NuqsAdapter>
+ <body className={cn("bg-background text-foreground h-full", inter.className)} suppressHydrationWarning>
+ <ThemeProvider attribute="class" enableSystem={true} disableTransitionOnChange>
+ <TooltipProvider>
+ <QueryProvider>
+ <OrganizationInitializer />
+ <AuthenticationGuard />
+ {children}
+ </QueryProvider>
+ <Toaster />
+ </TooltipProvider>
+ </ThemeProvider>
+ {isAppProduction && (
+ <>
+ <Script
+ src="https://demo.rybbit.com/api/script.js"
+ data-site-id="21"
+ strategy="afterInteractive"
+ data-web-vitals="true"
+ data-track-errors="true"
+ data-session-replay="true"
+ />
+ </>
+ )}
+ </body>
+ </NuqsAdapter>
</html>
);
}
diff --git a/client/src/app/settings/account/components/DeleteAccount.tsx b/client/src/app/settings/account/components/DeleteAccount.tsx
index 3a661d901..874bc8d14 100644
--- a/client/src/app/settings/account/components/DeleteAccount.tsx
+++ b/client/src/app/settings/account/components/DeleteAccount.tsx
@@ -17,37 +17,21 @@ import {
AlertDialogTrigger,
} from "../../../../components/ui/alert-dialog";
import { Button } from "../../../../components/ui/button";
-import { Input } from "../../../../components/ui/input";
-import { Label } from "../../../../components/ui/label";
import { authClient } from "../../../../lib/auth";
-import { cn } from "../../../../lib/utils";
export function DeleteAccount() {
const [isDeleting, setIsDeleting] = useState(false);
- const [password, setPassword] = useState("");
const [isOpen, setIsOpen] = useState(false);
- const [passwordError, setPasswordError] = useState("");
const router = useRouter();
const queryClient = useQueryClient();
const handleAccountDeletion = async () => {
- if (!password) {
- setPasswordError("Password is required to delete your account");
- return;
- }
-
try {
setIsDeleting(true);
- setPasswordError("");
- const response = await authClient.deleteUser({
- password,
- });
+ const response = await authClient.deleteUser();
if (response.error) {
toast.error(`Failed to delete account: ${response.error.message || "Unknown error"}`);
- if (response.error.message && response.error.message.toLowerCase().includes("password")) {
- setPasswordError("Incorrect password");
- }
return;
}
queryClient.clear();
@@ -63,8 +47,6 @@ export function DeleteAccount() {
const handleClose = () => {
setIsOpen(false);
- setPassword("");
- setPasswordError("");
};
return (
@@ -86,22 +68,6 @@ export function DeleteAccount() {
</AlertDialogDescription>
</AlertDialogHeader>
- <div className="py-1">
- <Label htmlFor="password" className="text-sm font-medium">
- Enter your password to confirm
- </Label>
- <Input
- id="password"
- type="password"
- placeholder="••••••••"
- value={password}
- onChange={e => setPassword(e.target.value)}
- className={cn("mt-1", passwordError && "border-red-500")}
- disabled={isDeleting}
- />
- {passwordError && <p className="text-sm text-red-500 mt-1">{passwordError}</p>}
- </div>
-
<AlertDialogFooter>
<AlertDialogCancel onClick={handleClose} disabled={isDeleting}>
Cancel
diff --git a/client/src/app/signup/page.tsx b/client/src/app/signup/page.tsx
index 9db103b3f..1aa1bafd1 100644
--- a/client/src/app/signup/page.tsx
+++ b/client/src/app/signup/page.tsx
@@ -174,7 +174,8 @@ export default function SignupPage() {
const normalizedDomain = normalizeDomain(domain);
const response = await addSite(normalizedDomain, normalizedDomain, organizationId);
// Navigate directly to dashboard after adding website
- router.push(`/${response.siteId}`);
+ // router.push(`/${response.siteId}`);
+ router.push("/subscribe?siteId=" + response.siteId);
} catch (error) {
setError(String(error));
}
diff --git a/client/src/app/subscribe/components/PricingCard.tsx b/client/src/app/subscribe/components/PricingCard.tsx
index ed8c62b24..5fae19aaa 100644
--- a/client/src/app/subscribe/components/PricingCard.tsx
+++ b/client/src/app/subscribe/components/PricingCard.tsx
@@ -1,23 +1,31 @@
-import React, { useState } from "react";
+"use client";
+
import { Slider } from "@/components/ui/slider";
+import { authClient } from "@/lib/auth";
+import { BACKEND_URL } from "@/lib/const";
import { cn } from "@/lib/utils";
+import { useState } from "react";
import { toast } from "sonner";
-import { BACKEND_URL } from "@/lib/const";
-import { authClient } from "@/lib/auth";
+import { DEFAULT_EVENT_LIMIT } from "../../../lib/subscription/constants";
+import { trackAdEvent } from "../../../lib/trackAdEvent";
+import { FeaturesList } from "./FeaturesList";
import {
- EVENT_TIERS,
- STANDARD_FEATURES,
- PRO_FEATURES,
ENTERPRISE_FEATURES,
+ EVENT_TIERS,
FREE_FEATURES,
+ PRO_FEATURES,
+ STANDARD_FEATURES,
findPriceForTier,
formatEventTier,
} from "./utils";
-import { trackAdEvent } from "../../../lib/trackAdEvent";
-import { DEFAULT_EVENT_LIMIT } from "../../../lib/subscription/constants";
-import { FeaturesList } from "./FeaturesList";
+
+import { useRouter } from "next/navigation";
+import { useQueryState } from "nuqs";
export function PricingCard({ isLoggedIn }: { isLoggedIn: boolean }) {
+ const [siteId] = useQueryState("siteId");
+ const router = useRouter();
+
const [eventLimitIndex, setEventLimitIndex] = useState<number>(0);
const [isAnnual, setIsAnnual] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(false);
@@ -57,7 +65,7 @@ export function PricingCard({ isLoggedIn }: { isLoggedIn: boolean }) {
// Use NEXT_PUBLIC_BACKEND_URL if available, otherwise use relative path for same-origin requests
const baseUrl = window.location.origin;
const successUrl = `${baseUrl}/settings/organization/subscription?session_id={CHECKOUT_SESSION_ID}`;
- const cancelUrl = `${baseUrl}/subscribe`;
+ const cancelUrl = `${baseUrl}/subscribe${siteId ? `?siteId=${siteId}` : ""}`;
const response = await fetch(`${BACKEND_URL}/stripe/create-checkout-session`, {
method: "POST",
@@ -168,7 +176,7 @@ export function PricingCard({ isLoggedIn }: { isLoggedIn: boolean }) {
</div>
{/* Cards section */}
- <div className="grid min-[1100px]:grid-cols-4 min-[600px]:grid-cols-2 min-[400px]:grid-cols-1 gap-6 max-w-6xl mx-auto">
+ <div className="grid min-[1100px]:grid-cols-4 min-[600px]:grid-cols-2 min-[400px]:grid-cols-1 gap-6 max-w-6xl mx-auto mb-16">
{/* Free Plan Card */}
<div className="bg-neutral-100/30 dark:bg-neutral-800/15 rounded-xl border border-neutral-150 dark:border-neutral-800/60 overflow-hidden text-neutral-600 dark:text-neutral-300 shadow:lg">
<div className="p-6">
@@ -181,16 +189,17 @@ export function PricingCard({ isLoggedIn }: { isLoggedIn: boolean }) {
<div className="mb-6">
<div>
<span className="text-3xl font-bold">{DEFAULT_EVENT_LIMIT.toLocaleString()}</span>
- <span className="ml-1 text-neutral-600 dark:text-neutral-400">/month events</span>
+ <span className="ml-1 text-neutral-600 dark:text-neutral-400">events/month</span>
</div>
</div>
{/* Current plan button */}
<button
- disabled
- className="w-full bg-neutral-300 dark:bg-neutral-700 text-neutral-500 dark:text-neutral-400 font-medium px-5 py-3 rounded-xl border border-neutral-200 dark:border-neutral-600 cursor-not-allowed opacity-50"
+ onClick={() => (siteId ? router.push(`/${siteId}`) : {})}
+ disabled={!siteId}
+ className="w-full bg-neutral-200 dark:bg-neutral-850 hover:bg-neutral-150 dark:hover:bg-neutral-800 text-neutral-600 dark:text-neutral-300 font-medium px-5 py-3 rounded-xl border border-neutral-250 dark:border-neutral-800 shadow-lg focus:outline-none focus:ring-2 focus:ring-neutral-400 focus:ring-opacity-50 cursor-pointer transition all duration-200"
>
- Current Plan
+ {siteId ? "Continue free" : "Current plan"}
</button>
{/* Features */}
@@ -306,11 +315,6 @@ export function PricingCard({ isLoggedIn }: { isLoggedIn: boolean }) {
</div>
</div>
</div>
-
- {/* Footer text */}
- <p className="text-center text-sm text-neutral-600 dark:text-neutral-400 mt-6">
- {isCustomTier ? "Email us at [email protected] for custom pricing" : "Secure checkout powered by Stripe."}
- </p>
</div>
);
}
diff --git a/client/src/app/subscribe/components/utils.ts b/client/src/app/subscribe/components/utils.ts
index 555dbfa6c..9006a3e50 100644
--- a/client/src/app/subscribe/components/utils.ts
+++ b/client/src/app/subscribe/components/utils.ts
@@ -56,7 +56,6 @@ export const ENTERPRISE_FEATURES = [
export const FREE_FEATURES = [
"1 user",
`${FREE_SITE_LIMIT} website`,
- "Cookieless tracking",
"Web analytics dashboard",
"Custom events",
"6 month data retention",
diff --git a/client/src/app/subscribe/page.tsx b/client/src/app/subscribe/page.tsx
index bf9a614c2..f2e8dcf5f 100644
--- a/client/src/app/subscribe/page.tsx
+++ b/client/src/app/subscribe/page.tsx
@@ -3,19 +3,23 @@
import { authClient } from "@/lib/auth";
import { DateTime } from "luxon";
import { useRouter } from "next/navigation";
+import { Suspense } from "react";
import { StandardPage } from "../../components/StandardPage";
import { UsageChart } from "../../components/UsageChart";
import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
import { FAQSection } from "./components/FAQSection";
import { PricingCard } from "./components/PricingCard";
import { PricingHeader } from "./components/PricingHeader";
+import { useQueryState } from "nuqs";
-export default function Subscribe() {
+function SubscribeContent() {
const { data: sessionData } = authClient.useSession();
const { data: subscription } = useStripeSubscription();
const { data: activeOrg } = authClient.useActiveOrganization();
const router = useRouter();
+ const [siteId, setSiteId] = useQueryState("siteId");
+
// Redirect if already subscribed
// if (subscription?.status === "active") {
// router.push("/settings/organization/subscription");
@@ -28,6 +32,19 @@ export default function Subscribe() {
const endDate = DateTime.now().toISODate();
const startDate = DateTime.now().minus({ days: 30 }).toISODate();
+ if (siteId) {
+ return (
+ <StandardPage>
+ <div className="container mx-auto py-12 px-4">
+ <PricingHeader />
+
+ {/* Pricing Card */}
+ <PricingCard isLoggedIn={!!sessionData?.user} />
+ </div>
+ </StandardPage>
+ );
+ }
+
return (
<StandardPage>
<div className="container mx-auto py-12 px-4">
@@ -51,3 +68,11 @@ export default function Subscribe() {
</StandardPage>
);
}
+
+export default function Subscribe() {
+ return (
+ <Suspense fallback={<div className="flex items-center justify-center min-h-screen">Loading...</div>}>
+ <SubscribeContent />
+ </Suspense>
+ );
+}
diff --git a/client/src/components/auth/SocialButtons.tsx b/client/src/components/auth/SocialButtons.tsx
index 0f1761181..eeca2bed0 100644
--- a/client/src/components/auth/SocialButtons.tsx
+++ b/client/src/components/auth/SocialButtons.tsx
@@ -19,7 +19,9 @@ export function SocialButtons({ onError, callbackURL, mode = "signin", className
try {
await authClient.signIn.social({
provider,
- ...(callbackURL ? { callbackURL } : {}),
+ ...(callbackURL && mode !== "signup" ? { callbackURL } : {}),
+ // For signup flow, new users should be redirected to the same callbackURL
+ ...(mode === "signup" && callbackURL ? { newUserCallbackURL: callbackURL } : {}),
});
} catch (error) {
onError(String(error));
diff --git a/docs/src/components/PricingCard.tsx b/docs/src/components/PricingCard.tsx
index 41b063e1f..41a16b9f9 100644
--- a/docs/src/components/PricingCard.tsx
+++ b/docs/src/components/PricingCard.tsx
@@ -95,7 +95,7 @@ export function PricingCard({
</Link>
)}
- <div className={cn("my-6", "space-y-3")}>
+ <div className={cn("mt-6 mb-1", "space-y-3")}>
{displayedFeatures.map((item, i) => {
const isObject = typeof item === "object";
const feature = isObject ? item.feature : item;
diff --git a/docs/src/components/PricingSection.tsx b/docs/src/components/PricingSection.tsx
index 1d1171bdd..d84f367db 100644
--- a/docs/src/components/PricingSection.tsx
+++ b/docs/src/components/PricingSection.tsx
@@ -66,7 +66,6 @@ const ENTERPRISE_FEATURES = [
const FREE_FEATURES = [
{ feature: "1 user", included: true },
{ feature: `${FREE_SITE_LIMIT} website`, included: true },
- { feature: "Cookieless tracking", included: true },
{ feature: "Web analytics dashboard", included: true },
{ feature: "Custom events", included: true },
{ feature: "6 month data retention", included: true },
@@ -145,7 +144,9 @@ export function PricingSection() {
<h2 className="text-4xl md:text-5xl font-bold tracking-tight pb-4 text-transparent bg-clip-text bg-gradient-to-b from-neutral-900 via-neutral-700 to-neutral-500 dark:from-white dark:via-gray-200 dark:to-gray-400">
Simple, Transparent Pricing
</h2>
- <p className="text-lg text-neutral-600 dark:text-neutral-300">Privacy-friendly analytics with all the features you need to grow</p>
+ <p className="text-lg text-neutral-600 dark:text-neutral-300">
+ Privacy-friendly analytics with all the features you need to grow
+ </p>
</div>
{/* Shared controls section */}
@@ -222,7 +223,7 @@ export function PricingSection() {
priceDisplay={
<div>
<span className="text-3xl font-bold">{DEFAULT_EVENT_LIMIT.toLocaleString()}</span>
- <span className="ml-1 text-neutral-400">/month events</span>
+ <span className="ml-1 text-neutral-400">events/month</span>
</div>
}
buttonText="Start for free"
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index a2e52f8dc..6fa2e61ec 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -53,49 +53,32 @@ export const verification = pgTable("verification", {
});
// Sites table
-export const sites = pgTable(
- "sites",
- {
- id: text("id").$defaultFn(() => sql`encode(gen_random_bytes(6), 'hex')`),
- // deprecated - keeping as primary key for backwards compatibility
- siteId: serial("site_id").primaryKey().notNull(),
- name: text("name").notNull(),
- domain: text("domain").notNull(),
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- createdBy: text("created_by")
- .notNull()
- .references(() => user.id),
- organizationId: text("organization_id").references(() => organization.id),
- public: boolean().default(false),
- saltUserIds: boolean().default(false),
- blockBots: boolean().default(true).notNull(),
- excludedIPs: jsonb("excluded_ips").default([]), // Array of IP addresses/ranges to exclude
- excludedCountries: jsonb("excluded_countries").default([]), // Array of ISO country codes to exclude (e.g., ["US", "GB"])
- sessionReplay: boolean().default(false),
- webVitals: boolean().default(false),
- trackErrors: boolean().default(false),
- trackOutbound: boolean().default(true),
- trackUrlParams: boolean().default(true),
- trackInitialPageView: boolean().default(true),
- trackSpaNavigation: boolean().default(true),
- trackIp: boolean().default(false),
- apiKey: text("api_key"), // Format: rb_{32_hex_chars} = 35 chars total
- privateLinkKey: text("private_link_key"),
- },
- table => [
- foreignKey({
- columns: [table.createdBy],
- foreignColumns: [user.id],
- name: "sites_created_by_user_id_fk",
- }),
- foreignKey({
- columns: [table.organizationId],
- foreignColumns: [organization.id],
- name: "sites_organization_id_organization_id_fk",
- }),
- ]
-);
+export const sites = pgTable("sites", {
+ id: text("id").$defaultFn(() => sql`encode(gen_random_bytes(6), 'hex')`),
+ // deprecated - keeping as primary key for backwards compatibility
+ siteId: serial("site_id").primaryKey().notNull(),
+ name: text("name").notNull(),
+ domain: text("domain").notNull(),
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
+ createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
+ organizationId: text("organization_id").references(() => organization.id),
+ public: boolean().default(false),
+ saltUserIds: boolean().default(false),
+ blockBots: boolean().default(true).notNull(),
+ excludedIPs: jsonb("excluded_ips").default([]), // Array of IP addresses/ranges to exclude
+ excludedCountries: jsonb("excluded_countries").default([]), // Array of ISO country codes to exclude (e.g., ["US", "GB"])
+ sessionReplay: boolean().default(false),
+ webVitals: boolean().default(false),
+ trackErrors: boolean().default(false),
+ trackOutbound: boolean().default(true),
+ trackUrlParams: boolean().default(true),
+ trackInitialPageView: boolean().default(true),
+ trackSpaNavigation: boolean().default(true),
+ trackIp: boolean().default(false),
+ apiKey: text("api_key"), // Format: rb_{32_hex_chars} = 35 chars total
+ privateLinkKey: text("private_link_key"),
+});
// Active sessions table
export const activeSessions = pgTable("active_sessions", {
@@ -106,56 +89,33 @@ export const activeSessions = pgTable("active_sessions", {
lastActivity: timestamp("last_activity").defaultNow(),
});
-export const funnels = pgTable(
- "funnels",
- {
- reportId: serial("report_id").primaryKey().notNull(),
- siteId: integer("site_id"),
- userId: text("user_id"),
- data: jsonb(),
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- },
- table => [
- foreignKey({
- columns: [table.siteId],
- foreignColumns: [sites.siteId],
- name: "funnels_site_id_sites_site_id_fk",
- }),
- foreignKey({
- columns: [table.userId],
- foreignColumns: [user.id],
- name: "funnels_user_id_user_id_fk",
- }),
- ]
-);
+export const funnels = pgTable("funnels", {
+ reportId: serial("report_id").primaryKey().notNull(),
+ siteId: integer("site_id").references(() => sites.siteId),
+ userId: text("user_id").references(() => user.id, { onDelete: "set null" }),
+ data: jsonb(),
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
+});
// Account table (BetterAuth)
-export const account = pgTable(
- "account",
- {
- id: text().primaryKey().notNull(),
- accountId: text().notNull(),
- providerId: text().notNull(),
- userId: text().notNull(),
- accessToken: text(),
- refreshToken: text(),
- idToken: text(),
- accessTokenExpiresAt: timestamp({ mode: "string" }),
- refreshTokenExpiresAt: timestamp({ mode: "string" }),
- scope: text(),
- password: text(),
- createdAt: timestamp({ mode: "string" }).notNull(),
- updatedAt: timestamp({ mode: "string" }).notNull(),
- },
- table => [
- foreignKey({
- columns: [table.userId],
- foreignColumns: [user.id],
- name: "account_userId_user_id_fk",
- }),
- ]
-);
+export const account = pgTable("account", {
+ id: text().primaryKey().notNull(),
+ accountId: text().notNull(),
+ providerId: text().notNull(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ accessToken: text(),
+ refreshToken: text(),
+ idToken: text(),
+ accessTokenExpiresAt: timestamp({ mode: "string" }),
+ refreshTokenExpiresAt: timestamp({ mode: "string" }),
+ scope: text(),
+ password: text(),
+ createdAt: timestamp({ mode: "string" }).notNull(),
+ updatedAt: timestamp({ mode: "string" }).notNull(),
+});
// Organization table (BetterAuth)
export const organization = pgTable(
@@ -175,54 +135,30 @@ export const organization = pgTable(
);
// Member table (BetterAuth)
-export const member = pgTable(
- "member",
- {
- id: text().primaryKey().notNull(),
- organizationId: text().notNull(),
- userId: text().notNull(),
- role: text().notNull(),
- createdAt: timestamp({ mode: "string" }).notNull(),
- },
- table => [
- foreignKey({
- columns: [table.organizationId],
- foreignColumns: [organization.id],
- name: "member_organizationId_organization_id_fk",
- }),
- foreignKey({
- columns: [table.userId],
- foreignColumns: [user.id],
- name: "member_userId_user_id_fk",
- }),
- ]
-);
+export const member = pgTable("member", {
+ id: text().primaryKey().notNull(),
+ organizationId: text()
+ .notNull()
+ .references(() => organization.id),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ role: text().notNull(),
+ createdAt: timestamp({ mode: "string" }).notNull(),
+});
// Invitation table (BetterAuth)
-export const invitation = pgTable(
- "invitation",
- {
- id: text().primaryKey().notNull(),
- email: text().notNull(),
- inviterId: text().notNull(),
- organizationId: text().notNull(),
- role: text().notNull(),
- status: text().notNull(),
- expiresAt: timestamp({ mode: "string" }).notNull(),
- },
- table => [
- foreignKey({
- columns: [table.inviterId],
- foreignColumns: [user.id],
- name: "invitation_inviterId_user_id_fk",
- }),
- foreignKey({
- columns: [table.organizationId],
- foreignColumns: [organization.id],
- name: "invitation_organizationId_organization_id_fk",
- }),
- ]
-);
+export const invitation = pgTable("invitation", {
+ id: text().primaryKey().notNull(),
+ email: text().notNull(),
+ inviterId: text().references(() => user.id, { onDelete: "set null" }),
+ organizationId: text()
+ .notNull()
+ .references(() => organization.id),
+ role: text().notNull(),
+ status: text().notNull(),
+ expiresAt: timestamp({ mode: "string" }).notNull(),
+});
// Session table (BetterAuth)
export const session = pgTable(
@@ -235,54 +171,41 @@ export const session = pgTable(
updatedAt: timestamp({ mode: "string" }).notNull(),
ipAddress: text(),
userAgent: text(),
- userId: text().notNull(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
impersonatedBy: text(),
activeOrganizationId: text(),
},
- table => [
- foreignKey({
- columns: [table.userId],
- foreignColumns: [user.id],
- name: "session_userId_user_id_fk",
- }),
- unique("session_token_unique").on(table.token),
- ]
+ table => [unique("session_token_unique").on(table.token)]
);
// API Key table (BetterAuth)
-export const apiKey = pgTable(
- "apikey",
- {
- id: text().primaryKey().notNull(),
- name: text(),
- start: text(),
- prefix: text(),
- key: text().notNull(),
- userId: text().notNull(),
- refillInterval: integer(),
- refillAmount: integer(),
- lastRefillAt: timestamp({ mode: "string" }),
- enabled: boolean().notNull().default(true),
- rateLimitEnabled: boolean().notNull().default(false),
- rateLimitTimeWindow: integer(),
- rateLimitMax: integer(),
- requestCount: integer().notNull().default(0),
- remaining: integer(),
- lastRequest: timestamp({ mode: "string" }),
- expiresAt: timestamp({ mode: "string" }),
- createdAt: timestamp({ mode: "string" }).notNull(),
- updatedAt: timestamp({ mode: "string" }).notNull(),
- permissions: text(),
- metadata: jsonb(),
- },
- table => [
- foreignKey({
- columns: [table.userId],
- foreignColumns: [user.id],
- name: "apiKey_userId_user_id_fk",
- }),
- ]
-);
+export const apiKey = pgTable("apikey", {
+ id: text().primaryKey().notNull(),
+ name: text(),
+ start: text(),
+ prefix: text(),
+ key: text().notNull(),
+ userId: text()
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ refillInterval: integer(),
+ refillAmount: integer(),
+ lastRefillAt: timestamp({ mode: "string" }),
+ enabled: boolean().notNull().default(true),
+ rateLimitEnabled: boolean().notNull().default(false),
+ rateLimitTimeWindow: integer(),
+ rateLimitMax: integer(),
+ requestCount: integer().notNull().default(0),
+ remaining: integer(),
+ lastRequest: timestamp({ mode: "string" }),
+ expiresAt: timestamp({ mode: "string" }),
+ createdAt: timestamp({ mode: "string" }).notNull(),
+ updatedAt: timestamp({ mode: "string" }).notNull(),
+ permissions: text(),
+ metadata: jsonb(),
+});
// Goals table for tracking conversion goals
export const goals = pgTable(
@@ -323,109 +246,92 @@ export const telemetry = pgTable("telemetry", {
});
// Uptime monitor definitions
-export const uptimeMonitors = pgTable(
- "uptime_monitors",
- {
- id: serial("id").primaryKey().notNull(),
- organizationId: text("organization_id")
- .notNull()
- .references(() => organization.id),
- name: text("name"),
- monitorType: text("monitor_type").notNull(), // 'http', 'tcp'
+export const uptimeMonitors = pgTable("uptime_monitors", {
+ id: serial("id").primaryKey().notNull(),
+ organizationId: text("organization_id")
+ .notNull()
+ .references(() => organization.id),
+ name: text("name"),
+ monitorType: text("monitor_type").notNull(), // 'http', 'tcp'
- // Common settings
- intervalSeconds: integer("interval_seconds").notNull(),
- enabled: boolean("enabled").default(true),
+ // Common settings
+ intervalSeconds: integer("interval_seconds").notNull(),
+ enabled: boolean("enabled").default(true),
- // HTTP/HTTPS specific configuration
- httpConfig: jsonb("http_config").$type<{
- url: string;
- method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";
- headers?: Record<string, string>;
- body?: string;
- auth?: {
- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";
- credentials?: {
- username?: string;
- password?: string;
- token?: string;
- headerName?: string;
- headerValue?: string;
- };
+ // HTTP/HTTPS specific configuration
+ httpConfig: jsonb("http_config").$type<{
+ url: string;
+ method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";
+ headers?: Record<string, string>;
+ body?: string;
+ auth?: {
+ type: "none" | "basic" | "bearer" | "api_key" | "custom_header";
+ credentials?: {
+ username?: string;
+ password?: string;
+ token?: string;
+ headerName?: string;
+ headerValue?: string;
};
- followRedirects?: boolean;
- timeoutMs?: number;
- ipVersion?: "any" | "ipv4" | "ipv6";
- userAgent?: string;
- }>(),
-
- // TCP specific configuration
- tcpConfig: jsonb("tcp_config").$type<{
- host: string;
- port: number;
- timeoutMs?: number;
- }>(),
-
- // Validation rules
- validationRules: jsonb("validation_rules").notNull().default([]).$type<
- Array<
- | {
- type: "status_code";
- operator: "equals" | "not_equals" | "in" | "not_in";
- value: number | number[];
- }
- | {
- type: "response_time";
- operator: "less_than" | "greater_than";
- value: number;
- }
- | {
- type: "response_body_contains" | "response_body_not_contains";
- value: string;
- caseSensitive?: boolean;
- }
- | {
- type: "header_exists";
- header: string;
- }
- | {
- type: "header_value";
- header: string;
- operator: "equals" | "contains";
- value: string;
- }
- | {
- type: "response_size";
- operator: "less_than" | "greater_than";
- value: number;
- }
- >
- >(),
-
- // Multi-region configuration
- monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'
- selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),
-
- // Metadata
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- createdBy: text("created_by")
- .notNull()
- .references(() => user.id),
- },
- table => [
- foreignKey({
- columns: [table.organizationId],
- foreignColumns: [organization.id],
- name: "uptime_monitors_organization_id_organization_id_fk",
- }),
- foreignKey({
- columns: [table.createdBy],
- foreignColumns: [user.id],
- name: "uptime_monitors_created_by_user_id_fk",
- }),
- ]
-);
+ };
+ followRedirects?: boolean;
+ timeoutMs?: number;
+ ipVersion?: "any" | "ipv4" | "ipv6";
+ userAgent?: string;
+ }>(),
+
+ // TCP specific configuration
+ tcpConfig: jsonb("tcp_config").$type<{
+ host: string;
+ port: number;
+ timeoutMs?: number;
+ }>(),
+
+ // Validation rules
+ validationRules: jsonb("validation_rules").notNull().default([]).$type<
+ Array<
+ | {
+ type: "status_code";
+ operator: "equals" | "not_equals" | "in" | "not_in";
+ value: number | number[];
+ }
+ | {
+ type: "response_time";
+ operator: "less_than" | "greater_than";
+ value: number;
+ }
+ | {
+ type: "response_body_contains" | "response_body_not_contains";
+ value: string;
+ caseSensitive?: boolean;
+ }
+ | {
+ type: "header_exists";
+ header: string;
+ }
+ | {
+ type: "header_value";
+ header: string;
+ operator: "equals" | "contains";
+ value: string;
+ }
+ | {
+ type: "response_size";
+ operator: "less_than" | "greater_than";
+ value: number;
+ }
+ >
+ >(),
+
+ // Multi-region configuration
+ monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'
+ selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),
+
+ // Metadata
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
+ createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
+});
// Monitor status tracking
export const uptimeMonitorStatus = pgTable(
@@ -527,118 +433,76 @@ export const agentRegions = pgTable("agent_regions", {
});
// Uptime incidents table
-export const uptimeIncidents = pgTable(
- "uptime_incidents",
- {
- id: serial("id").primaryKey().notNull(),
- organizationId: text("organization_id")
- .notNull()
- .references(() => organization.id),
- monitorId: integer("monitor_id")
- .notNull()
- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),
- region: text("region"), // Region where incident occurred
-
- // Incident timing
- startTime: timestamp("start_time", { mode: "string" }).notNull(),
- endTime: timestamp("end_time", { mode: "string" }), // null if ongoing
-
- // Status
- status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'
-
- // Acknowledgement details
- acknowledgedBy: text("acknowledged_by").references(() => user.id),
- acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),
-
- // Resolution details
- resolvedBy: text("resolved_by").references(() => user.id),
- resolvedAt: timestamp("resolved_at", { mode: "string" }),
-
- // Error details
- lastError: text("last_error"),
- lastErrorType: text("last_error_type"),
- failureCount: integer("failure_count").default(1),
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- },
- table => [
- foreignKey({
- columns: [table.organizationId],
- foreignColumns: [organization.id],
- name: "uptime_incidents_organization_id_organization_id_fk",
- }),
- foreignKey({
- columns: [table.monitorId],
- foreignColumns: [uptimeMonitors.id],
- name: "uptime_incidents_monitor_id_uptime_monitors_id_fk",
- }),
- foreignKey({
- columns: [table.acknowledgedBy],
- foreignColumns: [user.id],
- name: "uptime_incidents_acknowledged_by_user_id_fk",
- }),
- foreignKey({
- columns: [table.resolvedBy],
- foreignColumns: [user.id],
- name: "uptime_incidents_resolved_by_user_id_fk",
- }),
- ]
-);
+export const uptimeIncidents = pgTable("uptime_incidents", {
+ id: serial("id").primaryKey().notNull(),
+ organizationId: text("organization_id")
+ .notNull()
+ .references(() => organization.id),
+ monitorId: integer("monitor_id")
+ .notNull()
+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),
+ region: text("region"), // Region where incident occurred
+
+ // Incident timing
+ startTime: timestamp("start_time", { mode: "string" }).notNull(),
+ endTime: timestamp("end_time", { mode: "string" }), // null if ongoing
+
+ // Status
+ status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'
+
+ // Acknowledgement details
+ acknowledgedBy: text("acknowledged_by").references(() => user.id, { onDelete: "set null" }),
+ acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),
+
+ // Resolution details
+ resolvedBy: text("resolved_by").references(() => user.id, { onDelete: "set null" }),
+ resolvedAt: timestamp("resolved_at", { mode: "string" }),
+
+ // Error details
+ lastError: text("last_error"),
+ lastErrorType: text("last_error_type"),
+ failureCount: integer("failure_count").default(1),
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
+});
// Notification channels table
-export const notificationChannels = pgTable(
- "notification_channels",
- {
- id: serial("id").primaryKey().notNull(),
- organizationId: text("organization_id")
- .notNull()
- .references(() => organization.id),
- type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'
- name: text("name").notNull(),
- enabled: boolean("enabled").default(true),
+export const notificationChannels = pgTable("notification_channels", {
+ id: serial("id").primaryKey().notNull(),
+ organizationId: text("organization_id")
+ .notNull()
+ .references(() => organization.id),
+ type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'
+ name: text("name").notNull(),
+ enabled: boolean("enabled").default(true),
- // Channel-specific configuration
- config: jsonb("config").notNull().$type<{
- // Email config
- email?: string;
+ // Channel-specific configuration
+ config: jsonb("config").notNull().$type<{
+ // Email config
+ email?: string;
- // Discord config
- webhookUrl?: string;
+ // Discord config
+ webhookUrl?: string;
- // Slack config
- slackWebhookUrl?: string;
- slackChannel?: string;
+ // Slack config
+ slackWebhookUrl?: string;
+ slackChannel?: string;
- // SMS config (placeholder)
- phoneNumber?: string;
- provider?: string;
- }>(),
+ // SMS config (placeholder)
+ phoneNumber?: string;
+ provider?: string;
+ }>(),
- // Monitor selection and notification settings
- monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors
- triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'
- cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications
- lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),
+ // Monitor selection and notification settings
+ monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors
+ triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'
+ cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications
+ lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- createdBy: text("created_by")
- .notNull()
- .references(() => user.id),
- },
- table => [
- foreignKey({
- columns: [table.organizationId],
- foreignColumns: [organization.id],
- name: "notification_channels_organization_id_organization_id_fk",
- }),
- foreignKey({
- columns: [table.createdBy],
- foreignColumns: [user.id],
- name: "notification_channels_created_by_user_id_fk",
- }),
- ]
-);
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
+ createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
+});
// Google Search Console connections table
export const gscConnections = pgTable("gsc_connections", {