@digilogiclabs/platform-core 1.20.0 → 1.20.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,6 +62,7 @@ function emailLayout(branding, options) {
62
62
  const preheaderHtml = options.preheader ? `<div style="display:none;font-size:1px;color:#f3f4f6;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;">${escapeHtml(options.preheader)}</div>` : "";
63
63
  const iconHtml = options.icon ? `${options.icon} ` : "";
64
64
  const subtitleHtml = options.subtitle ? `<p style="margin:4px 0 0;color:rgba(255,255,255,0.85);font-size:14px;">${escapeHtml(options.subtitle)}</p>` : "";
65
+ const logoHtml = branding.logoUrl ? `<img src="${escapeHtml(branding.logoUrl)}" alt="${escapeHtml(branding.appName)}" width="56" height="56" style="display:block;margin:0 auto 10px;border:0;outline:none;text-decoration:none;border-radius:10px;background:#ffffff;padding:6px;" />` : "";
65
66
  const ctaHtml = options.cta ? `
66
67
  <tr>
67
68
  <td style="padding:0 32px 24px;text-align:center;">
@@ -88,7 +89,7 @@ function emailLayout(branding, options) {
88
89
  <!-- Header -->
89
90
  <tr>
90
91
  <td style="background:linear-gradient(135deg,${gradientFrom},${gradientTo});padding:28px 32px;text-align:center;">
91
- <h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">${iconHtml}${escapeHtml(branding.appName)}</h1>
92
+ ${logoHtml}<h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">${iconHtml}${escapeHtml(branding.appName)}</h1>
92
93
  ${subtitleHtml}
93
94
  </td>
94
95
  </tr>
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/email-templates/index.ts","../src/security.ts","../src/email-templates/layout.ts","../src/email-templates/templates.ts"],"sourcesContent":["/**\n * Shared email template module.\n *\n * Provides a branding-driven email layout system with pre-built templates\n * and composable HTML building blocks. Zero external dependencies —\n * only uses escapeHtml from platform-core's security module.\n *\n * @example\n * ```ts\n * import {\n * welcomeEmail,\n * digestEmail,\n * emailLayout,\n * calloutBlock,\n * } from \"@digilogiclabs/platform-core/email-templates\";\n *\n * const branding: EmailBranding = {\n * appName: \"MyApp\",\n * primaryColor: \"#667eea\",\n * fromEmail: \"noreply@myapp.com\",\n * baseUrl: \"https://myapp.com\",\n * };\n *\n * const { subject, html, text } = welcomeEmail(branding, {\n * userName: \"Alice\",\n * dashboardUrl: \"https://myapp.com/dashboard\",\n * steps: [\n * { title: \"Set up profile\", description: \"Add your photo and bio\" },\n * { title: \"Explore features\", description: \"Check out what's available\" },\n * ],\n * });\n * ```\n */\n\n// Types\nexport type {\n EmailBranding,\n EmailCTA,\n EmailStep,\n EmailStat,\n EmailTableRow,\n EmailLayoutOptions,\n EmailOutput,\n} from \"./types\";\n\n// Layout engine + building blocks\nexport {\n emailLayout,\n calloutBlock,\n stepBlock,\n statsBar,\n dataTable,\n tipBlock,\n sectionHeading,\n divider,\n escapeHtml,\n} from \"./layout\";\n\n// Pre-built templates\nexport {\n welcomeEmail,\n digestEmail,\n notificationEmail,\n moderationEmail,\n transactionEmail,\n securityEmail,\n} from \"./templates\";\n\n// Template data types\nexport type {\n WelcomeEmailData,\n DigestEmailData,\n NotificationEmailData,\n ModerationEmailData,\n ModerationAction,\n TransactionEmailData,\n SecurityEmailData,\n} from \"./templates\";\n","/**\n * Security Utilities\n *\n * HTML escaping, input detection, sanitization helpers,\n * timing-safe comparison, error sanitization, and request\n * correlation for safe, consistent security across all apps.\n */\n\nimport { timingSafeEqual } from \"crypto\";\n\n/** Regex for protocol-prefixed URLs */\nexport const URL_PROTOCOL_PATTERN = /(https?:\\/\\/|ftp:\\/\\/|www\\.)\\S+/i;\n\n/** Regex for bare domain names with common TLDs */\nexport const URL_DOMAIN_PATTERN =\n /\\b[\\w.-]+\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/i;\n\n/** Regex for HTML tags */\nexport const HTML_TAG_PATTERN = /<[^>]*>/;\n\n/**\n * Escape HTML special characters to prevent injection.\n * Use when inserting user content into HTML email templates or rendered HTML.\n */\nexport function escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/** Check if a string contains protocol-prefixed URLs or bare domains */\nexport function containsUrls(str: string): boolean {\n return URL_PROTOCOL_PATTERN.test(str) || URL_DOMAIN_PATTERN.test(str);\n}\n\n/** Check if a string contains HTML tags */\nexport function containsHtml(str: string): boolean {\n return HTML_TAG_PATTERN.test(str);\n}\n\n/** Strip all HTML tags from a string */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, \"\");\n}\n\n/**\n * Strip null bytes (U+0000) from a string.\n *\n * Postgres rejects null bytes in `text`/`varchar` columns with a hard\n * `invalid byte sequence` error (→ HTTP 500 in app handlers). Apps that\n * forward raw user input — search queries, filter params, form fields —\n * into Drizzle/raw SQL queries hit this on malicious or malformed clients\n * that inject `%00` in URLs.\n *\n * Pass `undefined`/`null` through unchanged so it composes cleanly with\n * optional query params: `stripNullBytes(url.searchParams.get('q'))?.trim()`.\n *\n * @example\n * ```typescript\n * import { stripNullBytes } from '@digilogiclabs/platform-core/auth';\n *\n * const q = stripNullBytes(url.searchParams.get('q'))?.trim();\n * const results = await db.select().where(ilike(column, `%${q}%`));\n * ```\n */\nexport function stripNullBytes(value: string): string;\nexport function stripNullBytes(value: null | undefined): null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined {\n if (value === null || value === undefined) return value;\n return value.replace(/\\u0000/g, \"\");\n}\n\n/**\n * Recursively strip null bytes from all string values in a plain object or\n * array. Non-string values pass through unchanged. Use on parsed JSON\n * request bodies before forwarding to DB queries.\n *\n * Preserves the object's own keys and order; does NOT mutate the input.\n * Arrays stay arrays. Stops at 8 levels deep as a guard against accidental\n * circular references (throws at depth-limit exceeded).\n *\n * @example\n * ```typescript\n * import { stripNullBytesDeep } from '@digilogiclabs/platform-core/auth';\n *\n * const body = stripNullBytesDeep(await request.json());\n * const parsed = schema.safeParse(body);\n * ```\n */\nexport function stripNullBytesDeep<T>(value: T, depth = 8): T {\n if (depth <= 0) {\n throw new Error(\"stripNullBytesDeep: max depth exceeded (circular?)\");\n }\n if (typeof value === \"string\") {\n return value.replace(/\\u0000/g, \"\") as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) => stripNullBytesDeep(v, depth - 1)) as unknown as T;\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = stripNullBytesDeep(v, depth - 1);\n }\n return out as T;\n }\n return value;\n}\n\n/**\n * Defang URLs to prevent auto-linking in email clients.\n * Converts https://evil.com → hxxps://evil[.]com\n */\nexport function defangUrl(str: string): string {\n return str\n .replace(/https:\\/\\//gi, \"hxxps://\")\n .replace(/http:\\/\\//gi, \"hxxp://\")\n .replace(/ftp:\\/\\//gi, \"fxp://\")\n .replace(\n /\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/gi,\n \"[$1]\",\n );\n}\n\n/**\n * Sanitize user content for safe insertion into HTML email templates.\n * Escapes HTML entities AND defangs any URLs that slipped through validation.\n */\nexport function sanitizeForEmail(str: string): string {\n return escapeHtml(str);\n}\n\n// ═══════════════════════════════════════════════════════════════\n// API SECURITY UTILITIES\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Constant-time string comparison to prevent timing side-channel attacks.\n * Use for comparing secrets, tokens, API keys, HMAC signatures, etc.\n *\n * Returns false (not throws) for length mismatches — still constant-time\n * relative to the shorter string to avoid leaking length info.\n *\n * @example\n * ```typescript\n * if (!constantTimeEqual(providedToken, expectedSecret)) {\n * return { status: 401, error: 'Invalid token' }\n * }\n * ```\n */\nexport function constantTimeEqual(a: string, b: string): boolean {\n try {\n const aBuf = Buffer.from(a, \"utf-8\");\n const bBuf = Buffer.from(b, \"utf-8\");\n if (aBuf.length !== bBuf.length) return false;\n return timingSafeEqual(aBuf, bBuf);\n } catch {\n return false;\n }\n}\n\n/**\n * Sanitize an error for client-facing API responses.\n *\n * - 4xx errors: returns the actual message (client needs to know what went wrong)\n * - 5xx errors: returns a generic message (never leak internals to clients)\n * - Development mode: optionally includes stack trace for debugging\n *\n * @example\n * ```typescript\n * catch (error) {\n * const { message, code } = sanitizeApiError(error, 500)\n * return Response.json({ error: message, code }, { status: 500 })\n * }\n * ```\n */\nexport function sanitizeApiError(\n error: unknown,\n statusCode: number,\n isDevelopment = false,\n): { message: string; code?: string; stack?: string } {\n // Client errors — safe to expose the message\n if (statusCode >= 400 && statusCode < 500) {\n const message =\n error instanceof Error ? error.message : String(error || \"Bad request\");\n return { message };\n }\n\n // Server errors — generic message to clients, real error in logs only\n const result: { message: string; code: string; stack?: string } = {\n message: \"An internal error occurred. Please try again later.\",\n code: \"INTERNAL_ERROR\",\n };\n\n if (isDevelopment && error instanceof Error) {\n result.stack = error.stack;\n }\n\n return result;\n}\n\n/**\n * Extract a correlation/request ID from standard headers, or generate one.\n *\n * Checks (in order): X-Request-ID, X-Correlation-ID, then falls back to\n * crypto.randomUUID(). Works with any headers-like object (plain object,\n * Headers API, or a getter function).\n *\n * @example\n * ```typescript\n * // With Next.js request\n * const id = getCorrelationId((name) => request.headers.get(name))\n *\n * // With plain object\n * const id = getCorrelationId({ 'x-request-id': 'abc-123' })\n * ```\n */\nexport function getCorrelationId(\n headers:\n | Record<string, string | string[] | undefined>\n | ((name: string) => string | null | undefined),\n): string {\n const get =\n typeof headers === \"function\"\n ? headers\n : (name: string) => {\n const val = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(val) ? val[0] : val;\n };\n\n return (\n get(\"x-request-id\") ||\n get(\"X-Request-ID\") ||\n get(\"x-correlation-id\") ||\n get(\"X-Correlation-ID\") ||\n crypto.randomUUID()\n );\n}\n","/**\n * Base email layout builder.\n *\n * Generates a fully responsive, email-client-compatible HTML email\n * using only inline styles and table-based layout.\n *\n * Every user-facing string in the layout is pre-escaped. Template functions\n * that accept user input MUST escape those values before passing them to body.\n */\nimport type { EmailBranding, EmailLayoutOptions, EmailOutput } from \"./types\";\nimport { escapeHtml } from \"../security\";\n\nconst FONT_STACK =\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\";\n\n/**\n * Darken a hex color by a percentage (0-100).\n * Used to auto-generate gradientTo from primaryColor.\n */\nfunction darkenHex(hex: string, percent: number): string {\n const num = parseInt(hex.replace(\"#\", \"\"), 16);\n const r = Math.max(0, (num >> 16) - Math.round(2.55 * percent));\n const g = Math.max(0, ((num >> 8) & 0x00ff) - Math.round(2.55 * percent));\n const b = Math.max(0, (num & 0x0000ff) - Math.round(2.55 * percent));\n return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, \"0\")}`;\n}\n\n/**\n * Strip HTML tags for plain-text fallback.\n */\nfunction htmlToText(html: string): string {\n return html\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/p>/gi, \"\\n\\n\")\n .replace(/<\\/div>/gi, \"\\n\")\n .replace(/<\\/tr>/gi, \"\\n\")\n .replace(/<\\/li>/gi, \"\\n\")\n .replace(/<li[^>]*>/gi, \"- \")\n .replace(/<a[^>]*href=\"([^\"]*)\"[^>]*>([^<]*)<\\/a>/gi, \"$2 ($1)\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&rarr;/g, \"→\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\n/**\n * Build a complete HTML email from branding + layout options.\n *\n * Returns `{ subject, html, text }` ready to pass to any IEmail adapter.\n */\nexport function emailLayout(\n branding: EmailBranding,\n options: EmailLayoutOptions,\n): EmailOutput {\n const gradientFrom = branding.gradientFrom ?? branding.primaryColor;\n const gradientTo =\n branding.gradientTo ?? darkenHex(branding.primaryColor, 15);\n const accentColor = branding.accentColor ?? branding.primaryColor;\n\n const preheaderHtml = options.preheader\n ? `<div style=\"display:none;font-size:1px;color:#f3f4f6;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;\">${escapeHtml(options.preheader)}</div>`\n : \"\";\n\n const iconHtml = options.icon ? `${options.icon} ` : \"\";\n\n const subtitleHtml = options.subtitle\n ? `<p style=\"margin:4px 0 0;color:rgba(255,255,255,0.85);font-size:14px;\">${escapeHtml(options.subtitle)}</p>`\n : \"\";\n\n const ctaHtml = options.cta\n ? `\n <tr>\n <td style=\"padding:0 32px 24px;text-align:center;\">\n <a href=\"${escapeHtml(options.cta.url)}\"\n style=\"display:inline-block;padding:12px 28px;background:${accentColor};color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;\">\n ${escapeHtml(options.cta.text)}\n </a>\n </td>\n </tr>`\n : \"\";\n\n const footerLinksHtml =\n options.footerLinks && options.footerLinks.length > 0\n ? options.footerLinks\n .map(\n (link) =>\n `<a href=\"${escapeHtml(link.url)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(link.label)}</a>`,\n )\n .join(\" &middot; \")\n : \"\";\n\n const preferencesHtml = branding.preferencesUrl\n ? `<p style=\"margin:4px 0 0;font-size:12px;color:#9ca3af;\">\n <a href=\"${escapeHtml(branding.preferencesUrl)}\" style=\"color:${accentColor};text-decoration:none;\">Update email preferences</a>\n </p>`\n : \"\";\n\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"><title>${escapeHtml(options.subject)}</title></head>\n<body style=\"margin:0;padding:0;background:#f3f4f6;font-family:${FONT_STACK};\">\n ${preheaderHtml}\n <table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\">\n <tr><td align=\"center\">\n <table width=\"600\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#ffffff;border-radius:8px;overflow:hidden;max-width:600px;\">\n <!-- Header -->\n <tr>\n <td style=\"background:linear-gradient(135deg,${gradientFrom},${gradientTo});padding:28px 32px;text-align:center;\">\n <h1 style=\"margin:0;color:#ffffff;font-size:22px;font-weight:700;\">${iconHtml}${escapeHtml(branding.appName)}</h1>\n ${subtitleHtml}\n </td>\n </tr>\n\n <!-- Body -->\n <tr>\n <td style=\"padding:28px 32px;color:#374151;font-size:15px;line-height:1.6;\">\n ${options.body}\n </td>\n </tr>\n\n ${ctaHtml}\n\n <!-- Footer -->\n <tr>\n <td style=\"padding:16px 32px;background:#f9fafb;text-align:center;border-top:1px solid #e5e7eb;\">\n ${footerLinksHtml ? `<p style=\"margin:0 0 4px;font-size:12px;color:#9ca3af;\">${footerLinksHtml}</p>` : \"\"}\n <p style=\"margin:0;font-size:12px;color:#9ca3af;\">\n ${branding.footerText ? escapeHtml(branding.footerText) + \" &middot; \" : \"\"}\n <a href=\"${escapeHtml(branding.baseUrl)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(branding.appName)}</a>\n </p>\n ${preferencesHtml}\n </td>\n </tr>\n </table>\n </td></tr>\n </table>\n</body>\n</html>`;\n\n const text = `${options.icon ? options.icon + \" \" : \"\"}${options.subject}\\n${\"=\".repeat(40)}\\n\\n${htmlToText(options.body)}${options.cta ? `\\n\\n${options.cta.text}: ${options.cta.url}` : \"\"}\\n\\n---\\n${branding.footerText ? branding.footerText + \"\\n\" : \"\"}${branding.appName} - ${branding.baseUrl}${branding.preferencesUrl ? \"\\nEmail preferences: \" + branding.preferencesUrl : \"\"}`;\n\n return { subject: options.subject, html, text };\n}\n\n// ─── HTML Building Blocks ────────────────────────────────────────────────────\n// These helpers generate safe HTML fragments for use inside template body content.\n// All user-provided values MUST be escaped before calling these.\n\n/** Highlighted callout box with colored left border. */\nexport function calloutBlock(\n content: string,\n color: string = \"#3b82f6\",\n): string {\n return `<div style=\"background:#f9fafb;padding:16px 20px;border-radius:8px;border-left:4px solid ${color};margin:16px 0;\">${content}</div>`;\n}\n\n/** Numbered step card (for onboarding sequences). */\nexport function stepBlock(\n number: number,\n title: string,\n description: string,\n color: string = \"#667eea\",\n): string {\n return `<div style=\"background:#f3f4f6;padding:16px;border-radius:8px;margin-bottom:12px;border-left:4px solid ${color};\">\n <p style=\"margin:0;font-weight:600;color:#111827;\">${number}. ${title}</p>\n <p style=\"margin:8px 0 0;font-size:14px;color:#6b7280;\">${description}</p>\n </div>`;\n}\n\n/** Stats bar — row of metric cards. */\nexport function statsBar(\n stats: { label: string; value: string | number }[],\n): string {\n const cells = stats\n .map(\n (s) =>\n `<span style=\"display:inline-block;margin:0 16px;font-size:14px;color:#374151;\"><strong>${escapeHtml(String(s.value))}</strong> ${escapeHtml(s.label)}</span>`,\n )\n .join(\"\");\n return `<div style=\"padding:12px 0;text-align:center;background:#f0fdf4;border-radius:6px;margin-bottom:16px;\">${cells}</div>`;\n}\n\n/** Simple data table with header row. */\nexport function dataTable(headers: string[], rows: string[][]): string {\n const headerCells = headers\n .map(\n (h) =>\n `<th style=\"padding:8px 12px;text-align:left;font-size:13px;color:#374151;border-bottom:1px solid #e5e7eb;\">${escapeHtml(h)}</th>`,\n )\n .join(\"\");\n\n const bodyRows = rows\n .map(\n (row) =>\n `<tr>${row.map((cell) => `<td style=\"padding:8px 12px;border-bottom:1px solid #e5e7eb;font-size:14px;color:#374151;\">${cell}</td>`).join(\"\")}</tr>`,\n )\n .join(\"\");\n\n return `<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;\">\n <tr style=\"background:#f9fafb;\">${headerCells}</tr>\n ${bodyRows}\n </table>`;\n}\n\n/** Info/tip box with icon. */\nexport function tipBlock(content: string, icon: string = \"💡\"): string {\n return `<div style=\"background:#eff6ff;border:2px solid #3b82f6;padding:16px 20px;border-radius:8px;margin:16px 0;\">\n <p style=\"margin:0;color:#1e40af;font-size:14px;\"><strong>${icon} Pro Tip:</strong> ${content}</p>\n </div>`;\n}\n\n/** Centered heading within email body. */\nexport function sectionHeading(text: string): string {\n return `<h2 style=\"margin:24px 0 12px;font-size:16px;color:#111827;\">${escapeHtml(text)}</h2>`;\n}\n\n/** Horizontal rule divider. */\nexport function divider(): string {\n return `<hr style=\"border:none;border-top:1px solid #e5e7eb;margin:24px 0;\">`;\n}\n\n/** Re-export escapeHtml for template authors. */\nexport { escapeHtml } from \"../security\";\n","/**\n * Pre-built email templates.\n *\n * Each template accepts branding + template-specific data, composes the\n * layout + building blocks, and returns { subject, html, text }.\n *\n * Apps call these directly — no need to touch layout internals.\n * All user-provided strings are escaped internally.\n */\nimport type { EmailBranding, EmailOutput, EmailStep, EmailStat } from \"./types\";\nimport {\n emailLayout,\n calloutBlock,\n stepBlock,\n statsBar,\n dataTable,\n tipBlock,\n sectionHeading,\n divider,\n escapeHtml,\n} from \"./layout\";\n\n// ─── Welcome / Onboarding ────────────────────────────────────────────────────\n\nexport interface WelcomeEmailData {\n /** User's display name */\n userName: string;\n /** URL to their dashboard or profile */\n dashboardUrl: string;\n /** Onboarding steps (typically 3) */\n steps: EmailStep[];\n /** Optional pro-tip text */\n tip?: string;\n}\n\nexport function welcomeEmail(\n branding: EmailBranding,\n data: WelcomeEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const stepsHtml = data.steps\n .map((s, i) =>\n stepBlock(\n i + 1,\n escapeHtml(s.title),\n escapeHtml(s.description),\n branding.accentColor ?? branding.primaryColor,\n ),\n )\n .join(\"\");\n\n const tipHtml = data.tip ? tipBlock(escapeHtml(data.tip)) : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:20px;\">\n Welcome aboard! Your account is all set up and ready to go.\n </p>\n ${sectionHeading(\"Get Started\")}\n ${stepsHtml}\n ${tipHtml}\n `;\n\n return emailLayout(branding, {\n subject: `Welcome to ${branding.appName}!`,\n preheader: `Your ${branding.appName} account is ready`,\n icon: \"🎉\",\n subtitle: \"Welcome aboard\",\n body,\n cta: { text: \"Go to Dashboard\", url: data.dashboardUrl },\n footerLinks: branding.supportEmail\n ? [{ label: \"Get Help\", url: `mailto:${branding.supportEmail}` }]\n : undefined,\n });\n}\n\n// ─── Digest / Summary ────────────────────────────────────────────────────────\n\nexport interface DigestEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Period label (e.g. \"This Week\", \"March 2026\") */\n period: string;\n /** Summary stats shown in the stats bar */\n stats: EmailStat[];\n /** Main body HTML (app-specific content — must be pre-escaped) */\n contentHtml: string;\n /** Optional: URL to view full report */\n reportUrl?: string;\n /** Optional: why they're receiving this */\n subscriptionNote?: string;\n}\n\nexport function digestEmail(\n branding: EmailBranding,\n data: DigestEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safePeriod = escapeHtml(data.period);\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n Here's your ${safePeriod.toLowerCase()} summary:\n </p>\n ${statsBar(data.stats)}\n ${data.contentHtml}\n ${data.subscriptionNote ? `<p style=\"margin-top:20px;font-size:13px;color:#9ca3af;\">${escapeHtml(data.subscriptionNote)}</p>` : \"\"}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName} — ${data.period} Summary`,\n preheader: `Your ${data.period.toLowerCase()} activity on ${branding.appName}`,\n icon: \"📊\",\n subtitle: safePeriod,\n body,\n cta: data.reportUrl\n ? { text: \"View Full Report\", url: data.reportUrl }\n : undefined,\n });\n}\n\n// ─── Notification ────────────────────────────────────────────────────────────\n\nexport interface NotificationEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Notification headline */\n headline: string;\n /** Main message body (HTML-safe — will be escaped) */\n message: string;\n /** Optional highlighted detail block */\n detail?: string;\n /** Optional CTA */\n actionUrl?: string;\n /** Optional CTA label (defaults to \"View Details\") */\n actionText?: string;\n}\n\nexport function notificationEmail(\n branding: EmailBranding,\n data: NotificationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n const safeMessage = escapeHtml(data.message);\n\n const detailHtml = data.detail\n ? calloutBlock(\n escapeHtml(data.detail),\n branding.accentColor ?? branding.primaryColor,\n )\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n <p style=\"font-size:15px;margin-bottom:16px;\">${safeMessage}</p>\n ${detailHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.message.slice(0, 100),\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"View Details\", url: data.actionUrl }\n : undefined,\n });\n}\n\n// ─── Moderation ──────────────────────────────────────────────────────────────\n\nexport type ModerationAction =\n | \"warning\"\n | \"suspension\"\n | \"ban\"\n | \"reinstatement\";\n\nexport interface ModerationEmailData {\n /** User display name */\n userName: string;\n /** Type of moderation action */\n action: ModerationAction;\n /** Reason for the action */\n reason: string;\n /** What the user should do next (optional) */\n nextSteps?: string;\n /** Appeal/support URL (optional) */\n appealUrl?: string;\n}\n\nconst MODERATION_CONFIG: Record<\n ModerationAction,\n { icon: string; color: string; label: string }\n> = {\n warning: { icon: \"⚠️\", color: \"#f59e0b\", label: \"Account Warning\" },\n suspension: { icon: \"🔒\", color: \"#ef4444\", label: \"Account Suspended\" },\n ban: { icon: \"🚫\", color: \"#dc2626\", label: \"Account Banned\" },\n reinstatement: { icon: \"✅\", color: \"#10b981\", label: \"Account Reinstated\" },\n};\n\nexport function moderationEmail(\n branding: EmailBranding,\n data: ModerationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n const config = MODERATION_CONFIG[data.action];\n\n const reasonHtml = calloutBlock(\n `<strong>Reason:</strong> ${escapeHtml(data.reason)}`,\n config.color,\n );\n\n const nextStepsHtml = data.nextSteps\n ? `<p style=\"font-size:15px;margin:16px 0;\">${escapeHtml(data.nextSteps)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${\n data.action === \"reinstatement\"\n ? \"Good news — your account has been reinstated.\"\n : `Your account has received a ${escapeHtml(data.action)}.`\n }\n </p>\n ${reasonHtml}\n ${nextStepsHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${config.label}`,\n preheader: config.label,\n icon: config.icon,\n subtitle: config.label,\n body,\n cta: data.appealUrl\n ? { text: \"Appeal or Contact Support\", url: data.appealUrl }\n : undefined,\n });\n}\n\n// ─── Transaction / Receipt ───────────────────────────────────────────────────\n\nexport interface TransactionEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Transaction headline (e.g. \"Payment Received\", \"Order Confirmed\") */\n headline: string;\n /** Line items: [label, value] pairs */\n lineItems: [string, string][];\n /** Total amount string (e.g. \"$25.00\") */\n total?: string;\n /** Optional message above the table */\n message?: string;\n /** Optional receipt/order URL */\n receiptUrl?: string;\n}\n\nexport function transactionEmail(\n branding: EmailBranding,\n data: TransactionEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n\n const rows = data.lineItems.map(([label, value]) => [\n escapeHtml(label),\n escapeHtml(value),\n ]);\n\n if (data.total) {\n rows.push([\n `<strong>Total</strong>`,\n `<strong>${escapeHtml(data.total)}</strong>`,\n ]);\n }\n\n const messageHtml = data.message\n ? `<p style=\"font-size:15px;margin-bottom:16px;\">${escapeHtml(data.message)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n ${messageHtml}\n ${dataTable([\"Item\", \"Amount\"], rows)}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.headline,\n icon: \"🧾\",\n body,\n cta: data.receiptUrl\n ? { text: \"View Receipt\", url: data.receiptUrl }\n : undefined,\n });\n}\n\n// ─── Security Alert ──────────────────────────────────────────────────────────\n\nexport interface SecurityEmailData {\n /** User display name */\n userName: string;\n /** What happened (e.g. \"Password Changed\", \"New Login Detected\") */\n event: string;\n /** Details about the event */\n details: string;\n /** Optional action URL (e.g. reset password link) */\n actionUrl?: string;\n /** Optional action label */\n actionText?: string;\n /** Expiry note (e.g. \"This link expires in 1 hour\") */\n expiryNote?: string;\n}\n\nexport function securityEmail(\n branding: EmailBranding,\n data: SecurityEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const detailHtml = calloutBlock(escapeHtml(data.details), \"#ef4444\");\n\n const expiryHtml = data.expiryNote\n ? `<p style=\"font-size:13px;color:#9ca3af;margin-top:12px;text-align:center;\">${escapeHtml(data.expiryNote)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${escapeHtml(data.event)}\n </p>\n ${detailHtml}\n ${expiryHtml}\n <p style=\"font-size:14px;color:#6b7280;margin-top:16px;\">\n If you didn't initiate this action, please contact support immediately.\n </p>\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.event}`,\n preheader: data.event,\n icon: \"🔐\",\n subtitle: \"Security Alert\",\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"Take Action\", url: data.actionUrl }\n : undefined,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;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EJ,QAAM,OAAO;AAAA,uDACwC,QAAQ;AAAA,gEACC,YAAY;AAAA,MACtE,WAAW;AAAA,MACX,UAAU,CAAC,QAAQ,QAAQ,GAAG,IAAI,CAAC;AAAA;AAGvC,SAAO,YAAY,UAAU;AAAA,IAC3B,SAAS,GAAG,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,IAC9C,WAAW,KAAK;AAAA,IAChB,MAAM;AAAA,IACN;AAAA,IACA,KAAK,KAAK,aACN,EAAE,MAAM,gBAAgB,KAAK,KAAK,WAAW,IAC7C;AAAA,EACN,CAAC;AACH;AAmBO,SAAS,cACd,UACA,MACa;AACb,QAAM,WAAW,WAAW,KAAK,QAAQ;AAEzC,QAAM,aAAa,aAAa,WAAW,KAAK,OAAO,GAAG,SAAS;AAEnE,QAAM,aAAa,KAAK,aACpB,8EAA8E,WAAW,KAAK,UAAU,CAAC,SACzG;AAEJ,QAAM,OAAO;AAAA,uDACwC,QAAQ;AAAA;AAAA,QAEvD,WAAW,KAAK,KAAK,CAAC;AAAA;AAAA,MAExB,UAAU;AAAA,MACV,UAAU;AAAA;AAAA;AAAA;AAAA;AAMd,SAAO,YAAY,UAAU;AAAA,IAC3B,SAAS,GAAG,SAAS,OAAO,KAAK,KAAK,KAAK;AAAA,IAC3C,WAAW,KAAK;AAAA,IAChB,MAAM;AAAA,IACN,UAAU;AAAA,IACV;AAAA,IACA,KAAK,KAAK,YACN,EAAE,MAAM,KAAK,cAAc,eAAe,KAAK,KAAK,UAAU,IAC9D;AAAA,EACN,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/email-templates/index.ts","../src/security.ts","../src/email-templates/layout.ts","../src/email-templates/templates.ts"],"sourcesContent":["/**\n * Shared email template module.\n *\n * Provides a branding-driven email layout system with pre-built templates\n * and composable HTML building blocks. Zero external dependencies —\n * only uses escapeHtml from platform-core's security module.\n *\n * @example\n * ```ts\n * import {\n * welcomeEmail,\n * digestEmail,\n * emailLayout,\n * calloutBlock,\n * } from \"@digilogiclabs/platform-core/email-templates\";\n *\n * const branding: EmailBranding = {\n * appName: \"MyApp\",\n * primaryColor: \"#667eea\",\n * fromEmail: \"noreply@myapp.com\",\n * baseUrl: \"https://myapp.com\",\n * };\n *\n * const { subject, html, text } = welcomeEmail(branding, {\n * userName: \"Alice\",\n * dashboardUrl: \"https://myapp.com/dashboard\",\n * steps: [\n * { title: \"Set up profile\", description: \"Add your photo and bio\" },\n * { title: \"Explore features\", description: \"Check out what's available\" },\n * ],\n * });\n * ```\n */\n\n// Types\nexport type {\n EmailBranding,\n EmailCTA,\n EmailStep,\n EmailStat,\n EmailTableRow,\n EmailLayoutOptions,\n EmailOutput,\n} from \"./types\";\n\n// Layout engine + building blocks\nexport {\n emailLayout,\n calloutBlock,\n stepBlock,\n statsBar,\n dataTable,\n tipBlock,\n sectionHeading,\n divider,\n escapeHtml,\n} from \"./layout\";\n\n// Pre-built templates\nexport {\n welcomeEmail,\n digestEmail,\n notificationEmail,\n moderationEmail,\n transactionEmail,\n securityEmail,\n} from \"./templates\";\n\n// Template data types\nexport type {\n WelcomeEmailData,\n DigestEmailData,\n NotificationEmailData,\n ModerationEmailData,\n ModerationAction,\n TransactionEmailData,\n SecurityEmailData,\n} from \"./templates\";\n","/**\n * Security Utilities\n *\n * HTML escaping, input detection, sanitization helpers,\n * timing-safe comparison, error sanitization, and request\n * correlation for safe, consistent security across all apps.\n */\n\nimport { timingSafeEqual } from \"crypto\";\n\n/** Regex for protocol-prefixed URLs */\nexport const URL_PROTOCOL_PATTERN = /(https?:\\/\\/|ftp:\\/\\/|www\\.)\\S+/i;\n\n/** Regex for bare domain names with common TLDs */\nexport const URL_DOMAIN_PATTERN =\n /\\b[\\w.-]+\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/i;\n\n/** Regex for HTML tags */\nexport const HTML_TAG_PATTERN = /<[^>]*>/;\n\n/**\n * Escape HTML special characters to prevent injection.\n * Use when inserting user content into HTML email templates or rendered HTML.\n */\nexport function escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/** Check if a string contains protocol-prefixed URLs or bare domains */\nexport function containsUrls(str: string): boolean {\n return URL_PROTOCOL_PATTERN.test(str) || URL_DOMAIN_PATTERN.test(str);\n}\n\n/** Check if a string contains HTML tags */\nexport function containsHtml(str: string): boolean {\n return HTML_TAG_PATTERN.test(str);\n}\n\n/** Strip all HTML tags from a string */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, \"\");\n}\n\n/**\n * Strip null bytes (U+0000) from a string.\n *\n * Postgres rejects null bytes in `text`/`varchar` columns with a hard\n * `invalid byte sequence` error (→ HTTP 500 in app handlers). Apps that\n * forward raw user input — search queries, filter params, form fields —\n * into Drizzle/raw SQL queries hit this on malicious or malformed clients\n * that inject `%00` in URLs.\n *\n * Pass `undefined`/`null` through unchanged so it composes cleanly with\n * optional query params: `stripNullBytes(url.searchParams.get('q'))?.trim()`.\n *\n * @example\n * ```typescript\n * import { stripNullBytes } from '@digilogiclabs/platform-core/auth';\n *\n * const q = stripNullBytes(url.searchParams.get('q'))?.trim();\n * const results = await db.select().where(ilike(column, `%${q}%`));\n * ```\n */\nexport function stripNullBytes(value: string): string;\nexport function stripNullBytes(value: null | undefined): null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined {\n if (value === null || value === undefined) return value;\n return value.replace(/\\u0000/g, \"\");\n}\n\n/**\n * Recursively strip null bytes from all string values in a plain object or\n * array. Non-string values pass through unchanged. Use on parsed JSON\n * request bodies before forwarding to DB queries.\n *\n * Preserves the object's own keys and order; does NOT mutate the input.\n * Arrays stay arrays. Stops at 8 levels deep as a guard against accidental\n * circular references (throws at depth-limit exceeded).\n *\n * @example\n * ```typescript\n * import { stripNullBytesDeep } from '@digilogiclabs/platform-core/auth';\n *\n * const body = stripNullBytesDeep(await request.json());\n * const parsed = schema.safeParse(body);\n * ```\n */\nexport function stripNullBytesDeep<T>(value: T, depth = 8): T {\n if (depth <= 0) {\n throw new Error(\"stripNullBytesDeep: max depth exceeded (circular?)\");\n }\n if (typeof value === \"string\") {\n return value.replace(/\\u0000/g, \"\") as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) => stripNullBytesDeep(v, depth - 1)) as unknown as T;\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = stripNullBytesDeep(v, depth - 1);\n }\n return out as T;\n }\n return value;\n}\n\n/**\n * Defang URLs to prevent auto-linking in email clients.\n * Converts https://evil.com → hxxps://evil[.]com\n */\nexport function defangUrl(str: string): string {\n return str\n .replace(/https:\\/\\//gi, \"hxxps://\")\n .replace(/http:\\/\\//gi, \"hxxp://\")\n .replace(/ftp:\\/\\//gi, \"fxp://\")\n .replace(\n /\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/gi,\n \"[$1]\",\n );\n}\n\n/**\n * Sanitize user content for safe insertion into HTML email templates.\n * Escapes HTML entities AND defangs any URLs that slipped through validation.\n */\nexport function sanitizeForEmail(str: string): string {\n return escapeHtml(str);\n}\n\n// ═══════════════════════════════════════════════════════════════\n// API SECURITY UTILITIES\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Constant-time string comparison to prevent timing side-channel attacks.\n * Use for comparing secrets, tokens, API keys, HMAC signatures, etc.\n *\n * Returns false (not throws) for length mismatches — still constant-time\n * relative to the shorter string to avoid leaking length info.\n *\n * @example\n * ```typescript\n * if (!constantTimeEqual(providedToken, expectedSecret)) {\n * return { status: 401, error: 'Invalid token' }\n * }\n * ```\n */\nexport function constantTimeEqual(a: string, b: string): boolean {\n try {\n const aBuf = Buffer.from(a, \"utf-8\");\n const bBuf = Buffer.from(b, \"utf-8\");\n if (aBuf.length !== bBuf.length) return false;\n return timingSafeEqual(aBuf, bBuf);\n } catch {\n return false;\n }\n}\n\n/**\n * Sanitize an error for client-facing API responses.\n *\n * - 4xx errors: returns the actual message (client needs to know what went wrong)\n * - 5xx errors: returns a generic message (never leak internals to clients)\n * - Development mode: optionally includes stack trace for debugging\n *\n * @example\n * ```typescript\n * catch (error) {\n * const { message, code } = sanitizeApiError(error, 500)\n * return Response.json({ error: message, code }, { status: 500 })\n * }\n * ```\n */\nexport function sanitizeApiError(\n error: unknown,\n statusCode: number,\n isDevelopment = false,\n): { message: string; code?: string; stack?: string } {\n // Client errors — safe to expose the message\n if (statusCode >= 400 && statusCode < 500) {\n const message =\n error instanceof Error ? error.message : String(error || \"Bad request\");\n return { message };\n }\n\n // Server errors — generic message to clients, real error in logs only\n const result: { message: string; code: string; stack?: string } = {\n message: \"An internal error occurred. Please try again later.\",\n code: \"INTERNAL_ERROR\",\n };\n\n if (isDevelopment && error instanceof Error) {\n result.stack = error.stack;\n }\n\n return result;\n}\n\n/**\n * Extract a correlation/request ID from standard headers, or generate one.\n *\n * Checks (in order): X-Request-ID, X-Correlation-ID, then falls back to\n * crypto.randomUUID(). Works with any headers-like object (plain object,\n * Headers API, or a getter function).\n *\n * @example\n * ```typescript\n * // With Next.js request\n * const id = getCorrelationId((name) => request.headers.get(name))\n *\n * // With plain object\n * const id = getCorrelationId({ 'x-request-id': 'abc-123' })\n * ```\n */\nexport function getCorrelationId(\n headers:\n | Record<string, string | string[] | undefined>\n | ((name: string) => string | null | undefined),\n): string {\n const get =\n typeof headers === \"function\"\n ? headers\n : (name: string) => {\n const val = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(val) ? val[0] : val;\n };\n\n return (\n get(\"x-request-id\") ||\n get(\"X-Request-ID\") ||\n get(\"x-correlation-id\") ||\n get(\"X-Correlation-ID\") ||\n crypto.randomUUID()\n );\n}\n","/**\n * Base email layout builder.\n *\n * Generates a fully responsive, email-client-compatible HTML email\n * using only inline styles and table-based layout.\n *\n * Every user-facing string in the layout is pre-escaped. Template functions\n * that accept user input MUST escape those values before passing them to body.\n */\nimport type { EmailBranding, EmailLayoutOptions, EmailOutput } from \"./types\";\nimport { escapeHtml } from \"../security\";\n\nconst FONT_STACK =\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\";\n\n/**\n * Darken a hex color by a percentage (0-100).\n * Used to auto-generate gradientTo from primaryColor.\n */\nfunction darkenHex(hex: string, percent: number): string {\n const num = parseInt(hex.replace(\"#\", \"\"), 16);\n const r = Math.max(0, (num >> 16) - Math.round(2.55 * percent));\n const g = Math.max(0, ((num >> 8) & 0x00ff) - Math.round(2.55 * percent));\n const b = Math.max(0, (num & 0x0000ff) - Math.round(2.55 * percent));\n return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, \"0\")}`;\n}\n\n/**\n * Strip HTML tags for plain-text fallback.\n */\nfunction htmlToText(html: string): string {\n return html\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/p>/gi, \"\\n\\n\")\n .replace(/<\\/div>/gi, \"\\n\")\n .replace(/<\\/tr>/gi, \"\\n\")\n .replace(/<\\/li>/gi, \"\\n\")\n .replace(/<li[^>]*>/gi, \"- \")\n .replace(/<a[^>]*href=\"([^\"]*)\"[^>]*>([^<]*)<\\/a>/gi, \"$2 ($1)\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&rarr;/g, \"→\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\n/**\n * Build a complete HTML email from branding + layout options.\n *\n * Returns `{ subject, html, text }` ready to pass to any IEmail adapter.\n */\nexport function emailLayout(\n branding: EmailBranding,\n options: EmailLayoutOptions,\n): EmailOutput {\n const gradientFrom = branding.gradientFrom ?? branding.primaryColor;\n const gradientTo =\n branding.gradientTo ?? darkenHex(branding.primaryColor, 15);\n const accentColor = branding.accentColor ?? branding.primaryColor;\n\n const preheaderHtml = options.preheader\n ? `<div style=\"display:none;font-size:1px;color:#f3f4f6;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;\">${escapeHtml(options.preheader)}</div>`\n : \"\";\n\n const iconHtml = options.icon ? `${options.icon} ` : \"\";\n\n const subtitleHtml = options.subtitle\n ? `<p style=\"margin:4px 0 0;color:rgba(255,255,255,0.85);font-size:14px;\">${escapeHtml(options.subtitle)}</p>`\n : \"\";\n\n // Logo image — when branding.logoUrl is supplied, render an <img> above\n // the appName text. Email-client-safe attributes only: explicit width,\n // alt text, display:block, border:0. Hosted PNG (or JPG) only — most\n // email clients (Outlook, Gmail's image proxy) do not render SVG.\n const logoHtml = branding.logoUrl\n ? `<img src=\"${escapeHtml(branding.logoUrl)}\" alt=\"${escapeHtml(branding.appName)}\" width=\"56\" height=\"56\" style=\"display:block;margin:0 auto 10px;border:0;outline:none;text-decoration:none;border-radius:10px;background:#ffffff;padding:6px;\" />`\n : \"\";\n\n const ctaHtml = options.cta\n ? `\n <tr>\n <td style=\"padding:0 32px 24px;text-align:center;\">\n <a href=\"${escapeHtml(options.cta.url)}\"\n style=\"display:inline-block;padding:12px 28px;background:${accentColor};color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;\">\n ${escapeHtml(options.cta.text)}\n </a>\n </td>\n </tr>`\n : \"\";\n\n const footerLinksHtml =\n options.footerLinks && options.footerLinks.length > 0\n ? options.footerLinks\n .map(\n (link) =>\n `<a href=\"${escapeHtml(link.url)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(link.label)}</a>`,\n )\n .join(\" &middot; \")\n : \"\";\n\n const preferencesHtml = branding.preferencesUrl\n ? `<p style=\"margin:4px 0 0;font-size:12px;color:#9ca3af;\">\n <a href=\"${escapeHtml(branding.preferencesUrl)}\" style=\"color:${accentColor};text-decoration:none;\">Update email preferences</a>\n </p>`\n : \"\";\n\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"><title>${escapeHtml(options.subject)}</title></head>\n<body style=\"margin:0;padding:0;background:#f3f4f6;font-family:${FONT_STACK};\">\n ${preheaderHtml}\n <table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\">\n <tr><td align=\"center\">\n <table width=\"600\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#ffffff;border-radius:8px;overflow:hidden;max-width:600px;\">\n <!-- Header -->\n <tr>\n <td style=\"background:linear-gradient(135deg,${gradientFrom},${gradientTo});padding:28px 32px;text-align:center;\">\n ${logoHtml}<h1 style=\"margin:0;color:#ffffff;font-size:22px;font-weight:700;\">${iconHtml}${escapeHtml(branding.appName)}</h1>\n ${subtitleHtml}\n </td>\n </tr>\n\n <!-- Body -->\n <tr>\n <td style=\"padding:28px 32px;color:#374151;font-size:15px;line-height:1.6;\">\n ${options.body}\n </td>\n </tr>\n\n ${ctaHtml}\n\n <!-- Footer -->\n <tr>\n <td style=\"padding:16px 32px;background:#f9fafb;text-align:center;border-top:1px solid #e5e7eb;\">\n ${footerLinksHtml ? `<p style=\"margin:0 0 4px;font-size:12px;color:#9ca3af;\">${footerLinksHtml}</p>` : \"\"}\n <p style=\"margin:0;font-size:12px;color:#9ca3af;\">\n ${branding.footerText ? escapeHtml(branding.footerText) + \" &middot; \" : \"\"}\n <a href=\"${escapeHtml(branding.baseUrl)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(branding.appName)}</a>\n </p>\n ${preferencesHtml}\n </td>\n </tr>\n </table>\n </td></tr>\n </table>\n</body>\n</html>`;\n\n const text = `${options.icon ? options.icon + \" \" : \"\"}${options.subject}\\n${\"=\".repeat(40)}\\n\\n${htmlToText(options.body)}${options.cta ? `\\n\\n${options.cta.text}: ${options.cta.url}` : \"\"}\\n\\n---\\n${branding.footerText ? branding.footerText + \"\\n\" : \"\"}${branding.appName} - ${branding.baseUrl}${branding.preferencesUrl ? \"\\nEmail preferences: \" + branding.preferencesUrl : \"\"}`;\n\n return { subject: options.subject, html, text };\n}\n\n// ─── HTML Building Blocks ────────────────────────────────────────────────────\n// These helpers generate safe HTML fragments for use inside template body content.\n// All user-provided values MUST be escaped before calling these.\n\n/** Highlighted callout box with colored left border. */\nexport function calloutBlock(\n content: string,\n color: string = \"#3b82f6\",\n): string {\n return `<div style=\"background:#f9fafb;padding:16px 20px;border-radius:8px;border-left:4px solid ${color};margin:16px 0;\">${content}</div>`;\n}\n\n/** Numbered step card (for onboarding sequences). */\nexport function stepBlock(\n number: number,\n title: string,\n description: string,\n color: string = \"#667eea\",\n): string {\n return `<div style=\"background:#f3f4f6;padding:16px;border-radius:8px;margin-bottom:12px;border-left:4px solid ${color};\">\n <p style=\"margin:0;font-weight:600;color:#111827;\">${number}. ${title}</p>\n <p style=\"margin:8px 0 0;font-size:14px;color:#6b7280;\">${description}</p>\n </div>`;\n}\n\n/** Stats bar — row of metric cards. */\nexport function statsBar(\n stats: { label: string; value: string | number }[],\n): string {\n const cells = stats\n .map(\n (s) =>\n `<span style=\"display:inline-block;margin:0 16px;font-size:14px;color:#374151;\"><strong>${escapeHtml(String(s.value))}</strong> ${escapeHtml(s.label)}</span>`,\n )\n .join(\"\");\n return `<div style=\"padding:12px 0;text-align:center;background:#f0fdf4;border-radius:6px;margin-bottom:16px;\">${cells}</div>`;\n}\n\n/** Simple data table with header row. */\nexport function dataTable(headers: string[], rows: string[][]): string {\n const headerCells = headers\n .map(\n (h) =>\n `<th style=\"padding:8px 12px;text-align:left;font-size:13px;color:#374151;border-bottom:1px solid #e5e7eb;\">${escapeHtml(h)}</th>`,\n )\n .join(\"\");\n\n const bodyRows = rows\n .map(\n (row) =>\n `<tr>${row.map((cell) => `<td style=\"padding:8px 12px;border-bottom:1px solid #e5e7eb;font-size:14px;color:#374151;\">${cell}</td>`).join(\"\")}</tr>`,\n )\n .join(\"\");\n\n return `<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;\">\n <tr style=\"background:#f9fafb;\">${headerCells}</tr>\n ${bodyRows}\n </table>`;\n}\n\n/** Info/tip box with icon. */\nexport function tipBlock(content: string, icon: string = \"💡\"): string {\n return `<div style=\"background:#eff6ff;border:2px solid #3b82f6;padding:16px 20px;border-radius:8px;margin:16px 0;\">\n <p style=\"margin:0;color:#1e40af;font-size:14px;\"><strong>${icon} Pro Tip:</strong> ${content}</p>\n </div>`;\n}\n\n/** Centered heading within email body. */\nexport function sectionHeading(text: string): string {\n return `<h2 style=\"margin:24px 0 12px;font-size:16px;color:#111827;\">${escapeHtml(text)}</h2>`;\n}\n\n/** Horizontal rule divider. */\nexport function divider(): string {\n return `<hr style=\"border:none;border-top:1px solid #e5e7eb;margin:24px 0;\">`;\n}\n\n/** Re-export escapeHtml for template authors. */\nexport { escapeHtml } from \"../security\";\n","/**\n * Pre-built email templates.\n *\n * Each template accepts branding + template-specific data, composes the\n * layout + building blocks, and returns { subject, html, text }.\n *\n * Apps call these directly — no need to touch layout internals.\n * All user-provided strings are escaped internally.\n */\nimport type { EmailBranding, EmailOutput, EmailStep, EmailStat } from \"./types\";\nimport {\n emailLayout,\n calloutBlock,\n stepBlock,\n statsBar,\n dataTable,\n tipBlock,\n sectionHeading,\n divider,\n escapeHtml,\n} from \"./layout\";\n\n// ─── Welcome / Onboarding ────────────────────────────────────────────────────\n\nexport interface WelcomeEmailData {\n /** User's display name */\n userName: string;\n /** URL to their dashboard or profile */\n dashboardUrl: string;\n /** Onboarding steps (typically 3) */\n steps: EmailStep[];\n /** Optional pro-tip text */\n tip?: string;\n}\n\nexport function welcomeEmail(\n branding: EmailBranding,\n data: WelcomeEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const stepsHtml = data.steps\n .map((s, i) =>\n stepBlock(\n i + 1,\n escapeHtml(s.title),\n escapeHtml(s.description),\n branding.accentColor ?? branding.primaryColor,\n ),\n )\n .join(\"\");\n\n const tipHtml = data.tip ? tipBlock(escapeHtml(data.tip)) : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:20px;\">\n Welcome aboard! Your account is all set up and ready to go.\n </p>\n ${sectionHeading(\"Get Started\")}\n ${stepsHtml}\n ${tipHtml}\n `;\n\n return emailLayout(branding, {\n subject: `Welcome to ${branding.appName}!`,\n preheader: `Your ${branding.appName} account is ready`,\n icon: \"🎉\",\n subtitle: \"Welcome aboard\",\n body,\n cta: { text: \"Go to Dashboard\", url: data.dashboardUrl },\n footerLinks: branding.supportEmail\n ? [{ label: \"Get Help\", url: `mailto:${branding.supportEmail}` }]\n : undefined,\n });\n}\n\n// ─── Digest / Summary ────────────────────────────────────────────────────────\n\nexport interface DigestEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Period label (e.g. \"This Week\", \"March 2026\") */\n period: string;\n /** Summary stats shown in the stats bar */\n stats: EmailStat[];\n /** Main body HTML (app-specific content — must be pre-escaped) */\n contentHtml: string;\n /** Optional: URL to view full report */\n reportUrl?: string;\n /** Optional: why they're receiving this */\n subscriptionNote?: string;\n}\n\nexport function digestEmail(\n branding: EmailBranding,\n data: DigestEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safePeriod = escapeHtml(data.period);\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n Here's your ${safePeriod.toLowerCase()} summary:\n </p>\n ${statsBar(data.stats)}\n ${data.contentHtml}\n ${data.subscriptionNote ? `<p style=\"margin-top:20px;font-size:13px;color:#9ca3af;\">${escapeHtml(data.subscriptionNote)}</p>` : \"\"}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName} — ${data.period} Summary`,\n preheader: `Your ${data.period.toLowerCase()} activity on ${branding.appName}`,\n icon: \"📊\",\n subtitle: safePeriod,\n body,\n cta: data.reportUrl\n ? { text: \"View Full Report\", url: data.reportUrl }\n : undefined,\n });\n}\n\n// ─── Notification ────────────────────────────────────────────────────────────\n\nexport interface NotificationEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Notification headline */\n headline: string;\n /** Main message body (HTML-safe — will be escaped) */\n message: string;\n /** Optional highlighted detail block */\n detail?: string;\n /** Optional CTA */\n actionUrl?: string;\n /** Optional CTA label (defaults to \"View Details\") */\n actionText?: string;\n}\n\nexport function notificationEmail(\n branding: EmailBranding,\n data: NotificationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n const safeMessage = escapeHtml(data.message);\n\n const detailHtml = data.detail\n ? calloutBlock(\n escapeHtml(data.detail),\n branding.accentColor ?? branding.primaryColor,\n )\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n <p style=\"font-size:15px;margin-bottom:16px;\">${safeMessage}</p>\n ${detailHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.message.slice(0, 100),\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"View Details\", url: data.actionUrl }\n : undefined,\n });\n}\n\n// ─── Moderation ──────────────────────────────────────────────────────────────\n\nexport type ModerationAction =\n | \"warning\"\n | \"suspension\"\n | \"ban\"\n | \"reinstatement\";\n\nexport interface ModerationEmailData {\n /** User display name */\n userName: string;\n /** Type of moderation action */\n action: ModerationAction;\n /** Reason for the action */\n reason: string;\n /** What the user should do next (optional) */\n nextSteps?: string;\n /** Appeal/support URL (optional) */\n appealUrl?: string;\n}\n\nconst MODERATION_CONFIG: Record<\n ModerationAction,\n { icon: string; color: string; label: string }\n> = {\n warning: { icon: \"⚠️\", color: \"#f59e0b\", label: \"Account Warning\" },\n suspension: { icon: \"🔒\", color: \"#ef4444\", label: \"Account Suspended\" },\n ban: { icon: \"🚫\", color: \"#dc2626\", label: \"Account Banned\" },\n reinstatement: { icon: \"✅\", color: \"#10b981\", label: \"Account Reinstated\" },\n};\n\nexport function moderationEmail(\n branding: EmailBranding,\n data: ModerationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n const config = MODERATION_CONFIG[data.action];\n\n const reasonHtml = calloutBlock(\n `<strong>Reason:</strong> ${escapeHtml(data.reason)}`,\n config.color,\n );\n\n const nextStepsHtml = data.nextSteps\n ? `<p style=\"font-size:15px;margin:16px 0;\">${escapeHtml(data.nextSteps)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${\n data.action === \"reinstatement\"\n ? \"Good news — your account has been reinstated.\"\n : `Your account has received a ${escapeHtml(data.action)}.`\n }\n </p>\n ${reasonHtml}\n ${nextStepsHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${config.label}`,\n preheader: config.label,\n icon: config.icon,\n subtitle: config.label,\n body,\n cta: data.appealUrl\n ? { text: \"Appeal or Contact Support\", url: data.appealUrl }\n : undefined,\n });\n}\n\n// ─── Transaction / Receipt ───────────────────────────────────────────────────\n\nexport interface TransactionEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Transaction headline (e.g. \"Payment Received\", \"Order Confirmed\") */\n headline: string;\n /** Line items: [label, value] pairs */\n lineItems: [string, string][];\n /** Total amount string (e.g. \"$25.00\") */\n total?: string;\n /** Optional message above the table */\n message?: string;\n /** Optional receipt/order URL */\n receiptUrl?: string;\n}\n\nexport function transactionEmail(\n branding: EmailBranding,\n data: TransactionEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n\n const rows = data.lineItems.map(([label, value]) => [\n escapeHtml(label),\n escapeHtml(value),\n ]);\n\n if (data.total) {\n rows.push([\n `<strong>Total</strong>`,\n `<strong>${escapeHtml(data.total)}</strong>`,\n ]);\n }\n\n const messageHtml = data.message\n ? `<p style=\"font-size:15px;margin-bottom:16px;\">${escapeHtml(data.message)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n ${messageHtml}\n ${dataTable([\"Item\", \"Amount\"], rows)}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.headline,\n icon: \"🧾\",\n body,\n cta: data.receiptUrl\n ? { text: \"View Receipt\", url: data.receiptUrl }\n : undefined,\n });\n}\n\n// ─── Security Alert ──────────────────────────────────────────────────────────\n\nexport interface SecurityEmailData {\n /** User display name */\n userName: string;\n /** What happened (e.g. \"Password Changed\", \"New Login Detected\") */\n event: string;\n /** Details about the event */\n details: string;\n /** Optional action URL (e.g. reset password link) */\n actionUrl?: string;\n /** Optional action label */\n actionText?: string;\n /** Expiry note (e.g. \"This link expires in 1 hour\") */\n expiryNote?: string;\n}\n\nexport function securityEmail(\n branding: EmailBranding,\n data: SecurityEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const detailHtml = calloutBlock(escapeHtml(data.details), \"#ef4444\");\n\n const expiryHtml = data.expiryNote\n ? `<p style=\"font-size:13px;color:#9ca3af;margin-top:12px;text-align:center;\">${escapeHtml(data.expiryNote)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${escapeHtml(data.event)}\n </p>\n ${detailHtml}\n ${expiryHtml}\n <p style=\"font-size:14px;color:#6b7280;margin-top:16px;\">\n If you didn't initiate this action, please contact support immediately.\n </p>\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.event}`,\n preheader: data.event,\n icon: \"🔐\",\n subtitle: \"Security Alert\",\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"Take Action\", url: data.actionUrl }\n : undefined,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,WAAW,KAAqB;AAC9C,SAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ;AAC3B;;;ACnBA,IAAM,aACJ;AAMF,SAAS,UAAU,KAAa,SAAyB;AACvD,QAAM,MAAM,SAAS,IAAI,QAAQ,KAAK,EAAE,GAAG,EAAE;AAC7C,QAAM,IAAI,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,MAAM,OAAO,OAAO,CAAC;AAC9D,QAAM,IAAI,KAAK,IAAI,IAAK,OAAO,IAAK,OAAU,KAAK,MAAM,OAAO,OAAO,CAAC;AACxE,QAAM,IAAI,KAAK,IAAI,IAAI,MAAM,OAAY,KAAK,MAAM,OAAO,OAAO,CAAC;AACnE,SAAO,KAAM,KAAK,KAAO,KAAK,IAAK,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AACrE;AAKA,SAAS,WAAW,MAAsB;AACxC,SAAO,KACJ,QAAQ,gBAAgB,IAAI,EAC5B,QAAQ,WAAW,MAAM,EACzB,QAAQ,aAAa,IAAI,EACzB,QAAQ,YAAY,IAAI,EACxB,QAAQ,YAAY,IAAI,EACxB,QAAQ,eAAe,IAAI,EAC3B,QAAQ,6CAA6C,SAAS,EAC9D,QAAQ,YAAY,EAAE,EACtB,QAAQ,WAAW,GAAG,EACtB,QAAQ,UAAU,GAAG,EACrB,QA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AAM;AAAA,IACN,UAAU;AAAA,IACV;AAAA,IACA,KAAK,KAAK,YACN,EAAE,MAAM,KAAK,cAAc,eAAe,KAAK,KAAK,UAAU,IAC9D;AAAA,EACN,CAAC;AACH;","names":[]}
@@ -22,6 +22,7 @@ function emailLayout(branding, options) {
22
22
  const preheaderHtml = options.preheader ? `<div style="display:none;font-size:1px;color:#f3f4f6;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;">${escapeHtml(options.preheader)}</div>` : "";
23
23
  const iconHtml = options.icon ? `${options.icon} ` : "";
24
24
  const subtitleHtml = options.subtitle ? `<p style="margin:4px 0 0;color:rgba(255,255,255,0.85);font-size:14px;">${escapeHtml(options.subtitle)}</p>` : "";
25
+ const logoHtml = branding.logoUrl ? `<img src="${escapeHtml(branding.logoUrl)}" alt="${escapeHtml(branding.appName)}" width="56" height="56" style="display:block;margin:0 auto 10px;border:0;outline:none;text-decoration:none;border-radius:10px;background:#ffffff;padding:6px;" />` : "";
25
26
  const ctaHtml = options.cta ? `
26
27
  <tr>
27
28
  <td style="padding:0 32px 24px;text-align:center;">
@@ -48,7 +49,7 @@ function emailLayout(branding, options) {
48
49
  <!-- Header -->
49
50
  <tr>
50
51
  <td style="background:linear-gradient(135deg,${gradientFrom},${gradientTo});padding:28px 32px;text-align:center;">
51
- <h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">${iconHtml}${escapeHtml(branding.appName)}</h1>
52
+ ${logoHtml}<h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">${iconHtml}${escapeHtml(branding.appName)}</h1>
52
53
  ${subtitleHtml}
53
54
  </td>
54
55
  </tr>
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/security.ts","../src/email-templates/layout.ts","../src/email-templates/templates.ts"],"sourcesContent":["/**\n * Security Utilities\n *\n * HTML escaping, input detection, sanitization helpers,\n * timing-safe comparison, error sanitization, and request\n * correlation for safe, consistent security across all apps.\n */\n\nimport { timingSafeEqual } from \"crypto\";\n\n/** Regex for protocol-prefixed URLs */\nexport const URL_PROTOCOL_PATTERN = /(https?:\\/\\/|ftp:\\/\\/|www\\.)\\S+/i;\n\n/** Regex for bare domain names with common TLDs */\nexport const URL_DOMAIN_PATTERN =\n /\\b[\\w.-]+\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/i;\n\n/** Regex for HTML tags */\nexport const HTML_TAG_PATTERN = /<[^>]*>/;\n\n/**\n * Escape HTML special characters to prevent injection.\n * Use when inserting user content into HTML email templates or rendered HTML.\n */\nexport function escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/** Check if a string contains protocol-prefixed URLs or bare domains */\nexport function containsUrls(str: string): boolean {\n return URL_PROTOCOL_PATTERN.test(str) || URL_DOMAIN_PATTERN.test(str);\n}\n\n/** Check if a string contains HTML tags */\nexport function containsHtml(str: string): boolean {\n return HTML_TAG_PATTERN.test(str);\n}\n\n/** Strip all HTML tags from a string */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, \"\");\n}\n\n/**\n * Strip null bytes (U+0000) from a string.\n *\n * Postgres rejects null bytes in `text`/`varchar` columns with a hard\n * `invalid byte sequence` error (→ HTTP 500 in app handlers). Apps that\n * forward raw user input — search queries, filter params, form fields —\n * into Drizzle/raw SQL queries hit this on malicious or malformed clients\n * that inject `%00` in URLs.\n *\n * Pass `undefined`/`null` through unchanged so it composes cleanly with\n * optional query params: `stripNullBytes(url.searchParams.get('q'))?.trim()`.\n *\n * @example\n * ```typescript\n * import { stripNullBytes } from '@digilogiclabs/platform-core/auth';\n *\n * const q = stripNullBytes(url.searchParams.get('q'))?.trim();\n * const results = await db.select().where(ilike(column, `%${q}%`));\n * ```\n */\nexport function stripNullBytes(value: string): string;\nexport function stripNullBytes(value: null | undefined): null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined {\n if (value === null || value === undefined) return value;\n return value.replace(/\\u0000/g, \"\");\n}\n\n/**\n * Recursively strip null bytes from all string values in a plain object or\n * array. Non-string values pass through unchanged. Use on parsed JSON\n * request bodies before forwarding to DB queries.\n *\n * Preserves the object's own keys and order; does NOT mutate the input.\n * Arrays stay arrays. Stops at 8 levels deep as a guard against accidental\n * circular references (throws at depth-limit exceeded).\n *\n * @example\n * ```typescript\n * import { stripNullBytesDeep } from '@digilogiclabs/platform-core/auth';\n *\n * const body = stripNullBytesDeep(await request.json());\n * const parsed = schema.safeParse(body);\n * ```\n */\nexport function stripNullBytesDeep<T>(value: T, depth = 8): T {\n if (depth <= 0) {\n throw new Error(\"stripNullBytesDeep: max depth exceeded (circular?)\");\n }\n if (typeof value === \"string\") {\n return value.replace(/\\u0000/g, \"\") as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) => stripNullBytesDeep(v, depth - 1)) as unknown as T;\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = stripNullBytesDeep(v, depth - 1);\n }\n return out as T;\n }\n return value;\n}\n\n/**\n * Defang URLs to prevent auto-linking in email clients.\n * Converts https://evil.com → hxxps://evil[.]com\n */\nexport function defangUrl(str: string): string {\n return str\n .replace(/https:\\/\\//gi, \"hxxps://\")\n .replace(/http:\\/\\//gi, \"hxxp://\")\n .replace(/ftp:\\/\\//gi, \"fxp://\")\n .replace(\n /\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/gi,\n \"[$1]\",\n );\n}\n\n/**\n * Sanitize user content for safe insertion into HTML email templates.\n * Escapes HTML entities AND defangs any URLs that slipped through validation.\n */\nexport function sanitizeForEmail(str: string): string {\n return escapeHtml(str);\n}\n\n// ═══════════════════════════════════════════════════════════════\n// API SECURITY UTILITIES\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Constant-time string comparison to prevent timing side-channel attacks.\n * Use for comparing secrets, tokens, API keys, HMAC signatures, etc.\n *\n * Returns false (not throws) for length mismatches — still constant-time\n * relative to the shorter string to avoid leaking length info.\n *\n * @example\n * ```typescript\n * if (!constantTimeEqual(providedToken, expectedSecret)) {\n * return { status: 401, error: 'Invalid token' }\n * }\n * ```\n */\nexport function constantTimeEqual(a: string, b: string): boolean {\n try {\n const aBuf = Buffer.from(a, \"utf-8\");\n const bBuf = Buffer.from(b, \"utf-8\");\n if (aBuf.length !== bBuf.length) return false;\n return timingSafeEqual(aBuf, bBuf);\n } catch {\n return false;\n }\n}\n\n/**\n * Sanitize an error for client-facing API responses.\n *\n * - 4xx errors: returns the actual message (client needs to know what went wrong)\n * - 5xx errors: returns a generic message (never leak internals to clients)\n * - Development mode: optionally includes stack trace for debugging\n *\n * @example\n * ```typescript\n * catch (error) {\n * const { message, code } = sanitizeApiError(error, 500)\n * return Response.json({ error: message, code }, { status: 500 })\n * }\n * ```\n */\nexport function sanitizeApiError(\n error: unknown,\n statusCode: number,\n isDevelopment = false,\n): { message: string; code?: string; stack?: string } {\n // Client errors — safe to expose the message\n if (statusCode >= 400 && statusCode < 500) {\n const message =\n error instanceof Error ? error.message : String(error || \"Bad request\");\n return { message };\n }\n\n // Server errors — generic message to clients, real error in logs only\n const result: { message: string; code: string; stack?: string } = {\n message: \"An internal error occurred. Please try again later.\",\n code: \"INTERNAL_ERROR\",\n };\n\n if (isDevelopment && error instanceof Error) {\n result.stack = error.stack;\n }\n\n return result;\n}\n\n/**\n * Extract a correlation/request ID from standard headers, or generate one.\n *\n * Checks (in order): X-Request-ID, X-Correlation-ID, then falls back to\n * crypto.randomUUID(). Works with any headers-like object (plain object,\n * Headers API, or a getter function).\n *\n * @example\n * ```typescript\n * // With Next.js request\n * const id = getCorrelationId((name) => request.headers.get(name))\n *\n * // With plain object\n * const id = getCorrelationId({ 'x-request-id': 'abc-123' })\n * ```\n */\nexport function getCorrelationId(\n headers:\n | Record<string, string | string[] | undefined>\n | ((name: string) => string | null | undefined),\n): string {\n const get =\n typeof headers === \"function\"\n ? headers\n : (name: string) => {\n const val = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(val) ? val[0] : val;\n };\n\n return (\n get(\"x-request-id\") ||\n get(\"X-Request-ID\") ||\n get(\"x-correlation-id\") ||\n get(\"X-Correlation-ID\") ||\n crypto.randomUUID()\n );\n}\n","/**\n * Base email layout builder.\n *\n * Generates a fully responsive, email-client-compatible HTML email\n * using only inline styles and table-based layout.\n *\n * Every user-facing string in the layout is pre-escaped. Template functions\n * that accept user input MUST escape those values before passing them to body.\n */\nimport type { EmailBranding, EmailLayoutOptions, EmailOutput } from \"./types\";\nimport { escapeHtml } from \"../security\";\n\nconst FONT_STACK =\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\";\n\n/**\n * Darken a hex color by a percentage (0-100).\n * Used to auto-generate gradientTo from primaryColor.\n */\nfunction darkenHex(hex: string, percent: number): string {\n const num = parseInt(hex.replace(\"#\", \"\"), 16);\n const r = Math.max(0, (num >> 16) - Math.round(2.55 * percent));\n const g = Math.max(0, ((num >> 8) & 0x00ff) - Math.round(2.55 * percent));\n const b = Math.max(0, (num & 0x0000ff) - Math.round(2.55 * percent));\n return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, \"0\")}`;\n}\n\n/**\n * Strip HTML tags for plain-text fallback.\n */\nfunction htmlToText(html: string): string {\n return html\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/p>/gi, \"\\n\\n\")\n .replace(/<\\/div>/gi, \"\\n\")\n .replace(/<\\/tr>/gi, \"\\n\")\n .replace(/<\\/li>/gi, \"\\n\")\n .replace(/<li[^>]*>/gi, \"- \")\n .replace(/<a[^>]*href=\"([^\"]*)\"[^>]*>([^<]*)<\\/a>/gi, \"$2 ($1)\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&rarr;/g, \"→\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\n/**\n * Build a complete HTML email from branding + layout options.\n *\n * Returns `{ subject, html, text }` ready to pass to any IEmail adapter.\n */\nexport function emailLayout(\n branding: EmailBranding,\n options: EmailLayoutOptions,\n): EmailOutput {\n const gradientFrom = branding.gradientFrom ?? branding.primaryColor;\n const gradientTo =\n branding.gradientTo ?? darkenHex(branding.primaryColor, 15);\n const accentColor = branding.accentColor ?? branding.primaryColor;\n\n const preheaderHtml = options.preheader\n ? `<div style=\"display:none;font-size:1px;color:#f3f4f6;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;\">${escapeHtml(options.preheader)}</div>`\n : \"\";\n\n const iconHtml = options.icon ? `${options.icon} ` : \"\";\n\n const subtitleHtml = options.subtitle\n ? `<p style=\"margin:4px 0 0;color:rgba(255,255,255,0.85);font-size:14px;\">${escapeHtml(options.subtitle)}</p>`\n : \"\";\n\n const ctaHtml = options.cta\n ? `\n <tr>\n <td style=\"padding:0 32px 24px;text-align:center;\">\n <a href=\"${escapeHtml(options.cta.url)}\"\n style=\"display:inline-block;padding:12px 28px;background:${accentColor};color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;\">\n ${escapeHtml(options.cta.text)}\n </a>\n </td>\n </tr>`\n : \"\";\n\n const footerLinksHtml =\n options.footerLinks && options.footerLinks.length > 0\n ? options.footerLinks\n .map(\n (link) =>\n `<a href=\"${escapeHtml(link.url)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(link.label)}</a>`,\n )\n .join(\" &middot; \")\n : \"\";\n\n const preferencesHtml = branding.preferencesUrl\n ? `<p style=\"margin:4px 0 0;font-size:12px;color:#9ca3af;\">\n <a href=\"${escapeHtml(branding.preferencesUrl)}\" style=\"color:${accentColor};text-decoration:none;\">Update email preferences</a>\n </p>`\n : \"\";\n\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"><title>${escapeHtml(options.subject)}</title></head>\n<body style=\"margin:0;padding:0;background:#f3f4f6;font-family:${FONT_STACK};\">\n ${preheaderHtml}\n <table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\">\n <tr><td align=\"center\">\n <table width=\"600\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#ffffff;border-radius:8px;overflow:hidden;max-width:600px;\">\n <!-- Header -->\n <tr>\n <td style=\"background:linear-gradient(135deg,${gradientFrom},${gradientTo});padding:28px 32px;text-align:center;\">\n <h1 style=\"margin:0;color:#ffffff;font-size:22px;font-weight:700;\">${iconHtml}${escapeHtml(branding.appName)}</h1>\n ${subtitleHtml}\n </td>\n </tr>\n\n <!-- Body -->\n <tr>\n <td style=\"padding:28px 32px;color:#374151;font-size:15px;line-height:1.6;\">\n ${options.body}\n </td>\n </tr>\n\n ${ctaHtml}\n\n <!-- Footer -->\n <tr>\n <td style=\"padding:16px 32px;background:#f9fafb;text-align:center;border-top:1px solid #e5e7eb;\">\n ${footerLinksHtml ? `<p style=\"margin:0 0 4px;font-size:12px;color:#9ca3af;\">${footerLinksHtml}</p>` : \"\"}\n <p style=\"margin:0;font-size:12px;color:#9ca3af;\">\n ${branding.footerText ? escapeHtml(branding.footerText) + \" &middot; \" : \"\"}\n <a href=\"${escapeHtml(branding.baseUrl)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(branding.appName)}</a>\n </p>\n ${preferencesHtml}\n </td>\n </tr>\n </table>\n </td></tr>\n </table>\n</body>\n</html>`;\n\n const text = `${options.icon ? options.icon + \" \" : \"\"}${options.subject}\\n${\"=\".repeat(40)}\\n\\n${htmlToText(options.body)}${options.cta ? `\\n\\n${options.cta.text}: ${options.cta.url}` : \"\"}\\n\\n---\\n${branding.footerText ? branding.footerText + \"\\n\" : \"\"}${branding.appName} - ${branding.baseUrl}${branding.preferencesUrl ? \"\\nEmail preferences: \" + branding.preferencesUrl : \"\"}`;\n\n return { subject: options.subject, html, text };\n}\n\n// ─── HTML Building Blocks ────────────────────────────────────────────────────\n// These helpers generate safe HTML fragments for use inside template body content.\n// All user-provided values MUST be escaped before calling these.\n\n/** Highlighted callout box with colored left border. */\nexport function calloutBlock(\n content: string,\n color: string = \"#3b82f6\",\n): string {\n return `<div style=\"background:#f9fafb;padding:16px 20px;border-radius:8px;border-left:4px solid ${color};margin:16px 0;\">${content}</div>`;\n}\n\n/** Numbered step card (for onboarding sequences). */\nexport function stepBlock(\n number: number,\n title: string,\n description: string,\n color: string = \"#667eea\",\n): string {\n return `<div style=\"background:#f3f4f6;padding:16px;border-radius:8px;margin-bottom:12px;border-left:4px solid ${color};\">\n <p style=\"margin:0;font-weight:600;color:#111827;\">${number}. ${title}</p>\n <p style=\"margin:8px 0 0;font-size:14px;color:#6b7280;\">${description}</p>\n </div>`;\n}\n\n/** Stats bar — row of metric cards. */\nexport function statsBar(\n stats: { label: string; value: string | number }[],\n): string {\n const cells = stats\n .map(\n (s) =>\n `<span style=\"display:inline-block;margin:0 16px;font-size:14px;color:#374151;\"><strong>${escapeHtml(String(s.value))}</strong> ${escapeHtml(s.label)}</span>`,\n )\n .join(\"\");\n return `<div style=\"padding:12px 0;text-align:center;background:#f0fdf4;border-radius:6px;margin-bottom:16px;\">${cells}</div>`;\n}\n\n/** Simple data table with header row. */\nexport function dataTable(headers: string[], rows: string[][]): string {\n const headerCells = headers\n .map(\n (h) =>\n `<th style=\"padding:8px 12px;text-align:left;font-size:13px;color:#374151;border-bottom:1px solid #e5e7eb;\">${escapeHtml(h)}</th>`,\n )\n .join(\"\");\n\n const bodyRows = rows\n .map(\n (row) =>\n `<tr>${row.map((cell) => `<td style=\"padding:8px 12px;border-bottom:1px solid #e5e7eb;font-size:14px;color:#374151;\">${cell}</td>`).join(\"\")}</tr>`,\n )\n .join(\"\");\n\n return `<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;\">\n <tr style=\"background:#f9fafb;\">${headerCells}</tr>\n ${bodyRows}\n </table>`;\n}\n\n/** Info/tip box with icon. */\nexport function tipBlock(content: string, icon: string = \"💡\"): string {\n return `<div style=\"background:#eff6ff;border:2px solid #3b82f6;padding:16px 20px;border-radius:8px;margin:16px 0;\">\n <p style=\"margin:0;color:#1e40af;font-size:14px;\"><strong>${icon} Pro Tip:</strong> ${content}</p>\n </div>`;\n}\n\n/** Centered heading within email body. */\nexport function sectionHeading(text: string): string {\n return `<h2 style=\"margin:24px 0 12px;font-size:16px;color:#111827;\">${escapeHtml(text)}</h2>`;\n}\n\n/** Horizontal rule divider. */\nexport function divider(): string {\n return `<hr style=\"border:none;border-top:1px solid #e5e7eb;margin:24px 0;\">`;\n}\n\n/** Re-export escapeHtml for template authors. */\nexport { escapeHtml } from \"../security\";\n","/**\n * Pre-built email templates.\n *\n * Each template accepts branding + template-specific data, composes the\n * layout + building blocks, and returns { subject, html, text }.\n *\n * Apps call these directly — no need to touch layout internals.\n * All user-provided strings are escaped internally.\n */\nimport type { EmailBranding, EmailOutput, EmailStep, EmailStat } from \"./types\";\nimport {\n emailLayout,\n calloutBlock,\n stepBlock,\n statsBar,\n dataTable,\n tipBlock,\n sectionHeading,\n divider,\n escapeHtml,\n} from \"./layout\";\n\n// ─── Welcome / Onboarding ────────────────────────────────────────────────────\n\nexport interface WelcomeEmailData {\n /** User's display name */\n userName: string;\n /** URL to their dashboard or profile */\n dashboardUrl: string;\n /** Onboarding steps (typically 3) */\n steps: EmailStep[];\n /** Optional pro-tip text */\n tip?: string;\n}\n\nexport function welcomeEmail(\n branding: EmailBranding,\n data: WelcomeEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const stepsHtml = data.steps\n .map((s, i) =>\n stepBlock(\n i + 1,\n escapeHtml(s.title),\n escapeHtml(s.description),\n branding.accentColor ?? branding.primaryColor,\n ),\n )\n .join(\"\");\n\n const tipHtml = data.tip ? tipBlock(escapeHtml(data.tip)) : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:20px;\">\n Welcome aboard! Your account is all set up and ready to go.\n </p>\n ${sectionHeading(\"Get Started\")}\n ${stepsHtml}\n ${tipHtml}\n `;\n\n return emailLayout(branding, {\n subject: `Welcome to ${branding.appName}!`,\n preheader: `Your ${branding.appName} account is ready`,\n icon: \"🎉\",\n subtitle: \"Welcome aboard\",\n body,\n cta: { text: \"Go to Dashboard\", url: data.dashboardUrl },\n footerLinks: branding.supportEmail\n ? [{ label: \"Get Help\", url: `mailto:${branding.supportEmail}` }]\n : undefined,\n });\n}\n\n// ─── Digest / Summary ────────────────────────────────────────────────────────\n\nexport interface DigestEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Period label (e.g. \"This Week\", \"March 2026\") */\n period: string;\n /** Summary stats shown in the stats bar */\n stats: EmailStat[];\n /** Main body HTML (app-specific content — must be pre-escaped) */\n contentHtml: string;\n /** Optional: URL to view full report */\n reportUrl?: string;\n /** Optional: why they're receiving this */\n subscriptionNote?: string;\n}\n\nexport function digestEmail(\n branding: EmailBranding,\n data: DigestEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safePeriod = escapeHtml(data.period);\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n Here's your ${safePeriod.toLowerCase()} summary:\n </p>\n ${statsBar(data.stats)}\n ${data.contentHtml}\n ${data.subscriptionNote ? `<p style=\"margin-top:20px;font-size:13px;color:#9ca3af;\">${escapeHtml(data.subscriptionNote)}</p>` : \"\"}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName} — ${data.period} Summary`,\n preheader: `Your ${data.period.toLowerCase()} activity on ${branding.appName}`,\n icon: \"📊\",\n subtitle: safePeriod,\n body,\n cta: data.reportUrl\n ? { text: \"View Full Report\", url: data.reportUrl }\n : undefined,\n });\n}\n\n// ─── Notification ────────────────────────────────────────────────────────────\n\nexport interface NotificationEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Notification headline */\n headline: string;\n /** Main message body (HTML-safe — will be escaped) */\n message: string;\n /** Optional highlighted detail block */\n detail?: string;\n /** Optional CTA */\n actionUrl?: string;\n /** Optional CTA label (defaults to \"View Details\") */\n actionText?: string;\n}\n\nexport function notificationEmail(\n branding: EmailBranding,\n data: NotificationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n const safeMessage = escapeHtml(data.message);\n\n const detailHtml = data.detail\n ? calloutBlock(\n escapeHtml(data.detail),\n branding.accentColor ?? branding.primaryColor,\n )\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n <p style=\"font-size:15px;margin-bottom:16px;\">${safeMessage}</p>\n ${detailHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.message.slice(0, 100),\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"View Details\", url: data.actionUrl }\n : undefined,\n });\n}\n\n// ─── Moderation ──────────────────────────────────────────────────────────────\n\nexport type ModerationAction =\n | \"warning\"\n | \"suspension\"\n | \"ban\"\n | \"reinstatement\";\n\nexport interface ModerationEmailData {\n /** User display name */\n userName: string;\n /** Type of moderation action */\n action: ModerationAction;\n /** Reason for the action */\n reason: string;\n /** What the user should do next (optional) */\n nextSteps?: string;\n /** Appeal/support URL (optional) */\n appealUrl?: string;\n}\n\nconst MODERATION_CONFIG: Record<\n ModerationAction,\n { icon: string; color: string; label: string }\n> = {\n warning: { icon: \"⚠️\", color: \"#f59e0b\", label: \"Account Warning\" },\n suspension: { icon: \"🔒\", color: \"#ef4444\", label: \"Account Suspended\" },\n ban: { icon: \"🚫\", color: \"#dc2626\", label: \"Account Banned\" },\n reinstatement: { icon: \"✅\", color: \"#10b981\", label: \"Account Reinstated\" },\n};\n\nexport function moderationEmail(\n branding: EmailBranding,\n data: ModerationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n const config = MODERATION_CONFIG[data.action];\n\n const reasonHtml = calloutBlock(\n `<strong>Reason:</strong> ${escapeHtml(data.reason)}`,\n config.color,\n );\n\n const nextStepsHtml = data.nextSteps\n ? `<p style=\"font-size:15px;margin:16px 0;\">${escapeHtml(data.nextSteps)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${\n data.action === \"reinstatement\"\n ? \"Good news — your account has been reinstated.\"\n : `Your account has received a ${escapeHtml(data.action)}.`\n }\n </p>\n ${reasonHtml}\n ${nextStepsHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${config.label}`,\n preheader: config.label,\n icon: config.icon,\n subtitle: config.label,\n body,\n cta: data.appealUrl\n ? { text: \"Appeal or Contact Support\", url: data.appealUrl }\n : undefined,\n });\n}\n\n// ─── Transaction / Receipt ───────────────────────────────────────────────────\n\nexport interface TransactionEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Transaction headline (e.g. \"Payment Received\", \"Order Confirmed\") */\n headline: string;\n /** Line items: [label, value] pairs */\n lineItems: [string, string][];\n /** Total amount string (e.g. \"$25.00\") */\n total?: string;\n /** Optional message above the table */\n message?: string;\n /** Optional receipt/order URL */\n receiptUrl?: string;\n}\n\nexport function transactionEmail(\n branding: EmailBranding,\n data: TransactionEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n\n const rows = data.lineItems.map(([label, value]) => [\n escapeHtml(label),\n escapeHtml(value),\n ]);\n\n if (data.total) {\n rows.push([\n `<strong>Total</strong>`,\n `<strong>${escapeHtml(data.total)}</strong>`,\n ]);\n }\n\n const messageHtml = data.message\n ? `<p style=\"font-size:15px;margin-bottom:16px;\">${escapeHtml(data.message)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n ${messageHtml}\n ${dataTable([\"Item\", \"Amount\"], rows)}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.headline,\n icon: \"🧾\",\n body,\n cta: data.receiptUrl\n ? { text: \"View Receipt\", url: data.receiptUrl }\n : undefined,\n });\n}\n\n// ─── Security Alert ──────────────────────────────────────────────────────────\n\nexport interface SecurityEmailData {\n /** User display name */\n userName: string;\n /** What happened (e.g. \"Password Changed\", \"New Login Detected\") */\n event: string;\n /** Details about the event */\n details: string;\n /** Optional action URL (e.g. reset password link) */\n actionUrl?: string;\n /** Optional action label */\n actionText?: string;\n /** Expiry note (e.g. \"This link expires in 1 hour\") */\n expiryNote?: string;\n}\n\nexport function securityEmail(\n branding: EmailBranding,\n data: SecurityEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const detailHtml = calloutBlock(escapeHtml(data.details), \"#ef4444\");\n\n const expiryHtml = data.expiryNote\n ? `<p style=\"font-size:13px;color:#9ca3af;margin-top:12px;text-align:center;\">${escapeHtml(data.expiryNote)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${escapeHtml(data.event)}\n </p>\n ${detailHtml}\n ${expiryHtml}\n <p style=\"font-size:14px;color:#6b7280;margin-top:16px;\">\n If you didn't initiate this action, please contact support immediately.\n </p>\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.event}`,\n preheader: data.event,\n icon: \"🔐\",\n subtitle: \"Security Alert\",\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"Take Action\", url: data.actionUrl }\n : undefined,\n });\n}\n"],"mappings":";AAwBO,SAAS,WAAW,KAAqB;AAC9C,SAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ;AAC3B;;;ACnBA,IAAM,aACJ;AAMF,SAAS,UAAU,KAAa,SAAyB;AACvD,QAAM,MAAM,SAAS,IAAI,QAAQ,KAAK,EAAE,GAAG,EAAE;AAC7C,QAAM,IAAI,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,MAAM,OAAO,OAAO,CAAC;AAC9D,QAAM,IAAI,KAAK,IAAI,IAAK,OAAO,IAAK,OAAU,KAAK,MAAM,OAAO,OAAO,CAAC;AACxE,QAAM,IAAI,KAAK,IAAI,IAAI,MAAM,OAAY,KAAK,MAAM,OAAO,OAAO,CAAC;AACnE,SAAO,KAAM,KAAK,KAAO,KAAK,IAAK,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AACrE;AAKA,SAAS,WAAW,MAAsB;AACxC,SAAO,KACJ,QAAQ,gBAAgB,IAAI,EAC5B,QAAQ,WAAW,MAAM,EACzB,QAAQ,aAAa,IAAI,EACzB,QAAQ,YAAY,IAAI,EACxB,QAAQ,YAAY,IAAI,EACxB,QAAQ,eAAe,IAAI,EAC3B,QAAQ,6CAA6C,SAAS,EAC9D,QAAQ,YAAY,EAAE,EACtB,QAAQ,WAAW,GAAG,EACtB,QAAQ,UAAU,GAAG,EACrB,QAAQ,SAAS,GAAG,EACpB,QAAQ,SAAS,GAAG,EACpB,QAAQ,WAAW,GAAG,EACtB,QAAQ,UAAU,GAAG,EACrB,QAAQ,WAAW,QAAG,EACtB,QAAQ,WAAW,M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,KAAK;AAAA,MACR;AAAA,MACA,WAAW,WAAW,KAAK,KAAK,CAAC;AAAA,IACnC,CAAC;AAAA,EACH;AAEA,QAAM,cAAc,KAAK,UACrB,iDAAiD,WAAW,KAAK,OAAO,CAAC,SACzE;AAEJ,QAAM,OAAO;AAAA,uDACwC,QAAQ;AAAA,gEACC,YAAY;AAAA,MACtE,WAAW;AAAA,MACX,UAAU,CAAC,QAAQ,QAAQ,GAAG,IAAI,CAAC;AAAA;AAGvC,SAAO,YAAY,UAAU;AAAA,IAC3B,SAAS,GAAG,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,IAC9C,WAAW,KAAK;AAAA,IAChB,MAAM;AAAA,IACN;AAAA,IACA,KAAK,KAAK,aACN,EAAE,MAAM,gBAAgB,KAAK,KAAK,WAAW,IAC7C;AAAA,EACN,CAAC;AACH;AAmBO,SAAS,cACd,UACA,MACa;AACb,QAAM,WAAW,WAAW,KAAK,QAAQ;AAEzC,QAAM,aAAa,aAAa,WAAW,KAAK,OAAO,GAAG,SAAS;AAEnE,QAAM,aAAa,KAAK,aACpB,8EAA8E,WAAW,KAAK,UAAU,CAAC,SACzG;AAEJ,QAAM,OAAO;AAAA,uDACwC,QAAQ;AAAA;AAAA,QAEvD,WAAW,KAAK,KAAK,CAAC;AAAA;AAAA,MAExB,UAAU;AAAA,MACV,UAAU;AAAA;AAAA;AAAA;AAAA;AAMd,SAAO,YAAY,UAAU;AAAA,IAC3B,SAAS,GAAG,SAAS,OAAO,KAAK,KAAK,KAAK;AAAA,IAC3C,WAAW,KAAK;AAAA,IAChB,MAAM;AAAA,IACN,UAAU;AAAA,IACV;AAAA,IACA,KAAK,KAAK,YACN,EAAE,MAAM,KAAK,cAAc,eAAe,KAAK,KAAK,UAAU,IAC9D;AAAA,EACN,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/security.ts","../src/email-templates/layout.ts","../src/email-templates/templates.ts"],"sourcesContent":["/**\n * Security Utilities\n *\n * HTML escaping, input detection, sanitization helpers,\n * timing-safe comparison, error sanitization, and request\n * correlation for safe, consistent security across all apps.\n */\n\nimport { timingSafeEqual } from \"crypto\";\n\n/** Regex for protocol-prefixed URLs */\nexport const URL_PROTOCOL_PATTERN = /(https?:\\/\\/|ftp:\\/\\/|www\\.)\\S+/i;\n\n/** Regex for bare domain names with common TLDs */\nexport const URL_DOMAIN_PATTERN =\n /\\b[\\w.-]+\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/i;\n\n/** Regex for HTML tags */\nexport const HTML_TAG_PATTERN = /<[^>]*>/;\n\n/**\n * Escape HTML special characters to prevent injection.\n * Use when inserting user content into HTML email templates or rendered HTML.\n */\nexport function escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n/** Check if a string contains protocol-prefixed URLs or bare domains */\nexport function containsUrls(str: string): boolean {\n return URL_PROTOCOL_PATTERN.test(str) || URL_DOMAIN_PATTERN.test(str);\n}\n\n/** Check if a string contains HTML tags */\nexport function containsHtml(str: string): boolean {\n return HTML_TAG_PATTERN.test(str);\n}\n\n/** Strip all HTML tags from a string */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, \"\");\n}\n\n/**\n * Strip null bytes (U+0000) from a string.\n *\n * Postgres rejects null bytes in `text`/`varchar` columns with a hard\n * `invalid byte sequence` error (→ HTTP 500 in app handlers). Apps that\n * forward raw user input — search queries, filter params, form fields —\n * into Drizzle/raw SQL queries hit this on malicious or malformed clients\n * that inject `%00` in URLs.\n *\n * Pass `undefined`/`null` through unchanged so it composes cleanly with\n * optional query params: `stripNullBytes(url.searchParams.get('q'))?.trim()`.\n *\n * @example\n * ```typescript\n * import { stripNullBytes } from '@digilogiclabs/platform-core/auth';\n *\n * const q = stripNullBytes(url.searchParams.get('q'))?.trim();\n * const results = await db.select().where(ilike(column, `%${q}%`));\n * ```\n */\nexport function stripNullBytes(value: string): string;\nexport function stripNullBytes(value: null | undefined): null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined;\nexport function stripNullBytes(\n value: string | null | undefined,\n): string | null | undefined {\n if (value === null || value === undefined) return value;\n return value.replace(/\\u0000/g, \"\");\n}\n\n/**\n * Recursively strip null bytes from all string values in a plain object or\n * array. Non-string values pass through unchanged. Use on parsed JSON\n * request bodies before forwarding to DB queries.\n *\n * Preserves the object's own keys and order; does NOT mutate the input.\n * Arrays stay arrays. Stops at 8 levels deep as a guard against accidental\n * circular references (throws at depth-limit exceeded).\n *\n * @example\n * ```typescript\n * import { stripNullBytesDeep } from '@digilogiclabs/platform-core/auth';\n *\n * const body = stripNullBytesDeep(await request.json());\n * const parsed = schema.safeParse(body);\n * ```\n */\nexport function stripNullBytesDeep<T>(value: T, depth = 8): T {\n if (depth <= 0) {\n throw new Error(\"stripNullBytesDeep: max depth exceeded (circular?)\");\n }\n if (typeof value === \"string\") {\n return value.replace(/\\u0000/g, \"\") as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) => stripNullBytesDeep(v, depth - 1)) as unknown as T;\n }\n if (value !== null && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = stripNullBytesDeep(v, depth - 1);\n }\n return out as T;\n }\n return value;\n}\n\n/**\n * Defang URLs to prevent auto-linking in email clients.\n * Converts https://evil.com → hxxps://evil[.]com\n */\nexport function defangUrl(str: string): string {\n return str\n .replace(/https:\\/\\//gi, \"hxxps://\")\n .replace(/http:\\/\\//gi, \"hxxp://\")\n .replace(/ftp:\\/\\//gi, \"fxp://\")\n .replace(\n /\\.(com|net|org|io|co|dev|app|xyz|info|biz|me|us|uk|edu|gov)\\b/gi,\n \"[$1]\",\n );\n}\n\n/**\n * Sanitize user content for safe insertion into HTML email templates.\n * Escapes HTML entities AND defangs any URLs that slipped through validation.\n */\nexport function sanitizeForEmail(str: string): string {\n return escapeHtml(str);\n}\n\n// ═══════════════════════════════════════════════════════════════\n// API SECURITY UTILITIES\n// ═══════════════════════════════════════════════════════════════\n\n/**\n * Constant-time string comparison to prevent timing side-channel attacks.\n * Use for comparing secrets, tokens, API keys, HMAC signatures, etc.\n *\n * Returns false (not throws) for length mismatches — still constant-time\n * relative to the shorter string to avoid leaking length info.\n *\n * @example\n * ```typescript\n * if (!constantTimeEqual(providedToken, expectedSecret)) {\n * return { status: 401, error: 'Invalid token' }\n * }\n * ```\n */\nexport function constantTimeEqual(a: string, b: string): boolean {\n try {\n const aBuf = Buffer.from(a, \"utf-8\");\n const bBuf = Buffer.from(b, \"utf-8\");\n if (aBuf.length !== bBuf.length) return false;\n return timingSafeEqual(aBuf, bBuf);\n } catch {\n return false;\n }\n}\n\n/**\n * Sanitize an error for client-facing API responses.\n *\n * - 4xx errors: returns the actual message (client needs to know what went wrong)\n * - 5xx errors: returns a generic message (never leak internals to clients)\n * - Development mode: optionally includes stack trace for debugging\n *\n * @example\n * ```typescript\n * catch (error) {\n * const { message, code } = sanitizeApiError(error, 500)\n * return Response.json({ error: message, code }, { status: 500 })\n * }\n * ```\n */\nexport function sanitizeApiError(\n error: unknown,\n statusCode: number,\n isDevelopment = false,\n): { message: string; code?: string; stack?: string } {\n // Client errors — safe to expose the message\n if (statusCode >= 400 && statusCode < 500) {\n const message =\n error instanceof Error ? error.message : String(error || \"Bad request\");\n return { message };\n }\n\n // Server errors — generic message to clients, real error in logs only\n const result: { message: string; code: string; stack?: string } = {\n message: \"An internal error occurred. Please try again later.\",\n code: \"INTERNAL_ERROR\",\n };\n\n if (isDevelopment && error instanceof Error) {\n result.stack = error.stack;\n }\n\n return result;\n}\n\n/**\n * Extract a correlation/request ID from standard headers, or generate one.\n *\n * Checks (in order): X-Request-ID, X-Correlation-ID, then falls back to\n * crypto.randomUUID(). Works with any headers-like object (plain object,\n * Headers API, or a getter function).\n *\n * @example\n * ```typescript\n * // With Next.js request\n * const id = getCorrelationId((name) => request.headers.get(name))\n *\n * // With plain object\n * const id = getCorrelationId({ 'x-request-id': 'abc-123' })\n * ```\n */\nexport function getCorrelationId(\n headers:\n | Record<string, string | string[] | undefined>\n | ((name: string) => string | null | undefined),\n): string {\n const get =\n typeof headers === \"function\"\n ? headers\n : (name: string) => {\n const val = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(val) ? val[0] : val;\n };\n\n return (\n get(\"x-request-id\") ||\n get(\"X-Request-ID\") ||\n get(\"x-correlation-id\") ||\n get(\"X-Correlation-ID\") ||\n crypto.randomUUID()\n );\n}\n","/**\n * Base email layout builder.\n *\n * Generates a fully responsive, email-client-compatible HTML email\n * using only inline styles and table-based layout.\n *\n * Every user-facing string in the layout is pre-escaped. Template functions\n * that accept user input MUST escape those values before passing them to body.\n */\nimport type { EmailBranding, EmailLayoutOptions, EmailOutput } from \"./types\";\nimport { escapeHtml } from \"../security\";\n\nconst FONT_STACK =\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif\";\n\n/**\n * Darken a hex color by a percentage (0-100).\n * Used to auto-generate gradientTo from primaryColor.\n */\nfunction darkenHex(hex: string, percent: number): string {\n const num = parseInt(hex.replace(\"#\", \"\"), 16);\n const r = Math.max(0, (num >> 16) - Math.round(2.55 * percent));\n const g = Math.max(0, ((num >> 8) & 0x00ff) - Math.round(2.55 * percent));\n const b = Math.max(0, (num & 0x0000ff) - Math.round(2.55 * percent));\n return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, \"0\")}`;\n}\n\n/**\n * Strip HTML tags for plain-text fallback.\n */\nfunction htmlToText(html: string): string {\n return html\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/p>/gi, \"\\n\\n\")\n .replace(/<\\/div>/gi, \"\\n\")\n .replace(/<\\/tr>/gi, \"\\n\")\n .replace(/<\\/li>/gi, \"\\n\")\n .replace(/<li[^>]*>/gi, \"- \")\n .replace(/<a[^>]*href=\"([^\"]*)\"[^>]*>([^<]*)<\\/a>/gi, \"$2 ($1)\")\n .replace(/<[^>]+>/g, \"\")\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&rarr;/g, \"→\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\n/**\n * Build a complete HTML email from branding + layout options.\n *\n * Returns `{ subject, html, text }` ready to pass to any IEmail adapter.\n */\nexport function emailLayout(\n branding: EmailBranding,\n options: EmailLayoutOptions,\n): EmailOutput {\n const gradientFrom = branding.gradientFrom ?? branding.primaryColor;\n const gradientTo =\n branding.gradientTo ?? darkenHex(branding.primaryColor, 15);\n const accentColor = branding.accentColor ?? branding.primaryColor;\n\n const preheaderHtml = options.preheader\n ? `<div style=\"display:none;font-size:1px;color:#f3f4f6;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;\">${escapeHtml(options.preheader)}</div>`\n : \"\";\n\n const iconHtml = options.icon ? `${options.icon} ` : \"\";\n\n const subtitleHtml = options.subtitle\n ? `<p style=\"margin:4px 0 0;color:rgba(255,255,255,0.85);font-size:14px;\">${escapeHtml(options.subtitle)}</p>`\n : \"\";\n\n // Logo image — when branding.logoUrl is supplied, render an <img> above\n // the appName text. Email-client-safe attributes only: explicit width,\n // alt text, display:block, border:0. Hosted PNG (or JPG) only — most\n // email clients (Outlook, Gmail's image proxy) do not render SVG.\n const logoHtml = branding.logoUrl\n ? `<img src=\"${escapeHtml(branding.logoUrl)}\" alt=\"${escapeHtml(branding.appName)}\" width=\"56\" height=\"56\" style=\"display:block;margin:0 auto 10px;border:0;outline:none;text-decoration:none;border-radius:10px;background:#ffffff;padding:6px;\" />`\n : \"\";\n\n const ctaHtml = options.cta\n ? `\n <tr>\n <td style=\"padding:0 32px 24px;text-align:center;\">\n <a href=\"${escapeHtml(options.cta.url)}\"\n style=\"display:inline-block;padding:12px 28px;background:${accentColor};color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;\">\n ${escapeHtml(options.cta.text)}\n </a>\n </td>\n </tr>`\n : \"\";\n\n const footerLinksHtml =\n options.footerLinks && options.footerLinks.length > 0\n ? options.footerLinks\n .map(\n (link) =>\n `<a href=\"${escapeHtml(link.url)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(link.label)}</a>`,\n )\n .join(\" &middot; \")\n : \"\";\n\n const preferencesHtml = branding.preferencesUrl\n ? `<p style=\"margin:4px 0 0;font-size:12px;color:#9ca3af;\">\n <a href=\"${escapeHtml(branding.preferencesUrl)}\" style=\"color:${accentColor};text-decoration:none;\">Update email preferences</a>\n </p>`\n : \"\";\n\n const html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0\"><title>${escapeHtml(options.subject)}</title></head>\n<body style=\"margin:0;padding:0;background:#f3f4f6;font-family:${FONT_STACK};\">\n ${preheaderHtml}\n <table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\">\n <tr><td align=\"center\">\n <table width=\"600\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#ffffff;border-radius:8px;overflow:hidden;max-width:600px;\">\n <!-- Header -->\n <tr>\n <td style=\"background:linear-gradient(135deg,${gradientFrom},${gradientTo});padding:28px 32px;text-align:center;\">\n ${logoHtml}<h1 style=\"margin:0;color:#ffffff;font-size:22px;font-weight:700;\">${iconHtml}${escapeHtml(branding.appName)}</h1>\n ${subtitleHtml}\n </td>\n </tr>\n\n <!-- Body -->\n <tr>\n <td style=\"padding:28px 32px;color:#374151;font-size:15px;line-height:1.6;\">\n ${options.body}\n </td>\n </tr>\n\n ${ctaHtml}\n\n <!-- Footer -->\n <tr>\n <td style=\"padding:16px 32px;background:#f9fafb;text-align:center;border-top:1px solid #e5e7eb;\">\n ${footerLinksHtml ? `<p style=\"margin:0 0 4px;font-size:12px;color:#9ca3af;\">${footerLinksHtml}</p>` : \"\"}\n <p style=\"margin:0;font-size:12px;color:#9ca3af;\">\n ${branding.footerText ? escapeHtml(branding.footerText) + \" &middot; \" : \"\"}\n <a href=\"${escapeHtml(branding.baseUrl)}\" style=\"color:${accentColor};text-decoration:none;\">${escapeHtml(branding.appName)}</a>\n </p>\n ${preferencesHtml}\n </td>\n </tr>\n </table>\n </td></tr>\n </table>\n</body>\n</html>`;\n\n const text = `${options.icon ? options.icon + \" \" : \"\"}${options.subject}\\n${\"=\".repeat(40)}\\n\\n${htmlToText(options.body)}${options.cta ? `\\n\\n${options.cta.text}: ${options.cta.url}` : \"\"}\\n\\n---\\n${branding.footerText ? branding.footerText + \"\\n\" : \"\"}${branding.appName} - ${branding.baseUrl}${branding.preferencesUrl ? \"\\nEmail preferences: \" + branding.preferencesUrl : \"\"}`;\n\n return { subject: options.subject, html, text };\n}\n\n// ─── HTML Building Blocks ────────────────────────────────────────────────────\n// These helpers generate safe HTML fragments for use inside template body content.\n// All user-provided values MUST be escaped before calling these.\n\n/** Highlighted callout box with colored left border. */\nexport function calloutBlock(\n content: string,\n color: string = \"#3b82f6\",\n): string {\n return `<div style=\"background:#f9fafb;padding:16px 20px;border-radius:8px;border-left:4px solid ${color};margin:16px 0;\">${content}</div>`;\n}\n\n/** Numbered step card (for onboarding sequences). */\nexport function stepBlock(\n number: number,\n title: string,\n description: string,\n color: string = \"#667eea\",\n): string {\n return `<div style=\"background:#f3f4f6;padding:16px;border-radius:8px;margin-bottom:12px;border-left:4px solid ${color};\">\n <p style=\"margin:0;font-weight:600;color:#111827;\">${number}. ${title}</p>\n <p style=\"margin:8px 0 0;font-size:14px;color:#6b7280;\">${description}</p>\n </div>`;\n}\n\n/** Stats bar — row of metric cards. */\nexport function statsBar(\n stats: { label: string; value: string | number }[],\n): string {\n const cells = stats\n .map(\n (s) =>\n `<span style=\"display:inline-block;margin:0 16px;font-size:14px;color:#374151;\"><strong>${escapeHtml(String(s.value))}</strong> ${escapeHtml(s.label)}</span>`,\n )\n .join(\"\");\n return `<div style=\"padding:12px 0;text-align:center;background:#f0fdf4;border-radius:6px;margin-bottom:16px;\">${cells}</div>`;\n}\n\n/** Simple data table with header row. */\nexport function dataTable(headers: string[], rows: string[][]): string {\n const headerCells = headers\n .map(\n (h) =>\n `<th style=\"padding:8px 12px;text-align:left;font-size:13px;color:#374151;border-bottom:1px solid #e5e7eb;\">${escapeHtml(h)}</th>`,\n )\n .join(\"\");\n\n const bodyRows = rows\n .map(\n (row) =>\n `<tr>${row.map((cell) => `<td style=\"padding:8px 12px;border-bottom:1px solid #e5e7eb;font-size:14px;color:#374151;\">${cell}</td>`).join(\"\")}</tr>`,\n )\n .join(\"\");\n\n return `<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;\">\n <tr style=\"background:#f9fafb;\">${headerCells}</tr>\n ${bodyRows}\n </table>`;\n}\n\n/** Info/tip box with icon. */\nexport function tipBlock(content: string, icon: string = \"💡\"): string {\n return `<div style=\"background:#eff6ff;border:2px solid #3b82f6;padding:16px 20px;border-radius:8px;margin:16px 0;\">\n <p style=\"margin:0;color:#1e40af;font-size:14px;\"><strong>${icon} Pro Tip:</strong> ${content}</p>\n </div>`;\n}\n\n/** Centered heading within email body. */\nexport function sectionHeading(text: string): string {\n return `<h2 style=\"margin:24px 0 12px;font-size:16px;color:#111827;\">${escapeHtml(text)}</h2>`;\n}\n\n/** Horizontal rule divider. */\nexport function divider(): string {\n return `<hr style=\"border:none;border-top:1px solid #e5e7eb;margin:24px 0;\">`;\n}\n\n/** Re-export escapeHtml for template authors. */\nexport { escapeHtml } from \"../security\";\n","/**\n * Pre-built email templates.\n *\n * Each template accepts branding + template-specific data, composes the\n * layout + building blocks, and returns { subject, html, text }.\n *\n * Apps call these directly — no need to touch layout internals.\n * All user-provided strings are escaped internally.\n */\nimport type { EmailBranding, EmailOutput, EmailStep, EmailStat } from \"./types\";\nimport {\n emailLayout,\n calloutBlock,\n stepBlock,\n statsBar,\n dataTable,\n tipBlock,\n sectionHeading,\n divider,\n escapeHtml,\n} from \"./layout\";\n\n// ─── Welcome / Onboarding ────────────────────────────────────────────────────\n\nexport interface WelcomeEmailData {\n /** User's display name */\n userName: string;\n /** URL to their dashboard or profile */\n dashboardUrl: string;\n /** Onboarding steps (typically 3) */\n steps: EmailStep[];\n /** Optional pro-tip text */\n tip?: string;\n}\n\nexport function welcomeEmail(\n branding: EmailBranding,\n data: WelcomeEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const stepsHtml = data.steps\n .map((s, i) =>\n stepBlock(\n i + 1,\n escapeHtml(s.title),\n escapeHtml(s.description),\n branding.accentColor ?? branding.primaryColor,\n ),\n )\n .join(\"\");\n\n const tipHtml = data.tip ? tipBlock(escapeHtml(data.tip)) : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:20px;\">\n Welcome aboard! Your account is all set up and ready to go.\n </p>\n ${sectionHeading(\"Get Started\")}\n ${stepsHtml}\n ${tipHtml}\n `;\n\n return emailLayout(branding, {\n subject: `Welcome to ${branding.appName}!`,\n preheader: `Your ${branding.appName} account is ready`,\n icon: \"🎉\",\n subtitle: \"Welcome aboard\",\n body,\n cta: { text: \"Go to Dashboard\", url: data.dashboardUrl },\n footerLinks: branding.supportEmail\n ? [{ label: \"Get Help\", url: `mailto:${branding.supportEmail}` }]\n : undefined,\n });\n}\n\n// ─── Digest / Summary ────────────────────────────────────────────────────────\n\nexport interface DigestEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Period label (e.g. \"This Week\", \"March 2026\") */\n period: string;\n /** Summary stats shown in the stats bar */\n stats: EmailStat[];\n /** Main body HTML (app-specific content — must be pre-escaped) */\n contentHtml: string;\n /** Optional: URL to view full report */\n reportUrl?: string;\n /** Optional: why they're receiving this */\n subscriptionNote?: string;\n}\n\nexport function digestEmail(\n branding: EmailBranding,\n data: DigestEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safePeriod = escapeHtml(data.period);\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n Here's your ${safePeriod.toLowerCase()} summary:\n </p>\n ${statsBar(data.stats)}\n ${data.contentHtml}\n ${data.subscriptionNote ? `<p style=\"margin-top:20px;font-size:13px;color:#9ca3af;\">${escapeHtml(data.subscriptionNote)}</p>` : \"\"}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName} — ${data.period} Summary`,\n preheader: `Your ${data.period.toLowerCase()} activity on ${branding.appName}`,\n icon: \"📊\",\n subtitle: safePeriod,\n body,\n cta: data.reportUrl\n ? { text: \"View Full Report\", url: data.reportUrl }\n : undefined,\n });\n}\n\n// ─── Notification ────────────────────────────────────────────────────────────\n\nexport interface NotificationEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Notification headline */\n headline: string;\n /** Main message body (HTML-safe — will be escaped) */\n message: string;\n /** Optional highlighted detail block */\n detail?: string;\n /** Optional CTA */\n actionUrl?: string;\n /** Optional CTA label (defaults to \"View Details\") */\n actionText?: string;\n}\n\nexport function notificationEmail(\n branding: EmailBranding,\n data: NotificationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n const safeMessage = escapeHtml(data.message);\n\n const detailHtml = data.detail\n ? calloutBlock(\n escapeHtml(data.detail),\n branding.accentColor ?? branding.primaryColor,\n )\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n <p style=\"font-size:15px;margin-bottom:16px;\">${safeMessage}</p>\n ${detailHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.message.slice(0, 100),\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"View Details\", url: data.actionUrl }\n : undefined,\n });\n}\n\n// ─── Moderation ──────────────────────────────────────────────────────────────\n\nexport type ModerationAction =\n | \"warning\"\n | \"suspension\"\n | \"ban\"\n | \"reinstatement\";\n\nexport interface ModerationEmailData {\n /** User display name */\n userName: string;\n /** Type of moderation action */\n action: ModerationAction;\n /** Reason for the action */\n reason: string;\n /** What the user should do next (optional) */\n nextSteps?: string;\n /** Appeal/support URL (optional) */\n appealUrl?: string;\n}\n\nconst MODERATION_CONFIG: Record<\n ModerationAction,\n { icon: string; color: string; label: string }\n> = {\n warning: { icon: \"⚠️\", color: \"#f59e0b\", label: \"Account Warning\" },\n suspension: { icon: \"🔒\", color: \"#ef4444\", label: \"Account Suspended\" },\n ban: { icon: \"🚫\", color: \"#dc2626\", label: \"Account Banned\" },\n reinstatement: { icon: \"✅\", color: \"#10b981\", label: \"Account Reinstated\" },\n};\n\nexport function moderationEmail(\n branding: EmailBranding,\n data: ModerationEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n const config = MODERATION_CONFIG[data.action];\n\n const reasonHtml = calloutBlock(\n `<strong>Reason:</strong> ${escapeHtml(data.reason)}`,\n config.color,\n );\n\n const nextStepsHtml = data.nextSteps\n ? `<p style=\"font-size:15px;margin:16px 0;\">${escapeHtml(data.nextSteps)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${\n data.action === \"reinstatement\"\n ? \"Good news — your account has been reinstated.\"\n : `Your account has received a ${escapeHtml(data.action)}.`\n }\n </p>\n ${reasonHtml}\n ${nextStepsHtml}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${config.label}`,\n preheader: config.label,\n icon: config.icon,\n subtitle: config.label,\n body,\n cta: data.appealUrl\n ? { text: \"Appeal or Contact Support\", url: data.appealUrl }\n : undefined,\n });\n}\n\n// ─── Transaction / Receipt ───────────────────────────────────────────────────\n\nexport interface TransactionEmailData {\n /** Recipient display name */\n recipientName: string;\n /** Transaction headline (e.g. \"Payment Received\", \"Order Confirmed\") */\n headline: string;\n /** Line items: [label, value] pairs */\n lineItems: [string, string][];\n /** Total amount string (e.g. \"$25.00\") */\n total?: string;\n /** Optional message above the table */\n message?: string;\n /** Optional receipt/order URL */\n receiptUrl?: string;\n}\n\nexport function transactionEmail(\n branding: EmailBranding,\n data: TransactionEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.recipientName);\n const safeHeadline = escapeHtml(data.headline);\n\n const rows = data.lineItems.map(([label, value]) => [\n escapeHtml(label),\n escapeHtml(value),\n ]);\n\n if (data.total) {\n rows.push([\n `<strong>Total</strong>`,\n `<strong>${escapeHtml(data.total)}</strong>`,\n ]);\n }\n\n const messageHtml = data.message\n ? `<p style=\"font-size:15px;margin-bottom:16px;\">${escapeHtml(data.message)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <h2 style=\"margin:0 0 12px;font-size:18px;color:#111827;\">${safeHeadline}</h2>\n ${messageHtml}\n ${dataTable([\"Item\", \"Amount\"], rows)}\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.headline}`,\n preheader: data.headline,\n icon: \"🧾\",\n body,\n cta: data.receiptUrl\n ? { text: \"View Receipt\", url: data.receiptUrl }\n : undefined,\n });\n}\n\n// ─── Security Alert ──────────────────────────────────────────────────────────\n\nexport interface SecurityEmailData {\n /** User display name */\n userName: string;\n /** What happened (e.g. \"Password Changed\", \"New Login Detected\") */\n event: string;\n /** Details about the event */\n details: string;\n /** Optional action URL (e.g. reset password link) */\n actionUrl?: string;\n /** Optional action label */\n actionText?: string;\n /** Expiry note (e.g. \"This link expires in 1 hour\") */\n expiryNote?: string;\n}\n\nexport function securityEmail(\n branding: EmailBranding,\n data: SecurityEmailData,\n): EmailOutput {\n const safeName = escapeHtml(data.userName);\n\n const detailHtml = calloutBlock(escapeHtml(data.details), \"#ef4444\");\n\n const expiryHtml = data.expiryNote\n ? `<p style=\"font-size:13px;color:#9ca3af;margin-top:12px;text-align:center;\">${escapeHtml(data.expiryNote)}</p>`\n : \"\";\n\n const body = `\n <p style=\"font-size:16px;margin-bottom:20px;\">Hi ${safeName},</p>\n <p style=\"font-size:15px;margin-bottom:16px;\">\n ${escapeHtml(data.event)}\n </p>\n ${detailHtml}\n ${expiryHtml}\n <p style=\"font-size:14px;color:#6b7280;margin-top:16px;\">\n If you didn't initiate this action, please contact support immediately.\n </p>\n `;\n\n return emailLayout(branding, {\n subject: `${branding.appName}: ${data.event}`,\n preheader: data.event,\n icon: \"🔐\",\n subtitle: \"Security Alert\",\n body,\n cta: data.actionUrl\n ? { text: data.actionText ?? \"Take Action\", url: data.actionUrl }\n : undefined,\n });\n}\n"],"mappings":";AAwBO,SAAS,WAAW,KAAqB;AAC9C,SAAO,IACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ;AAC3B;;;ACnBA,IAAM,aACJ;AAMF,SAAS,UAAU,KAAa,SAAyB;AACvD,QAAM,MAAM,SAAS,IAAI,QAAQ,KAAK,EAAE,GAAG,EAAE;AAC7C,QAAM,IAAI,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,MAAM,OAAO,OAAO,CAAC;AAC9D,QAAM,IAAI,KAAK,IAAI,IAAK,OAAO,IAAK,OAAU,KAAK,MAAM,OAAO,OAAO,CAAC;AACxE,QAAM,IAAI,KAAK,IAAI,IAAI,MAAM,OAAY,KAAK,MAAM,OAAO,OAAO,CAAC;AACnE,SAAO,KAAM,KAAK,KAAO,KAAK,IAAK,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AACrE;AAKA,SAAS,WAAW,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AAK,UAAU,CAAC,SACzG;AAEJ,QAAM,OAAO;AAAA,uDACwC,QAAQ;AAAA;AAAA,QAEvD,WAAW,KAAK,KAAK,CAAC;AAAA;AAAA,MAExB,UAAU;AAAA,MACV,UAAU;AAAA;AAAA;AAAA;AAAA;AAMd,SAAO,YAAY,UAAU;AAAA,IAC3B,SAAS,GAAG,SAAS,OAAO,KAAK,KAAK,KAAK;AAAA,IAC3C,WAAW,KAAK;AAAA,IAChB,MAAM;AAAA,IACN,UAAU;AAAA,IACV;AAAA,IACA,KAAK,KAAK,YACN,EAAE,MAAM,KAAK,cAAc,eAAe,KAAK,KAAK,UAAU,IAC9D;AAAA,EACN,CAAC;AACH;","names":[]}
@@ -270,6 +270,47 @@ interface BuildExportFilenameInput {
270
270
  */
271
271
  declare function buildExportFilename({ brand, tool, titleOrDate, ext, }: BuildExportFilenameInput): string;
272
272
 
273
+ /**
274
+ * @react-pdf/renderer is declared as an OPTIONAL peer dependency. Apps that
275
+ * import this subpath must install it themselves; bundlers will surface a
276
+ * clear "Cannot find module" error if it isn't present, which is the standard
277
+ * platform-core pattern for optional peers (`pg`, `ioredis`, `bullmq`, etc).
278
+ */
279
+ /**
280
+ * Vertical space (in PDF points) that a `<Page>` must reserve at the bottom
281
+ * to keep flowed body content from rendering under the `fixed` footer.
282
+ *
283
+ * react-pdf paginates flow content when it reaches `pageHeight - paddingBottom`;
284
+ * `fixed` elements like `<ExportFooterPdf>` are pinned at their flow anchor on
285
+ * every page but DO NOT push the pagination boundary. So if `paddingBottom` is
286
+ * smaller than the footer's natural height, the last lines of body content on
287
+ * each page render directly underneath the footer chrome.
288
+ *
289
+ * The `ExportFooterPdf` rendered by this module claims roughly 55-60pt at
290
+ * `maximum` prominence (44pt QR + 8pt paddingTop + 2pt borderTop + line-height
291
+ * descenders + small render-engine slack). 72pt = footer + ~12pt clearance,
292
+ * which is the minimum we recommend for any `<Page>` that mounts an
293
+ * `<ExportFooterPdf>` (or `<BrandedPdfPage>`).
294
+ *
295
+ * **Why two carves are applied inside `BrandedPdfPage`:** `paddingBottom` alone
296
+ * protects normal flow content from paginating into the footer band, but it
297
+ * does NOT protect against overflow rendering — children inside the body
298
+ * container that use `justifyContent: "space-around"` (or any non-paginating
299
+ * distribution) and exceed the container's height render PAST the container's
300
+ * bottom edge, into the footer's render band. To absorb this case,
301
+ * `BrandedPdfPage` ALSO sets `marginBottom: FOOTER_SAFE_AREA_PT` on the body
302
+ * `<View>`, carving an explicit safe-zone inside the flow area. The double
303
+ * carve is intentional and defensive — combined, they cover both the
304
+ * pagination boundary AND modest overflow from custom layouts.
305
+ *
306
+ * Consumers that build their own `<Page>` directly (rather than using
307
+ * `<BrandedPdfPage>`) should set `paddingBottom` to at least this value AND,
308
+ * if they nest body content inside a flex container with non-paginating
309
+ * `justifyContent`, also apply `marginBottom: FOOTER_SAFE_AREA_PT` to that
310
+ * container. Documents that only use plain flow content (`<Text>`, `<View>`
311
+ * stacks) need only the `paddingBottom`.
312
+ */
313
+ declare const FOOTER_SAFE_AREA_PT = 72;
273
314
  interface ExportHeaderPdfProps {
274
315
  /** Brand configuration. */
275
316
  brand: BrandConfig;
@@ -300,14 +341,33 @@ interface ExportFooterPdfProps {
300
341
  qrDataUrl?: string | null;
301
342
  /** Branding prominence. Defaults to `maximum`. */
302
343
  prominence?: ExportProminence;
344
+ /**
345
+ * Render with react-pdf's `fixed` prop so the footer appears on every page
346
+ * of a multi-page document. Defaults to `true` (the typical behavior).
347
+ *
348
+ * Set to `false` for documents whose body content cannot be reliably
349
+ * constrained above the footer's render band — e.g., a `flex: 1` layout
350
+ * with overflow children that paginate (large brackets, dense tables,
351
+ * etc.). With `fixed: false` the footer flows after the body and renders
352
+ * only on the LAST page; intermediate pages have no footer chrome but
353
+ * also no body-on-footer overlap. This is the architecturally correct
354
+ * trade-off for content where pagination is the rule, not the exception.
355
+ *
356
+ * For ordinary documents (rules sheets, score sheets, single-page
357
+ * profile cards) leave at the default `true`.
358
+ */
359
+ fixed?: boolean;
303
360
  }
304
361
  /**
305
- * Branded PDF document footer — `fixed` so it renders on every page.
362
+ * Branded PDF document footer — `fixed` so it renders on every page (default).
306
363
  *
307
364
  * Composition: brand mark + name (left), URL + date (center-right), QR (far right).
308
365
  * Tagline shown only at `maximum` prominence; QR shrinks at `refined`.
366
+ *
367
+ * Pass `fixed={false}` for layouts where body content can spill into the
368
+ * footer's render band on intermediate pages — see the prop JSDoc above.
309
369
  */
310
- declare function ExportFooterPdf({ brand, url, dateLabel, qrDataUrl, prominence, }: ExportFooterPdfProps): ReactElement;
370
+ declare function ExportFooterPdf({ brand, url, dateLabel, qrDataUrl, prominence, fixed, }: ExportFooterPdfProps): ReactElement;
311
371
  interface BrandedPdfPageProps {
312
372
  /** Brand configuration. */
313
373
  brand: BrandConfig;
@@ -363,4 +423,4 @@ interface BrandedPdfPageProps {
363
423
  */
364
424
  declare function BrandedPdfPage({ brand, title, toolLabel, subtitle, url, dateLabel, qrDataUrl, prominence, pageStyle, size, children, }: BrandedPdfPageProps): ReactElement;
365
425
 
366
- export { type BrandColors, type BrandConfig, BrandedPdfPage, type BrandedPdfPageProps, type BuildExportFilenameInput, type BuildExportUrlInput, type ExportFileExt, ExportFooterPdf, type ExportFooterPdfProps, ExportHeaderPdf, type ExportHeaderPdfProps, type ExportMedium, type ExportProminence, type ExportTier, type GenerateQrDataUrlOptions, type LogoMarkRenderProps, type LogoVariant, type PrintProfile, buildExportFilename, buildExportUrl, generateQrDataUrl, resolveProminence, tierToProminence };
426
+ export { type BrandColors, type BrandConfig, BrandedPdfPage, type BrandedPdfPageProps, type BuildExportFilenameInput, type BuildExportUrlInput, type ExportFileExt, ExportFooterPdf, type ExportFooterPdfProps, ExportHeaderPdf, type ExportHeaderPdfProps, type ExportMedium, type ExportProminence, type ExportTier, FOOTER_SAFE_AREA_PT, type GenerateQrDataUrlOptions, type LogoMarkRenderProps, type LogoVariant, type PrintProfile, buildExportFilename, buildExportUrl, generateQrDataUrl, resolveProminence, tierToProminence };
@@ -270,6 +270,47 @@ interface BuildExportFilenameInput {
270
270
  */
271
271
  declare function buildExportFilename({ brand, tool, titleOrDate, ext, }: BuildExportFilenameInput): string;
272
272
 
273
+ /**
274
+ * @react-pdf/renderer is declared as an OPTIONAL peer dependency. Apps that
275
+ * import this subpath must install it themselves; bundlers will surface a
276
+ * clear "Cannot find module" error if it isn't present, which is the standard
277
+ * platform-core pattern for optional peers (`pg`, `ioredis`, `bullmq`, etc).
278
+ */
279
+ /**
280
+ * Vertical space (in PDF points) that a `<Page>` must reserve at the bottom
281
+ * to keep flowed body content from rendering under the `fixed` footer.
282
+ *
283
+ * react-pdf paginates flow content when it reaches `pageHeight - paddingBottom`;
284
+ * `fixed` elements like `<ExportFooterPdf>` are pinned at their flow anchor on
285
+ * every page but DO NOT push the pagination boundary. So if `paddingBottom` is
286
+ * smaller than the footer's natural height, the last lines of body content on
287
+ * each page render directly underneath the footer chrome.
288
+ *
289
+ * The `ExportFooterPdf` rendered by this module claims roughly 55-60pt at
290
+ * `maximum` prominence (44pt QR + 8pt paddingTop + 2pt borderTop + line-height
291
+ * descenders + small render-engine slack). 72pt = footer + ~12pt clearance,
292
+ * which is the minimum we recommend for any `<Page>` that mounts an
293
+ * `<ExportFooterPdf>` (or `<BrandedPdfPage>`).
294
+ *
295
+ * **Why two carves are applied inside `BrandedPdfPage`:** `paddingBottom` alone
296
+ * protects normal flow content from paginating into the footer band, but it
297
+ * does NOT protect against overflow rendering — children inside the body
298
+ * container that use `justifyContent: "space-around"` (or any non-paginating
299
+ * distribution) and exceed the container's height render PAST the container's
300
+ * bottom edge, into the footer's render band. To absorb this case,
301
+ * `BrandedPdfPage` ALSO sets `marginBottom: FOOTER_SAFE_AREA_PT` on the body
302
+ * `<View>`, carving an explicit safe-zone inside the flow area. The double
303
+ * carve is intentional and defensive — combined, they cover both the
304
+ * pagination boundary AND modest overflow from custom layouts.
305
+ *
306
+ * Consumers that build their own `<Page>` directly (rather than using
307
+ * `<BrandedPdfPage>`) should set `paddingBottom` to at least this value AND,
308
+ * if they nest body content inside a flex container with non-paginating
309
+ * `justifyContent`, also apply `marginBottom: FOOTER_SAFE_AREA_PT` to that
310
+ * container. Documents that only use plain flow content (`<Text>`, `<View>`
311
+ * stacks) need only the `paddingBottom`.
312
+ */
313
+ declare const FOOTER_SAFE_AREA_PT = 72;
273
314
  interface ExportHeaderPdfProps {
274
315
  /** Brand configuration. */
275
316
  brand: BrandConfig;
@@ -300,14 +341,33 @@ interface ExportFooterPdfProps {
300
341
  qrDataUrl?: string | null;
301
342
  /** Branding prominence. Defaults to `maximum`. */
302
343
  prominence?: ExportProminence;
344
+ /**
345
+ * Render with react-pdf's `fixed` prop so the footer appears on every page
346
+ * of a multi-page document. Defaults to `true` (the typical behavior).
347
+ *
348
+ * Set to `false` for documents whose body content cannot be reliably
349
+ * constrained above the footer's render band — e.g., a `flex: 1` layout
350
+ * with overflow children that paginate (large brackets, dense tables,
351
+ * etc.). With `fixed: false` the footer flows after the body and renders
352
+ * only on the LAST page; intermediate pages have no footer chrome but
353
+ * also no body-on-footer overlap. This is the architecturally correct
354
+ * trade-off for content where pagination is the rule, not the exception.
355
+ *
356
+ * For ordinary documents (rules sheets, score sheets, single-page
357
+ * profile cards) leave at the default `true`.
358
+ */
359
+ fixed?: boolean;
303
360
  }
304
361
  /**
305
- * Branded PDF document footer — `fixed` so it renders on every page.
362
+ * Branded PDF document footer — `fixed` so it renders on every page (default).
306
363
  *
307
364
  * Composition: brand mark + name (left), URL + date (center-right), QR (far right).
308
365
  * Tagline shown only at `maximum` prominence; QR shrinks at `refined`.
366
+ *
367
+ * Pass `fixed={false}` for layouts where body content can spill into the
368
+ * footer's render band on intermediate pages — see the prop JSDoc above.
309
369
  */
310
- declare function ExportFooterPdf({ brand, url, dateLabel, qrDataUrl, prominence, }: ExportFooterPdfProps): ReactElement;
370
+ declare function ExportFooterPdf({ brand, url, dateLabel, qrDataUrl, prominence, fixed, }: ExportFooterPdfProps): ReactElement;
311
371
  interface BrandedPdfPageProps {
312
372
  /** Brand configuration. */
313
373
  brand: BrandConfig;
@@ -363,4 +423,4 @@ interface BrandedPdfPageProps {
363
423
  */
364
424
  declare function BrandedPdfPage({ brand, title, toolLabel, subtitle, url, dateLabel, qrDataUrl, prominence, pageStyle, size, children, }: BrandedPdfPageProps): ReactElement;
365
425
 
366
- export { type BrandColors, type BrandConfig, BrandedPdfPage, type BrandedPdfPageProps, type BuildExportFilenameInput, type BuildExportUrlInput, type ExportFileExt, ExportFooterPdf, type ExportFooterPdfProps, ExportHeaderPdf, type ExportHeaderPdfProps, type ExportMedium, type ExportProminence, type ExportTier, type GenerateQrDataUrlOptions, type LogoMarkRenderProps, type LogoVariant, type PrintProfile, buildExportFilename, buildExportUrl, generateQrDataUrl, resolveProminence, tierToProminence };
426
+ export { type BrandColors, type BrandConfig, BrandedPdfPage, type BrandedPdfPageProps, type BuildExportFilenameInput, type BuildExportUrlInput, type ExportFileExt, ExportFooterPdf, type ExportFooterPdfProps, ExportHeaderPdf, type ExportHeaderPdfProps, type ExportMedium, type ExportProminence, type ExportTier, FOOTER_SAFE_AREA_PT, type GenerateQrDataUrlOptions, type LogoMarkRenderProps, type LogoVariant, type PrintProfile, buildExportFilename, buildExportUrl, generateQrDataUrl, resolveProminence, tierToProminence };
@@ -33,6 +33,7 @@ __export(pdf_exports_exports, {
33
33
  BrandedPdfPage: () => BrandedPdfPage,
34
34
  ExportFooterPdf: () => ExportFooterPdf,
35
35
  ExportHeaderPdf: () => ExportHeaderPdf,
36
+ FOOTER_SAFE_AREA_PT: () => FOOTER_SAFE_AREA_PT,
36
37
  buildExportFilename: () => buildExportFilename,
37
38
  buildExportUrl: () => buildExportUrl,
38
39
  generateQrDataUrl: () => generateQrDataUrl,
@@ -109,6 +110,7 @@ function slugify(input) {
109
110
  // src/pdf-exports/pdf-chrome.tsx
110
111
  var import_renderer = require("@react-pdf/renderer");
111
112
  var import_jsx_runtime = require("react/jsx-runtime");
113
+ var FOOTER_SAFE_AREA_PT = 72;
112
114
  function makeChromeStyles(brand) {
113
115
  return import_renderer.StyleSheet.create({
114
116
  headerRow: {
@@ -195,8 +197,19 @@ function makeChromeStyles(brand) {
195
197
  width: 32,
196
198
  height: 32
197
199
  },
200
+ // `flex: 1` makes the body fill the page's available flow area between the
201
+ // header and the footer's flow anchor. `marginBottom: FOOTER_SAFE_AREA_PT`
202
+ // carves an explicit safe-zone INSIDE that flow area so overflow children
203
+ // (e.g., a flex column with `justifyContent: "space-around"` and content
204
+ // exceeding the container height) cannot render past the body's bottom
205
+ // edge into the footer's render band. Combined with the page-level
206
+ // `paddingBottom: FOOTER_SAFE_AREA_PT`, this is a 2x defensive carve that
207
+ // covers both normal-flow pagination (where `paddingBottom` is sufficient)
208
+ // and non-paginating distributions (where only `marginBottom` saves you).
209
+ // See the JSDoc on `FOOTER_SAFE_AREA_PT` above for the full rationale.
198
210
  pageBody: {
199
- flex: 1
211
+ flex: 1,
212
+ marginBottom: FOOTER_SAFE_AREA_PT
200
213
  }
201
214
  });
202
215
  }
@@ -228,7 +241,8 @@ function ExportFooterPdf({
228
241
  url,
229
242
  dateLabel,
230
243
  qrDataUrl,
231
- prominence = "maximum"
244
+ prominence = "maximum",
245
+ fixed = true
232
246
  }) {
233
247
  const styles = makeChromeStyles(brand);
234
248
  const isRefined = prominence === "refined";
@@ -236,7 +250,7 @@ function ExportFooterPdf({
236
250
  const markSize = isRefined ? 20 : 26;
237
251
  const showQr = Boolean(qrDataUrl);
238
252
  const Logo = brand.renderLogoMarkPdf;
239
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_renderer.View, { style: styles.footerRow, fixed: true, children: [
253
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_renderer.View, { style: styles.footerRow, fixed, children: [
240
254
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_renderer.View, { style: styles.footerLeft, children: [
241
255
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Logo, { size: markSize, variant: "original" }),
242
256
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_renderer.View, { children: [
@@ -272,7 +286,9 @@ function BrandedPdfPage({
272
286
  }) {
273
287
  const styles = makeChromeStyles(brand);
274
288
  const defaultPageStyle = {
275
- padding: 36,
289
+ paddingTop: 36,
290
+ paddingHorizontal: 36,
291
+ paddingBottom: FOOTER_SAFE_AREA_PT,
276
292
  fontFamily: "Helvetica",
277
293
  backgroundColor: brand.colors.surface ?? "#ffffff",
278
294
  fontSize: 10,
@@ -308,6 +324,7 @@ function BrandedPdfPage({
308
324
  BrandedPdfPage,
309
325
  ExportFooterPdf,
310
326
  ExportHeaderPdf,
327
+ FOOTER_SAFE_AREA_PT,
311
328
  buildExportFilename,
312
329
  buildExportUrl,
313
330
  generateQrDataUrl,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/pdf-exports/index.ts","../../src/pdf-exports/prominence.ts","../../src/pdf-exports/qr.ts","../../src/pdf-exports/url-utils.ts","../../src/pdf-exports/pdf-chrome.tsx"],"sourcesContent":["/**\n * Shared PDF export primitives — branded chrome, tier-aware prominence, QR codes,\n * UTM-tagged URLs, and filename builders for branded export pipelines.\n *\n * Companion to `/email-templates`: same shape (types + layout + utilities), different\n * runtime (server-side react-pdf rendering).\n *\n * **Optional peer dependencies:**\n * - `@react-pdf/renderer` (^4.0.0) — required for chrome components\n * - `qrcode` (^1.5.0) — required for `generateQrDataUrl`\n *\n * **Brand-agnostic:** the package ships zero brand data. Apps supply a `BrandConfig`\n * with their own logo render functions, color palette, name, and domain.\n *\n * @example\n * ```ts\n * import {\n * BrandedPdfPage,\n * tierToProminence,\n * generateQrDataUrl,\n * buildExportUrl,\n * buildExportFilename,\n * type BrandConfig,\n * } from \"@digilogiclabs/platform-core/pdf-exports\";\n *\n * const ossBrand: BrandConfig = {\n * name: \"OpenSourceSports\",\n * domain: \"opensourcesports.io\",\n * tagline: \"Where Sports Are Defined\",\n * colors: { primary: \"#f16c25\", secondary: \"#1a4d52\", ink: \"#0c1f22\", muted: \"#3a5a5f\" },\n * renderLogoMark: (p) => <OssLogoMark {...p} />,\n * renderLogoMarkPdf: (p) => <OssLogoMarkPdf {...p} />,\n * };\n * ```\n */\n\n// Types\nexport type {\n BrandColors,\n BrandConfig,\n ExportProminence,\n ExportTier,\n LogoMarkRenderProps,\n LogoVariant,\n PrintProfile,\n} from \"./types\";\n\n// Tier mapping\nexport { tierToProminence, resolveProminence } from \"./prominence\";\n\n// QR code generator\nexport { generateQrDataUrl } from \"./qr\";\nexport type { GenerateQrDataUrlOptions } from \"./qr\";\n\n// URL + filename builders\nexport { buildExportUrl, buildExportFilename } from \"./url-utils\";\nexport type {\n BuildExportUrlInput,\n BuildExportFilenameInput,\n ExportMedium,\n ExportFileExt,\n} from \"./url-utils\";\n\n// PDF chrome components\nexport { ExportHeaderPdf, ExportFooterPdf, BrandedPdfPage } from \"./pdf-chrome\";\nexport type {\n ExportHeaderPdfProps,\n ExportFooterPdfProps,\n BrandedPdfPageProps,\n} from \"./pdf-chrome\";\n","import type { BrandConfig, ExportProminence, ExportTier } from \"./types\";\n\n/**\n * Default tier → prominence mapping.\n *\n * Patron and supporter tiers earn `refined` prominence (smaller branding chrome,\n * tagline hidden). All other tiers — including signed-in free users and anonymous\n * visitors — receive `maximum` prominence so OSS/app branding stays visible.\n *\n * Branding is **never removed**, only modulated in size and detail. Apps that need\n * a different vocabulary (e.g., \"plus\" / \"pro\") should supply\n * `BrandConfig.prominenceMap` instead of forking this function.\n *\n * @example\n * ```ts\n * tierToProminence(\"patron\"); // \"refined\"\n * tierToProminence(\"supporter\"); // \"refined\"\n * tierToProminence(\"free\"); // \"maximum\"\n * tierToProminence(null); // \"maximum\"\n * tierToProminence(\"plus\"); // \"maximum\" (unknown token falls back)\n * ```\n */\nexport function tierToProminence(tier: ExportTier): ExportProminence {\n if (tier === \"patron\") return \"refined\";\n if (tier === \"supporter\") return \"refined\";\n return \"maximum\";\n}\n\n/**\n * Resolve prominence for a brand — uses the brand's `prominenceMap` if supplied,\n * otherwise the default `tierToProminence` mapping.\n */\nexport function resolveProminence(\n brand: BrandConfig,\n tier: ExportTier,\n): ExportProminence {\n if (brand.prominenceMap) return brand.prominenceMap(tier);\n return tierToProminence(tier);\n}\n","/**\n * QR code generation for branded export footers.\n *\n * Uses the `qrcode` package (optional peer dependency). Calls return a base64\n * data URL ready to be embedded as an `<Image src={...}>` in react-pdf or as a\n * standard `<img>` in HTML preview routes.\n *\n * Failures (invalid URL, encoder errors) return `null` rather than throwing —\n * exports should degrade gracefully without a QR rather than failing the whole\n * PDF render.\n */\n\nexport interface GenerateQrDataUrlOptions {\n /** Output pixel size (square). Default: 320. */\n size?: number;\n /** Quiet-zone margin in modules. Default: 1. */\n margin?: number;\n /** Module (foreground) color. Default: \"#0c1f22\" (dark ink). */\n darkColor?: string;\n /** Background color. Default: \"#ffffff\". */\n lightColor?: string;\n /**\n * Error-correction level. Default: \"M\" (15% recovery — balances density vs durability\n * on printed sheets that may scuff or fold).\n */\n errorCorrectionLevel?: \"L\" | \"M\" | \"Q\" | \"H\";\n}\n\n/**\n * Generate a QR code as a base64 PNG data URL.\n *\n * @param url - The URL to encode (typically a UTM-tagged link back to the live page).\n * @param options - Color, size, and error-correction overrides.\n * @returns Data URL string, or `null` on failure.\n *\n * @example\n * ```ts\n * const qrDataUrl = await generateQrDataUrl(\n * \"https://opensourcesports.io/rules/basketball?utm_source=export\",\n * { darkColor: brand.colors.ink },\n * );\n * if (qrDataUrl) {\n * // <Image src={qrDataUrl} style={...} />\n * }\n * ```\n */\nexport async function generateQrDataUrl(\n url: string,\n options?: GenerateQrDataUrlOptions,\n): Promise<string | null> {\n try {\n // Dynamic import keeps qrcode as an optional peer dep — only loaded if used.\n const qr = await import(\"qrcode\");\n const toDataURL = qr.default?.toDataURL ?? qr.toDataURL;\n return await toDataURL(url, {\n width: options?.size ?? 320,\n margin: options?.margin ?? 1,\n errorCorrectionLevel: options?.errorCorrectionLevel ?? \"M\",\n color: {\n dark: options?.darkColor ?? \"#0c1f22\",\n light: options?.lightColor ?? \"#ffffff\",\n },\n });\n } catch {\n return null;\n }\n}\n","import type { BrandConfig } from \"./types\";\n\n/**\n * Export medium — used in UTM tagging and filename suffixes.\n */\nexport type ExportMedium = \"pdf\" | \"png\" | \"ical\" | \"csv\" | \"tsv\";\n\n/**\n * File extension — distinct from medium because iCal uses `.ics` not `.ical`.\n */\nexport type ExportFileExt = \"pdf\" | \"png\" | \"ics\" | \"csv\" | \"tsv\";\n\nexport interface BuildExportUrlInput {\n /** Brand config — supplies the domain. */\n brand: BrandConfig;\n /**\n * Tool / template identifier (e.g., \"bracket-generator\", \"rules\", \"scoreboard\").\n * Becomes part of the URL path and `utm_tool`.\n */\n tool: string;\n /** Export medium for `utm_medium`. */\n medium: ExportMedium;\n /**\n * Optional share-link slug — when present, the URL points at `/s/<slug>` rather than\n * `/tools/<tool>` so QR scanners land on the actual shared artifact.\n */\n shareSlug?: string;\n /**\n * Optional URL path override. When supplied, replaces both `/s/<slug>` and\n * `/tools/<tool>` defaults. Useful for non-tool exports (e.g., `/rules/basketball`).\n */\n path?: string;\n /** Optional extra UTM/query params merged into the URL. */\n params?: Record<string, string>;\n}\n\n/**\n * Build a UTM-tagged URL for QR codes / footer links on branded exports.\n *\n * Every printed sheet that scans back to the live page becomes a measurable acquisition\n * channel — the UTM trio (`utm_source=export`, `utm_medium=<medium>`, `utm_tool=<tool>`)\n * lets analytics attribute traffic to specific export types.\n *\n * @example\n * ```ts\n * buildExportUrl({\n * brand: ossBrand,\n * tool: \"rules\",\n * medium: \"pdf\",\n * path: \"/rules/basketball\",\n * });\n * // → \"https://opensourcesports.io/rules/basketball?utm_source=export&utm_medium=pdf&utm_tool=rules\"\n * ```\n */\nexport function buildExportUrl({\n brand,\n tool,\n medium,\n shareSlug,\n path,\n params,\n}: BuildExportUrlInput): string {\n const resolvedPath = path\n ? path\n : shareSlug\n ? `/s/${shareSlug}`\n : `/tools/${tool}`;\n const base = `https://${brand.domain}${resolvedPath}`;\n const search = new URLSearchParams({\n utm_source: \"export\",\n utm_medium: medium,\n utm_tool: tool,\n ...params,\n });\n return `${base}?${search.toString()}`;\n}\n\nexport interface BuildExportFilenameInput {\n /** Brand config — supplies the filename prefix. */\n brand: BrandConfig;\n /** Tool / template identifier. */\n tool: string;\n /** Optional title or date suffix (slugified). */\n titleOrDate?: string;\n /** File extension. */\n ext: ExportFileExt;\n}\n\n/**\n * Build a filename of the form `{brand-slug}-{tool}[-{title-slug}].{ext}`.\n *\n * The brand slug is derived from `brand.name` (lowercased, hyphenated) so the filename\n * carries brand identity even when downloaded outside the app context.\n *\n * @example\n * ```ts\n * buildExportFilename({\n * brand: ossBrand,\n * tool: \"rules\",\n * titleOrDate: \"Basketball NBA\",\n * ext: \"pdf\",\n * });\n * // → \"opensourcesports-rules-basketball-nba.pdf\"\n * ```\n */\nexport function buildExportFilename({\n brand,\n tool,\n titleOrDate,\n ext,\n}: BuildExportFilenameInput): string {\n const brandSlug = slugify(brand.name);\n const titleSlug = slugify(titleOrDate);\n const middle = titleSlug ? `${tool}-${titleSlug}` : tool;\n return `${brandSlug}-${middle}.${ext}`;\n}\n\nfunction slugify(input: string | undefined): string {\n if (!input) return \"\";\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60);\n}\n","import { Image, Page, StyleSheet, Text, View } from \"@react-pdf/renderer\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nimport type { BrandConfig, ExportProminence } from \"./types\";\n\n/**\n * @react-pdf/renderer is declared as an OPTIONAL peer dependency. Apps that\n * import this subpath must install it themselves; bundlers will surface a\n * clear \"Cannot find module\" error if it isn't present, which is the standard\n * platform-core pattern for optional peers (`pg`, `ioredis`, `bullmq`, etc).\n */\n\n/**\n * Build a brand-aware StyleSheet for header + footer chrome.\n *\n * Called once per render — react-pdf's StyleSheet.create is intentionally\n * lightweight and the perf cost is negligible relative to the actual document\n * render. Building per render means brand colors are honored without\n * module-level caching tricks.\n */\nfunction makeChromeStyles(brand: BrandConfig) {\n return StyleSheet.create({\n headerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderBottomWidth: 3,\n borderBottomColor: brand.colors.primary,\n paddingBottom: 10,\n marginBottom: 12,\n gap: 16,\n },\n headerLeft: { flexDirection: \"column\", flexGrow: 1, flexShrink: 1 },\n eyebrow: {\n fontSize: 9,\n letterSpacing: 1.5,\n color: brand.colors.muted,\n textTransform: \"uppercase\",\n fontFamily: \"Helvetica-Bold\",\n marginBottom: 2,\n },\n title: {\n fontSize: 22,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.ink,\n lineHeight: 1.15,\n },\n subtitle: {\n fontSize: 10,\n color: brand.colors.muted,\n marginTop: 3,\n },\n lockupRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n gap: 8,\n },\n wordmark: {\n fontSize: 13,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n letterSpacing: -0.2,\n },\n footerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderTopWidth: 2,\n borderTopColor: brand.colors.primary,\n paddingTop: 8,\n marginTop: 10,\n gap: 16,\n },\n footerLeft: { flexDirection: \"row\", alignItems: \"center\", gap: 8 },\n footerMid: {\n flexDirection: \"column\",\n alignItems: \"flex-end\",\n flexShrink: 1,\n },\n footerUrl: {\n fontSize: 9,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n footerDate: {\n fontSize: 8,\n color: brand.colors.muted,\n marginTop: 2,\n },\n footerTagline: {\n fontSize: 8,\n color: brand.colors.muted,\n },\n footerName: {\n fontSize: 11,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n qr: {\n width: 44,\n height: 44,\n },\n qrRefined: {\n width: 32,\n height: 32,\n },\n pageBody: {\n flex: 1,\n },\n });\n}\n\nexport interface ExportHeaderPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title (e.g., \"Basketball (NBA) — Official Rules\"). */\n title: string;\n /** Small uppercase eyebrow above the title (e.g., \"Rules Sheet\", \"Bracket Generator\"). */\n toolLabel: string;\n /** Optional supplemental line under the title. */\n subtitle?: string;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n}\n\n/**\n * Branded PDF document header — first-page only by default.\n *\n * Renders eyebrow + title + optional subtitle on the left, brand mark + wordmark on\n * the right, with a primary-color rule below.\n */\nexport function ExportHeaderPdf({\n brand,\n title,\n toolLabel,\n subtitle,\n prominence = \"maximum\",\n}: ExportHeaderPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const lockupSize = prominence === \"maximum\" ? 32 : 26;\n const titleSize = prominence === \"maximum\" ? 22 : 18;\n const Logo = brand.renderLogoMarkPdf;\n return (\n <View style={styles.headerRow} fixed={false}>\n <View style={styles.headerLeft}>\n <Text style={styles.eyebrow}>{toolLabel}</Text>\n <Text style={[styles.title, { fontSize: titleSize }]}>{title}</Text>\n {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null}\n </View>\n <View style={styles.lockupRow}>\n <Logo size={lockupSize} variant=\"original\" />\n <Text style={styles.wordmark}>{brand.name}</Text>\n </View>\n </View>\n );\n}\n\nexport interface ExportFooterPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Public URL displayed in footer (typically UTM-tagged via `buildExportUrl`). */\n url: string;\n /** Generation date label (e.g., \"Generated April 26, 2026\"). */\n dateLabel?: string;\n /** Pre-rendered QR data URL (from `generateQrDataUrl`). Pass `null` to omit. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n}\n\n/**\n * Branded PDF document footer — `fixed` so it renders on every page.\n *\n * Composition: brand mark + name (left), URL + date (center-right), QR (far right).\n * Tagline shown only at `maximum` prominence; QR shrinks at `refined`.\n */\nexport function ExportFooterPdf({\n brand,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n}: ExportFooterPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const isRefined = prominence === \"refined\";\n const showTagline = prominence === \"maximum\" && Boolean(brand.tagline);\n const markSize = isRefined ? 20 : 26;\n const showQr = Boolean(qrDataUrl);\n const Logo = brand.renderLogoMarkPdf;\n\n return (\n <View style={styles.footerRow} fixed>\n <View style={styles.footerLeft}>\n <Logo size={markSize} variant=\"original\" />\n <View>\n <Text style={styles.footerName}>{brand.name}</Text>\n {showTagline ? (\n <Text style={styles.footerTagline}>{brand.tagline}</Text>\n ) : null}\n </View>\n </View>\n <View style={styles.footerMid}>\n <Text style={styles.footerUrl}>{url}</Text>\n {dateLabel ? <Text style={styles.footerDate}>{dateLabel}</Text> : null}\n </View>\n {showQr && qrDataUrl ? (\n <Image\n src={qrDataUrl}\n style={isRefined ? styles.qrRefined : styles.qr}\n />\n ) : null}\n </View>\n );\n}\n\nexport interface BrandedPdfPageProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title shown in the header. */\n title: string;\n /** Eyebrow label above the title. */\n toolLabel: string;\n /** Optional subtitle under the title. */\n subtitle?: string;\n /** Footer URL (typically UTM-tagged). */\n url: string;\n /** Footer date label. */\n dateLabel?: string;\n /** Pre-rendered QR data URL. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n /**\n * Optional react-pdf Page-level style overrides (e.g., padding, fontFamily).\n * Merged onto the default page styles.\n */\n pageStyle?: Record<string, unknown>;\n /** Optional react-pdf page size. Defaults to \"LETTER\". */\n size?: \"LETTER\" | \"A4\" | \"LEGAL\" | \"TABLOID\";\n /** Document body — your selected sections, content, etc. */\n children: ReactNode;\n}\n\n/**\n * Full branded PDF page wrapper — composes header + body slot + sticky footer.\n *\n * The footer is `fixed` so it renders on every page automatically. The header is\n * first-page only; if you need a per-page compact strip on page 2+, use\n * `ExportHeaderPdf` with your own placement logic.\n *\n * @example\n * ```tsx\n * import { Document } from \"@react-pdf/renderer\";\n * import { BrandedPdfPage } from \"@digilogiclabs/platform-core/pdf-exports\";\n *\n * <Document>\n * <BrandedPdfPage\n * brand={ossBrand}\n * title=\"Basketball — Official Rules\"\n * toolLabel=\"Rules Sheet\"\n * url=\"https://opensourcesports.io/rules/basketball?utm_source=export\"\n * qrDataUrl={qrDataUrl}\n * prominence={tierToProminence(userTier)}\n * >\n * <RulesBody sections={selectedSections} />\n * </BrandedPdfPage>\n * </Document>\n * ```\n */\nexport function BrandedPdfPage({\n brand,\n title,\n toolLabel,\n subtitle,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n pageStyle,\n size = \"LETTER\",\n children,\n}: BrandedPdfPageProps): ReactElement {\n const styles = makeChromeStyles(brand);\n\n const defaultPageStyle = {\n padding: 36,\n fontFamily: \"Helvetica\",\n backgroundColor: brand.colors.surface ?? \"#ffffff\",\n fontSize: 10,\n color: brand.colors.ink,\n };\n const mergedPageStyle = { ...defaultPageStyle, ...pageStyle };\n\n return (\n <Page size={size} style={mergedPageStyle}>\n <ExportHeaderPdf\n brand={brand}\n title={title}\n toolLabel={toolLabel}\n subtitle={subtitle}\n prominence={prominence}\n />\n <View style={styles.pageBody}>{children}</View>\n <ExportFooterPdf\n brand={brand}\n url={url}\n dateLabel={dateLabel}\n qrDataUrl={qrDataUrl}\n prominence={prominence}\n />\n </Page>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,SAAS,iBAAiB,MAAoC;AACnE,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,SAAS,YAAa,QAAO;AACjC,SAAO;AACT;AAMO,SAAS,kBACd,OACA,MACkB;AAClB,MAAI,MAAM,cAAe,QAAO,MAAM,cAAc,IAAI;AACxD,SAAO,iBAAiB,IAAI;AAC9B;;;ACQA,eAAsB,kBACpB,KACA,SACwB;AACxB,MAAI;AAEF,UAA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,MAAY,OAAO,iBACvB;AAAA;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,IACA,4CAAC,wBAAK,OAAO,OAAO,UAAW,UAAS;AAAA,IACxC;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../src/pdf-exports/index.ts","../../src/pdf-exports/prominence.ts","../../src/pdf-exports/qr.ts","../../src/pdf-exports/url-utils.ts","../../src/pdf-exports/pdf-chrome.tsx"],"sourcesContent":["/**\n * Shared PDF export primitives — branded chrome, tier-aware prominence, QR codes,\n * UTM-tagged URLs, and filename builders for branded export pipelines.\n *\n * Companion to `/email-templates`: same shape (types + layout + utilities), different\n * runtime (server-side react-pdf rendering).\n *\n * **Optional peer dependencies:**\n * - `@react-pdf/renderer` (^4.0.0) — required for chrome components\n * - `qrcode` (^1.5.0) — required for `generateQrDataUrl`\n *\n * **Brand-agnostic:** the package ships zero brand data. Apps supply a `BrandConfig`\n * with their own logo render functions, color palette, name, and domain.\n *\n * @example\n * ```ts\n * import {\n * BrandedPdfPage,\n * tierToProminence,\n * generateQrDataUrl,\n * buildExportUrl,\n * buildExportFilename,\n * type BrandConfig,\n * } from \"@digilogiclabs/platform-core/pdf-exports\";\n *\n * const ossBrand: BrandConfig = {\n * name: \"OpenSourceSports\",\n * domain: \"opensourcesports.io\",\n * tagline: \"Where Sports Are Defined\",\n * colors: { primary: \"#f16c25\", secondary: \"#1a4d52\", ink: \"#0c1f22\", muted: \"#3a5a5f\" },\n * renderLogoMark: (p) => <OssLogoMark {...p} />,\n * renderLogoMarkPdf: (p) => <OssLogoMarkPdf {...p} />,\n * };\n * ```\n */\n\n// Types\nexport type {\n BrandColors,\n BrandConfig,\n ExportProminence,\n ExportTier,\n LogoMarkRenderProps,\n LogoVariant,\n PrintProfile,\n} from \"./types\";\n\n// Tier mapping\nexport { tierToProminence, resolveProminence } from \"./prominence\";\n\n// QR code generator\nexport { generateQrDataUrl } from \"./qr\";\nexport type { GenerateQrDataUrlOptions } from \"./qr\";\n\n// URL + filename builders\nexport { buildExportUrl, buildExportFilename } from \"./url-utils\";\nexport type {\n BuildExportUrlInput,\n BuildExportFilenameInput,\n ExportMedium,\n ExportFileExt,\n} from \"./url-utils\";\n\n// PDF chrome components\nexport {\n ExportHeaderPdf,\n ExportFooterPdf,\n BrandedPdfPage,\n FOOTER_SAFE_AREA_PT,\n} from \"./pdf-chrome\";\nexport type {\n ExportHeaderPdfProps,\n ExportFooterPdfProps,\n BrandedPdfPageProps,\n} from \"./pdf-chrome\";\n","import type { BrandConfig, ExportProminence, ExportTier } from \"./types\";\n\n/**\n * Default tier → prominence mapping.\n *\n * Patron and supporter tiers earn `refined` prominence (smaller branding chrome,\n * tagline hidden). All other tiers — including signed-in free users and anonymous\n * visitors — receive `maximum` prominence so OSS/app branding stays visible.\n *\n * Branding is **never removed**, only modulated in size and detail. Apps that need\n * a different vocabulary (e.g., \"plus\" / \"pro\") should supply\n * `BrandConfig.prominenceMap` instead of forking this function.\n *\n * @example\n * ```ts\n * tierToProminence(\"patron\"); // \"refined\"\n * tierToProminence(\"supporter\"); // \"refined\"\n * tierToProminence(\"free\"); // \"maximum\"\n * tierToProminence(null); // \"maximum\"\n * tierToProminence(\"plus\"); // \"maximum\" (unknown token falls back)\n * ```\n */\nexport function tierToProminence(tier: ExportTier): ExportProminence {\n if (tier === \"patron\") return \"refined\";\n if (tier === \"supporter\") return \"refined\";\n return \"maximum\";\n}\n\n/**\n * Resolve prominence for a brand — uses the brand's `prominenceMap` if supplied,\n * otherwise the default `tierToProminence` mapping.\n */\nexport function resolveProminence(\n brand: BrandConfig,\n tier: ExportTier,\n): ExportProminence {\n if (brand.prominenceMap) return brand.prominenceMap(tier);\n return tierToProminence(tier);\n}\n","/**\n * QR code generation for branded export footers.\n *\n * Uses the `qrcode` package (optional peer dependency). Calls return a base64\n * data URL ready to be embedded as an `<Image src={...}>` in react-pdf or as a\n * standard `<img>` in HTML preview routes.\n *\n * Failures (invalid URL, encoder errors) return `null` rather than throwing —\n * exports should degrade gracefully without a QR rather than failing the whole\n * PDF render.\n */\n\nexport interface GenerateQrDataUrlOptions {\n /** Output pixel size (square). Default: 320. */\n size?: number;\n /** Quiet-zone margin in modules. Default: 1. */\n margin?: number;\n /** Module (foreground) color. Default: \"#0c1f22\" (dark ink). */\n darkColor?: string;\n /** Background color. Default: \"#ffffff\". */\n lightColor?: string;\n /**\n * Error-correction level. Default: \"M\" (15% recovery — balances density vs durability\n * on printed sheets that may scuff or fold).\n */\n errorCorrectionLevel?: \"L\" | \"M\" | \"Q\" | \"H\";\n}\n\n/**\n * Generate a QR code as a base64 PNG data URL.\n *\n * @param url - The URL to encode (typically a UTM-tagged link back to the live page).\n * @param options - Color, size, and error-correction overrides.\n * @returns Data URL string, or `null` on failure.\n *\n * @example\n * ```ts\n * const qrDataUrl = await generateQrDataUrl(\n * \"https://opensourcesports.io/rules/basketball?utm_source=export\",\n * { darkColor: brand.colors.ink },\n * );\n * if (qrDataUrl) {\n * // <Image src={qrDataUrl} style={...} />\n * }\n * ```\n */\nexport async function generateQrDataUrl(\n url: string,\n options?: GenerateQrDataUrlOptions,\n): Promise<string | null> {\n try {\n // Dynamic import keeps qrcode as an optional peer dep — only loaded if used.\n const qr = await import(\"qrcode\");\n const toDataURL = qr.default?.toDataURL ?? qr.toDataURL;\n return await toDataURL(url, {\n width: options?.size ?? 320,\n margin: options?.margin ?? 1,\n errorCorrectionLevel: options?.errorCorrectionLevel ?? \"M\",\n color: {\n dark: options?.darkColor ?? \"#0c1f22\",\n light: options?.lightColor ?? \"#ffffff\",\n },\n });\n } catch {\n return null;\n }\n}\n","import type { BrandConfig } from \"./types\";\n\n/**\n * Export medium — used in UTM tagging and filename suffixes.\n */\nexport type ExportMedium = \"pdf\" | \"png\" | \"ical\" | \"csv\" | \"tsv\";\n\n/**\n * File extension — distinct from medium because iCal uses `.ics` not `.ical`.\n */\nexport type ExportFileExt = \"pdf\" | \"png\" | \"ics\" | \"csv\" | \"tsv\";\n\nexport interface BuildExportUrlInput {\n /** Brand config — supplies the domain. */\n brand: BrandConfig;\n /**\n * Tool / template identifier (e.g., \"bracket-generator\", \"rules\", \"scoreboard\").\n * Becomes part of the URL path and `utm_tool`.\n */\n tool: string;\n /** Export medium for `utm_medium`. */\n medium: ExportMedium;\n /**\n * Optional share-link slug — when present, the URL points at `/s/<slug>` rather than\n * `/tools/<tool>` so QR scanners land on the actual shared artifact.\n */\n shareSlug?: string;\n /**\n * Optional URL path override. When supplied, replaces both `/s/<slug>` and\n * `/tools/<tool>` defaults. Useful for non-tool exports (e.g., `/rules/basketball`).\n */\n path?: string;\n /** Optional extra UTM/query params merged into the URL. */\n params?: Record<string, string>;\n}\n\n/**\n * Build a UTM-tagged URL for QR codes / footer links on branded exports.\n *\n * Every printed sheet that scans back to the live page becomes a measurable acquisition\n * channel — the UTM trio (`utm_source=export`, `utm_medium=<medium>`, `utm_tool=<tool>`)\n * lets analytics attribute traffic to specific export types.\n *\n * @example\n * ```ts\n * buildExportUrl({\n * brand: ossBrand,\n * tool: \"rules\",\n * medium: \"pdf\",\n * path: \"/rules/basketball\",\n * });\n * // → \"https://opensourcesports.io/rules/basketball?utm_source=export&utm_medium=pdf&utm_tool=rules\"\n * ```\n */\nexport function buildExportUrl({\n brand,\n tool,\n medium,\n shareSlug,\n path,\n params,\n}: BuildExportUrlInput): string {\n const resolvedPath = path\n ? path\n : shareSlug\n ? `/s/${shareSlug}`\n : `/tools/${tool}`;\n const base = `https://${brand.domain}${resolvedPath}`;\n const search = new URLSearchParams({\n utm_source: \"export\",\n utm_medium: medium,\n utm_tool: tool,\n ...params,\n });\n return `${base}?${search.toString()}`;\n}\n\nexport interface BuildExportFilenameInput {\n /** Brand config — supplies the filename prefix. */\n brand: BrandConfig;\n /** Tool / template identifier. */\n tool: string;\n /** Optional title or date suffix (slugified). */\n titleOrDate?: string;\n /** File extension. */\n ext: ExportFileExt;\n}\n\n/**\n * Build a filename of the form `{brand-slug}-{tool}[-{title-slug}].{ext}`.\n *\n * The brand slug is derived from `brand.name` (lowercased, hyphenated) so the filename\n * carries brand identity even when downloaded outside the app context.\n *\n * @example\n * ```ts\n * buildExportFilename({\n * brand: ossBrand,\n * tool: \"rules\",\n * titleOrDate: \"Basketball NBA\",\n * ext: \"pdf\",\n * });\n * // → \"opensourcesports-rules-basketball-nba.pdf\"\n * ```\n */\nexport function buildExportFilename({\n brand,\n tool,\n titleOrDate,\n ext,\n}: BuildExportFilenameInput): string {\n const brandSlug = slugify(brand.name);\n const titleSlug = slugify(titleOrDate);\n const middle = titleSlug ? `${tool}-${titleSlug}` : tool;\n return `${brandSlug}-${middle}.${ext}`;\n}\n\nfunction slugify(input: string | undefined): string {\n if (!input) return \"\";\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60);\n}\n","import { Image, Page, StyleSheet, Text, View } from \"@react-pdf/renderer\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nimport type { BrandConfig, ExportProminence } from \"./types\";\n\n/**\n * @react-pdf/renderer is declared as an OPTIONAL peer dependency. Apps that\n * import this subpath must install it themselves; bundlers will surface a\n * clear \"Cannot find module\" error if it isn't present, which is the standard\n * platform-core pattern for optional peers (`pg`, `ioredis`, `bullmq`, etc).\n */\n\n/**\n * Vertical space (in PDF points) that a `<Page>` must reserve at the bottom\n * to keep flowed body content from rendering under the `fixed` footer.\n *\n * react-pdf paginates flow content when it reaches `pageHeight - paddingBottom`;\n * `fixed` elements like `<ExportFooterPdf>` are pinned at their flow anchor on\n * every page but DO NOT push the pagination boundary. So if `paddingBottom` is\n * smaller than the footer's natural height, the last lines of body content on\n * each page render directly underneath the footer chrome.\n *\n * The `ExportFooterPdf` rendered by this module claims roughly 55-60pt at\n * `maximum` prominence (44pt QR + 8pt paddingTop + 2pt borderTop + line-height\n * descenders + small render-engine slack). 72pt = footer + ~12pt clearance,\n * which is the minimum we recommend for any `<Page>` that mounts an\n * `<ExportFooterPdf>` (or `<BrandedPdfPage>`).\n *\n * **Why two carves are applied inside `BrandedPdfPage`:** `paddingBottom` alone\n * protects normal flow content from paginating into the footer band, but it\n * does NOT protect against overflow rendering — children inside the body\n * container that use `justifyContent: \"space-around\"` (or any non-paginating\n * distribution) and exceed the container's height render PAST the container's\n * bottom edge, into the footer's render band. To absorb this case,\n * `BrandedPdfPage` ALSO sets `marginBottom: FOOTER_SAFE_AREA_PT` on the body\n * `<View>`, carving an explicit safe-zone inside the flow area. The double\n * carve is intentional and defensive — combined, they cover both the\n * pagination boundary AND modest overflow from custom layouts.\n *\n * Consumers that build their own `<Page>` directly (rather than using\n * `<BrandedPdfPage>`) should set `paddingBottom` to at least this value AND,\n * if they nest body content inside a flex container with non-paginating\n * `justifyContent`, also apply `marginBottom: FOOTER_SAFE_AREA_PT` to that\n * container. Documents that only use plain flow content (`<Text>`, `<View>`\n * stacks) need only the `paddingBottom`.\n */\nexport const FOOTER_SAFE_AREA_PT = 72;\n\n/**\n * Build a brand-aware StyleSheet for header + footer chrome.\n *\n * Called once per render — react-pdf's StyleSheet.create is intentionally\n * lightweight and the perf cost is negligible relative to the actual document\n * render. Building per render means brand colors are honored without\n * module-level caching tricks.\n */\nfunction makeChromeStyles(brand: BrandConfig) {\n return StyleSheet.create({\n headerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderBottomWidth: 3,\n borderBottomColor: brand.colors.primary,\n paddingBottom: 10,\n marginBottom: 12,\n gap: 16,\n },\n headerLeft: { flexDirection: \"column\", flexGrow: 1, flexShrink: 1 },\n eyebrow: {\n fontSize: 9,\n letterSpacing: 1.5,\n color: brand.colors.muted,\n textTransform: \"uppercase\",\n fontFamily: \"Helvetica-Bold\",\n marginBottom: 2,\n },\n title: {\n fontSize: 22,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.ink,\n lineHeight: 1.15,\n },\n subtitle: {\n fontSize: 10,\n color: brand.colors.muted,\n marginTop: 3,\n },\n lockupRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n gap: 8,\n },\n wordmark: {\n fontSize: 13,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n letterSpacing: -0.2,\n },\n footerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderTopWidth: 2,\n borderTopColor: brand.colors.primary,\n paddingTop: 8,\n marginTop: 10,\n gap: 16,\n },\n footerLeft: { flexDirection: \"row\", alignItems: \"center\", gap: 8 },\n footerMid: {\n flexDirection: \"column\",\n alignItems: \"flex-end\",\n flexShrink: 1,\n },\n footerUrl: {\n fontSize: 9,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n footerDate: {\n fontSize: 8,\n color: brand.colors.muted,\n marginTop: 2,\n },\n footerTagline: {\n fontSize: 8,\n color: brand.colors.muted,\n },\n footerName: {\n fontSize: 11,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n qr: {\n width: 44,\n height: 44,\n },\n qrRefined: {\n width: 32,\n height: 32,\n },\n // `flex: 1` makes the body fill the page's available flow area between the\n // header and the footer's flow anchor. `marginBottom: FOOTER_SAFE_AREA_PT`\n // carves an explicit safe-zone INSIDE that flow area so overflow children\n // (e.g., a flex column with `justifyContent: \"space-around\"` and content\n // exceeding the container height) cannot render past the body's bottom\n // edge into the footer's render band. Combined with the page-level\n // `paddingBottom: FOOTER_SAFE_AREA_PT`, this is a 2x defensive carve that\n // covers both normal-flow pagination (where `paddingBottom` is sufficient)\n // and non-paginating distributions (where only `marginBottom` saves you).\n // See the JSDoc on `FOOTER_SAFE_AREA_PT` above for the full rationale.\n pageBody: {\n flex: 1,\n marginBottom: FOOTER_SAFE_AREA_PT,\n },\n });\n}\n\nexport interface ExportHeaderPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title (e.g., \"Basketball (NBA) — Official Rules\"). */\n title: string;\n /** Small uppercase eyebrow above the title (e.g., \"Rules Sheet\", \"Bracket Generator\"). */\n toolLabel: string;\n /** Optional supplemental line under the title. */\n subtitle?: string;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n}\n\n/**\n * Branded PDF document header — first-page only by default.\n *\n * Renders eyebrow + title + optional subtitle on the left, brand mark + wordmark on\n * the right, with a primary-color rule below.\n */\nexport function ExportHeaderPdf({\n brand,\n title,\n toolLabel,\n subtitle,\n prominence = \"maximum\",\n}: ExportHeaderPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const lockupSize = prominence === \"maximum\" ? 32 : 26;\n const titleSize = prominence === \"maximum\" ? 22 : 18;\n const Logo = brand.renderLogoMarkPdf;\n return (\n <View style={styles.headerRow} fixed={false}>\n <View style={styles.headerLeft}>\n <Text style={styles.eyebrow}>{toolLabel}</Text>\n <Text style={[styles.title, { fontSize: titleSize }]}>{title}</Text>\n {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null}\n </View>\n <View style={styles.lockupRow}>\n <Logo size={lockupSize} variant=\"original\" />\n <Text style={styles.wordmark}>{brand.name}</Text>\n </View>\n </View>\n );\n}\n\nexport interface ExportFooterPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Public URL displayed in footer (typically UTM-tagged via `buildExportUrl`). */\n url: string;\n /** Generation date label (e.g., \"Generated April 26, 2026\"). */\n dateLabel?: string;\n /** Pre-rendered QR data URL (from `generateQrDataUrl`). Pass `null` to omit. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n /**\n * Render with react-pdf's `fixed` prop so the footer appears on every page\n * of a multi-page document. Defaults to `true` (the typical behavior).\n *\n * Set to `false` for documents whose body content cannot be reliably\n * constrained above the footer's render band — e.g., a `flex: 1` layout\n * with overflow children that paginate (large brackets, dense tables,\n * etc.). With `fixed: false` the footer flows after the body and renders\n * only on the LAST page; intermediate pages have no footer chrome but\n * also no body-on-footer overlap. This is the architecturally correct\n * trade-off for content where pagination is the rule, not the exception.\n *\n * For ordinary documents (rules sheets, score sheets, single-page\n * profile cards) leave at the default `true`.\n */\n fixed?: boolean;\n}\n\n/**\n * Branded PDF document footer — `fixed` so it renders on every page (default).\n *\n * Composition: brand mark + name (left), URL + date (center-right), QR (far right).\n * Tagline shown only at `maximum` prominence; QR shrinks at `refined`.\n *\n * Pass `fixed={false}` for layouts where body content can spill into the\n * footer's render band on intermediate pages — see the prop JSDoc above.\n */\nexport function ExportFooterPdf({\n brand,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n fixed = true,\n}: ExportFooterPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const isRefined = prominence === \"refined\";\n const showTagline = prominence === \"maximum\" && Boolean(brand.tagline);\n const markSize = isRefined ? 20 : 26;\n const showQr = Boolean(qrDataUrl);\n const Logo = brand.renderLogoMarkPdf;\n\n return (\n <View style={styles.footerRow} fixed={fixed}>\n <View style={styles.footerLeft}>\n <Logo size={markSize} variant=\"original\" />\n <View>\n <Text style={styles.footerName}>{brand.name}</Text>\n {showTagline ? (\n <Text style={styles.footerTagline}>{brand.tagline}</Text>\n ) : null}\n </View>\n </View>\n <View style={styles.footerMid}>\n <Text style={styles.footerUrl}>{url}</Text>\n {dateLabel ? <Text style={styles.footerDate}>{dateLabel}</Text> : null}\n </View>\n {showQr && qrDataUrl ? (\n <Image\n src={qrDataUrl}\n style={isRefined ? styles.qrRefined : styles.qr}\n />\n ) : null}\n </View>\n );\n}\n\nexport interface BrandedPdfPageProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title shown in the header. */\n title: string;\n /** Eyebrow label above the title. */\n toolLabel: string;\n /** Optional subtitle under the title. */\n subtitle?: string;\n /** Footer URL (typically UTM-tagged). */\n url: string;\n /** Footer date label. */\n dateLabel?: string;\n /** Pre-rendered QR data URL. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n /**\n * Optional react-pdf Page-level style overrides (e.g., padding, fontFamily).\n * Merged onto the default page styles.\n */\n pageStyle?: Record<string, unknown>;\n /** Optional react-pdf page size. Defaults to \"LETTER\". */\n size?: \"LETTER\" | \"A4\" | \"LEGAL\" | \"TABLOID\";\n /** Document body — your selected sections, content, etc. */\n children: ReactNode;\n}\n\n/**\n * Full branded PDF page wrapper — composes header + body slot + sticky footer.\n *\n * The footer is `fixed` so it renders on every page automatically. The header is\n * first-page only; if you need a per-page compact strip on page 2+, use\n * `ExportHeaderPdf` with your own placement logic.\n *\n * @example\n * ```tsx\n * import { Document } from \"@react-pdf/renderer\";\n * import { BrandedPdfPage } from \"@digilogiclabs/platform-core/pdf-exports\";\n *\n * <Document>\n * <BrandedPdfPage\n * brand={ossBrand}\n * title=\"Basketball — Official Rules\"\n * toolLabel=\"Rules Sheet\"\n * url=\"https://opensourcesports.io/rules/basketball?utm_source=export\"\n * qrDataUrl={qrDataUrl}\n * prominence={tierToProminence(userTier)}\n * >\n * <RulesBody sections={selectedSections} />\n * </BrandedPdfPage>\n * </Document>\n * ```\n */\nexport function BrandedPdfPage({\n brand,\n title,\n toolLabel,\n subtitle,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n pageStyle,\n size = \"LETTER\",\n children,\n}: BrandedPdfPageProps): ReactElement {\n const styles = makeChromeStyles(brand);\n\n // Padding is split rather than uniform so the bottom edge reserves room\n // for the `fixed` footer (see `FOOTER_SAFE_AREA_PT` for the rationale).\n // Consumers can still override individual values via `pageStyle`.\n const defaultPageStyle = {\n paddingTop: 36,\n paddingHorizontal: 36,\n paddingBottom: FOOTER_SAFE_AREA_PT,\n fontFamily: \"Helvetica\",\n backgroundColor: brand.colors.surface ?? \"#ffffff\",\n fontSize: 10,\n color: brand.colors.ink,\n };\n const mergedPageStyle = { ...defaultPageStyle, ...pageStyle };\n\n return (\n <Page size={size} style={mergedPageStyle}>\n <ExportHeaderPdf\n brand={brand}\n title={title}\n toolLabel={toolLabel}\n subtitle={subtitle}\n prominence={prominence}\n />\n <View style={styles.pageBody}>{children}</View>\n <ExportFooterPdf\n brand={brand}\n url={url}\n dateLabel={dateLabel}\n qrDataUrl={qrDataUrl}\n prominence={prominence}\n />\n </Page>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,SAAS,iBAAiB,MAAoC;AACnE,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,SAAS,YAAa,QAAO;AACjC,SAAO;AACT;AAMO,SAAS,kBACd,OACA,MACkB;AAClB,MAAI,MAAM,cAAe,QAAO,MAAM,cAAc,IAAI;AACxD,SAAO,iBAAiB,IAAI;AAC9B;;;ACQA,eAAsB,kBACpB,KACA,SACwB;AACxB,MAAI;AAEF,UAAM,KAAK,MAAM,OAAO,QAAQ;AAChC,UAAM,YAAY,GAAG,SAAS,aAAa,GAAG;AAC9C,WAAO,MAAM,UAAU,KAAK;AAAA,MAC1B,OAAO,SAAS,QAAQ;AAAA,MACxB,QAAQ,SAAS,UAAU;AAAA,MAC3B,sBAAsB,SAAS,wBAAwB;AAAA,MACvD,OAAO;AAAA,QACL,MAAM,SAAS,aAAa;AAAA,QAC5B,OAAO,SAAS,cAAc;AAAA,MAChC;AAAA,IACF,CAAC;AAAA,EACH,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACZO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,eAAe,OACjB,OACA,YACE,MAAM,SAAS,KACf,UAAU,IAAI;AACpB,QAAM,OAAO,WAAW,MAAM,MAAM,GAAG,YAAY;AACnD,QAAM,SAAS,IAAI,gBAAgB;AA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SACN;AAAA,OACF;AAAA,IACA,6CAAC,wBAAK,OAAO,OAAO,WAClB;AAAA,kDAAC,wBAAK,OAAO,OAAO,WAAY,eAAI;AAAA,MACnC,YAAY,4CAAC,wBAAK,OAAO,OAAO,YAAa,qBAAU,IAAU;AAAA,OACpE;AAAA,IACC,UAAU,YACT;AAAA,MAAC;AAAA;AAAA,QACC,KAAK;AAAA,QACL,OAAO,YAAY,OAAO,YAAY,OAAO;AAAA;AAAA,IAC/C,IACE;AAAA,KACN;AAEJ;AAwDO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA,OAAO;AAAA,EACP;AACF,GAAsC;AACpC,QAAM,SAAS,iBAAiB,KAAK;AAKrC,QAAM,mBAAmB;AAAA,IACvB,YAAY;AAAA,IACZ,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,YAAY;AAAA,IACZ,iBAAiB,MAAM,OAAO,WAAW;AAAA,IACzC,UAAU;AAAA,IACV,OAAO,MAAM,OAAO;AAAA,EACtB;AACA,QAAM,kBAAkB,EAAE,GAAG,kBAAkB,GAAG,UAAU;AAE5D,SACE,6CAAC,wBAAK,MAAY,OAAO,iBACvB;AAAA;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,IACA,4CAAC,wBAAK,OAAO,OAAO,UAAW,UAAS;AAAA,IACxC;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":[]}
@@ -66,6 +66,7 @@ function slugify(input) {
66
66
  // src/pdf-exports/pdf-chrome.tsx
67
67
  import { Image, Page, StyleSheet, Text, View } from "@react-pdf/renderer";
68
68
  import { jsx, jsxs } from "react/jsx-runtime";
69
+ var FOOTER_SAFE_AREA_PT = 72;
69
70
  function makeChromeStyles(brand) {
70
71
  return StyleSheet.create({
71
72
  headerRow: {
@@ -152,8 +153,19 @@ function makeChromeStyles(brand) {
152
153
  width: 32,
153
154
  height: 32
154
155
  },
156
+ // `flex: 1` makes the body fill the page's available flow area between the
157
+ // header and the footer's flow anchor. `marginBottom: FOOTER_SAFE_AREA_PT`
158
+ // carves an explicit safe-zone INSIDE that flow area so overflow children
159
+ // (e.g., a flex column with `justifyContent: "space-around"` and content
160
+ // exceeding the container height) cannot render past the body's bottom
161
+ // edge into the footer's render band. Combined with the page-level
162
+ // `paddingBottom: FOOTER_SAFE_AREA_PT`, this is a 2x defensive carve that
163
+ // covers both normal-flow pagination (where `paddingBottom` is sufficient)
164
+ // and non-paginating distributions (where only `marginBottom` saves you).
165
+ // See the JSDoc on `FOOTER_SAFE_AREA_PT` above for the full rationale.
155
166
  pageBody: {
156
- flex: 1
167
+ flex: 1,
168
+ marginBottom: FOOTER_SAFE_AREA_PT
157
169
  }
158
170
  });
159
171
  }
@@ -185,7 +197,8 @@ function ExportFooterPdf({
185
197
  url,
186
198
  dateLabel,
187
199
  qrDataUrl,
188
- prominence = "maximum"
200
+ prominence = "maximum",
201
+ fixed = true
189
202
  }) {
190
203
  const styles = makeChromeStyles(brand);
191
204
  const isRefined = prominence === "refined";
@@ -193,7 +206,7 @@ function ExportFooterPdf({
193
206
  const markSize = isRefined ? 20 : 26;
194
207
  const showQr = Boolean(qrDataUrl);
195
208
  const Logo = brand.renderLogoMarkPdf;
196
- return /* @__PURE__ */ jsxs(View, { style: styles.footerRow, fixed: true, children: [
209
+ return /* @__PURE__ */ jsxs(View, { style: styles.footerRow, fixed, children: [
197
210
  /* @__PURE__ */ jsxs(View, { style: styles.footerLeft, children: [
198
211
  /* @__PURE__ */ jsx(Logo, { size: markSize, variant: "original" }),
199
212
  /* @__PURE__ */ jsxs(View, { children: [
@@ -229,7 +242,9 @@ function BrandedPdfPage({
229
242
  }) {
230
243
  const styles = makeChromeStyles(brand);
231
244
  const defaultPageStyle = {
232
- padding: 36,
245
+ paddingTop: 36,
246
+ paddingHorizontal: 36,
247
+ paddingBottom: FOOTER_SAFE_AREA_PT,
233
248
  fontFamily: "Helvetica",
234
249
  backgroundColor: brand.colors.surface ?? "#ffffff",
235
250
  fontSize: 10,
@@ -264,6 +279,7 @@ export {
264
279
  BrandedPdfPage,
265
280
  ExportFooterPdf,
266
281
  ExportHeaderPdf,
282
+ FOOTER_SAFE_AREA_PT,
267
283
  buildExportFilename,
268
284
  buildExportUrl,
269
285
  generateQrDataUrl,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/pdf-exports/prominence.ts","../../src/pdf-exports/qr.ts","../../src/pdf-exports/url-utils.ts","../../src/pdf-exports/pdf-chrome.tsx"],"sourcesContent":["import type { BrandConfig, ExportProminence, ExportTier } from \"./types\";\n\n/**\n * Default tier → prominence mapping.\n *\n * Patron and supporter tiers earn `refined` prominence (smaller branding chrome,\n * tagline hidden). All other tiers — including signed-in free users and anonymous\n * visitors — receive `maximum` prominence so OSS/app branding stays visible.\n *\n * Branding is **never removed**, only modulated in size and detail. Apps that need\n * a different vocabulary (e.g., \"plus\" / \"pro\") should supply\n * `BrandConfig.prominenceMap` instead of forking this function.\n *\n * @example\n * ```ts\n * tierToProminence(\"patron\"); // \"refined\"\n * tierToProminence(\"supporter\"); // \"refined\"\n * tierToProminence(\"free\"); // \"maximum\"\n * tierToProminence(null); // \"maximum\"\n * tierToProminence(\"plus\"); // \"maximum\" (unknown token falls back)\n * ```\n */\nexport function tierToProminence(tier: ExportTier): ExportProminence {\n if (tier === \"patron\") return \"refined\";\n if (tier === \"supporter\") return \"refined\";\n return \"maximum\";\n}\n\n/**\n * Resolve prominence for a brand — uses the brand's `prominenceMap` if supplied,\n * otherwise the default `tierToProminence` mapping.\n */\nexport function resolveProminence(\n brand: BrandConfig,\n tier: ExportTier,\n): ExportProminence {\n if (brand.prominenceMap) return brand.prominenceMap(tier);\n return tierToProminence(tier);\n}\n","/**\n * QR code generation for branded export footers.\n *\n * Uses the `qrcode` package (optional peer dependency). Calls return a base64\n * data URL ready to be embedded as an `<Image src={...}>` in react-pdf or as a\n * standard `<img>` in HTML preview routes.\n *\n * Failures (invalid URL, encoder errors) return `null` rather than throwing —\n * exports should degrade gracefully without a QR rather than failing the whole\n * PDF render.\n */\n\nexport interface GenerateQrDataUrlOptions {\n /** Output pixel size (square). Default: 320. */\n size?: number;\n /** Quiet-zone margin in modules. Default: 1. */\n margin?: number;\n /** Module (foreground) color. Default: \"#0c1f22\" (dark ink). */\n darkColor?: string;\n /** Background color. Default: \"#ffffff\". */\n lightColor?: string;\n /**\n * Error-correction level. Default: \"M\" (15% recovery — balances density vs durability\n * on printed sheets that may scuff or fold).\n */\n errorCorrectionLevel?: \"L\" | \"M\" | \"Q\" | \"H\";\n}\n\n/**\n * Generate a QR code as a base64 PNG data URL.\n *\n * @param url - The URL to encode (typically a UTM-tagged link back to the live page).\n * @param options - Color, size, and error-correction overrides.\n * @returns Data URL string, or `null` on failure.\n *\n * @example\n * ```ts\n * const qrDataUrl = await generateQrDataUrl(\n * \"https://opensourcesports.io/rules/basketball?utm_source=export\",\n * { darkColor: brand.colors.ink },\n * );\n * if (qrDataUrl) {\n * // <Image src={qrDataUrl} style={...} />\n * }\n * ```\n */\nexport async function generateQrDataUrl(\n url: string,\n options?: GenerateQrDataUrlOptions,\n): Promise<string | null> {\n try {\n // Dynamic import keeps qrcode as an optional peer dep — only loaded if used.\n const qr = await import(\"qrcode\");\n const toDataURL = qr.default?.toDataURL ?? qr.toDataURL;\n return await toDataURL(url, {\n width: options?.size ?? 320,\n margin: options?.margin ?? 1,\n errorCorrectionLevel: options?.errorCorrectionLevel ?? \"M\",\n color: {\n dark: options?.darkColor ?? \"#0c1f22\",\n light: options?.lightColor ?? \"#ffffff\",\n },\n });\n } catch {\n return null;\n }\n}\n","import type { BrandConfig } from \"./types\";\n\n/**\n * Export medium — used in UTM tagging and filename suffixes.\n */\nexport type ExportMedium = \"pdf\" | \"png\" | \"ical\" | \"csv\" | \"tsv\";\n\n/**\n * File extension — distinct from medium because iCal uses `.ics` not `.ical`.\n */\nexport type ExportFileExt = \"pdf\" | \"png\" | \"ics\" | \"csv\" | \"tsv\";\n\nexport interface BuildExportUrlInput {\n /** Brand config — supplies the domain. */\n brand: BrandConfig;\n /**\n * Tool / template identifier (e.g., \"bracket-generator\", \"rules\", \"scoreboard\").\n * Becomes part of the URL path and `utm_tool`.\n */\n tool: string;\n /** Export medium for `utm_medium`. */\n medium: ExportMedium;\n /**\n * Optional share-link slug — when present, the URL points at `/s/<slug>` rather than\n * `/tools/<tool>` so QR scanners land on the actual shared artifact.\n */\n shareSlug?: string;\n /**\n * Optional URL path override. When supplied, replaces both `/s/<slug>` and\n * `/tools/<tool>` defaults. Useful for non-tool exports (e.g., `/rules/basketball`).\n */\n path?: string;\n /** Optional extra UTM/query params merged into the URL. */\n params?: Record<string, string>;\n}\n\n/**\n * Build a UTM-tagged URL for QR codes / footer links on branded exports.\n *\n * Every printed sheet that scans back to the live page becomes a measurable acquisition\n * channel — the UTM trio (`utm_source=export`, `utm_medium=<medium>`, `utm_tool=<tool>`)\n * lets analytics attribute traffic to specific export types.\n *\n * @example\n * ```ts\n * buildExportUrl({\n * brand: ossBrand,\n * tool: \"rules\",\n * medium: \"pdf\",\n * path: \"/rules/basketball\",\n * });\n * // → \"https://opensourcesports.io/rules/basketball?utm_source=export&utm_medium=pdf&utm_tool=rules\"\n * ```\n */\nexport function buildExportUrl({\n brand,\n tool,\n medium,\n shareSlug,\n path,\n params,\n}: BuildExportUrlInput): string {\n const resolvedPath = path\n ? path\n : shareSlug\n ? `/s/${shareSlug}`\n : `/tools/${tool}`;\n const base = `https://${brand.domain}${resolvedPath}`;\n const search = new URLSearchParams({\n utm_source: \"export\",\n utm_medium: medium,\n utm_tool: tool,\n ...params,\n });\n return `${base}?${search.toString()}`;\n}\n\nexport interface BuildExportFilenameInput {\n /** Brand config — supplies the filename prefix. */\n brand: BrandConfig;\n /** Tool / template identifier. */\n tool: string;\n /** Optional title or date suffix (slugified). */\n titleOrDate?: string;\n /** File extension. */\n ext: ExportFileExt;\n}\n\n/**\n * Build a filename of the form `{brand-slug}-{tool}[-{title-slug}].{ext}`.\n *\n * The brand slug is derived from `brand.name` (lowercased, hyphenated) so the filename\n * carries brand identity even when downloaded outside the app context.\n *\n * @example\n * ```ts\n * buildExportFilename({\n * brand: ossBrand,\n * tool: \"rules\",\n * titleOrDate: \"Basketball NBA\",\n * ext: \"pdf\",\n * });\n * // → \"opensourcesports-rules-basketball-nba.pdf\"\n * ```\n */\nexport function buildExportFilename({\n brand,\n tool,\n titleOrDate,\n ext,\n}: BuildExportFilenameInput): string {\n const brandSlug = slugify(brand.name);\n const titleSlug = slugify(titleOrDate);\n const middle = titleSlug ? `${tool}-${titleSlug}` : tool;\n return `${brandSlug}-${middle}.${ext}`;\n}\n\nfunction slugify(input: string | undefined): string {\n if (!input) return \"\";\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60);\n}\n","import { Image, Page, StyleSheet, Text, View } from \"@react-pdf/renderer\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nimport type { BrandConfig, ExportProminence } from \"./types\";\n\n/**\n * @react-pdf/renderer is declared as an OPTIONAL peer dependency. Apps that\n * import this subpath must install it themselves; bundlers will surface a\n * clear \"Cannot find module\" error if it isn't present, which is the standard\n * platform-core pattern for optional peers (`pg`, `ioredis`, `bullmq`, etc).\n */\n\n/**\n * Build a brand-aware StyleSheet for header + footer chrome.\n *\n * Called once per render — react-pdf's StyleSheet.create is intentionally\n * lightweight and the perf cost is negligible relative to the actual document\n * render. Building per render means brand colors are honored without\n * module-level caching tricks.\n */\nfunction makeChromeStyles(brand: BrandConfig) {\n return StyleSheet.create({\n headerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderBottomWidth: 3,\n borderBottomColor: brand.colors.primary,\n paddingBottom: 10,\n marginBottom: 12,\n gap: 16,\n },\n headerLeft: { flexDirection: \"column\", flexGrow: 1, flexShrink: 1 },\n eyebrow: {\n fontSize: 9,\n letterSpacing: 1.5,\n color: brand.colors.muted,\n textTransform: \"uppercase\",\n fontFamily: \"Helvetica-Bold\",\n marginBottom: 2,\n },\n title: {\n fontSize: 22,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.ink,\n lineHeight: 1.15,\n },\n subtitle: {\n fontSize: 10,\n color: brand.colors.muted,\n marginTop: 3,\n },\n lockupRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n gap: 8,\n },\n wordmark: {\n fontSize: 13,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n letterSpacing: -0.2,\n },\n footerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderTopWidth: 2,\n borderTopColor: brand.colors.primary,\n paddingTop: 8,\n marginTop: 10,\n gap: 16,\n },\n footerLeft: { flexDirection: \"row\", alignItems: \"center\", gap: 8 },\n footerMid: {\n flexDirection: \"column\",\n alignItems: \"flex-end\",\n flexShrink: 1,\n },\n footerUrl: {\n fontSize: 9,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n footerDate: {\n fontSize: 8,\n color: brand.colors.muted,\n marginTop: 2,\n },\n footerTagline: {\n fontSize: 8,\n color: brand.colors.muted,\n },\n footerName: {\n fontSize: 11,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n qr: {\n width: 44,\n height: 44,\n },\n qrRefined: {\n width: 32,\n height: 32,\n },\n pageBody: {\n flex: 1,\n },\n });\n}\n\nexport interface ExportHeaderPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title (e.g., \"Basketball (NBA) — Official Rules\"). */\n title: string;\n /** Small uppercase eyebrow above the title (e.g., \"Rules Sheet\", \"Bracket Generator\"). */\n toolLabel: string;\n /** Optional supplemental line under the title. */\n subtitle?: string;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n}\n\n/**\n * Branded PDF document header — first-page only by default.\n *\n * Renders eyebrow + title + optional subtitle on the left, brand mark + wordmark on\n * the right, with a primary-color rule below.\n */\nexport function ExportHeaderPdf({\n brand,\n title,\n toolLabel,\n subtitle,\n prominence = \"maximum\",\n}: ExportHeaderPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const lockupSize = prominence === \"maximum\" ? 32 : 26;\n const titleSize = prominence === \"maximum\" ? 22 : 18;\n const Logo = brand.renderLogoMarkPdf;\n return (\n <View style={styles.headerRow} fixed={false}>\n <View style={styles.headerLeft}>\n <Text style={styles.eyebrow}>{toolLabel}</Text>\n <Text style={[styles.title, { fontSize: titleSize }]}>{title}</Text>\n {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null}\n </View>\n <View style={styles.lockupRow}>\n <Logo size={lockupSize} variant=\"original\" />\n <Text style={styles.wordmark}>{brand.name}</Text>\n </View>\n </View>\n );\n}\n\nexport interface ExportFooterPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Public URL displayed in footer (typically UTM-tagged via `buildExportUrl`). */\n url: string;\n /** Generation date label (e.g., \"Generated April 26, 2026\"). */\n dateLabel?: string;\n /** Pre-rendered QR data URL (from `generateQrDataUrl`). Pass `null` to omit. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n}\n\n/**\n * Branded PDF document footer — `fixed` so it renders on every page.\n *\n * Composition: brand mark + name (left), URL + date (center-right), QR (far right).\n * Tagline shown only at `maximum` prominence; QR shrinks at `refined`.\n */\nexport function ExportFooterPdf({\n brand,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n}: ExportFooterPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const isRefined = prominence === \"refined\";\n const showTagline = prominence === \"maximum\" && Boolean(brand.tagline);\n const markSize = isRefined ? 20 : 26;\n const showQr = Boolean(qrDataUrl);\n const Logo = brand.renderLogoMarkPdf;\n\n return (\n <View style={styles.footerRow} fixed>\n <View style={styles.footerLeft}>\n <Logo size={markSize} variant=\"original\" />\n <View>\n <Text style={styles.footerName}>{brand.name}</Text>\n {showTagline ? (\n <Text style={styles.footerTagline}>{brand.tagline}</Text>\n ) : null}\n </View>\n </View>\n <View style={styles.footerMid}>\n <Text style={styles.footerUrl}>{url}</Text>\n {dateLabel ? <Text style={styles.footerDate}>{dateLabel}</Text> : null}\n </View>\n {showQr && qrDataUrl ? (\n <Image\n src={qrDataUrl}\n style={isRefined ? styles.qrRefined : styles.qr}\n />\n ) : null}\n </View>\n );\n}\n\nexport interface BrandedPdfPageProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title shown in the header. */\n title: string;\n /** Eyebrow label above the title. */\n toolLabel: string;\n /** Optional subtitle under the title. */\n subtitle?: string;\n /** Footer URL (typically UTM-tagged). */\n url: string;\n /** Footer date label. */\n dateLabel?: string;\n /** Pre-rendered QR data URL. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n /**\n * Optional react-pdf Page-level style overrides (e.g., padding, fontFamily).\n * Merged onto the default page styles.\n */\n pageStyle?: Record<string, unknown>;\n /** Optional react-pdf page size. Defaults to \"LETTER\". */\n size?: \"LETTER\" | \"A4\" | \"LEGAL\" | \"TABLOID\";\n /** Document body — your selected sections, content, etc. */\n children: ReactNode;\n}\n\n/**\n * Full branded PDF page wrapper — composes header + body slot + sticky footer.\n *\n * The footer is `fixed` so it renders on every page automatically. The header is\n * first-page only; if you need a per-page compact strip on page 2+, use\n * `ExportHeaderPdf` with your own placement logic.\n *\n * @example\n * ```tsx\n * import { Document } from \"@react-pdf/renderer\";\n * import { BrandedPdfPage } from \"@digilogiclabs/platform-core/pdf-exports\";\n *\n * <Document>\n * <BrandedPdfPage\n * brand={ossBrand}\n * title=\"Basketball — Official Rules\"\n * toolLabel=\"Rules Sheet\"\n * url=\"https://opensourcesports.io/rules/basketball?utm_source=export\"\n * qrDataUrl={qrDataUrl}\n * prominence={tierToProminence(userTier)}\n * >\n * <RulesBody sections={selectedSections} />\n * </BrandedPdfPage>\n * </Document>\n * ```\n */\nexport function BrandedPdfPage({\n brand,\n title,\n toolLabel,\n subtitle,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n pageStyle,\n size = \"LETTER\",\n children,\n}: BrandedPdfPageProps): ReactElement {\n const styles = makeChromeStyles(brand);\n\n const defaultPageStyle = {\n padding: 36,\n fontFamily: \"Helvetica\",\n backgroundColor: brand.colors.surface ?? \"#ffffff\",\n fontSize: 10,\n color: brand.colors.ink,\n };\n const mergedPageStyle = { ...defaultPageStyle, ...pageStyle };\n\n return (\n <Page size={size} style={mergedPageStyle}>\n <ExportHeaderPdf\n brand={brand}\n title={title}\n toolLabel={toolLabel}\n subtitle={subtitle}\n prominence={prominence}\n />\n <View style={styles.pageBody}>{children}</View>\n <ExportFooterPdf\n brand={brand}\n url={url}\n dateLabel={dateLabel}\n qrDataUrl={qrDataUrl}\n prominence={prominence}\n />\n </Page>\n );\n}\n"],"mappings":";AAsBO,SAAS,iBAAiB,MAAoC;AACnE,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,SAAS,YAAa,QAAO;AACjC,SAAO;AACT;AAMO,SAAS,kBACd,OACA,MACkB;AAClB,MAAI,MAAM,cAAe,QAAO,MAAM,cAAc,IAAI;AACxD,SAAO,iBAAiB,IAAI;AAC9B;;;ACQA,eAAsB,kBACpB,KACA,SACwB;AACxB,MAAI;AAEF,UAAM,KAAK,MAAM,OAAO,QAAQ;AAChC,UAAM,YAAY,GAAG,SAAS,aAAa,GAAG;AAC9C,WAAO,MAAM,UAAU,KAAK;AAAA,MAC1B,OAAO,SAAS,QAAQ;AAAA,MACxB,QAAQ,SAAS,UAAU;AAAA,MAC3B,sBAAsB,SAAS,wBAAwB;AAAA,MACvD,OAAO;AAAA,QACL,MAA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AAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../src/pdf-exports/prominence.ts","../../src/pdf-exports/qr.ts","../../src/pdf-exports/url-utils.ts","../../src/pdf-exports/pdf-chrome.tsx"],"sourcesContent":["import type { BrandConfig, ExportProminence, ExportTier } from \"./types\";\n\n/**\n * Default tier → prominence mapping.\n *\n * Patron and supporter tiers earn `refined` prominence (smaller branding chrome,\n * tagline hidden). All other tiers — including signed-in free users and anonymous\n * visitors — receive `maximum` prominence so OSS/app branding stays visible.\n *\n * Branding is **never removed**, only modulated in size and detail. Apps that need\n * a different vocabulary (e.g., \"plus\" / \"pro\") should supply\n * `BrandConfig.prominenceMap` instead of forking this function.\n *\n * @example\n * ```ts\n * tierToProminence(\"patron\"); // \"refined\"\n * tierToProminence(\"supporter\"); // \"refined\"\n * tierToProminence(\"free\"); // \"maximum\"\n * tierToProminence(null); // \"maximum\"\n * tierToProminence(\"plus\"); // \"maximum\" (unknown token falls back)\n * ```\n */\nexport function tierToProminence(tier: ExportTier): ExportProminence {\n if (tier === \"patron\") return \"refined\";\n if (tier === \"supporter\") return \"refined\";\n return \"maximum\";\n}\n\n/**\n * Resolve prominence for a brand — uses the brand's `prominenceMap` if supplied,\n * otherwise the default `tierToProminence` mapping.\n */\nexport function resolveProminence(\n brand: BrandConfig,\n tier: ExportTier,\n): ExportProminence {\n if (brand.prominenceMap) return brand.prominenceMap(tier);\n return tierToProminence(tier);\n}\n","/**\n * QR code generation for branded export footers.\n *\n * Uses the `qrcode` package (optional peer dependency). Calls return a base64\n * data URL ready to be embedded as an `<Image src={...}>` in react-pdf or as a\n * standard `<img>` in HTML preview routes.\n *\n * Failures (invalid URL, encoder errors) return `null` rather than throwing —\n * exports should degrade gracefully without a QR rather than failing the whole\n * PDF render.\n */\n\nexport interface GenerateQrDataUrlOptions {\n /** Output pixel size (square). Default: 320. */\n size?: number;\n /** Quiet-zone margin in modules. Default: 1. */\n margin?: number;\n /** Module (foreground) color. Default: \"#0c1f22\" (dark ink). */\n darkColor?: string;\n /** Background color. Default: \"#ffffff\". */\n lightColor?: string;\n /**\n * Error-correction level. Default: \"M\" (15% recovery — balances density vs durability\n * on printed sheets that may scuff or fold).\n */\n errorCorrectionLevel?: \"L\" | \"M\" | \"Q\" | \"H\";\n}\n\n/**\n * Generate a QR code as a base64 PNG data URL.\n *\n * @param url - The URL to encode (typically a UTM-tagged link back to the live page).\n * @param options - Color, size, and error-correction overrides.\n * @returns Data URL string, or `null` on failure.\n *\n * @example\n * ```ts\n * const qrDataUrl = await generateQrDataUrl(\n * \"https://opensourcesports.io/rules/basketball?utm_source=export\",\n * { darkColor: brand.colors.ink },\n * );\n * if (qrDataUrl) {\n * // <Image src={qrDataUrl} style={...} />\n * }\n * ```\n */\nexport async function generateQrDataUrl(\n url: string,\n options?: GenerateQrDataUrlOptions,\n): Promise<string | null> {\n try {\n // Dynamic import keeps qrcode as an optional peer dep — only loaded if used.\n const qr = await import(\"qrcode\");\n const toDataURL = qr.default?.toDataURL ?? qr.toDataURL;\n return await toDataURL(url, {\n width: options?.size ?? 320,\n margin: options?.margin ?? 1,\n errorCorrectionLevel: options?.errorCorrectionLevel ?? \"M\",\n color: {\n dark: options?.darkColor ?? \"#0c1f22\",\n light: options?.lightColor ?? \"#ffffff\",\n },\n });\n } catch {\n return null;\n }\n}\n","import type { BrandConfig } from \"./types\";\n\n/**\n * Export medium — used in UTM tagging and filename suffixes.\n */\nexport type ExportMedium = \"pdf\" | \"png\" | \"ical\" | \"csv\" | \"tsv\";\n\n/**\n * File extension — distinct from medium because iCal uses `.ics` not `.ical`.\n */\nexport type ExportFileExt = \"pdf\" | \"png\" | \"ics\" | \"csv\" | \"tsv\";\n\nexport interface BuildExportUrlInput {\n /** Brand config — supplies the domain. */\n brand: BrandConfig;\n /**\n * Tool / template identifier (e.g., \"bracket-generator\", \"rules\", \"scoreboard\").\n * Becomes part of the URL path and `utm_tool`.\n */\n tool: string;\n /** Export medium for `utm_medium`. */\n medium: ExportMedium;\n /**\n * Optional share-link slug — when present, the URL points at `/s/<slug>` rather than\n * `/tools/<tool>` so QR scanners land on the actual shared artifact.\n */\n shareSlug?: string;\n /**\n * Optional URL path override. When supplied, replaces both `/s/<slug>` and\n * `/tools/<tool>` defaults. Useful for non-tool exports (e.g., `/rules/basketball`).\n */\n path?: string;\n /** Optional extra UTM/query params merged into the URL. */\n params?: Record<string, string>;\n}\n\n/**\n * Build a UTM-tagged URL for QR codes / footer links on branded exports.\n *\n * Every printed sheet that scans back to the live page becomes a measurable acquisition\n * channel — the UTM trio (`utm_source=export`, `utm_medium=<medium>`, `utm_tool=<tool>`)\n * lets analytics attribute traffic to specific export types.\n *\n * @example\n * ```ts\n * buildExportUrl({\n * brand: ossBrand,\n * tool: \"rules\",\n * medium: \"pdf\",\n * path: \"/rules/basketball\",\n * });\n * // → \"https://opensourcesports.io/rules/basketball?utm_source=export&utm_medium=pdf&utm_tool=rules\"\n * ```\n */\nexport function buildExportUrl({\n brand,\n tool,\n medium,\n shareSlug,\n path,\n params,\n}: BuildExportUrlInput): string {\n const resolvedPath = path\n ? path\n : shareSlug\n ? `/s/${shareSlug}`\n : `/tools/${tool}`;\n const base = `https://${brand.domain}${resolvedPath}`;\n const search = new URLSearchParams({\n utm_source: \"export\",\n utm_medium: medium,\n utm_tool: tool,\n ...params,\n });\n return `${base}?${search.toString()}`;\n}\n\nexport interface BuildExportFilenameInput {\n /** Brand config — supplies the filename prefix. */\n brand: BrandConfig;\n /** Tool / template identifier. */\n tool: string;\n /** Optional title or date suffix (slugified). */\n titleOrDate?: string;\n /** File extension. */\n ext: ExportFileExt;\n}\n\n/**\n * Build a filename of the form `{brand-slug}-{tool}[-{title-slug}].{ext}`.\n *\n * The brand slug is derived from `brand.name` (lowercased, hyphenated) so the filename\n * carries brand identity even when downloaded outside the app context.\n *\n * @example\n * ```ts\n * buildExportFilename({\n * brand: ossBrand,\n * tool: \"rules\",\n * titleOrDate: \"Basketball NBA\",\n * ext: \"pdf\",\n * });\n * // → \"opensourcesports-rules-basketball-nba.pdf\"\n * ```\n */\nexport function buildExportFilename({\n brand,\n tool,\n titleOrDate,\n ext,\n}: BuildExportFilenameInput): string {\n const brandSlug = slugify(brand.name);\n const titleSlug = slugify(titleOrDate);\n const middle = titleSlug ? `${tool}-${titleSlug}` : tool;\n return `${brandSlug}-${middle}.${ext}`;\n}\n\nfunction slugify(input: string | undefined): string {\n if (!input) return \"\";\n return input\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 60);\n}\n","import { Image, Page, StyleSheet, Text, View } from \"@react-pdf/renderer\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nimport type { BrandConfig, ExportProminence } from \"./types\";\n\n/**\n * @react-pdf/renderer is declared as an OPTIONAL peer dependency. Apps that\n * import this subpath must install it themselves; bundlers will surface a\n * clear \"Cannot find module\" error if it isn't present, which is the standard\n * platform-core pattern for optional peers (`pg`, `ioredis`, `bullmq`, etc).\n */\n\n/**\n * Vertical space (in PDF points) that a `<Page>` must reserve at the bottom\n * to keep flowed body content from rendering under the `fixed` footer.\n *\n * react-pdf paginates flow content when it reaches `pageHeight - paddingBottom`;\n * `fixed` elements like `<ExportFooterPdf>` are pinned at their flow anchor on\n * every page but DO NOT push the pagination boundary. So if `paddingBottom` is\n * smaller than the footer's natural height, the last lines of body content on\n * each page render directly underneath the footer chrome.\n *\n * The `ExportFooterPdf` rendered by this module claims roughly 55-60pt at\n * `maximum` prominence (44pt QR + 8pt paddingTop + 2pt borderTop + line-height\n * descenders + small render-engine slack). 72pt = footer + ~12pt clearance,\n * which is the minimum we recommend for any `<Page>` that mounts an\n * `<ExportFooterPdf>` (or `<BrandedPdfPage>`).\n *\n * **Why two carves are applied inside `BrandedPdfPage`:** `paddingBottom` alone\n * protects normal flow content from paginating into the footer band, but it\n * does NOT protect against overflow rendering — children inside the body\n * container that use `justifyContent: \"space-around\"` (or any non-paginating\n * distribution) and exceed the container's height render PAST the container's\n * bottom edge, into the footer's render band. To absorb this case,\n * `BrandedPdfPage` ALSO sets `marginBottom: FOOTER_SAFE_AREA_PT` on the body\n * `<View>`, carving an explicit safe-zone inside the flow area. The double\n * carve is intentional and defensive — combined, they cover both the\n * pagination boundary AND modest overflow from custom layouts.\n *\n * Consumers that build their own `<Page>` directly (rather than using\n * `<BrandedPdfPage>`) should set `paddingBottom` to at least this value AND,\n * if they nest body content inside a flex container with non-paginating\n * `justifyContent`, also apply `marginBottom: FOOTER_SAFE_AREA_PT` to that\n * container. Documents that only use plain flow content (`<Text>`, `<View>`\n * stacks) need only the `paddingBottom`.\n */\nexport const FOOTER_SAFE_AREA_PT = 72;\n\n/**\n * Build a brand-aware StyleSheet for header + footer chrome.\n *\n * Called once per render — react-pdf's StyleSheet.create is intentionally\n * lightweight and the perf cost is negligible relative to the actual document\n * render. Building per render means brand colors are honored without\n * module-level caching tricks.\n */\nfunction makeChromeStyles(brand: BrandConfig) {\n return StyleSheet.create({\n headerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderBottomWidth: 3,\n borderBottomColor: brand.colors.primary,\n paddingBottom: 10,\n marginBottom: 12,\n gap: 16,\n },\n headerLeft: { flexDirection: \"column\", flexGrow: 1, flexShrink: 1 },\n eyebrow: {\n fontSize: 9,\n letterSpacing: 1.5,\n color: brand.colors.muted,\n textTransform: \"uppercase\",\n fontFamily: \"Helvetica-Bold\",\n marginBottom: 2,\n },\n title: {\n fontSize: 22,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.ink,\n lineHeight: 1.15,\n },\n subtitle: {\n fontSize: 10,\n color: brand.colors.muted,\n marginTop: 3,\n },\n lockupRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n gap: 8,\n },\n wordmark: {\n fontSize: 13,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n letterSpacing: -0.2,\n },\n footerRow: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n borderTopWidth: 2,\n borderTopColor: brand.colors.primary,\n paddingTop: 8,\n marginTop: 10,\n gap: 16,\n },\n footerLeft: { flexDirection: \"row\", alignItems: \"center\", gap: 8 },\n footerMid: {\n flexDirection: \"column\",\n alignItems: \"flex-end\",\n flexShrink: 1,\n },\n footerUrl: {\n fontSize: 9,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n footerDate: {\n fontSize: 8,\n color: brand.colors.muted,\n marginTop: 2,\n },\n footerTagline: {\n fontSize: 8,\n color: brand.colors.muted,\n },\n footerName: {\n fontSize: 11,\n fontFamily: \"Helvetica-Bold\",\n color: brand.colors.secondary,\n },\n qr: {\n width: 44,\n height: 44,\n },\n qrRefined: {\n width: 32,\n height: 32,\n },\n // `flex: 1` makes the body fill the page's available flow area between the\n // header and the footer's flow anchor. `marginBottom: FOOTER_SAFE_AREA_PT`\n // carves an explicit safe-zone INSIDE that flow area so overflow children\n // (e.g., a flex column with `justifyContent: \"space-around\"` and content\n // exceeding the container height) cannot render past the body's bottom\n // edge into the footer's render band. Combined with the page-level\n // `paddingBottom: FOOTER_SAFE_AREA_PT`, this is a 2x defensive carve that\n // covers both normal-flow pagination (where `paddingBottom` is sufficient)\n // and non-paginating distributions (where only `marginBottom` saves you).\n // See the JSDoc on `FOOTER_SAFE_AREA_PT` above for the full rationale.\n pageBody: {\n flex: 1,\n marginBottom: FOOTER_SAFE_AREA_PT,\n },\n });\n}\n\nexport interface ExportHeaderPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title (e.g., \"Basketball (NBA) — Official Rules\"). */\n title: string;\n /** Small uppercase eyebrow above the title (e.g., \"Rules Sheet\", \"Bracket Generator\"). */\n toolLabel: string;\n /** Optional supplemental line under the title. */\n subtitle?: string;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n}\n\n/**\n * Branded PDF document header — first-page only by default.\n *\n * Renders eyebrow + title + optional subtitle on the left, brand mark + wordmark on\n * the right, with a primary-color rule below.\n */\nexport function ExportHeaderPdf({\n brand,\n title,\n toolLabel,\n subtitle,\n prominence = \"maximum\",\n}: ExportHeaderPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const lockupSize = prominence === \"maximum\" ? 32 : 26;\n const titleSize = prominence === \"maximum\" ? 22 : 18;\n const Logo = brand.renderLogoMarkPdf;\n return (\n <View style={styles.headerRow} fixed={false}>\n <View style={styles.headerLeft}>\n <Text style={styles.eyebrow}>{toolLabel}</Text>\n <Text style={[styles.title, { fontSize: titleSize }]}>{title}</Text>\n {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null}\n </View>\n <View style={styles.lockupRow}>\n <Logo size={lockupSize} variant=\"original\" />\n <Text style={styles.wordmark}>{brand.name}</Text>\n </View>\n </View>\n );\n}\n\nexport interface ExportFooterPdfProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Public URL displayed in footer (typically UTM-tagged via `buildExportUrl`). */\n url: string;\n /** Generation date label (e.g., \"Generated April 26, 2026\"). */\n dateLabel?: string;\n /** Pre-rendered QR data URL (from `generateQrDataUrl`). Pass `null` to omit. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n /**\n * Render with react-pdf's `fixed` prop so the footer appears on every page\n * of a multi-page document. Defaults to `true` (the typical behavior).\n *\n * Set to `false` for documents whose body content cannot be reliably\n * constrained above the footer's render band — e.g., a `flex: 1` layout\n * with overflow children that paginate (large brackets, dense tables,\n * etc.). With `fixed: false` the footer flows after the body and renders\n * only on the LAST page; intermediate pages have no footer chrome but\n * also no body-on-footer overlap. This is the architecturally correct\n * trade-off for content where pagination is the rule, not the exception.\n *\n * For ordinary documents (rules sheets, score sheets, single-page\n * profile cards) leave at the default `true`.\n */\n fixed?: boolean;\n}\n\n/**\n * Branded PDF document footer — `fixed` so it renders on every page (default).\n *\n * Composition: brand mark + name (left), URL + date (center-right), QR (far right).\n * Tagline shown only at `maximum` prominence; QR shrinks at `refined`.\n *\n * Pass `fixed={false}` for layouts where body content can spill into the\n * footer's render band on intermediate pages — see the prop JSDoc above.\n */\nexport function ExportFooterPdf({\n brand,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n fixed = true,\n}: ExportFooterPdfProps): ReactElement {\n const styles = makeChromeStyles(brand);\n const isRefined = prominence === \"refined\";\n const showTagline = prominence === \"maximum\" && Boolean(brand.tagline);\n const markSize = isRefined ? 20 : 26;\n const showQr = Boolean(qrDataUrl);\n const Logo = brand.renderLogoMarkPdf;\n\n return (\n <View style={styles.footerRow} fixed={fixed}>\n <View style={styles.footerLeft}>\n <Logo size={markSize} variant=\"original\" />\n <View>\n <Text style={styles.footerName}>{brand.name}</Text>\n {showTagline ? (\n <Text style={styles.footerTagline}>{brand.tagline}</Text>\n ) : null}\n </View>\n </View>\n <View style={styles.footerMid}>\n <Text style={styles.footerUrl}>{url}</Text>\n {dateLabel ? <Text style={styles.footerDate}>{dateLabel}</Text> : null}\n </View>\n {showQr && qrDataUrl ? (\n <Image\n src={qrDataUrl}\n style={isRefined ? styles.qrRefined : styles.qr}\n />\n ) : null}\n </View>\n );\n}\n\nexport interface BrandedPdfPageProps {\n /** Brand configuration. */\n brand: BrandConfig;\n /** Document title shown in the header. */\n title: string;\n /** Eyebrow label above the title. */\n toolLabel: string;\n /** Optional subtitle under the title. */\n subtitle?: string;\n /** Footer URL (typically UTM-tagged). */\n url: string;\n /** Footer date label. */\n dateLabel?: string;\n /** Pre-rendered QR data URL. */\n qrDataUrl?: string | null;\n /** Branding prominence. Defaults to `maximum`. */\n prominence?: ExportProminence;\n /**\n * Optional react-pdf Page-level style overrides (e.g., padding, fontFamily).\n * Merged onto the default page styles.\n */\n pageStyle?: Record<string, unknown>;\n /** Optional react-pdf page size. Defaults to \"LETTER\". */\n size?: \"LETTER\" | \"A4\" | \"LEGAL\" | \"TABLOID\";\n /** Document body — your selected sections, content, etc. */\n children: ReactNode;\n}\n\n/**\n * Full branded PDF page wrapper — composes header + body slot + sticky footer.\n *\n * The footer is `fixed` so it renders on every page automatically. The header is\n * first-page only; if you need a per-page compact strip on page 2+, use\n * `ExportHeaderPdf` with your own placement logic.\n *\n * @example\n * ```tsx\n * import { Document } from \"@react-pdf/renderer\";\n * import { BrandedPdfPage } from \"@digilogiclabs/platform-core/pdf-exports\";\n *\n * <Document>\n * <BrandedPdfPage\n * brand={ossBrand}\n * title=\"Basketball — Official Rules\"\n * toolLabel=\"Rules Sheet\"\n * url=\"https://opensourcesports.io/rules/basketball?utm_source=export\"\n * qrDataUrl={qrDataUrl}\n * prominence={tierToProminence(userTier)}\n * >\n * <RulesBody sections={selectedSections} />\n * </BrandedPdfPage>\n * </Document>\n * ```\n */\nexport function BrandedPdfPage({\n brand,\n title,\n toolLabel,\n subtitle,\n url,\n dateLabel,\n qrDataUrl,\n prominence = \"maximum\",\n pageStyle,\n size = \"LETTER\",\n children,\n}: BrandedPdfPageProps): ReactElement {\n const styles = makeChromeStyles(brand);\n\n // Padding is split rather than uniform so the bottom edge reserves room\n // for the `fixed` footer (see `FOOTER_SAFE_AREA_PT` for the rationale).\n // Consumers can still override individual values via `pageStyle`.\n const defaultPageStyle = {\n paddingTop: 36,\n paddingHorizontal: 36,\n paddingBottom: FOOTER_SAFE_AREA_PT,\n fontFamily: \"Helvetica\",\n backgroundColor: brand.colors.surface ?? \"#ffffff\",\n fontSize: 10,\n color: brand.colors.ink,\n };\n const mergedPageStyle = { ...defaultPageStyle, ...pageStyle };\n\n return (\n <Page size={size} style={mergedPageStyle}>\n <ExportHeaderPdf\n brand={brand}\n title={title}\n toolLabel={toolLabel}\n subtitle={subtitle}\n prominence={prominence}\n />\n <View style={styles.pageBody}>{children}</View>\n <ExportFooterPdf\n brand={brand}\n url={url}\n dateLabel={dateLabel}\n qrDataUrl={qrDataUrl}\n prominence={prominence}\n />\n </Page>\n );\n}\n"],"mappings":";AAsBO,SAAS,iBAAiB,M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AA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA,OAAO;AAAA,EACP;AACF,GAAsC;AACpC,QAAM,SAAS,iBAAiB,KAAK;AAKrC,QAAM,mBAAmB;AAAA,IACvB,YAAY;AAAA,IACZ,mBAAmB;AAAA,IACnB,eAAe;AAAA,IACf,YAAY;AAAA,IACZ,iBAAiB,MAAM,OAAO,WAAW;AAAA,IACzC,UAAU;AAAA,IACV,OAAO,MAAM,OAAO;AAAA,EACtB;AACA,QAAM,kBAAkB,EAAE,GAAG,kBAAkB,GAAG,UAAU;AAE5D,SACE,qBAAC,QAAK,MAAY,OAAO,iBACvB;AAAA;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,IACA,oBAAC,QAAK,OAAO,OAAO,UAAW,UAAS;AAAA,IACxC;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digilogiclabs/platform-core",
3
- "version": "1.20.0",
3
+ "version": "1.20.3",
4
4
  "description": "Vendor-agnostic infrastructure abstraction layer for DLL Platform",
5
5
  "keywords": [
6
6
  "platform",