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.

4.0 KB
Raw Blame
import type { CreateEmailOptions } from "resend";
import { resend } from "./resend";
import { VARIANT_TO_FROM_MAP } from "./resend/constants";
import { ResendBulkEmailOptions, ResendEmailOptions } from "./resend/types";

// Resend 422s reserved test domains:
// https://resend.com/docs/knowledge-base/what-email-addresses-to-use-for-testing
const RESEND_BLOCKED_DOMAINS = [
  "example.com",
  "example.net",
  "example.org",
  "test.com",
] as const;

const isResendBlockedRecipient = (to: string) => {
  const domain = to.toLowerCase().trim().split("@").at(1);
  if (!domain) return false;

  return RESEND_BLOCKED_DOMAINS.some(
    (blocked) => domain === blocked || domain.endsWith(`.${blocked}`),
  );
};

// Keep batch cardinality so callers can zip Resend IDs by index.
// [email protected] is a Resend test sink (no real inbox).
const rewriteBlockedRecipient = (to: string) => {
  if (!isResendBlockedRecipient(to)) return to;

  const username = to.toLowerCase().trim().split("@").at(0) || "unknown";
  const rewritten = `delivered+${username}@resend.dev`;
  console.info(`Rewriting reserved Resend recipient ${to} → ${rewritten}`);
  return rewritten;
};

const resendEmailForOptions = (
  opts: ResendEmailOptions,
): CreateEmailOptions => {
  const {
    to,
    from,
    variant = "primary",
    bcc,
    replyTo,
    subject,
    text,
    react,
    scheduledAt,
    headers,
    tags,
    unsubscribeUrl,
  } = opts;

  const isPreviewEnv = process.env.VERCEL_ENV === "preview";
  const gitBranch = process.env.VERCEL_GIT_COMMIT_REF;

  // Build base options without rendered outputs (react/text)
  // CreateEmailOptions requires at least one of react or text
  const baseOptions = {
    to: isPreviewEnv ? "[email protected]" : rewriteBlockedRecipient(to),
    from: from || VARIANT_TO_FROM_MAP[variant],
    subject: `${subject}${isPreviewEnv && gitBranch ? ` [${gitBranch}]` : ""}`,
    bcc,
    // if replyTo is set to "[email protected]", don't set replyTo
    // else set it to the value of replyTo or fallback to [email protected]
    ...(replyTo === "noreply" ? {} : { replyTo: replyTo || "[email protected]" }),
    scheduledAt,
    tags,
    ...(variant === "marketing"
      ? {
          headers: {
            ...(headers || {}),
            "List-Unsubscribe":
              unsubscribeUrl || "https://app.dub.co/account/settings",
          },
        }
      : headers && { headers }),
  };

  // Add render options (react or text) - at least one must be present
  if (react) {
    return { ...baseOptions, react };
  }
  if (text) {
    return { ...baseOptions, text };
  }
  // If none of react or text is provided, we need to ensure at least one is present
  // This shouldn't happen in practice, but we'll default to an empty text
  return { ...baseOptions, text: "" };
};

// Send email using Resend (Recommended for production)
export const sendEmailViaResend = async (opts: ResendEmailOptions) => {
  if (!resend) {
    console.info(
      "RESEND_API_KEY is not set in the .env. Skipping sending email.",
    );
    return;
  }

  return await resend.emails.send(resendEmailForOptions(opts));
};

export const sendBatchEmailViaResend = async (
  emails: ResendBulkEmailOptions,
  options?: { idempotencyKey?: string },
) => {
  if (!resend) {
    console.info(
      "RESEND_API_KEY is not set in the .env. Skipping sending email.",
    );

    return {
      data: null,
      error: null,
    };
  }

  if (emails.length === 0) {
    return {
      data: null,
      error: null,
    };
  }

  // Filter out emails without to address
  // and format the emails for Resend
  const filteredBatch = emails.reduce(
    (acc, email) => {
      if (!email?.to) {
        return acc;
      }

      acc.push(resendEmailForOptions(email));

      return acc;
    },
    [] as ReturnType<typeof resendEmailForOptions>[],
  );

  if (filteredBatch.length === 0) {
    return {
      data: null,
      error: null,
    };
  }

  const idempotencyKey = options?.idempotencyKey || undefined;

  return await resend.batch.send(
    filteredBatch,
    idempotencyKey ? { idempotencyKey } : undefined,
  );
};