@aglyn/shared-util-email 1.0.0-beta.247 → 1.0.0-beta.249

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/shared-util-email",
3
- "version": "1.0.0-beta.247",
3
+ "version": "1.0.0-beta.249",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,8 +25,8 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/shared-data-enums": "1.0.0-beta.247",
29
- "@aglyn/shared-util-http": "1.0.0-beta.247",
28
+ "@aglyn/shared-data-enums": "1.0.0-beta.249",
29
+ "@aglyn/shared-util-http": "1.0.0-beta.249",
30
30
  "@msgpack/msgpack": "^3.1.3",
31
31
  "@swc/helpers": "0.5.23"
32
32
  },
@@ -636,7 +636,26 @@ const NUMBER = String.raw`[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?(?:%|deg|gra
636
636
  main: primaryColor
637
637
  }
638
638
  } : {};
639
- const layered = _extends({}, base, siteColorOverrides(input.colors), brand);
639
+ const site = siteColorOverrides(input.colors);
640
+ const layered = _extends({}, base, site, brand);
641
+ // `mergeThemeOptions`: a tint the site leaves unset is washed from an
642
+ // accent it does set (`accentTint`), and the base's others stay.
643
+ const siteTint = isRecord(site['tint']) ? site['tint'] : {};
644
+ const tint = _extends({}, isRecord(base['tint']) ? base['tint'] : {}, siteTint);
645
+ for (const key of [
646
+ 'primary',
647
+ 'secondary',
648
+ 'tertiary'
649
+ ]){
650
+ const main = isRecord(site[key]) ? site[key]['main'] : undefined;
651
+ if (siteTint[key] || typeof main !== 'string') continue;
652
+ try {
653
+ tint[key] = lighten(main, 0.9);
654
+ } catch (unused) {
655
+ // Not a color the manipulators parse: keep the inherited tint.
656
+ }
657
+ }
658
+ layered['tint'] = tint;
640
659
  try {
641
660
  return derivePalette(layered);
642
661
  } catch (unused) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/email-palette.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The palette an email is painted with (AGL-3370).\n *\n * A color an author picks in the Besigner is stored as a palette TOKEN PATH\n * (`primary.main`, `grey.600`), which MUI resolves on a web page and a mail\n * client never will. So an email needs the same palette the site renders\n * with, as plain data, before it writes a single `style` attribute.\n *\n * That palette is built by `@aglyn/shared-ui-theme` — MUI's `createTheme`,\n * then `createResponsiveTheme`'s shade and accessibility passes — and this\n * lib may not import it: a `type:util` package cannot stand on a `type:ui`\n * one, and a server rendering mail has no business loading MUI to do it. What\n * follows is that derivation ported, light scheme only, with the INPUT colors\n * of the two bases copied and everything else computed the way MUI computes\n * it. `email-palette-parity.spec.ts` in `shared-ui-theme` builds both and\n * holds them equal, so the copy cannot drift without a red.\n */\n\n/**\n * A light-scheme MUI palette as plain data: `primary`, `secondary`,\n * `tertiary`, `surface`, `error`, `warning`, `info`, `success` (each\n * `{ main, light, dark, contrastText }`), `background`, `text`, `tint`,\n * `divider`, `inputOutline`, `grey` and `common`.\n */\nexport type EmailPalette = Readonly<Record<string, unknown>>\n\n/** One authored palette color: a `main`, and any shade the author also set. */\nexport interface EmailPaletteColorInput {\n main?: string\n light?: string\n dark?: string\n contrastText?: string\n}\n\n/**\n * The shape of `HostThemeSchemeColors` (`@aglyn/shared-data-types`), spelled\n * out so this lib needs no dependency on the types package for one shape. An\n * interface has no index signature, so without this a site's typed colors\n * would not be assignable to a plain record.\n */\nexport interface EmailPaletteSchemeColors {\n primary?: EmailPaletteColorInput\n secondary?: EmailPaletteColorInput\n tertiary?: EmailPaletteColorInput\n surface?: EmailPaletteColorInput\n error?: EmailPaletteColorInput\n warning?: EmailPaletteColorInput\n info?: EmailPaletteColorInput\n success?: EmailPaletteColorInput\n background?: { default?: string; paper?: string }\n text?: { primary?: string; secondary?: string; disabled?: string }\n tint?: { primary?: string; secondary?: string; tertiary?: string }\n divider?: string\n}\n\nexport interface EmailPaletteInput {\n /**\n * The base a site or sender layers onto: `'platform'` is the console brand\n * (`consoleOptions`), `'tenant'` the neutral default a customer site wears\n * (`tenantOptions`). {@link emailPaletteBaseForHost} picks it for a site.\n */\n base: 'platform' | 'tenant'\n /**\n * A site's authored light-scheme colors — `host.theme.colorSchemes.light`.\n * Stored data, so every leaf is checked as it is read; a plain record is\n * accepted as readily as the typed shape.\n */\n colors?: EmailPaletteSchemeColors | Readonly<Record<string, unknown>> | null\n /**\n * A white-label org's brand color. It becomes `primary.main` and the whole\n * `primary` record is re-derived from it, exactly as a theme given\n * `palette.primary = { main }` would. Ignored unless it parses as a color.\n */\n primaryColor?: string | null\n}\n\ntype ColorRecord = Record<string, unknown>\ntype PaletteDraft = Record<string, unknown>\n\n// ── The two bases' authored inputs ─────────────────────────────────────────\n//\n// Copied from `console.theme.ts` (`colorScheme.light`) and `tenant.theme.ts`\n// (`tenantColorScheme.light`), minus the `svg*` records no email reads. Only\n// what those files AUTHOR is here; every shade they leave to MUI is derived\n// below, so the copy stays as short as the thing it mirrors.\n\nconst BRAND_GREY = {\n 50: '#FAFAFA',\n 100: '#F5F5F5',\n 200: '#EEEEEE',\n 300: '#E0E0E0',\n 400: '#BDBDBD',\n 500: '#9E9E9E',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#D5D5D5',\n A200: '#AAAAAA',\n A400: '#303030',\n A700: '#616161',\n}\n\nconst PLATFORM_LIGHT_INPUT: PaletteDraft = {\n mode: 'light',\n primary: { main: '#00b0ff', dark: '#0077ad', contrastText: '#FFFFFF' },\n secondary: { main: '#e040fb', dark: '#9d2db0', contrastText: '#FFFFFF' },\n tertiary: { main: '#404C5C', contrastText: '#FFFFFF' },\n surface: { main: '#F8F9FA', contrastText: '#000000' },\n tint: { primary: '#E6F5FF', secondary: '#FBE6FE', tertiary: '#EEF0F2' },\n inputOutline: 'rgba(0, 0, 0, 0.23)',\n background: { default: '#F5F5F5', paper: '#FFFFFF' },\n info: { main: '#1878cd', contrastText: '#FFFFFF' },\n error: { main: '#e32c27', contrastText: '#FFFFFF' },\n success: { main: '#4CAF50', contrastText: '#000000DE' },\n warning: { main: '#FFAB40', contrastText: '#000000DE' },\n grey: BRAND_GREY,\n}\n\nconst TENANT_LIGHT_INPUT: PaletteDraft = {\n mode: 'light',\n primary: { main: '#1976d2', dark: '#125393', contrastText: '#FFFFFF' },\n secondary: { main: '#9c27b0', dark: '#6d1b7b', contrastText: '#FFFFFF' },\n tertiary: { main: '#4a5568', dark: '#343b49', contrastText: '#FFFFFF' },\n surface: { main: '#f1f3f5', contrastText: '#000000DE' },\n tint: { primary: '#e8f1fb', secondary: '#f5e9f7', tertiary: '#eef0f3' },\n inputOutline: 'rgba(0, 0, 0, 0.23)',\n background: { default: '#fafafa', paper: '#ffffff' },\n info: { main: '#0288d1', dark: '#015f92', contrastText: '#000000DE' },\n error: { main: '#d32f2f', dark: '#942121', contrastText: '#FFFFFF' },\n success: { main: '#2e7d32', dark: '#205823', contrastText: '#FFFFFF' },\n warning: { main: '#ed6c02', dark: '#a64c01', contrastText: '#000000DE' },\n grey: BRAND_GREY,\n}\n\n// ── MUI's light-mode constants (`createPalette`, `colors/*`) ───────────────\n\nconst MUI_COMMON = { black: '#000', white: '#fff' }\n\nconst MUI_GREY = {\n 50: '#fafafa',\n 100: '#f5f5f5',\n 200: '#eeeeee',\n 300: '#e0e0e0',\n 400: '#bdbdbd',\n 500: '#9e9e9e',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#f5f5f5',\n A200: '#eeeeee',\n A400: '#bdbdbd',\n A700: '#616161',\n}\n\n/** `getLight()` — the mode-hydrated slots, minus `action` (no email reads it). */\nfunction muiLightDefaults(): PaletteDraft {\n return {\n text: {\n primary: 'rgba(0, 0, 0, 0.87)',\n secondary: 'rgba(0, 0, 0, 0.6)',\n disabled: 'rgba(0, 0, 0, 0.38)',\n },\n divider: 'rgba(0, 0, 0, 0.12)',\n background: { paper: MUI_COMMON.white, default: MUI_COMMON.white },\n }\n}\n\n/** MUI's `light.text.primary`, the dark ink `getContrastText` falls back to. */\nconst MUI_DARK_INK = 'rgba(0, 0, 0, 0.87)'\nconst MUI_CONTRAST_THRESHOLD = 3\n/** MUI's default `tonalOffset` of 0.2, split the way `addLightOrDark` splits it. */\nconst TONAL_OFFSET_LIGHT = 0.2\nconst TONAL_OFFSET_DARK = 0.2 * 1.5\n\n/** The six colors `createPalette` augments. Both bases author every one. */\nconst MUI_AUGMENTED_KEYS = [\n 'primary',\n 'secondary',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\n/** `createResponsiveTheme`'s FOREGROUND_COLOR_KEYS: `dark` is accent text. */\nconst FOREGROUND_COLOR_KEYS: ReadonlyArray<string> = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'error',\n 'warning',\n 'info',\n 'success',\n]\n/** …and `contrastText` is text wherever it lives, so `surface` joins. */\nconst CONTRAST_TEXT_COLOR_KEYS: ReadonlyArray<string> = [\n ...FOREGROUND_COLOR_KEYS,\n 'surface',\n]\n\n// ── MUI's colorManipulator, ported ─────────────────────────────────────────\n//\n// Byte-for-byte in behavior, including the parts that look odd: `recompose`\n// truncates rgb channels with `parseInt`, and `getLuminance` rounds to three\n// places. The palette's derived shades are strings, so a port that rounded\n// \"better\" would be a port that disagrees.\n\ninterface DecomposedColor {\n type: string\n values: Array<number>\n colorSpace?: string\n}\n\nfunction hexToRgb(color: string): string {\n const hex = color.slice(1)\n const pattern = new RegExp(`.{1,${hex.length >= 6 ? 2 : 1}}`, 'g')\n let parts: Array<string> | null = hex.match(pattern)\n if (parts && parts[0].length === 1) parts = parts.map((part) => part + part)\n return parts\n ? `rgb${parts.length === 4 ? 'a' : ''}(${parts\n .map((part, index) =>\n index < 3\n ? parseInt(part, 16)\n : Math.round((parseInt(part, 16) / 255) * 1000) / 1000,\n )\n .join(', ')})`\n : ''\n}\n\nfunction decomposeColor(color: string): DecomposedColor {\n if (color.charAt(0) === '#') return decomposeColor(hexToRgb(color))\n const marker = color.indexOf('(')\n const type = color.substring(0, marker)\n if (!['rgb', 'rgba', 'hsl', 'hsla', 'color'].includes(type)) {\n throw new Error(`email-palette: unsupported color \"${color}\"`)\n }\n const body = color.substring(marker + 1, color.length - 1)\n let raw: Array<string>\n let colorSpace: string | undefined\n if (type === 'color') {\n raw = body.split(' ')\n colorSpace = raw.shift()\n if (raw.length === 4 && raw[3].charAt(0) === '/') raw[3] = raw[3].slice(1)\n if (\n !['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].includes(\n colorSpace ?? '',\n )\n ) {\n throw new Error(`email-palette: unsupported color space \"${colorSpace}\"`)\n }\n } else {\n raw = body.split(',')\n }\n return { type, values: raw.map((value) => parseFloat(value)), colorSpace }\n}\n\nfunction recomposeColor({ type, colorSpace, values }: DecomposedColor): string {\n let parts: Array<string | number> = values\n if (type.includes('rgb')) {\n parts = values.map((value, index) =>\n index < 3 ? parseInt(String(value), 10) : value,\n )\n } else if (type.includes('hsl')) {\n parts = [...values]\n parts[1] = `${values[1]}%`\n parts[2] = `${values[2]}%`\n }\n const body = type.includes('color')\n ? `${colorSpace} ${parts.join(' ')}`\n : parts.join(', ')\n return `${type}(${body})`\n}\n\nfunction intToHex(value: number): string {\n const hex = value.toString(16)\n return hex.length === 1 ? `0${hex}` : hex\n}\n\nfunction rgbToHex(color: string): string {\n if (color.startsWith('#')) return color\n const { values } = decomposeColor(color)\n return `#${values\n .map((value, index) => intToHex(index === 3 ? Math.round(255 * value) : value))\n .join('')}`\n}\n\nfunction hslToRgb(color: string | DecomposedColor): string {\n const decomposed = typeof color === 'string' ? decomposeColor(color) : color\n const { values } = decomposed\n const hue = values[0]\n const saturation = values[1] / 100\n const lightness = values[2] / 100\n const chroma = saturation * Math.min(lightness, 1 - lightness)\n const channel = (n: number, k = (n + hue / 30) % 12) =>\n lightness - chroma * Math.max(Math.min(k - 3, 9 - k, 1), -1)\n const rgb = [\n Math.round(channel(0) * 255),\n Math.round(channel(8) * 255),\n Math.round(channel(4) * 255),\n ]\n let type = 'rgb'\n if (decomposed.type === 'hsla') {\n type += 'a'\n rgb.push(values[3])\n }\n return recomposeColor({ type, values: rgb })\n}\n\nfunction clampUnit(value: number): number {\n return Math.min(1, Math.max(0, value))\n}\n\nfunction lighten(color: string, coefficient: number): string {\n const decomposed = decomposeColor(color)\n const amount = clampUnit(coefficient)\n const { type, values } = decomposed\n if (type.includes('hsl')) {\n values[2] += (100 - values[2]) * amount\n } else if (type.includes('rgb')) {\n for (let i = 0; i < 3; i += 1) values[i] += (255 - values[i]) * amount\n } else if (type.includes('color')) {\n for (let i = 0; i < 3; i += 1) values[i] += (1 - values[i]) * amount\n }\n return recomposeColor(decomposed)\n}\n\nfunction darken(color: string, coefficient: number): string {\n const decomposed = decomposeColor(color)\n const amount = clampUnit(coefficient)\n const { type, values } = decomposed\n if (type.includes('hsl')) {\n values[2] *= 1 - amount\n } else if (type.includes('rgb') || type.includes('color')) {\n for (let i = 0; i < 3; i += 1) values[i] *= 1 - amount\n }\n return recomposeColor(decomposed)\n}\n\nfunction srgbChannelToLinear(value: number): number {\n return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4\n}\n\n/** MUI's `getLuminance`: WCAG luminance, rounded to three places. */\nfunction muiLuminance(color: string): number {\n const decomposed = decomposeColor(color)\n const rgb =\n decomposed.type === 'hsl' || decomposed.type === 'hsla'\n ? decomposeColor(hslToRgb(decomposed)).values\n : decomposed.values\n const linear = rgb.map((value) =>\n srgbChannelToLinear(decomposed.type !== 'color' ? value / 255 : value),\n )\n return Number(\n (0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]).toFixed(3),\n )\n}\n\n/** MUI's `getContrastRatio`, on the rounded luminance. */\nfunction muiContrastRatio(foreground: string, background: string): number {\n const a = muiLuminance(foreground)\n const b = muiLuminance(background)\n return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)\n}\n\n// ── `accessible-shade.ts`, ported ──────────────────────────────────────────\n\nconst AA_TEXT_CONTRAST = 4.5\n\n/** Full-precision WCAG luminance, as `accessible-shade.ts` measures it. */\nfunction relativeLuminance(color: string): number {\n const decomposed = decomposeColor(color)\n if (decomposed.type === 'color') {\n throw new Error(`email-palette: unsupported color format \"${color}\"`)\n }\n const values = decomposed.type.startsWith('hsl')\n ? decomposeColor(hslToRgb(color)).values\n : decomposed.values\n return (\n 0.2126 * srgbChannelToLinear(values[0] / 255) +\n 0.7152 * srgbChannelToLinear(values[1] / 255) +\n 0.0722 * srgbChannelToLinear(values[2] / 255)\n )\n}\n\nfunction contrastRatio(colorA: string, colorB: string): number {\n const a = relativeLuminance(colorA)\n const b = relativeLuminance(colorB)\n return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)\n}\n\nfunction meetsContrast(\n foreground: string,\n backgrounds: ReadonlyArray<string>,\n): boolean {\n return backgrounds.every(\n (background) => contrastRatio(foreground, background) >= AA_TEXT_CONTRAST,\n )\n}\n\nfunction toHslValues(color: string): [number, number, number] {\n const decomposed = decomposeColor(color)\n if (decomposed.type.startsWith('hsl')) {\n const [h, s, l] = decomposed.values\n return [h, s / 100, l / 100]\n }\n const r = decomposed.values[0] / 255\n const g = decomposed.values[1] / 255\n const b = decomposed.values[2] / 255\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n const lightness = (max + min) / 2\n if (max === min) return [0, 0, lightness]\n const delta = max - min\n const saturation =\n lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min)\n let hue: number\n if (max === r) hue = (g - b) / delta + (g < b ? 6 : 0)\n else if (max === g) hue = (b - r) / delta + 2\n else hue = (r - g) / delta + 4\n return [hue * 60, saturation, lightness]\n}\n\nfunction hslToHex(hue: number, saturation: number, lightness: number): string {\n return rgbToHex(\n hslToRgb(`hsl(${hue}, ${saturation * 100}%, ${lightness * 100}%)`),\n )\n}\n\n/** The nearest shade of `color`, walking lightness one way, that clears AA. */\nfunction accessibleShade(\n color: string,\n backgrounds: ReadonlyArray<string>,\n direction: 'darken' | 'lighten',\n): string {\n if (!backgrounds.length || meetsContrast(color, backgrounds)) return color\n const [hue, saturation, initialLightness] = toHslValues(color)\n const delta = direction === 'lighten' ? 0.01 : -0.01\n let lightness = initialLightness\n let candidate = color\n for (let i = 0; i < 120; i += 1) {\n lightness = Math.min(1, Math.max(0, lightness + delta))\n candidate = hslToHex(hue, saturation, lightness)\n if (meetsContrast(candidate, backgrounds)) return candidate\n if (lightness === 0 || lightness === 1) return candidate\n }\n return candidate\n}\n\n// ── Palette assembly ───────────────────────────────────────────────────────\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** MUI's `deepmerge` with `clone: true`, for plain data. */\nfunction deepMerge(target: PaletteDraft, source: PaletteDraft): PaletteDraft {\n const output: PaletteDraft = { ...target }\n for (const key of Object.keys(source)) {\n const next = source[key]\n const current = target[key]\n if (\n isRecord(next) &&\n Object.prototype.hasOwnProperty.call(target, key) &&\n isRecord(current)\n ) {\n output[key] = deepMerge(current, next)\n } else {\n output[key] = isRecord(next) ? deepMerge({}, next) : next\n }\n }\n return output\n}\n\n/**\n * `createPalette`'s `augmentColor` for an object with a `main`: fill `light`\n * and `dark` from the tonal offset, and `contrastText` by MUI's threshold.\n */\nfunction augmentColor(color: ColorRecord): ColorRecord {\n const augmented = { ...color }\n const main = augmented['main']\n if (typeof main !== 'string') {\n throw new Error('email-palette: a palette color needs a string `main`')\n }\n if (!augmented['light']) augmented['light'] = lighten(main, TONAL_OFFSET_LIGHT)\n if (!augmented['dark']) augmented['dark'] = darken(main, TONAL_OFFSET_DARK)\n if (!augmented['contrastText']) {\n augmented['contrastText'] =\n muiContrastRatio(main, MUI_COMMON.white) >= MUI_CONTRAST_THRESHOLD\n ? MUI_COMMON.white\n : MUI_DARK_INK\n }\n return augmented\n}\n\n/**\n * `createResponsiveTheme`'s `addShadeVariants`, for the two colors MUI does\n * not know about. Its contrast pick is handed the DARK tonal offset (0.3) as\n * the threshold, so it lands on white for any color at all; the port keeps\n * that, because the parity it owes is to what the site renders, and any\n * pairing below AA is repaired by the accessibility pass that follows.\n */\nfunction addShadeVariants(color: unknown): void {\n if (!isRecord(color) || !color['main']) return\n const main = color['main'] as string\n if (!color['dark']) color['dark'] = darken(main, TONAL_OFFSET_DARK)\n if (!color['light']) color['light'] = lighten(main, TONAL_OFFSET_LIGHT)\n if (!color['contrastText']) {\n color['contrastText'] =\n muiContrastRatio(main, '#FFFFFF') >= TONAL_OFFSET_DARK\n ? '#FFFFFF'\n : 'rgba(0, 0, 0, 0.87)'\n }\n}\n\n/**\n * `ensureAccessibleShades` for the light scheme: a DERIVED `dark` that misses\n * 4.5:1 on either background is walked darker, and a derived `contrastText`\n * that misses 4.5:1 on its `main` is walked toward the pole with more room.\n * Whatever the input authored passes through untouched.\n */\nfunction ensureAccessibleShades(\n palette: PaletteDraft,\n input: PaletteDraft,\n): void {\n const background = isRecord(palette['background']) ? palette['background'] : {}\n const backgrounds = [background['default'], background['paper']].filter(\n (value): value is string => typeof value === 'string',\n )\n if (!backgrounds.length) return\n\n for (const key of CONTRAST_TEXT_COLOR_KEYS) {\n const color = palette[key]\n if (!isRecord(color) || typeof color['main'] !== 'string') continue\n const provided = input[key]\n if (isRecord(provided) && !('main' in provided)) continue\n const explicit = isRecord(provided) ? provided : {}\n const main = color['main']\n\n try {\n if (\n FOREGROUND_COLOR_KEYS.includes(key) &&\n !explicit['dark'] &&\n typeof color['dark'] === 'string' &&\n !meetsContrast(color['dark'], backgrounds)\n ) {\n color['dark'] = accessibleShade(color['dark'], backgrounds, 'darken')\n }\n if (\n !explicit['contrastText'] &&\n typeof color['contrastText'] === 'string' &&\n !meetsContrast(color['contrastText'], [main])\n ) {\n const direction =\n contrastRatio('#fff', main) >= contrastRatio('#000', main)\n ? 'lighten'\n : 'darken'\n color['contrastText'] = accessibleShade(\n color['contrastText'],\n [main],\n direction,\n )\n }\n } catch {\n // An unparseable color is left as derived, as the theme leaves it.\n }\n }\n}\n\n/** `createTheme` + `createResponsiveTheme`'s passes, palette only. */\nfunction derivePalette(input: PaletteDraft): PaletteDraft {\n const rest: PaletteDraft = { ...input }\n delete rest['mode']\n delete rest['contrastThreshold']\n delete rest['tonalOffset']\n\n const augmented: PaletteDraft = {}\n for (const key of MUI_AUGMENTED_KEYS) {\n const color = input[key]\n if (!isRecord(color)) {\n throw new Error(`email-palette: the base palette is missing \\`${key}\\``)\n }\n augmented[key] = augmentColor(color)\n }\n\n const palette = deepMerge(\n {\n common: { ...MUI_COMMON },\n mode: 'light',\n ...augmented,\n grey: MUI_GREY,\n ...muiLightDefaults(),\n },\n rest,\n )\n addShadeVariants(palette['tertiary'])\n addShadeVariants(palette['surface'])\n ensureAccessibleShades(palette, input)\n return palette\n}\n\n// ── A site's colors, as `hostThemeToThemeOptions` reads them ───────────────\n\nconst SCHEME_COLOR_KEYS = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'surface',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\n/** Truthy string, or nothing: the \"copy what was set\" test the theme uses. */\nfunction setString(value: unknown): string | undefined {\n return typeof value === 'string' && value ? value : undefined\n}\n\n/** `pickPaletteColor`: a color needs a `main`; its shades ride along if set. */\nfunction pickPaletteColor(color: unknown): ColorRecord | undefined {\n if (!isRecord(color)) return undefined\n const main = setString(color['main'])\n if (!main) return undefined\n const picked: ColorRecord = { main }\n for (const shade of ['light', 'dark', 'contrastText'] as const) {\n const value = setString(color[shade])\n if (value) picked[shade] = value\n }\n return picked\n}\n\n/** Picks the listed string leaves of a group that were set, or nothing. */\nfunction pickLeaves(\n group: unknown,\n keys: ReadonlyArray<string>,\n): Record<string, string> | undefined {\n if (!isRecord(group)) return undefined\n const picked: Record<string, string> = {}\n for (const key of keys) {\n const value = setString(group[key])\n if (value) picked[key] = value\n }\n return Object.keys(picked).length ? picked : undefined\n}\n\n/** `schemeColorsToPaletteOptions` for the light scheme. */\nfunction siteColorOverrides(\n input: EmailPaletteInput['colors'],\n): PaletteDraft {\n const overrides: PaletteDraft = { mode: 'light' }\n if (!isRecord(input)) return overrides\n const colors: Readonly<Record<string, unknown>> = input\n for (const key of SCHEME_COLOR_KEYS) {\n const color = pickPaletteColor(colors[key])\n if (color) overrides[key] = color\n }\n const background = pickLeaves(colors['background'], ['default', 'paper'])\n if (background) overrides['background'] = background\n const text = pickLeaves(colors['text'], ['primary', 'secondary', 'disabled'])\n if (text) overrides['text'] = text\n const tint = pickLeaves(colors['tint'], ['primary', 'secondary', 'tertiary'])\n if (tint) overrides['tint'] = tint\n const divider = setString(colors['divider'])\n if (divider) overrides['divider'] = divider\n return overrides\n}\n\n// ── Literal CSS colors ─────────────────────────────────────────────────────\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nconst NUMBER = String.raw`[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[-+]?\\d+)?(?:%|deg|grad|rad|turn)?`\n/**\n * `rgb()`, `rgba()`, `hsl()`, `hsla()` holding numbers and nothing else —\n * comma or space separated, with an optional `/ alpha`. Anything that could\n * close the declaration or open another (`;`, `\"`, `(`, `url`) cannot match.\n */\nconst FUNCTION_COLOR = new RegExp(\n String.raw`^(?:rgba?|hsla?)\\(\\s*${NUMBER}(?:\\s*,\\s*|\\s+)${NUMBER}(?:\\s*,\\s*|\\s+)${NUMBER}(?:(?:\\s*,\\s*|\\s*\\/\\s*)${NUMBER})?\\s*\\)$`,\n 'i',\n)\n/** A color MUI's own manipulators parse: hex, or a comma-separated function. */\nconst MUI_PARSEABLE_FUNCTION = new RegExp(\n String.raw`^(?:rgba?|hsla?)\\(\\s*${NUMBER}\\s*,\\s*${NUMBER}\\s*,\\s*${NUMBER}(?:\\s*,\\s*${NUMBER})?\\s*\\)$`,\n 'i',\n)\n\n/** CSS Color Module Level 4 named colors, plus `transparent`. */\nconst NAMED_COLORS: ReadonlySet<string> = new Set(\n (\n 'aliceblue antiquewhite aqua aquamarine azure beige bisque black ' +\n 'blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse ' +\n 'chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan ' +\n 'darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta ' +\n 'darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen ' +\n 'darkslateblue darkslategray darkslategrey darkturquoise darkviolet ' +\n 'deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite ' +\n 'forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green ' +\n 'greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender ' +\n 'lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan ' +\n 'lightgoldenrodyellow lightgray lightgreen lightgrey lightpink ' +\n 'lightsalmon lightseagreen lightskyblue lightslategray lightslategrey ' +\n 'lightsteelblue lightyellow lime limegreen linen magenta maroon ' +\n 'mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen ' +\n 'mediumslateblue mediumspringgreen mediumturquoise mediumvioletred ' +\n 'midnightblue mintcream mistyrose moccasin navajowhite navy oldlace ' +\n 'olive olivedrab orange orangered orchid palegoldenrod palegreen ' +\n 'paleturquoise palevioletred papayawhip peachpuff peru pink plum ' +\n 'powderblue purple rebeccapurple red rosybrown royalblue saddlebrown ' +\n 'salmon sandybrown seagreen seashell sienna silver skyblue slateblue ' +\n 'slategray slategrey snow springgreen steelblue tan teal thistle tomato ' +\n 'turquoise violet wheat white whitesmoke yellow yellowgreen transparent'\n ).split(' '),\n)\n\n/** True for a literal CSS color that is safe to write into a style attribute. */\nfunction isLiteralColor(value: string): boolean {\n return (\n HEX_COLOR.test(value) ||\n FUNCTION_COLOR.test(value) ||\n NAMED_COLORS.has(value.toLowerCase())\n )\n}\n\n/** True for a color MUI can derive shades from without throwing. */\nfunction isDerivableColor(value: string): boolean {\n return HEX_COLOR.test(value) || MUI_PARSEABLE_FUNCTION.test(value)\n}\n\n// ── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * The fully derived light palette a site or sender renders with: the\n * chosen base, the site's authored colors layered one level deep (a color's\n * whole record replaced, so MUI re-derives its shades from the new `main`),\n * then a white-label `primaryColor` over that.\n *\n * Equal, for every token the Besigner's color picker offers, to the palette\n * of `createResponsiveTheme` over `mergeThemeOptions(siteBaseOptions(…))`\n * and the host theme's light `hostThemeToThemeOptions`.\n *\n * Where the site's colors cannot be derived at all — a `main` MUI cannot\n * parse, on which `createTheme` itself throws — the email falls back to the\n * base rather than failing the send: there is no rendered page to agree with.\n */\nexport function buildEmailPalette(input: EmailPaletteInput): EmailPalette {\n const base =\n input.base === 'platform' ? PLATFORM_LIGHT_INPUT : TENANT_LIGHT_INPUT\n const primaryColor =\n typeof input.primaryColor === 'string' &&\n isDerivableColor(input.primaryColor.trim())\n ? input.primaryColor.trim()\n : undefined\n const brand: PaletteDraft = primaryColor\n ? { primary: { main: primaryColor } }\n : {}\n\n const layered = { ...base, ...siteColorOverrides(input.colors), ...brand }\n try {\n return derivePalette(layered)\n } catch {\n return derivePalette({ ...base, ...brand })\n }\n}\n\n/** The platform's own palette — the console brand, light scheme. */\nexport const PLATFORM_EMAIL_PALETTE: EmailPalette = buildEmailPalette({\n base: 'platform',\n})\n\n/** Palette token paths: a key, optionally one dot and a leaf (`grey.600`). */\nconst TOKEN_PATH = /^[a-zA-Z][a-zA-Z0-9]*(?:\\.[a-zA-Z0-9]+)?$/\n\nfunction lookupToken(\n palette: EmailPalette,\n path: string,\n): string | undefined {\n let node: unknown = palette\n for (const key of path.split('.')) {\n if (!isRecord(node) || !Object.prototype.hasOwnProperty.call(node, key)) {\n return undefined\n }\n node = node[key]\n }\n return typeof node === 'string' ? node : undefined\n}\n\n/**\n * A palette value as an opaque `#rrggbb`. Translucent values (`text.primary`\n * is `rgba(0, 0, 0, 0.87)`, some `contrastText`s are `#000000DE`) are\n * composited over the palette's paper, the ground an email body sits on:\n * Outlook's Word engine drops `rgba()` and eight-digit hex outright, and the\n * flattened color is what a reader sees on that ground anyway.\n */\nfunction toOpaqueHex(value: string, palette: EmailPalette): string | undefined {\n const channels = rgbaChannels(value)\n if (!channels) return undefined\n const [r, g, b, alpha] = channels\n if (alpha >= 1) return channelsToHex(r, g, b)\n const background = palette['background']\n const paper = isRecord(background) ? background['paper'] : undefined\n const ground =\n (typeof paper === 'string' ? rgbaChannels(paper) : undefined) ?? [\n 255, 255, 255, 1,\n ]\n const over = (fore: number, back: number) =>\n fore * alpha + back * (1 - alpha)\n return channelsToHex(over(r, ground[0]), over(g, ground[1]), over(b, ground[2]))\n}\n\nfunction rgbaChannels(\n value: string,\n): [number, number, number, number] | undefined {\n if (!isDerivableColor(value)) return undefined\n try {\n const decomposed = decomposeColor(value)\n const rgb = decomposed.type.startsWith('hsl')\n ? decomposeColor(hslToRgb(decomposed)).values\n : decomposed.values\n const alpha = decomposed.values.length > 3 ? decomposed.values[3] : 1\n const channels: [number, number, number, number] = [\n rgb[0],\n rgb[1],\n rgb[2],\n alpha,\n ]\n return channels.every(Number.isFinite) ? channels : undefined\n } catch {\n return undefined\n }\n}\n\nfunction channelsToHex(r: number, g: number, b: number): string {\n return `#${[r, g, b]\n .map((value) => intToHex(Math.round(Math.min(255, Math.max(0, value)))))\n .join('')}`\n}\n\n/**\n * Resolves a stored color prop for an email's markup.\n *\n * - A palette token path (`primary.main`, `grey.600`, `divider`) resolves\n * against `palette` to an opaque hex — or to nothing without a palette.\n * - A literal CSS color (hex, `rgb()`/`rgba()`/`hsl()`/`hsla()`,\n * `transparent`, a named color) passes through as written.\n * - Anything else — an unknown token, garbage, an empty value, and anything\n * that could step outside a `style` attribute — is `undefined`, so the\n * caller uses its own default.\n */\nexport function resolveEmailColor(\n value: unknown,\n palette: EmailPalette | undefined,\n): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (!trimmed) return undefined\n\n if (palette && TOKEN_PATH.test(trimmed)) {\n const resolved = lookupToken(palette, trimmed)\n if (resolved !== undefined) {\n const hex = toOpaqueHex(resolved, palette)\n if (hex) return hex\n if (isLiteralColor(resolved)) return resolved\n return undefined\n }\n }\n return isLiteralColor(trimmed) ? trimmed : undefined\n}\n\n// ── Which base a site wears ────────────────────────────────────────────────\n\n/**\n * The prefix the tenant middleware puts on a custom domain before it becomes\n * the `[host]` route segment — mirrored from `tenant.theme.ts`.\n */\nconst CNAME_PREFIX = 'cname--'\n\n/**\n * The hosts whose brand is the operator's own, mirrored from\n * `PLATFORM_BRAND_HOSTS` in `tenant.theme.ts` and read from the same\n * variable. Dot notation for the same reason it has there: Next substitutes\n * `process.env.NAME` textually and never the bracket form.\n */\nconst PLATFORM_BRAND_HOSTS: ReadonlySet<string> = new Set(\n (process.env.NEXT_PUBLIC_PLATFORM_BRAND_HOSTS ?? 'aglyn.com,aglyn.io')\n .split(',')\n .map((host) => host.trim().toLowerCase())\n .filter(Boolean),\n)\n\n/**\n * Which base a site's mail layers onto: `'platform'` for the operator's own\n * hosts, `'tenant'` for every customer site — the answer\n * `wearsPlatformBrand(hostBrandKey(host))` gives the page itself, so a site's\n * email and its published page start from the same palette.\n */\nexport function emailPaletteBaseForHost(\n host: { cname?: string | null; subdomain?: string | null } | null | undefined,\n): 'platform' | 'tenant' {\n const key = host?.cname || host?.subdomain || undefined\n if (!key) return 'tenant'\n const normalized = key.trim().toLowerCase()\n const bare = normalized.startsWith(CNAME_PREFIX)\n ? normalized.slice(CNAME_PREFIX.length)\n : normalized\n return PLATFORM_BRAND_HOSTS.has(bare) ? 'platform' : 'tenant'\n}\n"],"names":["process","BRAND_GREY","A100","A200","A400","A700","PLATFORM_LIGHT_INPUT","mode","primary","main","dark","contrastText","secondary","tertiary","surface","tint","inputOutline","background","default","paper","info","error","success","warning","grey","TENANT_LIGHT_INPUT","MUI_COMMON","black","white","MUI_GREY","muiLightDefaults","text","disabled","divider","MUI_DARK_INK","MUI_CONTRAST_THRESHOLD","TONAL_OFFSET_LIGHT","TONAL_OFFSET_DARK","MUI_AUGMENTED_KEYS","FOREGROUND_COLOR_KEYS","CONTRAST_TEXT_COLOR_KEYS","hexToRgb","color","hex","slice","pattern","RegExp","length","parts","match","map","part","index","parseInt","Math","round","join","decomposeColor","charAt","marker","indexOf","type","substring","includes","Error","body","raw","colorSpace","split","shift","values","value","parseFloat","recomposeColor","String","intToHex","toString","rgbToHex","startsWith","hslToRgb","decomposed","hue","saturation","lightness","chroma","min","channel","n","k","max","rgb","push","clampUnit","lighten","coefficient","amount","i","darken","srgbChannelToLinear","muiLuminance","linear","Number","toFixed","muiContrastRatio","foreground","a","b","AA_TEXT_CONTRAST","relativeLuminance","contrastRatio","colorA","colorB","meetsContrast","backgrounds","every","toHslValues","h","s","l","r","g","delta","hslToHex","accessibleShade","direction","initialLightness","candidate","isRecord","Array","isArray","deepMerge","target","source","output","key","Object","keys","next","current","prototype","hasOwnProperty","call","augmentColor","augmented","addShadeVariants","ensureAccessibleShades","palette","input","filter","provided","explicit","derivePalette","rest","common","SCHEME_COLOR_KEYS","setString","undefined","pickPaletteColor","picked","shade","pickLeaves","group","siteColorOverrides","overrides","colors","HEX_COLOR","NUMBER","FUNCTION_COLOR","MUI_PARSEABLE_FUNCTION","NAMED_COLORS","Set","isLiteralColor","test","has","toLowerCase","isDerivableColor","buildEmailPalette","base","primaryColor","trim","brand","layered","PLATFORM_EMAIL_PALETTE","TOKEN_PATH","lookupToken","path","node","toOpaqueHex","channels","rgbaChannels","alpha","channelsToHex","ground","over","fore","back","isFinite","resolveEmailColor","trimmed","resolved","CNAME_PREFIX","PLATFORM_BRAND_HOSTS","env","NEXT_PUBLIC_PLATFORM_BRAND_HOSTS","host","Boolean","emailPaletteBaseForHost","cname","subdomain","normalized","bare"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;CAgBC,GAED;;;;;CAKC;IA81BEA;AAtyBH,8EAA8E;AAC9E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,4EAA4E;AAC5E,6DAA6D;AAE7D,MAAMC,aAAa;IACjB,IAAI;IACJ,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACLC,MAAM;IACNC,MAAM;IACNC,MAAM;IACNC,MAAM;AACR;AAEA,MAAMC,uBAAqC;IACzCC,MAAM;IACNC,SAAS;QAAEC,MAAM;QAAWC,MAAM;QAAWC,cAAc;IAAU;IACrEC,WAAW;QAAEH,MAAM;QAAWC,MAAM;QAAWC,cAAc;IAAU;IACvEE,UAAU;QAAEJ,MAAM;QAAWE,cAAc;IAAU;IACrDG,SAAS;QAAEL,MAAM;QAAWE,cAAc;IAAU;IACpDI,MAAM;QAAEP,SAAS;QAAWI,WAAW;QAAWC,UAAU;IAAU;IACtEG,cAAc;IACdC,YAAY;QAAEC,SAAS;QAAWC,OAAO;IAAU;IACnDC,MAAM;QAAEX,MAAM;QAAWE,cAAc;IAAU;IACjDU,OAAO;QAAEZ,MAAM;QAAWE,cAAc;IAAU;IAClDW,SAAS;QAAEb,MAAM;QAAWE,cAAc;IAAY;IACtDY,SAAS;QAAEd,MAAM;QAAWE,cAAc;IAAY;IACtDa,MAAMvB;AACR;AAEA,MAAMwB,qBAAmC;IACvClB,MAAM;IACNC,SAAS;QAAEC,MAAM;QAAWC,MAAM;QAAWC,cAAc;IAAU;IACrEC,WAAW;QAAEH,MAAM;QAAWC,MAAM;QAAW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ACrC,OAAO3C;QACT;IACF;IACA,OAAOe,eAAe2B,WAAWA,UAAU1C;AAC7C;AAEA,8EAA8E;AAE9E;;;CAGC,GACD,MAAM4C,eAAe;AAErB;;;;;CAKC,GACD,MAAMC,uBAA4C,IAAI/B,IACpD,EAAC1K,gDAAAA,QAAQ0M,GAAG,CAACC,gCAAgC,YAA5C3M,gDAAgD,sBAC9CoE,KAAK,CAAC,KACNlB,GAAG,CAAC,CAAC0J,OAASA,KAAKzB,IAAI,GAAGL,WAAW,IACrC1B,MAAM,CAACyD;AAGZ;;;;;CAKC,GACD,OAAO,SAASC,wBACdF,IAA6E;IAE7E,MAAMtE,MAAMsE,CAAAA,wBAAAA,KAAMG,KAAK,MAAIH,wBAAAA,KAAMI,SAAS,KAAIpD;IAC9C,IAAI,CAACtB,KAAK,OAAO;IACjB,MAAM2E,aAAa3E,IAAI6C,IAAI,GAAGL,WAAW;IACzC,MAAMoC,OAAOD,WAAWnI,UAAU,CAAC0H,gBAC/BS,WAAWrK,KAAK,CAAC4J,aAAazJ,MAAM,IACpCkK;IACJ,OAAOR,qBAAqB5B,GAAG,CAACqC,QAAQ,aAAa;AACvD"}
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/email-palette.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The palette an email is painted with (AGL-3370).\n *\n * A color an author picks in the Besigner is stored as a palette TOKEN PATH\n * (`primary.main`, `grey.600`), which MUI resolves on a web page and a mail\n * client never will. So an email needs the same palette the site renders\n * with, as plain data, before it writes a single `style` attribute.\n *\n * That palette is built by `@aglyn/shared-ui-theme` — MUI's `createTheme`,\n * then `createResponsiveTheme`'s shade and accessibility passes — and this\n * lib may not import it: a `type:util` package cannot stand on a `type:ui`\n * one, and a server rendering mail has no business loading MUI to do it. What\n * follows is that derivation ported, light scheme only, with the INPUT colors\n * of the two bases copied and everything else computed the way MUI computes\n * it. `email-palette-parity.spec.ts` in `shared-ui-theme` builds both and\n * holds them equal, so the copy cannot drift without a red.\n */\n\n/**\n * A light-scheme MUI palette as plain data: `primary`, `secondary`,\n * `tertiary`, `surface`, `error`, `warning`, `info`, `success` (each\n * `{ main, light, dark, contrastText }`), `background`, `text`, `tint`,\n * `divider`, `inputOutline`, `grey` and `common`.\n */\nexport type EmailPalette = Readonly<Record<string, unknown>>\n\n/** One authored palette color: a `main`, and any shade the author also set. */\nexport interface EmailPaletteColorInput {\n main?: string\n light?: string\n dark?: string\n contrastText?: string\n}\n\n/**\n * The shape of `HostThemeSchemeColors` (`@aglyn/shared-data-types`), spelled\n * out so this lib needs no dependency on the types package for one shape. An\n * interface has no index signature, so without this a site's typed colors\n * would not be assignable to a plain record.\n */\nexport interface EmailPaletteSchemeColors {\n primary?: EmailPaletteColorInput\n secondary?: EmailPaletteColorInput\n tertiary?: EmailPaletteColorInput\n surface?: EmailPaletteColorInput\n error?: EmailPaletteColorInput\n warning?: EmailPaletteColorInput\n info?: EmailPaletteColorInput\n success?: EmailPaletteColorInput\n background?: { default?: string; paper?: string }\n text?: { primary?: string; secondary?: string; disabled?: string }\n tint?: { primary?: string; secondary?: string; tertiary?: string }\n divider?: string\n}\n\nexport interface EmailPaletteInput {\n /**\n * The base a site or sender layers onto: `'platform'` is the console brand\n * (`consoleOptions`), `'tenant'` the neutral default a customer site wears\n * (`tenantOptions`). {@link emailPaletteBaseForHost} picks it for a site.\n */\n base: 'platform' | 'tenant'\n /**\n * A site's authored light-scheme colors — `host.theme.colorSchemes.light`.\n * Stored data, so every leaf is checked as it is read; a plain record is\n * accepted as readily as the typed shape.\n */\n colors?: EmailPaletteSchemeColors | Readonly<Record<string, unknown>> | null\n /**\n * A white-label org's brand color. It becomes `primary.main` and the whole\n * `primary` record is re-derived from it, exactly as a theme given\n * `palette.primary = { main }` would. Ignored unless it parses as a color.\n */\n primaryColor?: string | null\n}\n\ntype ColorRecord = Record<string, unknown>\ntype PaletteDraft = Record<string, unknown>\n\n// ── The two bases' authored inputs ─────────────────────────────────────────\n//\n// Copied from `console.theme.ts` (`colorScheme.light`) and `tenant.theme.ts`\n// (`tenantColorScheme.light`), minus the `svg*` records no email reads. Only\n// what those files AUTHOR is here; every shade they leave to MUI is derived\n// below, so the copy stays as short as the thing it mirrors.\n\nconst BRAND_GREY = {\n 50: '#FAFAFA',\n 100: '#F5F5F5',\n 200: '#EEEEEE',\n 300: '#E0E0E0',\n 400: '#BDBDBD',\n 500: '#9E9E9E',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#D5D5D5',\n A200: '#AAAAAA',\n A400: '#303030',\n A700: '#616161',\n}\n\nconst PLATFORM_LIGHT_INPUT: PaletteDraft = {\n mode: 'light',\n primary: { main: '#00b0ff', dark: '#0077ad', contrastText: '#FFFFFF' },\n secondary: { main: '#e040fb', dark: '#9d2db0', contrastText: '#FFFFFF' },\n tertiary: { main: '#404C5C', contrastText: '#FFFFFF' },\n surface: { main: '#F8F9FA', contrastText: '#000000' },\n tint: { primary: '#E6F5FF', secondary: '#FBE6FE', tertiary: '#EEF0F2' },\n inputOutline: 'rgba(0, 0, 0, 0.23)',\n background: { default: '#F5F5F5', paper: '#FFFFFF' },\n info: { main: '#1878cd', contrastText: '#FFFFFF' },\n error: { main: '#e32c27', contrastText: '#FFFFFF' },\n success: { main: '#4CAF50', contrastText: '#000000DE' },\n warning: { main: '#FFAB40', contrastText: '#000000DE' },\n grey: BRAND_GREY,\n}\n\nconst TENANT_LIGHT_INPUT: PaletteDraft = {\n mode: 'light',\n primary: { main: '#1976d2', dark: '#125393', contrastText: '#FFFFFF' },\n secondary: { main: '#9c27b0', dark: '#6d1b7b', contrastText: '#FFFFFF' },\n tertiary: { main: '#4a5568', dark: '#343b49', contrastText: '#FFFFFF' },\n surface: { main: '#f1f3f5', contrastText: '#000000DE' },\n tint: { primary: '#e8f1fb', secondary: '#f5e9f7', tertiary: '#eef0f3' },\n inputOutline: 'rgba(0, 0, 0, 0.23)',\n background: { default: '#fafafa', paper: '#ffffff' },\n info: { main: '#0288d1', dark: '#015f92', contrastText: '#000000DE' },\n error: { main: '#d32f2f', dark: '#942121', contrastText: '#FFFFFF' },\n success: { main: '#2e7d32', dark: '#205823', contrastText: '#FFFFFF' },\n warning: { main: '#ed6c02', dark: '#a64c01', contrastText: '#000000DE' },\n grey: BRAND_GREY,\n}\n\n// ── MUI's light-mode constants (`createPalette`, `colors/*`) ───────────────\n\nconst MUI_COMMON = { black: '#000', white: '#fff' }\n\nconst MUI_GREY = {\n 50: '#fafafa',\n 100: '#f5f5f5',\n 200: '#eeeeee',\n 300: '#e0e0e0',\n 400: '#bdbdbd',\n 500: '#9e9e9e',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#f5f5f5',\n A200: '#eeeeee',\n A400: '#bdbdbd',\n A700: '#616161',\n}\n\n/** `getLight()` — the mode-hydrated slots, minus `action` (no email reads it). */\nfunction muiLightDefaults(): PaletteDraft {\n return {\n text: {\n primary: 'rgba(0, 0, 0, 0.87)',\n secondary: 'rgba(0, 0, 0, 0.6)',\n disabled: 'rgba(0, 0, 0, 0.38)',\n },\n divider: 'rgba(0, 0, 0, 0.12)',\n background: { paper: MUI_COMMON.white, default: MUI_COMMON.white },\n }\n}\n\n/** MUI's `light.text.primary`, the dark ink `getContrastText` falls back to. */\nconst MUI_DARK_INK = 'rgba(0, 0, 0, 0.87)'\nconst MUI_CONTRAST_THRESHOLD = 3\n/** MUI's default `tonalOffset` of 0.2, split the way `addLightOrDark` splits it. */\nconst TONAL_OFFSET_LIGHT = 0.2\nconst TONAL_OFFSET_DARK = 0.2 * 1.5\n\n/** The six colors `createPalette` augments. Both bases author every one. */\nconst MUI_AUGMENTED_KEYS = [\n 'primary',\n 'secondary',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\n/** `createResponsiveTheme`'s FOREGROUND_COLOR_KEYS: `dark` is accent text. */\nconst FOREGROUND_COLOR_KEYS: ReadonlyArray<string> = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'error',\n 'warning',\n 'info',\n 'success',\n]\n/** …and `contrastText` is text wherever it lives, so `surface` joins. */\nconst CONTRAST_TEXT_COLOR_KEYS: ReadonlyArray<string> = [\n ...FOREGROUND_COLOR_KEYS,\n 'surface',\n]\n\n// ── MUI's colorManipulator, ported ─────────────────────────────────────────\n//\n// Byte-for-byte in behavior, including the parts that look odd: `recompose`\n// truncates rgb channels with `parseInt`, and `getLuminance` rounds to three\n// places. The palette's derived shades are strings, so a port that rounded\n// \"better\" would be a port that disagrees.\n\ninterface DecomposedColor {\n type: string\n values: Array<number>\n colorSpace?: string\n}\n\nfunction hexToRgb(color: string): string {\n const hex = color.slice(1)\n const pattern = new RegExp(`.{1,${hex.length >= 6 ? 2 : 1}}`, 'g')\n let parts: Array<string> | null = hex.match(pattern)\n if (parts && parts[0].length === 1) parts = parts.map((part) => part + part)\n return parts\n ? `rgb${parts.length === 4 ? 'a' : ''}(${parts\n .map((part, index) =>\n index < 3\n ? parseInt(part, 16)\n : Math.round((parseInt(part, 16) / 255) * 1000) / 1000,\n )\n .join(', ')})`\n : ''\n}\n\nfunction decomposeColor(color: string): DecomposedColor {\n if (color.charAt(0) === '#') return decomposeColor(hexToRgb(color))\n const marker = color.indexOf('(')\n const type = color.substring(0, marker)\n if (!['rgb', 'rgba', 'hsl', 'hsla', 'color'].includes(type)) {\n throw new Error(`email-palette: unsupported color \"${color}\"`)\n }\n const body = color.substring(marker + 1, color.length - 1)\n let raw: Array<string>\n let colorSpace: string | undefined\n if (type === 'color') {\n raw = body.split(' ')\n colorSpace = raw.shift()\n if (raw.length === 4 && raw[3].charAt(0) === '/') raw[3] = raw[3].slice(1)\n if (\n !['srgb', 'display-p3', 'a98-rgb', 'prophoto-rgb', 'rec-2020'].includes(\n colorSpace ?? '',\n )\n ) {\n throw new Error(`email-palette: unsupported color space \"${colorSpace}\"`)\n }\n } else {\n raw = body.split(',')\n }\n return { type, values: raw.map((value) => parseFloat(value)), colorSpace }\n}\n\nfunction recomposeColor({ type, colorSpace, values }: DecomposedColor): string {\n let parts: Array<string | number> = values\n if (type.includes('rgb')) {\n parts = values.map((value, index) =>\n index < 3 ? parseInt(String(value), 10) : value,\n )\n } else if (type.includes('hsl')) {\n parts = [...values]\n parts[1] = `${values[1]}%`\n parts[2] = `${values[2]}%`\n }\n const body = type.includes('color')\n ? `${colorSpace} ${parts.join(' ')}`\n : parts.join(', ')\n return `${type}(${body})`\n}\n\nfunction intToHex(value: number): string {\n const hex = value.toString(16)\n return hex.length === 1 ? `0${hex}` : hex\n}\n\nfunction rgbToHex(color: string): string {\n if (color.startsWith('#')) return color\n const { values } = decomposeColor(color)\n return `#${values\n .map((value, index) => intToHex(index === 3 ? Math.round(255 * value) : value))\n .join('')}`\n}\n\nfunction hslToRgb(color: string | DecomposedColor): string {\n const decomposed = typeof color === 'string' ? decomposeColor(color) : color\n const { values } = decomposed\n const hue = values[0]\n const saturation = values[1] / 100\n const lightness = values[2] / 100\n const chroma = saturation * Math.min(lightness, 1 - lightness)\n const channel = (n: number, k = (n + hue / 30) % 12) =>\n lightness - chroma * Math.max(Math.min(k - 3, 9 - k, 1), -1)\n const rgb = [\n Math.round(channel(0) * 255),\n Math.round(channel(8) * 255),\n Math.round(channel(4) * 255),\n ]\n let type = 'rgb'\n if (decomposed.type === 'hsla') {\n type += 'a'\n rgb.push(values[3])\n }\n return recomposeColor({ type, values: rgb })\n}\n\nfunction clampUnit(value: number): number {\n return Math.min(1, Math.max(0, value))\n}\n\nfunction lighten(color: string, coefficient: number): string {\n const decomposed = decomposeColor(color)\n const amount = clampUnit(coefficient)\n const { type, values } = decomposed\n if (type.includes('hsl')) {\n values[2] += (100 - values[2]) * amount\n } else if (type.includes('rgb')) {\n for (let i = 0; i < 3; i += 1) values[i] += (255 - values[i]) * amount\n } else if (type.includes('color')) {\n for (let i = 0; i < 3; i += 1) values[i] += (1 - values[i]) * amount\n }\n return recomposeColor(decomposed)\n}\n\nfunction darken(color: string, coefficient: number): string {\n const decomposed = decomposeColor(color)\n const amount = clampUnit(coefficient)\n const { type, values } = decomposed\n if (type.includes('hsl')) {\n values[2] *= 1 - amount\n } else if (type.includes('rgb') || type.includes('color')) {\n for (let i = 0; i < 3; i += 1) values[i] *= 1 - amount\n }\n return recomposeColor(decomposed)\n}\n\nfunction srgbChannelToLinear(value: number): number {\n return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4\n}\n\n/** MUI's `getLuminance`: WCAG luminance, rounded to three places. */\nfunction muiLuminance(color: string): number {\n const decomposed = decomposeColor(color)\n const rgb =\n decomposed.type === 'hsl' || decomposed.type === 'hsla'\n ? decomposeColor(hslToRgb(decomposed)).values\n : decomposed.values\n const linear = rgb.map((value) =>\n srgbChannelToLinear(decomposed.type !== 'color' ? value / 255 : value),\n )\n return Number(\n (0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]).toFixed(3),\n )\n}\n\n/** MUI's `getContrastRatio`, on the rounded luminance. */\nfunction muiContrastRatio(foreground: string, background: string): number {\n const a = muiLuminance(foreground)\n const b = muiLuminance(background)\n return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)\n}\n\n// ── `accessible-shade.ts`, ported ──────────────────────────────────────────\n\nconst AA_TEXT_CONTRAST = 4.5\n\n/** Full-precision WCAG luminance, as `accessible-shade.ts` measures it. */\nfunction relativeLuminance(color: string): number {\n const decomposed = decomposeColor(color)\n if (decomposed.type === 'color') {\n throw new Error(`email-palette: unsupported color format \"${color}\"`)\n }\n const values = decomposed.type.startsWith('hsl')\n ? decomposeColor(hslToRgb(color)).values\n : decomposed.values\n return (\n 0.2126 * srgbChannelToLinear(values[0] / 255) +\n 0.7152 * srgbChannelToLinear(values[1] / 255) +\n 0.0722 * srgbChannelToLinear(values[2] / 255)\n )\n}\n\nfunction contrastRatio(colorA: string, colorB: string): number {\n const a = relativeLuminance(colorA)\n const b = relativeLuminance(colorB)\n return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)\n}\n\nfunction meetsContrast(\n foreground: string,\n backgrounds: ReadonlyArray<string>,\n): boolean {\n return backgrounds.every(\n (background) => contrastRatio(foreground, background) >= AA_TEXT_CONTRAST,\n )\n}\n\nfunction toHslValues(color: string): [number, number, number] {\n const decomposed = decomposeColor(color)\n if (decomposed.type.startsWith('hsl')) {\n const [h, s, l] = decomposed.values\n return [h, s / 100, l / 100]\n }\n const r = decomposed.values[0] / 255\n const g = decomposed.values[1] / 255\n const b = decomposed.values[2] / 255\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n const lightness = (max + min) / 2\n if (max === min) return [0, 0, lightness]\n const delta = max - min\n const saturation =\n lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min)\n let hue: number\n if (max === r) hue = (g - b) / delta + (g < b ? 6 : 0)\n else if (max === g) hue = (b - r) / delta + 2\n else hue = (r - g) / delta + 4\n return [hue * 60, saturation, lightness]\n}\n\nfunction hslToHex(hue: number, saturation: number, lightness: number): string {\n return rgbToHex(\n hslToRgb(`hsl(${hue}, ${saturation * 100}%, ${lightness * 100}%)`),\n )\n}\n\n/** The nearest shade of `color`, walking lightness one way, that clears AA. */\nfunction accessibleShade(\n color: string,\n backgrounds: ReadonlyArray<string>,\n direction: 'darken' | 'lighten',\n): string {\n if (!backgrounds.length || meetsContrast(color, backgrounds)) return color\n const [hue, saturation, initialLightness] = toHslValues(color)\n const delta = direction === 'lighten' ? 0.01 : -0.01\n let lightness = initialLightness\n let candidate = color\n for (let i = 0; i < 120; i += 1) {\n lightness = Math.min(1, Math.max(0, lightness + delta))\n candidate = hslToHex(hue, saturation, lightness)\n if (meetsContrast(candidate, backgrounds)) return candidate\n if (lightness === 0 || lightness === 1) return candidate\n }\n return candidate\n}\n\n// ── Palette assembly ───────────────────────────────────────────────────────\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** MUI's `deepmerge` with `clone: true`, for plain data. */\nfunction deepMerge(target: PaletteDraft, source: PaletteDraft): PaletteDraft {\n const output: PaletteDraft = { ...target }\n for (const key of Object.keys(source)) {\n const next = source[key]\n const current = target[key]\n if (\n isRecord(next) &&\n Object.prototype.hasOwnProperty.call(target, key) &&\n isRecord(current)\n ) {\n output[key] = deepMerge(current, next)\n } else {\n output[key] = isRecord(next) ? deepMerge({}, next) : next\n }\n }\n return output\n}\n\n/**\n * `createPalette`'s `augmentColor` for an object with a `main`: fill `light`\n * and `dark` from the tonal offset, and `contrastText` by MUI's threshold.\n */\nfunction augmentColor(color: ColorRecord): ColorRecord {\n const augmented = { ...color }\n const main = augmented['main']\n if (typeof main !== 'string') {\n throw new Error('email-palette: a palette color needs a string `main`')\n }\n if (!augmented['light']) augmented['light'] = lighten(main, TONAL_OFFSET_LIGHT)\n if (!augmented['dark']) augmented['dark'] = darken(main, TONAL_OFFSET_DARK)\n if (!augmented['contrastText']) {\n augmented['contrastText'] =\n muiContrastRatio(main, MUI_COMMON.white) >= MUI_CONTRAST_THRESHOLD\n ? MUI_COMMON.white\n : MUI_DARK_INK\n }\n return augmented\n}\n\n/**\n * `createResponsiveTheme`'s `addShadeVariants`, for the two colors MUI does\n * not know about. Its contrast pick is handed the DARK tonal offset (0.3) as\n * the threshold, so it lands on white for any color at all; the port keeps\n * that, because the parity it owes is to what the site renders, and any\n * pairing below AA is repaired by the accessibility pass that follows.\n */\nfunction addShadeVariants(color: unknown): void {\n if (!isRecord(color) || !color['main']) return\n const main = color['main'] as string\n if (!color['dark']) color['dark'] = darken(main, TONAL_OFFSET_DARK)\n if (!color['light']) color['light'] = lighten(main, TONAL_OFFSET_LIGHT)\n if (!color['contrastText']) {\n color['contrastText'] =\n muiContrastRatio(main, '#FFFFFF') >= TONAL_OFFSET_DARK\n ? '#FFFFFF'\n : 'rgba(0, 0, 0, 0.87)'\n }\n}\n\n/**\n * `ensureAccessibleShades` for the light scheme: a DERIVED `dark` that misses\n * 4.5:1 on either background is walked darker, and a derived `contrastText`\n * that misses 4.5:1 on its `main` is walked toward the pole with more room.\n * Whatever the input authored passes through untouched.\n */\nfunction ensureAccessibleShades(\n palette: PaletteDraft,\n input: PaletteDraft,\n): void {\n const background = isRecord(palette['background']) ? palette['background'] : {}\n const backgrounds = [background['default'], background['paper']].filter(\n (value): value is string => typeof value === 'string',\n )\n if (!backgrounds.length) return\n\n for (const key of CONTRAST_TEXT_COLOR_KEYS) {\n const color = palette[key]\n if (!isRecord(color) || typeof color['main'] !== 'string') continue\n const provided = input[key]\n if (isRecord(provided) && !('main' in provided)) continue\n const explicit = isRecord(provided) ? provided : {}\n const main = color['main']\n\n try {\n if (\n FOREGROUND_COLOR_KEYS.includes(key) &&\n !explicit['dark'] &&\n typeof color['dark'] === 'string' &&\n !meetsContrast(color['dark'], backgrounds)\n ) {\n color['dark'] = accessibleShade(color['dark'], backgrounds, 'darken')\n }\n if (\n !explicit['contrastText'] &&\n typeof color['contrastText'] === 'string' &&\n !meetsContrast(color['contrastText'], [main])\n ) {\n const direction =\n contrastRatio('#fff', main) >= contrastRatio('#000', main)\n ? 'lighten'\n : 'darken'\n color['contrastText'] = accessibleShade(\n color['contrastText'],\n [main],\n direction,\n )\n }\n } catch {\n // An unparseable color is left as derived, as the theme leaves it.\n }\n }\n}\n\n/** `createTheme` + `createResponsiveTheme`'s passes, palette only. */\nfunction derivePalette(input: PaletteDraft): PaletteDraft {\n const rest: PaletteDraft = { ...input }\n delete rest['mode']\n delete rest['contrastThreshold']\n delete rest['tonalOffset']\n\n const augmented: PaletteDraft = {}\n for (const key of MUI_AUGMENTED_KEYS) {\n const color = input[key]\n if (!isRecord(color)) {\n throw new Error(`email-palette: the base palette is missing \\`${key}\\``)\n }\n augmented[key] = augmentColor(color)\n }\n\n const palette = deepMerge(\n {\n common: { ...MUI_COMMON },\n mode: 'light',\n ...augmented,\n grey: MUI_GREY,\n ...muiLightDefaults(),\n },\n rest,\n )\n addShadeVariants(palette['tertiary'])\n addShadeVariants(palette['surface'])\n ensureAccessibleShades(palette, input)\n return palette\n}\n\n// ── A site's colors, as `hostThemeToThemeOptions` reads them ───────────────\n\nconst SCHEME_COLOR_KEYS = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'surface',\n 'error',\n 'warning',\n 'info',\n 'success',\n] as const\n\n/** Truthy string, or nothing: the \"copy what was set\" test the theme uses. */\nfunction setString(value: unknown): string | undefined {\n return typeof value === 'string' && value ? value : undefined\n}\n\n/** `pickPaletteColor`: a color needs a `main`; its shades ride along if set. */\nfunction pickPaletteColor(color: unknown): ColorRecord | undefined {\n if (!isRecord(color)) return undefined\n const main = setString(color['main'])\n if (!main) return undefined\n const picked: ColorRecord = { main }\n for (const shade of ['light', 'dark', 'contrastText'] as const) {\n const value = setString(color[shade])\n if (value) picked[shade] = value\n }\n return picked\n}\n\n/** Picks the listed string leaves of a group that were set, or nothing. */\nfunction pickLeaves(\n group: unknown,\n keys: ReadonlyArray<string>,\n): Record<string, string> | undefined {\n if (!isRecord(group)) return undefined\n const picked: Record<string, string> = {}\n for (const key of keys) {\n const value = setString(group[key])\n if (value) picked[key] = value\n }\n return Object.keys(picked).length ? picked : undefined\n}\n\n/** `schemeColorsToPaletteOptions` for the light scheme. */\nfunction siteColorOverrides(\n input: EmailPaletteInput['colors'],\n): PaletteDraft {\n const overrides: PaletteDraft = { mode: 'light' }\n if (!isRecord(input)) return overrides\n const colors: Readonly<Record<string, unknown>> = input\n for (const key of SCHEME_COLOR_KEYS) {\n const color = pickPaletteColor(colors[key])\n if (color) overrides[key] = color\n }\n const background = pickLeaves(colors['background'], ['default', 'paper'])\n if (background) overrides['background'] = background\n const text = pickLeaves(colors['text'], ['primary', 'secondary', 'disabled'])\n if (text) overrides['text'] = text\n const tint = pickLeaves(colors['tint'], ['primary', 'secondary', 'tertiary'])\n if (tint) overrides['tint'] = tint\n const divider = setString(colors['divider'])\n if (divider) overrides['divider'] = divider\n return overrides\n}\n\n// ── Literal CSS colors ─────────────────────────────────────────────────────\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\nconst NUMBER = String.raw`[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[-+]?\\d+)?(?:%|deg|grad|rad|turn)?`\n/**\n * `rgb()`, `rgba()`, `hsl()`, `hsla()` holding numbers and nothing else —\n * comma or space separated, with an optional `/ alpha`. Anything that could\n * close the declaration or open another (`;`, `\"`, `(`, `url`) cannot match.\n */\nconst FUNCTION_COLOR = new RegExp(\n String.raw`^(?:rgba?|hsla?)\\(\\s*${NUMBER}(?:\\s*,\\s*|\\s+)${NUMBER}(?:\\s*,\\s*|\\s+)${NUMBER}(?:(?:\\s*,\\s*|\\s*\\/\\s*)${NUMBER})?\\s*\\)$`,\n 'i',\n)\n/** A color MUI's own manipulators parse: hex, or a comma-separated function. */\nconst MUI_PARSEABLE_FUNCTION = new RegExp(\n String.raw`^(?:rgba?|hsla?)\\(\\s*${NUMBER}\\s*,\\s*${NUMBER}\\s*,\\s*${NUMBER}(?:\\s*,\\s*${NUMBER})?\\s*\\)$`,\n 'i',\n)\n\n/** CSS Color Module Level 4 named colors, plus `transparent`. */\nconst NAMED_COLORS: ReadonlySet<string> = new Set(\n (\n 'aliceblue antiquewhite aqua aquamarine azure beige bisque black ' +\n 'blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse ' +\n 'chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan ' +\n 'darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta ' +\n 'darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen ' +\n 'darkslateblue darkslategray darkslategrey darkturquoise darkviolet ' +\n 'deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite ' +\n 'forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green ' +\n 'greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender ' +\n 'lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan ' +\n 'lightgoldenrodyellow lightgray lightgreen lightgrey lightpink ' +\n 'lightsalmon lightseagreen lightskyblue lightslategray lightslategrey ' +\n 'lightsteelblue lightyellow lime limegreen linen magenta maroon ' +\n 'mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen ' +\n 'mediumslateblue mediumspringgreen mediumturquoise mediumvioletred ' +\n 'midnightblue mintcream mistyrose moccasin navajowhite navy oldlace ' +\n 'olive olivedrab orange orangered orchid palegoldenrod palegreen ' +\n 'paleturquoise palevioletred papayawhip peachpuff peru pink plum ' +\n 'powderblue purple rebeccapurple red rosybrown royalblue saddlebrown ' +\n 'salmon sandybrown seagreen seashell sienna silver skyblue slateblue ' +\n 'slategray slategrey snow springgreen steelblue tan teal thistle tomato ' +\n 'turquoise violet wheat white whitesmoke yellow yellowgreen transparent'\n ).split(' '),\n)\n\n/** True for a literal CSS color that is safe to write into a style attribute. */\nfunction isLiteralColor(value: string): boolean {\n return (\n HEX_COLOR.test(value) ||\n FUNCTION_COLOR.test(value) ||\n NAMED_COLORS.has(value.toLowerCase())\n )\n}\n\n/** True for a color MUI can derive shades from without throwing. */\nfunction isDerivableColor(value: string): boolean {\n return HEX_COLOR.test(value) || MUI_PARSEABLE_FUNCTION.test(value)\n}\n\n// ── Public API ─────────────────────────────────────────────────────────────\n\n/**\n * The fully derived light palette a site or sender renders with: the\n * chosen base, the site's authored colors layered one level deep (a color's\n * whole record replaced, so MUI re-derives its shades from the new `main`),\n * then a white-label `primaryColor` over that.\n *\n * Equal, for every token the Besigner's color picker offers, to the palette\n * of `createResponsiveTheme` over `mergeThemeOptions(siteBaseOptions(…))`\n * and the host theme's light `hostThemeToThemeOptions`.\n *\n * Where the site's colors cannot be derived at all — a `main` MUI cannot\n * parse, on which `createTheme` itself throws — the email falls back to the\n * base rather than failing the send: there is no rendered page to agree with.\n */\nexport function buildEmailPalette(input: EmailPaletteInput): EmailPalette {\n const base =\n input.base === 'platform' ? PLATFORM_LIGHT_INPUT : TENANT_LIGHT_INPUT\n const primaryColor =\n typeof input.primaryColor === 'string' &&\n isDerivableColor(input.primaryColor.trim())\n ? input.primaryColor.trim()\n : undefined\n const brand: PaletteDraft = primaryColor\n ? { primary: { main: primaryColor } }\n : {}\n\n const site = siteColorOverrides(input.colors)\n const layered: PaletteDraft = { ...base, ...site, ...brand }\n // `mergeThemeOptions`: a tint the site leaves unset is washed from an\n // accent it does set (`accentTint`), and the base's others stay.\n const siteTint = isRecord(site['tint']) ? site['tint'] : {}\n const tint: Record<string, unknown> = { ...(isRecord(base['tint']) ? base['tint'] : {}), ...siteTint }\n for (const key of ['primary', 'secondary', 'tertiary'] as const) {\n const main = isRecord(site[key]) ? site[key]['main'] : undefined\n if (siteTint[key] || typeof main !== 'string') continue\n try {\n tint[key] = lighten(main, 0.9)\n } catch {\n // Not a color the manipulators parse: keep the inherited tint.\n }\n }\n layered['tint'] = tint\n try {\n return derivePalette(layered)\n } catch {\n return derivePalette({ ...base, ...brand })\n }\n}\n\n/** The platform's own palette — the console brand, light scheme. */\nexport const PLATFORM_EMAIL_PALETTE: EmailPalette = buildEmailPalette({\n base: 'platform',\n})\n\n/** Palette token paths: a key, optionally one dot and a leaf (`grey.600`). */\nconst TOKEN_PATH = /^[a-zA-Z][a-zA-Z0-9]*(?:\\.[a-zA-Z0-9]+)?$/\n\nfunction lookupToken(\n palette: EmailPalette,\n path: string,\n): string | undefined {\n let node: unknown = palette\n for (const key of path.split('.')) {\n if (!isRecord(node) || !Object.prototype.hasOwnProperty.call(node, key)) {\n return undefined\n }\n node = node[key]\n }\n return typeof node === 'string' ? node : undefined\n}\n\n/**\n * A palette value as an opaque `#rrggbb`. Translucent values (`text.primary`\n * is `rgba(0, 0, 0, 0.87)`, some `contrastText`s are `#000000DE`) are\n * composited over the palette's paper, the ground an email body sits on:\n * Outlook's Word engine drops `rgba()` and eight-digit hex outright, and the\n * flattened color is what a reader sees on that ground anyway.\n */\nfunction toOpaqueHex(value: string, palette: EmailPalette): string | undefined {\n const channels = rgbaChannels(value)\n if (!channels) return undefined\n const [r, g, b, alpha] = channels\n if (alpha >= 1) return channelsToHex(r, g, b)\n const background = palette['background']\n const paper = isRecord(background) ? background['paper'] : undefined\n const ground =\n (typeof paper === 'string' ? rgbaChannels(paper) : undefined) ?? [\n 255, 255, 255, 1,\n ]\n const over = (fore: number, back: number) =>\n fore * alpha + back * (1 - alpha)\n return channelsToHex(over(r, ground[0]), over(g, ground[1]), over(b, ground[2]))\n}\n\nfunction rgbaChannels(\n value: string,\n): [number, number, number, number] | undefined {\n if (!isDerivableColor(value)) return undefined\n try {\n const decomposed = decomposeColor(value)\n const rgb = decomposed.type.startsWith('hsl')\n ? decomposeColor(hslToRgb(decomposed)).values\n : decomposed.values\n const alpha = decomposed.values.length > 3 ? decomposed.values[3] : 1\n const channels: [number, number, number, number] = [\n rgb[0],\n rgb[1],\n rgb[2],\n alpha,\n ]\n return channels.every(Number.isFinite) ? channels : undefined\n } catch {\n return undefined\n }\n}\n\nfunction channelsToHex(r: number, g: number, b: number): string {\n return `#${[r, g, b]\n .map((value) => intToHex(Math.round(Math.min(255, Math.max(0, value)))))\n .join('')}`\n}\n\n/**\n * Resolves a stored color prop for an email's markup.\n *\n * - A palette token path (`primary.main`, `grey.600`, `divider`) resolves\n * against `palette` to an opaque hex — or to nothing without a palette.\n * - A literal CSS color (hex, `rgb()`/`rgba()`/`hsl()`/`hsla()`,\n * `transparent`, a named color) passes through as written.\n * - Anything else — an unknown token, garbage, an empty value, and anything\n * that could step outside a `style` attribute — is `undefined`, so the\n * caller uses its own default.\n */\nexport function resolveEmailColor(\n value: unknown,\n palette: EmailPalette | undefined,\n): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (!trimmed) return undefined\n\n if (palette && TOKEN_PATH.test(trimmed)) {\n const resolved = lookupToken(palette, trimmed)\n if (resolved !== undefined) {\n const hex = toOpaqueHex(resolved, palette)\n if (hex) return hex\n if (isLiteralColor(resolved)) return resolved\n return undefined\n }\n }\n return isLiteralColor(trimmed) ? trimmed : undefined\n}\n\n// ── Which base a site wears ────────────────────────────────────────────────\n\n/**\n * The prefix the tenant middleware puts on a custom domain before it becomes\n * the `[host]` route segment — mirrored from `tenant.theme.ts`.\n */\nconst CNAME_PREFIX = 'cname--'\n\n/**\n * The hosts whose brand is the operator's own, mirrored from\n * `PLATFORM_BRAND_HOSTS` in `tenant.theme.ts` and read from the same\n * variable. Dot notation for the same reason it has there: Next substitutes\n * `process.env.NAME` textually and never the bracket form.\n */\nconst PLATFORM_BRAND_HOSTS: ReadonlySet<string> = new Set(\n (process.env.NEXT_PUBLIC_PLATFORM_BRAND_HOSTS ?? 'aglyn.com,aglyn.io')\n .split(',')\n .map((host) => host.trim().toLowerCase())\n .filter(Boolean),\n)\n\n/**\n * Which base a site's mail layers onto: `'platform'` for the operator's own\n * hosts, `'tenant'` for every customer site — the answer\n * `wearsPlatformBrand(hostBrandKey(host))` gives the page itself, so a site's\n * email and its published page start from the same palette.\n */\nexport function emailPaletteBaseForHost(\n host: { cname?: string | null; subdomain?: string | null } | null | undefined,\n): 'platform' | 'tenant' {\n const key = host?.cname || host?.subdomain || undefined\n if (!key) return 'tenant'\n const normalized = key.trim().toLowerCase()\n const bare = normalized.startsWith(CNAME_PREFIX)\n ? normalized.slice(CNAME_PREFIX.length)\n : normalized\n return PLATFORM_BRAND_HOSTS.has(bare) ? 'platform' : 'tenant'\n}\n"],"names":["process","BRAND_GREY","A100","A200","A400","A700","PLATFORM_LIGHT_INPUT","mode","primary","main","dark","contrastText","secondary","tertiary","surface","tint","inputOutline","background","default","paper","info","error","success","warning","grey","TENANT_LIGHT_INPUT","MUI_COMMON","black","white","MUI_GREY","muiLightDefaults","text","disabled","divider","MUI_DARK_INK","MUI_CONTRAST_THRESHOLD","TONAL_OFFSET_LIGHT","TONAL_OFFSET_DARK","MUI_AUGMENTED_KEYS","FOREGROUND_COLOR_KEYS","CONTRAST_TEXT_COLOR_KEYS","hexToRgb","color","hex","slice","pattern","RegExp","length","parts","match","map","part","index","parseInt","Math","round","join","decomposeColor","charAt","marker","indexOf","type","substring","includes","Error","body","raw","colorSpace","split","shift","values","value","parseFloat","recomposeColor","String","intToHex","toString","rgbToHex","startsWith","hslToRgb","decomposed","hue","saturation","lightness","chroma","min","channel","n","k","max","rgb","push","clampUnit","lighten","coefficient","amount","i","darken","srgbChannelToLinear","muiLuminance","linear","Number","toFixed","muiContrastRatio","foreground","a","b","AA_TEXT_CONTRAST","relativeLuminance","contrastRatio","colorA","colorB","meetsContrast","backgrounds","every","toHslValues","h","s","l","r","g","delta","hslToHex","accessibleShade","direction","initialLightness","candidate","isRecord","Array","isArray","deepMerge","target","source","output","key","Object","keys","next","current","prototype","hasOwnProperty","call","augmentColor","augmented","addShadeVariants","ensureAccessibleShades","palette","input","filter","provided","explicit","derivePalette","rest","common","SCHEME_COLOR_KEYS","setString","undefined","pickPaletteColor","picked","shade","pickLeaves","group","siteColorOverrides","overrides","colors","HEX_COLOR","NUMBER","FUNCTION_COLOR","MUI_PARSEABLE_FUNCTION","NAMED_COLORS","Set","isLiteralColor","test","has","toLowerCase","isDerivableColor","buildEmailPalette","base","primaryColor","trim","brand","site","layered","siteTint","PLATFORM_EMAIL_PALETTE","TOKEN_PATH","lookupToken","path","node","toOpaqueHex","channels","rgbaChannels","alpha","channelsToHex","ground","over","fore","back","isFinite","resolveEmailColor","trimmed","resolved","CNAME_PREFIX","PLATFORM_BRAND_HOSTS","env","NEXT_PUBLIC_PLATFORM_BRAND_HOSTS","host","Boolean","emailPaletteBaseForHost","cname","subdomain","normalized","bare"],"mappings":"AAAA;;;;;;;;;;;;;;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