Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

7.5 KB
Raw Blame
import { workspaceSiteVisitTrackingSettingsFieldSchema } from "@/lib/sitemaps/site-visit-tracking";
import { DEFAULT_REDIRECTS, RESERVED_SLUGS, validSlugRegex } from "@dub/utils";
import { PlanPeriod, StripeConnectMode, WorkspaceRole } from "@prisma/client";
import slugify from "@sindresorhus/slugify";
import * as z from "zod/v4";
import { DomainSchema } from "./domains";
import { googleUserContentUrlSchema, uploadedImageSchema } from "./images";
import { planSchema, roleSchema } from "./misc";
export {
  MAX_TRACKED_SITEMAPS_PER_WORKSPACE,
  siteVisitTrackingSettingsPatchSchema,
  trackedSitemapSchema,
} from "./site-visit-tracking";

export const WorkspaceSchema = z
  .object({
    id: z.string().describe("The unique ID of the workspace."),
    name: z.string().describe("The name of the workspace."),
    slug: z.string().describe("The slug of the workspace."),
    logo: z
      .string()
      .nullable()
      .default(null)
      .describe("The logo of the workspace."),
    inviteCode: z
      .string()
      .nullable()
      .describe("The invite code of the workspace."),
    plan: planSchema,
    planTier: z
      .number()
      .describe("The tier of the workspace's plan.")
      .default(1),
    planPeriod: z
      .enum(PlanPeriod)
      .nullish()
      .describe(
        "Billing cadence for the Stripe subscription (monthly, yearly, quarterly, biweekly), when applicable.",
      ),
    stripeId: z.string().nullable().describe("The Stripe ID of the workspace."),
    trialEndsAt: z
      .date()
      .nullish()
      .describe(
        "When the current Stripe subscription billing trial ends, if applicable.",
      ),
    subscriptionCanceledAt: z
      .date()
      .nullish()
      .describe(
        "When the workspace's subscription was canceled (or set to cancel).",
      ),
    billingCycleEndsAt: z
      .date()
      .nullish()
      .describe(
        "When the current Stripe subscription period ends (derived from Stripe current_period_end).",
      ),
    billingCycleStart: z
      .number()
      .describe(
        "The date and time when the billing cycle starts for the workspace.",
      ),
    paymentFailedAt: z
      .date()
      .nullable()
      .describe("The date and time when the payment failed for the workspace."),
    disabledAt: z
      .date()
      .nullable()
      .describe("The date and time when the workspace was disabled."),
    stripeConnectId: z
      .string()
      .nullable()
      .describe("The Stripe Connect ID of the workspace."),
    stripeConnectMode: z
      .enum(StripeConnectMode)
      .nullish()
      .describe(
        "The Stripe mode the workspace's Stripe account is connected in.",
      ),
    totalLinks: z
      .number()
      .describe("The total number of links in the workspace."),
    usage: z.number().describe("The usage of the workspace."),
    usageLimit: z.number().describe("The usage limit of the workspace."),
    linksUsage: z.number().describe("The links usage of the workspace."),
    linksLimit: z.number().describe("The links limit of the workspace."),
    domainsLimit: z.number().describe("The domains limit of the workspace."),
    tagsLimit: z.number().describe("The tags limit of the workspace."),
    foldersUsage: z.number().describe("The folders usage of the workspace."),
    foldersLimit: z.number().describe("The folders limit of the workspace."),
    usersLimit: z.number().describe("The users limit of the workspace."),
    aiUsage: z.number().describe("The AI usage of the workspace."),
    aiLimit: z.number().describe("The AI limit of the workspace."),
    conversionEnabled: z
      .boolean()
      .describe(
        "Whether the workspace has conversion tracking enabled automatically for new links (d.to/conversions).",
      ),
    dotLinkClaimed: z
      .boolean()
      .describe("Whether the workspace has claimed a free .link domain."),
    createdAt: z
      .date()
      .describe("The date and time when the workspace was created."),
    users: z
      .array(
        z.object({
          role: roleSchema,
          defaultFolderId: z
            .string()
            .nullable()
            .describe(
              "The ID of the default folder for the user in the workspace.",
            ),
        }),
      )
      .describe("The role of the authenticated user in the workspace."),
    domains: z
      .array(
        DomainSchema.pick({
          slug: true,
          primary: true,
          verified: true,
        }),
      )
      .describe("The domains of the workspace."),
    flags: z
      .record(z.string(), z.boolean())
      .optional()
      .describe(
        "The feature flags of the workspace, indicating which features are enabled.",
      ),
    store: z
      .record(z.string(), z.any())
      .nullable()
      .describe("The miscellaneous key-value store of the workspace."),
    siteVisitTrackingSettings: workspaceSiteVisitTrackingSettingsFieldSchema
      .nullable()
      .optional()
      .describe(
        "Site visit tracking: sitemaps, short-link domain slug, and Site Links folder id.",
      ),
    allowedHostnames: z
      .array(z.string())
      .nullable()
      .describe("Specifies hostnames permitted for client-side click tracking.")
      .meta({ example: ["dub.sh"] }),
    ssoEmailDomain: z.string().nullable(),
    ssoEnforcedAt: z.date().nullable(),
  })
  .meta({
    title: "Workspace",
  });

export const createWorkspaceSchema = z.object({
  name: z.string().min(1).max(32),
  slug: z
    .string()
    .min(3, "Slug must be at least 3 characters")
    .max(48, "Slug must be less than 48 characters")
    .transform((v) => slugify(v))
    .refine((v) => validSlugRegex.test(v), { message: "Invalid slug format" })
    .refine((v) => !(RESERVED_SLUGS.includes(v) || DEFAULT_REDIRECTS[v]), {
      message: "Cannot use reserved slugs",
    }),
  logo: z
    .union([uploadedImageSchema, googleUserContentUrlSchema])
    .transform((v) => v || null)
    .nullish(),
  conversionEnabled: z.boolean().optional(),
});

export const notificationTypes = z.enum([
  "linkUsageSummary",
  "domainConfigurationUpdates",
]);

export const WorkspaceSchemaExtended = WorkspaceSchema.extend({
  domains: z.array(
    WorkspaceSchema.shape.domains.element.extend({
      linkRetentionDays: z.number().nullish(),
    }),
  ),
  users: z.array(
    WorkspaceSchema.shape.users.element.extend({
      workspacePreferences: z.record(z.string(), z.any()).nullish(),
    }),
  ),
  publishableKey: z.string().nullable(),
  shopifyStoreId: z.string().nullable(),
});

export const OnboardingUsageSchema = z.object({
  links: z.number(),
  clicks: z.number(),
  conversions: z.boolean(),
});

export const workspaceStoreKeys = z.enum([
  "onboardingUsage", // json
  "conversionsOnboarding", // boolean
  "dotLinkOfferDismissed", // string
  "analyticsSettingsConversionTrackingEnabled", // boolean
  "analyticsSettingsSiteVisitTrackingEnabled", // boolean
  "analyticsSettingsOutboundDomainTrackingEnabled", // boolean
  "analyticsSettingsSelectedStack", // string[]
  "analyticsSettingsConnectionSetupComplete", // boolean
  "analyticsSettingsLeadTrackingSetupComplete", // boolean
  "analyticsSettingsSaleTrackingSetupComplete", // boolean
  "analyticsSettingsInstallationVerified", // { hostname, verifiedAt, user }
]);

export const getWorkspaceUsersQuerySchema = z.object({
  search: z.string().optional(),
  role: z.enum(WorkspaceRole).optional(),
});

export const workspaceUserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().nullish(),
  image: z.string().nullish(),
  role: z.enum(WorkspaceRole),
  isMachine: z.boolean().default(false),
  createdAt: z.date(),
});