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.

Email Variables Fallback (#3593)

Pedro Ladeirae3f961b40e2f
diff --git a/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts b/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts
index 2e6a2abddb..a4efa98b42 100644
--- a/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts
+++ b/apps/web/app/(ee)/api/campaigns/[campaignId]/preview/route.ts
@@ -88,6 +88,7 @@ export const POST = withWorkspace(
variables: {
PartnerName: "Partner",
PartnerEmail: "[email protected]",
+ PartnerLink: "https://acme.com/partner",
},
}),
},
diff --git a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
index 2ffe979841..2f13eb028c 100644
--- a/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
+++ b/apps/web/app/(ee)/api/cron/campaigns/broadcast/route.ts
@@ -154,6 +154,12 @@ export async function POST(req: Request) {
},
select: {
id: true,
+ links: {
+ select: {
+ shortLink: true,
+ },
+ orderBy: { id: "asc" },
+ },
partner: {
select: {
id: true,
@@ -250,6 +256,8 @@ export async function POST(req: Request) {
variables: {
PartnerName: partnerUser.partner.name,
PartnerEmail: partnerUser.partner.email,
+ PartnerLink:
+ partnerUser.enrollment.links?.[0]?.shortLink ?? null,
},
}),
},
diff --git a/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts b/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
index 2a75499ff6..e4d89de812 100644
--- a/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
+++ b/apps/web/lib/api/workflows/execute-send-campaign-workflow.ts
@@ -174,6 +174,8 @@ export const executeSendCampaignWorkflow = async ({
variables: {
PartnerName: partnerUser.partner.name,
PartnerEmail: partnerUser.partner.email,
+ PartnerLink:
+ partnerUser.enrollment.links?.[0]?.shortLink ?? null,
},
}),
},
@@ -209,6 +211,23 @@ export const executeSendCampaignWorkflow = async ({
}
};
+const enrollmentLinksForEmail = {
+ select: { shortLink: true },
+ orderBy: { id: "asc" as const },
+};
+
+const enrollmentLinksForWorkflowStats = {
+ select: {
+ shortLink: true,
+ clicks: true,
+ leads: true,
+ conversions: true,
+ sales: true,
+ saleAmount: true,
+ },
+ orderBy: { id: "asc" as const },
+};
+
const includePartnerUsers = {
partner: {
include: {
@@ -219,6 +238,7 @@ const includePartnerUsers = {
},
},
},
+ links: enrollmentLinksForEmail,
} satisfies Prisma.ProgramEnrollmentInclude;
async function getProgramEnrollments({
@@ -256,7 +276,9 @@ async function getProgramEnrollments({
},
include: {
...includePartnerUsers,
- ...(isPartnerLinkStatsAttribute ? { links: true } : {}),
+ ...(isPartnerLinkStatsAttribute
+ ? { links: enrollmentLinksForWorkflowStats }
+ : {}),
},
});
@@ -267,7 +289,11 @@ async function getProgramEnrollments({
const context: Partial<Record<WorkflowConditionAttribute, number | null>> =
{
...(isPartnerLinkStatsAttribute
- ? aggregatePartnerLinksStats(programEnrollment.links)
+ ? aggregatePartnerLinksStats(
+ programEnrollment.links as unknown as NonNullable<
+ Parameters<typeof aggregatePartnerLinksStats>[0]
+ >,
+ )
: {}),
...(attribute === "totalCommissions"
? {
diff --git a/apps/web/lib/api/workflows/interpolate-email-template.ts b/apps/web/lib/api/workflows/interpolate-email-template.ts
index 733939369c..409941b713 100644
--- a/apps/web/lib/api/workflows/interpolate-email-template.ts
+++ b/apps/web/lib/api/workflows/interpolate-email-template.ts
@@ -1,25 +1,62 @@
import { EmailTemplateVariables } from "@/lib/types";
/**
- * Renders an email template by replacing variable placeholders with actual values.
+ * Escapes a string for safe insertion into HTML text nodes and double-quoted attributes.
+ */
+function escapeHtml(s: string): string {
+ return s
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+}
+
+/**
+ * Renders PartnerLink placeholders: http(s) URLs become a single anchor; otherwise escaped text.
+ */
+function partnerLinkToAnchorOrText(raw: string): string {
+ const trimmed = raw.trim();
+ if (!trimmed) return "";
+
+ try {
+ const u = new URL(trimmed);
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
+ return escapeHtml(trimmed);
+ }
+ return `<a href="${escapeHtml(u.href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(trimmed)}</a>`;
+ } catch {
+ return escapeHtml(trimmed);
+ }
+}
+
+/**
+ * Substitutes campaign email template placeholders after HTML sanitization.
+ *
+ * **Syntax** — Whitespace around names and `|` is optional, e.g. `{{PartnerName}}`,
+ * `{{ PartnerName | Guest }}`.
*
- * Supports Handlebars-style syntax with optional fallback values:
- * - `{{variableName}}` - replaced with the variable value
- * - `{{variableName|fallback}}` - replaced with the variable value, or fallback if variable is null/undefined
+ * **Values**
+ * - Variable present → use its string form.
+ * - Variable null/undefined → use pipe fallback if any, else empty string.
*
- * @param template - The email template string containing variable placeholders
- * @param variables - Object containing variable names and their values to substitute
- * @returns The rendered template with all placeholders replaced by their corresponding values
+ * **Output**
+ * - `PartnerName`, `PartnerEmail`, etc.: HTML-escaped (treat as plain text; no raw HTML).
+ * - `PartnerLink`: valid `http:` / `https:` URL → clickable `<a>`; else escaped text.
+ *
+ * @param text - HTML string containing `{{VariableName}}` or `{{Name | fallback}}`
+ * @param variables - Map of template variable names to values
+ * @returns HTML with placeholders replaced
*
* @example
- * ```
- * const template = "Hello {{PartnerName|Guest}}, welcome to the program!"
- * const variables = { PartnerName: "John" };
- * const result = renderEmailTemplate({ template, variables });
- * // Result: "Hello John, welcome to the program!"
+ * ```ts
+ * interpolateEmailTemplate({
+ * text: "Hello {{PartnerName|Guest}}!",
+ * variables: { PartnerName: "John" },
+ * });
+ * // "Hello John!" (Guest ignored when value present)
* ```
*/
-
export function interpolateEmailTemplate({
text,
variables,
@@ -28,10 +65,14 @@ export function interpolateEmailTemplate({
variables: Partial<EmailTemplateVariables>;
}): string {
return text.replace(
- /{{\s*([\w.]+)(?:\|([^}]+))?\s*}}/g,
+ /{{\s*([\w.]+)\s*(?:\|\s*([^}]*?))?\s*}}/g,
(_, key, fallback) => {
const value = variables[key];
- return value != null ? String(value) : fallback ?? "";
+ const resolved = value != null ? String(value) : fallback?.trim() ?? "";
+ if (key === "PartnerLink") {
+ return partnerLinkToAnchorOrText(resolved);
+ }
+ return escapeHtml(resolved);
},
);
}
diff --git a/apps/web/lib/api/workflows/render-campaign-email-html.ts b/apps/web/lib/api/workflows/render-campaign-email-html.ts
index 6d3ed2e5c0..c70b0d00b6 100644
--- a/apps/web/lib/api/workflows/render-campaign-email-html.ts
+++ b/apps/web/lib/api/workflows/render-campaign-email-html.ts
@@ -26,7 +26,16 @@ export function renderCampaignEmailHTML({
},
}),
Mention.extend({
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ fallback: { default: null },
+ };
+ },
renderHTML({ node }: { node: any }) {
+ const label = node.attrs.fallback
+ ? `{{${node.attrs.id} | ${node.attrs.fallback}}}`
+ : `{{${node.attrs.id}}}`;
return [
"span",
{
@@ -35,11 +44,13 @@ export function renderCampaignEmailHTML({
"data-type": "mention",
"data-id": node.attrs.id,
},
- `{{${node.attrs.id}}}`,
+ label,
];
},
renderText({ node }: { node: any }) {
- return `{{${node.attrs.id}}}`;
+ return node.attrs.fallback
+ ? `{{${node.attrs.id} | ${node.attrs.fallback}}}`
+ : `{{${node.attrs.id}}}`;
},
}).configure({
suggestion: {
diff --git a/apps/web/lib/zod/schemas/campaigns.ts b/apps/web/lib/zod/schemas/campaigns.ts
index c182b6929c..a19d43e693 100644
--- a/apps/web/lib/zod/schemas/campaigns.ts
+++ b/apps/web/lib/zod/schemas/campaigns.ts
@@ -13,6 +13,7 @@ import { WORKFLOW_ATTRIBUTES, workflowConditionSchema } from "./workflows";
export const EMAIL_TEMPLATE_VARIABLES = [
"PartnerName",
"PartnerEmail",
+ "PartnerLink",
] as const;
export const CAMPAIGN_WORKFLOW_ATTRIBUTE_CONFIG: Record<
diff --git a/apps/web/tests/misc/interpolate-email-template.test.ts b/apps/web/tests/misc/interpolate-email-template.test.ts
new file mode 100644
index 0000000000..77332c888e
--- /dev/null
+++ b/apps/web/tests/misc/interpolate-email-template.test.ts
@@ -0,0 +1,69 @@
+import { interpolateEmailTemplate } from "@/lib/api/workflows/interpolate-email-template";
+import { describe, expect, it } from "vitest";
+
+describe("interpolateEmailTemplate", () => {
+ it("replaces a variable with its value", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Hello {{PartnerName}}!",
+ variables: { PartnerName: "John" },
+ }),
+ ).toBe("Hello John!");
+ });
+
+ it("uses fallback when variable is null", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Hello {{PartnerName | Guest}}!",
+ variables: { PartnerName: null },
+ }),
+ ).toBe("Hello Guest!");
+ });
+
+ it("uses value over fallback when value is present", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Hello {{PartnerName | Guest}}!",
+ variables: { PartnerName: "John" },
+ }),
+ ).toBe("Hello John!");
+ });
+
+ it("falls back to empty string when variable is missing and no fallback set", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Hello {{PartnerName}}!",
+ variables: {},
+ }),
+ ).toBe("Hello !");
+ });
+
+ it("renders PartnerLink as a clickable anchor for https URLs", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Your link: {{PartnerLink}}",
+ variables: { PartnerLink: "https://example.com/foo" },
+ }),
+ ).toBe(
+ 'Your link: <a href="https://example.com/foo" target="_blank" rel="noopener noreferrer">https://example.com/foo</a>',
+ );
+ });
+
+ it("renders PartnerLink fallback as plain text when variable is missing", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Link: {{PartnerLink | N/A}}",
+ variables: {},
+ }),
+ ).toBe("Link: N/A");
+ });
+
+ it("HTML-escapes non-link variables to avoid injection", () => {
+ expect(
+ interpolateEmailTemplate({
+ text: "Hi {{PartnerName}}",
+ variables: { PartnerName: "<script>alert(1)</script>" },
+ }),
+ ).toBe("Hi &lt;script&gt;alert(1)&lt;/script&gt;");
+ });
+});
diff --git a/apps/web/ui/messages/messages-panel.tsx b/apps/web/ui/messages/messages-panel.tsx
index 8597ef99ff..c11e13b6eb 100644
--- a/apps/web/ui/messages/messages-panel.tsx
+++ b/apps/web/ui/messages/messages-panel.tsx
@@ -226,7 +226,7 @@ export function MessagesPanel({
? "text-content-inverted prose-invert prose-a:text-content-inverted"
: "text-content-default prose-a:text-content-emphasis",
"prose prose-sm break-words",
- PROSE_STYLES.condensed,
+ PROSE_STYLES.chat,
"prose-a:font-medium prose-a:underline-offset-4",
)}
allowedElements={[
diff --git a/packages/ui/src/rich-text-area/rich-text-provider.tsx b/packages/ui/src/rich-text-area/rich-text-provider.tsx
index 09be26cb11..f39e0cfce1 100644
--- a/packages/ui/src/rich-text-area/rich-text-provider.tsx
+++ b/packages/ui/src/rich-text-area/rich-text-provider.tsx
@@ -21,6 +21,7 @@ import { suggestions } from "./variables";
export const PROSE_STYLES = {
default: "prose-p:my-2 prose-ul:my-2 prose-ol:my-2",
condensed: "prose-p:my-0 prose-ul:my-2 prose-ol:my-2",
+ chat: "prose-p:my-0 prose-ul:my-2 prose-ol:my-2 [&_p+p]:mt-2",
relaxed: "",
} as const;
@@ -189,7 +190,24 @@ export const RichTextProvider = forwardRef<
...(features.includes("variables") && variables
? [
Mention.extend({
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ fallback: {
+ default: null,
+ parseHTML: (element) =>
+ element.getAttribute("data-fallback"),
+ renderHTML: (attrs) =>
+ attrs.fallback
+ ? { "data-fallback": attrs.fallback }
+ : {},
+ },
+ };
+ },
renderHTML({ node }: { node: any }) {
+ const label = node.attrs.fallback
+ ? `{{${node.attrs.id} | ${node.attrs.fallback}}}`
+ : `{{${node.attrs.id}}}`;
return [
"span",
{
@@ -197,12 +215,17 @@ export const RichTextProvider = forwardRef<
"px-1 py-0.5 bg-blue-100 text-blue-700 rounded font-semibold",
"data-type": "mention",
"data-id": node.attrs.id,
+ ...(node.attrs.fallback
+ ? { "data-fallback": node.attrs.fallback }
+ : {}),
},
- `{{${node.attrs.id}}}`,
+ label,
];
},
renderText({ node }: { node: any }) {
- return `{{${node.attrs.id}}}`;
+ return node.attrs.fallback
+ ? `{{${node.attrs.id} | ${node.attrs.fallback}}}`
+ : `{{${node.attrs.id}}}`;
},
}).configure({
suggestion: suggestions(variables),
diff --git a/packages/ui/src/rich-text-area/variables.tsx b/packages/ui/src/rich-text-area/variables.tsx
index d2980803e7..25d75da146 100644
--- a/packages/ui/src/rich-text-area/variables.tsx
+++ b/packages/ui/src/rich-text-area/variables.tsx
@@ -1,7 +1,15 @@
import { cn } from "@dub/utils";
import { computePosition, flip, shift } from "@floating-ui/dom";
import { Editor, posToDOMRect, ReactRenderer } from "@tiptap/react";
-import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
+import { Button } from "../button";
+import { Input } from "../input";
const updatePosition = (editor: Editor, element: HTMLElement) => {
const virtualElement = {
@@ -26,10 +34,21 @@ const updatePosition = (editor: Editor, element: HTMLElement) => {
};
export const suggestions = (variables: string[]) => ({
- items: ({ query }: { query: string }) =>
- variables
- .filter((item) => item.toLowerCase().startsWith(query.toLowerCase()))
- .slice(0, 5),
+ items: ({ query }: { query: string }) => {
+ const q = query.trim().toLowerCase();
+ if (!q) return variables.slice(0, 5);
+ return variables
+ .filter((item) => item.toLowerCase().includes(q))
+ .sort((a, b) => {
+ const al = a.toLowerCase();
+ const bl = b.toLowerCase();
+ const aPrefix = al.startsWith(q) ? 0 : 1;
+ const bPrefix = bl.startsWith(q) ? 0 : 1;
+ if (aPrefix !== bPrefix) return aPrefix - bPrefix;
+ return a.localeCompare(b);
+ })
+ .slice(0, 5);
+ },
render: () => {
let component: any;
@@ -63,13 +82,15 @@ export const suggestions = (variables: string[]) => ({
},
onKeyDown(props: any) {
+ const handled = component.ref?.onKeyDown(props);
+ if (handled) return true;
+
if (props.event.key === "Escape") {
component.destroy();
-
return true;
}
- return component.ref?.onKeyDown(props);
+ return false;
},
onExit() {
@@ -97,6 +118,9 @@ const Menu = forwardRef(
ref,
) => {
const [selectedIndex, setSelectedIndex] = useState(0);
+ const [pendingVar, setPendingVar] = useState<string | null>(null);
+ const [fallback, setFallback] = useState("");
+ const inputRef = useRef<HTMLInputElement>(null);
const upHandler = () => {
setSelectedIndex((selectedIndex + items.length - 1) % items.length);
@@ -106,14 +130,42 @@ const Menu = forwardRef(
setSelectedIndex((selectedIndex + 1) % items.length);
};
- const enterHandler = () => {
- command({ id: items[selectedIndex] });
+ const selectVar = (item: string) => {
+ if (item !== "PartnerName") {
+ command({ id: item, fallback: null });
+ return;
+ }
+ setPendingVar(item);
+ setFallback("");
+ };
+
+ const confirmFallback = () => {
+ if (!pendingVar) return;
+ command({ id: pendingVar, fallback: fallback.trim() || null });
+ };
+
+ const cancelFallback = () => {
+ setPendingVar(null);
+ setFallback("");
};
useEffect(() => setSelectedIndex(0), [items]);
useImperativeHandle(ref, () => ({
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
+ if (pendingVar) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ confirmFallback();
+ return true;
+ }
+ if (event.key === "Escape") {
+ cancelFallback();
+ return true;
+ }
+ return false;
+ }
+
if (event.key === "ArrowUp") {
upHandler();
return true;
@@ -125,14 +177,70 @@ const Menu = forwardRef(
}
if (event.key === "Enter") {
- enterHandler();
- return true;
+ if (
+ items.length > 0 &&
+ selectedIndex >= 0 &&
+ selectedIndex < items.length
+ ) {
+ selectVar(items[selectedIndex]);
+ return true;
+ }
+ return false;
}
return false;
},
}));
+ if (pendingVar) {
+ return (
+ <div className="border-border-subtle flex w-64 flex-col gap-2 rounded-lg border bg-white p-2 shadow-sm">
+ <span className="w-fit rounded bg-blue-100 px-1 py-0.5 font-mono text-xs font-semibold text-blue-700">
+ {pendingVar}
+ </span>
+
+ <div className="flex flex-col gap-1">
+ <Input
+ ref={(el) => {
+ inputRef.current = el;
+ el?.focus();
+ }}
+ value={fallback}
+ onChange={(e) => setFallback(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ confirmFallback();
+ } else if (e.key === "Escape") {
+ cancelFallback();
+ }
+ }}
+ placeholder="Fallback (optional)"
+ className="h-8 rounded-lg"
+ />
+ <p className="text-content-subtle text-xs">
+ Used only if {pendingVar} is missing.
+ </p>
+ </div>
+
+ <div className="flex justify-end gap-1">
+ <Button
+ text="Back"
+ variant="secondary"
+ className="h-7 w-fit rounded-lg px-3 py-2 text-sm"
+ onClick={cancelFallback}
+ />
+ <Button
+ text="Confirm"
+ variant="primary"
+ className="h-7 w-fit rounded-lg px-3 py-2 text-sm"
+ onClick={confirmFallback}
+ />
+ </div>
+ </div>
+ );
+ }
+
return (
<div className="border-border-subtle flex flex-col rounded-lg border bg-white p-1 shadow-sm">
{items.length ? (
@@ -140,7 +248,8 @@ const Menu = forwardRef(
<button
key={index}
type="button"
- onClick={() => command({ id: item })}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => selectVar(item)}
data-selected={selectedIndex === index}
onPointerEnter={() => setSelectedIndex(index)}
className={menuItemClassName}