Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/sim/app/api/chat/[identifier]/otp/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ vi.mock('@/lib/messaging/email/mailer', () => ({
}))

vi.mock('@/components/emails', () => ({
getOtpSubject: (label: string) => `Verification code for ${label}`,
renderOTPEmail: mockRenderOTPEmail,
}))

Expand Down
4 changes: 2 additions & 2 deletions apps/sim/app/api/chat/[identifier]/otp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { chat } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, isNull } from 'drizzle-orm'
import type { NextRequest } from 'next/server'
import { renderOTPEmail } from '@/components/emails'
import { getOtpSubject, renderOTPEmail } from '@/components/emails'
import { requestChatEmailOtpContract, verifyChatEmailOtpContract } from '@/lib/api/contracts/chats'
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
import { RateLimiter } from '@/lib/core/rate-limiter'
Expand Down Expand Up @@ -120,7 +120,7 @@ export const POST = withRouteHandler(

const emailResult = await sendEmail({
to: email,
subject: `Verification code for ${deployment.title || 'Chat'}`,
subject: getOtpSubject(deployment.title || 'Chat'),
html: emailHtml,
})

Expand Down
4 changes: 2 additions & 2 deletions apps/sim/app/api/contact/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { renderHelpConfirmationEmail } from '@/components/emails'
import { getRequestConfirmationSubject, renderHelpConfirmationEmail } from '@/components/emails'
import {
getContactTopicLabel,
mapContactTopicToHelpType,
Expand Down Expand Up @@ -168,7 +168,7 @@ ${message}

await sendEmail({
to: [email],
subject: `We've received your message: ${subject}`,
subject: getRequestConfirmationSubject(subject),
html: confirmationHtml,
from: getFromEmailAddress(),
replyTo: `help@${helpInboxDomain}`,
Expand Down
5 changes: 4 additions & 1 deletion apps/sim/app/api/files/public/[token]/otp/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ vi.mock('@/lib/core/security/otp', () => ({
OTP_IP_RATE_LIMIT: { maxTokens: 10, refillRate: 10, refillIntervalMs: 1000 },
OTP_EMAIL_RATE_LIMIT: { maxTokens: 3, refillRate: 3, refillIntervalMs: 1000 },
}))
vi.mock('@/components/emails', () => ({ renderOTPEmail: mockRenderOTPEmail }))
vi.mock('@/components/emails', () => ({
getOtpSubject: (label: string) => `Verification code for ${label}`,
renderOTPEmail: mockRenderOTPEmail,
}))
vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: mockSendEmail }))
vi.mock('@/lib/core/rate-limiter', () => ({
RateLimiter: class {
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/app/api/files/public/[token]/otp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger'
import { normalizeEmail } from '@sim/utils/string'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { renderOTPEmail } from '@/components/emails'
import { getOtpSubject, renderOTPEmail } from '@/components/emails'
import {
requestPublicFileOtpContract,
verifyPublicFileOtpContract,
Expand Down Expand Up @@ -104,7 +104,7 @@ export const POST = withRouteHandler(
const emailHtml = await renderOTPEmail(otp, email, 'email-verification', SHARE_EMAIL_LABEL)
const emailResult = await sendEmail({
to: email,
subject: `Verification code for ${SHARE_EMAIL_LABEL}`,
subject: getOtpSubject(SHARE_EMAIL_LABEL),
Comment thread
cursor[bot] marked this conversation as resolved.
html: emailHtml,
})
if (!emailResult.success) {
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/app/api/help/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { renderHelpConfirmationEmail } from '@/components/emails'
import { getRequestConfirmationSubject, renderHelpConfirmationEmail } from '@/components/emails'
import { helpFormBodySchema } from '@/lib/api/contracts/common'
import { validationErrorResponse } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
Expand Down Expand Up @@ -130,7 +130,7 @@ ${message}

await sendEmail({
to: [email],
subject: `Your ${type} request has been received: ${subject}`,
subject: getRequestConfirmationSubject(subject, type),
html: confirmationHtml,
from: getFromEmailAddress(),
replyTo: getHelpEmailAddress(),
Expand Down
56 changes: 21 additions & 35 deletions apps/sim/components/emails/_styles/base.tokens.test.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,44 @@
/**
* Email styles cannot use CSS variables — clients strip them — so `base.ts`
* hardcodes hex copies of the platform tokens. Nothing else detects it when
* `globals.css`, `tailwind.config.ts`, or the chip chrome moves and the copies
* go stale, which is exactly how they drifted before. This suite is that
* detector.
* hardcodes hex copies of the platform tokens. This suite fails when those
* copies drift from `globals.css`, `tailwind.config.ts`, or the chip chrome.
*
* @vitest-environment node
*/
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { baseStyles, colors, typography } from '@/components/emails/_styles'
import tailwindConfig from '@/tailwind.config'

const APP_ROOT = join(__dirname, '../../..')

const globalsCss = readFileSync(join(APP_ROOT, 'app/_styles/globals.css'), 'utf8')
const tailwindConfig = readFileSync(join(APP_ROOT, 'tailwind.config.ts'), 'utf8')
const chipChrome = readFileSync(
join(APP_ROOT, '../../packages/emcn/src/components/chip/chip-chrome.ts'),
'utf8'
)

const tailwindFontSize = tailwindConfig.theme?.extend?.fontSize as Record<string, string>

/**
* The light-mode `:root` block. Dark mode redefines the same names later in the
* file, and emails are light-only, so the FIRST definition is the one to read.
* Dark mode redefines the same names later in the file and emails are
* light-only, so the FIRST definition is the one to read.
*/
function readCssVar(name: string): string {
const match = globalsCss.match(new RegExp(`--${name}:\\s*([^;]+);`))
const match = globalsCss.match(new RegExp(`(?:^|[^-\\w])--${name}:\\s*([^;]+);`, 'm'))
if (!match) throw new Error(`--${name} not found in globals.css`)
return match[1].trim()
}

function readTailwindFontSize(name: string): string {
const match = tailwindConfig.match(new RegExp(`\\b${name}:\\s*'([^']+)'`))
if (!match) throw new Error(`fontSize.${name} not found in tailwind.config.ts`)
return match[1]
}

/** Every email color token and the platform variable it copies. */
const COLOR_MIRROR: Record<string, string> = {
bgOuter: 'surface-1',
bgCard: 'surface-2',
surfaceSubtle: 'surface-3',
textPrimary: 'text-primary',
textBody: 'text-body',
textSecondary: 'text-secondary',
textMuted: 'text-muted',
textInverse: 'text-inverse',
border: 'border',
Expand All @@ -52,10 +47,7 @@ const COLOR_MIRROR: Record<string, string> = {
footerBg: 'surface-1',
}

/**
* Tokens with no single CSS variable behind them. Each needs a stated reason —
* an entry here is a deliberate exception, not an oversight.
*/
/** Tokens with no single CSS variable behind them, and why. */
const UNMIRRORED_COLORS: Record<string, string> = {
brandTertiary: 'Runtime-conditional on getBrandConfig(); neutral default equals --text-primary.',
}
Expand All @@ -69,30 +61,25 @@ describe('email color tokens mirror globals.css', () => {

it('every color token is either mirrored or has a written exemption', () => {
const accounted = new Set([...Object.keys(COLOR_MIRROR), ...Object.keys(UNMIRRORED_COLORS)])
const unaccounted = Object.keys(colors).filter((key) => !accounted.has(key))
expect(unaccounted).toEqual([])
})

it('exemptions state a reason', () => {
for (const reason of Object.values(UNMIRRORED_COLORS)) {
expect(reason.trim().length).toBeGreaterThan(0)
}
expect(Object.keys(colors).filter((key) => !accounted.has(key))).toEqual([])
})
})

describe('email type scale mirrors tailwind.config.ts', () => {
it.each(['caption', 'base', 'md'])('fontSize.%s matches the Tailwind token', (name) => {
expect(typography.fontSize[name as 'caption' | 'base' | 'md']).toBe(readTailwindFontSize(name))
it.each(['caption', 'small', 'base', 'md'])('fontSize.%s matches the Tailwind token', (name) => {
expect(typography.fontSize[name as keyof typeof typography.fontSize]).toBe(
tailwindFontSize[name]
)
})

it('sm is Tailwind stock 14px — the size text-sm resolves to in chip chrome', () => {
expect(typography.fontSize.sm).toBe('14px')
expect(tailwindFontSize.sm).toBeUndefined()
expect(chipChrome).toContain('text-sm')
})

it('display is deliberately off-scale (no platform headline-numeral token)', () => {
expect(typography.fontSize.display).toBe('24px')
expect(tailwindConfig).not.toContain("'24px'")
it('display is deliberately off-scale — the platform has no headline numeral', () => {
expect(Object.values(tailwindFontSize)).not.toContain(typography.fontSize.display)
})
})

Expand All @@ -106,10 +93,9 @@ describe('email geometry mirrors the platform', () => {
it('the CTA transcribes chipGeometryClass', () => {
const geometry = chipChrome.match(/chipGeometryClass = `([^`]+)`/)?.[1]
expect(geometry).toBeDefined()
expect(geometry).toContain('h-[30px]')
expect(geometry).toContain('rounded-lg')
expect(geometry).toContain('px-2')
expect(geometry).toContain('text-sm')
for (const token of ['h-[30px]', 'rounded-lg', 'px-2', 'text-sm']) {
expect(geometry).toContain(token)
}

expect(baseStyles.button.lineHeight).toBe('30px')
expect(baseStyles.button.borderRadius).toBe('8px')
Expand Down
23 changes: 14 additions & 9 deletions apps/sim/components/emails/_styles/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ function buildColors() {
textPrimary: '#1a1a1a',
/** Body and value text — platform `--text-body` */
textBody: '#434343',
/** De-emphasized text inside a body block — platform `--text-secondary` */
textSecondary: '#525252',
/** Muted text (labels, footer) — platform `--text-muted` */
textMuted: '#7a7a7a',
/** Accent for buttons and links — neutral by default, brand color when whitelabeled */
Expand Down Expand Up @@ -56,17 +58,21 @@ export const typography = {
fontFamily:
"'Season Sans', system-ui, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif",
/**
* Deliberately brand-free, for the plain personal emails — those read as a
* message typed by a person, so they must NOT carry the brand face.
* Deliberately brand-free, for emails that must read as typed by a person
* (the plain founder notes, the agent's thread replies). Carries the same
* non-brand fallbacks as {@link fontFamily} so Android and Linux clients land
* on Roboto rather than a generic sans.
*/
systemFontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
systemFontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
/**
* `caption`/`base`/`md` are Sim's own scale from `tailwind.config.ts`. `sm` is
* Tailwind's stock 14px — not a Sim token, but what `text-sm` resolves to in
* `chipGeometryClass`, so the CTA has to use it.
*/
fontSize: {
caption: '12px',
small: '13px',
sm: '14px',
base: '15px',
/** Email body copy. Larger than the app's 15px `base` — the client default. */
Expand Down Expand Up @@ -104,7 +110,7 @@ export const spacing = {
paragraphGap: 12,
}

/** Shared body-copy ramp. {@link baseStyles.paragraph} and `greeting` differ only in margin. */
/** Shared body-copy ramp. */
const bodyText = {
fontSize: typography.fontSize.md,
lineHeight: typography.lineHeight.body,
Expand All @@ -113,7 +119,7 @@ const bodyText = {
fontFamily: typography.fontFamily,
}

/** Shared box geometry. {@link baseStyles.infoBox} and `errorBox` differ only in fill. */
/** Shared box geometry. */
const boxGeometry = {
padding: '16px 18px',
borderRadius: RADIUS,
Expand Down Expand Up @@ -218,10 +224,9 @@ export const baseStyles = {
},

/**
* The closing fine-print line inside the card (who this was sent to, when it
* fires again). Same ramp as {@link footerText}, but left-aligned — the card
* is left-aligned while the footer's cells are not. Every template spelled
* this out as a spread override; use the token.
* The closing fine-print line inside the card. Same ramp as
* {@link footerText}, but left-aligned — the card is left-aligned while the
* footer's own cells are not.
*/
footnote: {
fontSize: typography.fontSize.caption,
Expand Down
Loading
Loading