@email-love/cli 0.0.0-stage → 0.1.0
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/LICENSE +30 -0
- package/README.md +95 -2
- package/bin/email-love.js +84 -0
- package/dist/vendor/THIRD_PARTY_NOTICES.md +81 -0
- package/dist/vendor/chunks/chunk-362RNEL6.js +32 -0
- package/dist/vendor/chunks/chunk-G3WYTBZA.js +14 -0
- package/dist/vendor/react-dom-client.js +1 -0
- package/dist/vendor/react-dom.js +1 -0
- package/dist/vendor/react-jsx-runtime.js +14 -0
- package/dist/vendor/react.js +1 -0
- package/package.json +62 -4
- package/src/builder.js +8 -0
- package/src/components.js +81 -0
- package/src/coreSource.js +14 -0
- package/src/designSystem.js +119 -0
- package/src/editorPage.html +52 -0
- package/src/editorServer.js +153 -0
- package/src/email.js +196 -0
- package/src/errors.js +8 -0
- package/src/index.js +8 -0
- package/src/mcp.js +93 -0
- package/src/tools.js +153 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// The design system an email is built from: the Ultimate Email Design System (Core's starter) or a { tokens,
|
|
2
|
+
// components } JSON file, with a brand's colors, fonts and logo laid over its tokens.
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { resolve } from 'node:path'
|
|
5
|
+
import { coreSource } from './coreSource.js'
|
|
6
|
+
import { starterDesignSystem } from '@email-love/core/starter'
|
|
7
|
+
import { checkDesignSystem } from '@email-love/core/format'
|
|
8
|
+
import { UsageError } from './errors.js'
|
|
9
|
+
|
|
10
|
+
export const COLOR_ROLES = ['primary', 'secondary', 'accent', 'text', 'text_muted', 'background', 'surface', 'inverse', 'border', 'link', 'button_bg', 'button_text']
|
|
11
|
+
const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i
|
|
12
|
+
const SYSTEM_FONTS = new Set(['arial', 'helvetica', 'georgia', 'times new roman', 'times', 'verdana', 'tahoma', 'trebuchet ms', 'courier new', 'courier', 'system-ui', 'sans-serif', 'serif', 'monospace'])
|
|
13
|
+
|
|
14
|
+
let starterCopy
|
|
15
|
+
export function starter() {
|
|
16
|
+
starterCopy ||= starterDesignSystem()
|
|
17
|
+
return starterCopy
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const cache = new Map()
|
|
21
|
+
export async function loadDesignSystem(path) {
|
|
22
|
+
if (!path) return starter()
|
|
23
|
+
const file = resolve(path)
|
|
24
|
+
if (cache.has(file)) return cache.get(file)
|
|
25
|
+
let ds
|
|
26
|
+
try {
|
|
27
|
+
ds = JSON.parse(readFileSync(file, 'utf8'))
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw new UsageError(`Couldn't read the design system ${file}: ${error.message}`)
|
|
30
|
+
}
|
|
31
|
+
const { ok, problems } = await checkDesignSystem(ds)
|
|
32
|
+
if (!ok) throw new UsageError(`The design system ${file} has problems:\n${problems.slice(0, 10).map(p => `- ${p.component ? `${p.component}: ` : ''}${p.message}`).join('\n')}`)
|
|
33
|
+
cache.set(file, ds)
|
|
34
|
+
return ds
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Google Fonts Core knows, with the weights each has ("Inter|s|123456789"). Core keeps the list in its source; it
|
|
38
|
+
// isn't one of the package's exports, so it's read from the file, and fonts are taken as Google fonts without it.
|
|
39
|
+
let googleFonts
|
|
40
|
+
async function googleFontWeights(family) {
|
|
41
|
+
if (googleFonts === undefined) {
|
|
42
|
+
googleFonts = null
|
|
43
|
+
const entries = (await coreSource('edsGoogleFonts.mjs'))?.GOOGLE_FONT_ENTRIES
|
|
44
|
+
if (entries) googleFonts = new Map(entries.map(entry => entry.split('|')).map(([name, , weights]) => [name.toLowerCase(), [...weights].map(w => Number(w) * 100)]))
|
|
45
|
+
}
|
|
46
|
+
if (!googleFonts) return [400, 700]
|
|
47
|
+
return googleFonts.get(family.toLowerCase()) || null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function fontToken(value, base, role) {
|
|
51
|
+
if (!value) return base
|
|
52
|
+
const font = typeof value === 'string' ? { family: value } : { ...value }
|
|
53
|
+
if (!font.family || typeof font.family !== 'string') throw new UsageError(`brand.fonts.${role} needs a family`)
|
|
54
|
+
const next = { ...base, ...font, fallback: font.fallback || base?.fallback || 'Arial' }
|
|
55
|
+
if (font.webfont_url !== undefined || SYSTEM_FONTS.has(font.family.toLowerCase())) {
|
|
56
|
+
if (SYSTEM_FONTS.has(font.family.toLowerCase()) && font.webfont_url === undefined) delete next.webfont_url
|
|
57
|
+
return next
|
|
58
|
+
}
|
|
59
|
+
const weights = await googleFontWeights(font.family)
|
|
60
|
+
if (!weights) {
|
|
61
|
+
// Not a Google font Core knows: the email names it and falls back, with nothing to load it from.
|
|
62
|
+
delete next.webfont_url
|
|
63
|
+
return next
|
|
64
|
+
}
|
|
65
|
+
const wanted = [...new Set([400, 700, Number(next.weight) || 400])].filter(w => weights.includes(w))
|
|
66
|
+
const use = wanted.length ? wanted : [weights[0]]
|
|
67
|
+
if (!use.includes(Number(next.weight))) next.weight = use.includes(700) && role === 'heading' ? 700 : use[0]
|
|
68
|
+
next.webfont_url = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(font.family).replace(/%20/g, '+')}:wght@${use.sort((a, b) => a - b).join(';')}&display=swap`
|
|
69
|
+
return next
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function luminance(hex) {
|
|
73
|
+
let h = hex.slice(1)
|
|
74
|
+
if (h.length === 3) h = [...h].map(c => c + c).join('')
|
|
75
|
+
const [r, g, b] = [0, 2, 4].map(i => parseInt(h.slice(i, i + 2), 16) / 255).map(c => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4))
|
|
76
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
|
77
|
+
}
|
|
78
|
+
// The ink that reads on a color: white or near-black, whichever has more contrast.
|
|
79
|
+
export function inkOn(hex) {
|
|
80
|
+
const l = luminance(hex)
|
|
81
|
+
return (1.05 / (l + 0.05)) >= ((l + 0.05) / 0.05) ? '#ffffff' : '#111111'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function imageToken(value, base, what) {
|
|
85
|
+
if (!value) return base
|
|
86
|
+
const logo = typeof value === 'string' ? { src: value } : { ...value }
|
|
87
|
+
if (!/^https:\/\//.test(logo.src || '')) throw new UsageError(`${what}.src must be an https address (emails can't show local files)`)
|
|
88
|
+
return { ...base, alt: logo.alt ?? base?.alt ?? '', ...logo }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The design system with a brand laid over its tokens. brand: { name, colors: { primary, … }, fonts: { heading, body },
|
|
93
|
+
* logo: { src, alt, width }, logo_on_dark }. A brand with a logo and no logo_on_dark uses its logo on dark rows too.
|
|
94
|
+
*/
|
|
95
|
+
export async function brandDesignSystem(ds, brand) {
|
|
96
|
+
if (!brand || typeof brand !== 'object' || !Object.keys(brand).length) return ds
|
|
97
|
+
const tokens = structuredClone(ds.tokens || {})
|
|
98
|
+
const colors = brand.colors || {}
|
|
99
|
+
for (const [role, value] of Object.entries(colors)) {
|
|
100
|
+
if (!HEX.test(String(value))) throw new UsageError(`brand.colors.${role} must be a hex color like #1a2b3c, not ${JSON.stringify(value)}`)
|
|
101
|
+
}
|
|
102
|
+
if (Object.keys(colors).length) {
|
|
103
|
+
tokens.color = { ...tokens.color, ...colors }
|
|
104
|
+
if (colors.primary && !colors.button_bg) tokens.color.button_bg = colors.primary
|
|
105
|
+
if (tokens.color.button_bg && !colors.button_text && (colors.primary || colors.button_bg)) tokens.color.button_text = inkOn(tokens.color.button_bg)
|
|
106
|
+
tokens.color_on = { ...tokens.color_on }
|
|
107
|
+
for (const role of Object.keys(colors)) if (role in (tokens.color_on || {}) || ['primary', 'secondary', 'accent', 'inverse'].includes(role)) tokens.color_on[role] = inkOn(colors[role])
|
|
108
|
+
}
|
|
109
|
+
if (brand.fonts) {
|
|
110
|
+
tokens.font = { ...tokens.font }
|
|
111
|
+
for (const role of ['heading', 'body']) tokens.font[role] = await fontToken(brand.fonts[role], tokens.font[role], role)
|
|
112
|
+
}
|
|
113
|
+
if (brand.logo) {
|
|
114
|
+
tokens.logo = imageToken(brand.logo, tokens.logo, 'brand.logo')
|
|
115
|
+
if (!brand.logo_on_dark) tokens.logo_on_dark = { ...tokens.logo_on_dark, ...tokens.logo }
|
|
116
|
+
}
|
|
117
|
+
if (brand.logo_on_dark) tokens.logo_on_dark = imageToken(brand.logo_on_dark, tokens.logo_on_dark, 'brand.logo_on_dark')
|
|
118
|
+
return { ...ds, name: brand.name || ds.name, tokens }
|
|
119
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>{{name}} · Email Love Editor</title>
|
|
7
|
+
<link rel="stylesheet" href="{{base}}/editor/style.css">
|
|
8
|
+
<script type="importmap">
|
|
9
|
+
{ "imports": {
|
|
10
|
+
"react": "{{base}}/vendor/react.js",
|
|
11
|
+
"react/jsx-runtime": "{{base}}/vendor/react-jsx-runtime.js",
|
|
12
|
+
"react-dom": "{{base}}/vendor/react-dom.js",
|
|
13
|
+
"react-dom/client": "{{base}}/vendor/react-dom-client.js"
|
|
14
|
+
} }
|
|
15
|
+
</script>
|
|
16
|
+
<style>
|
|
17
|
+
html, body { margin: 0; height: 100%; font-family: Inter, system-ui, -apple-system, sans-serif; }
|
|
18
|
+
body { display: flex; flex-direction: column; }
|
|
19
|
+
body > header { display: flex; align-items: center; gap: 12px; padding: 10px 16px; border-bottom: 1px solid #e4e4e7; font-size: 14px; }
|
|
20
|
+
body > header #status { margin-right: auto; color: #52525b; }
|
|
21
|
+
body > header a { color: #0a79cc; }
|
|
22
|
+
#editor { flex: 1; min-height: 0; }
|
|
23
|
+
</style>
|
|
24
|
+
</head>
|
|
25
|
+
<body>
|
|
26
|
+
<header><strong>{{name}}</strong><span id="status">Loading…</span><a href="{{builder}}" target="_blank" rel="noopener">Email Love Builder</a></header>
|
|
27
|
+
<div id="editor"></div>
|
|
28
|
+
<script type="module">
|
|
29
|
+
import { mountEmailLoveEditor } from '{{base}}/editor/index.js'
|
|
30
|
+
|
|
31
|
+
const status = document.getElementById('status')
|
|
32
|
+
const words = { loading: 'Loading…', saved: 'Saved to the file', unsaved: 'Unsaved changes', saving: 'Saving…', 'save-failed': "Couldn't save", 'load-failed': "Couldn't open the email" }
|
|
33
|
+
const designSystem = await fetch('{{base}}/api/design-system').then(r => r.json())
|
|
34
|
+
const editor = mountEmailLoveEditor(document.getElementById('editor'), {
|
|
35
|
+
name: document.title.split(' · ')[0],
|
|
36
|
+
designSystem,
|
|
37
|
+
email: {
|
|
38
|
+
open: async () => fetch('{{base}}/api/email').then(r => r.json()),
|
|
39
|
+
save: async email => {
|
|
40
|
+
const response = await fetch('{{base}}/api/email', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(email) })
|
|
41
|
+
if (!response.ok) throw new Error((await response.json()).error || 'Not saved')
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
// Emails need pictures at https addresses: paste an address into a picture's field instead.
|
|
45
|
+
images: { upload: async () => { throw Object.assign(new Error('Pictures need an https address here: paste one into the picture field.'), { retry: false }) } },
|
|
46
|
+
})
|
|
47
|
+
const session = await editor.ready
|
|
48
|
+
status.textContent = words.saved
|
|
49
|
+
session.subscribe(({ status: now }) => { status.textContent = words[now] || now })
|
|
50
|
+
</script>
|
|
51
|
+
</body>
|
|
52
|
+
</html>
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Opens a saved email in the open-source Email Love editor (@email-love/editor), served from this computer only.
|
|
2
|
+
// The page loads the editor's own files and React from this package; nothing is fetched from anywhere else except the
|
|
3
|
+
// fonts and pictures the email itself names. Saving in the editor writes the .email.json back and renders the .html and
|
|
4
|
+
// .txt beside it again.
|
|
5
|
+
import { createServer } from 'node:http'
|
|
6
|
+
import { createReadStream, existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { dirname, extname, join, normalize, resolve, sep } from 'node:path'
|
|
8
|
+
import { createRequire } from 'node:module'
|
|
9
|
+
import { randomBytes } from 'node:crypto'
|
|
10
|
+
import { spawn } from 'node:child_process'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
import { buildEmail, readSpec, updateSaved } from './email.js'
|
|
13
|
+
import { BUILDER_URL } from './builder.js'
|
|
14
|
+
import { UsageError } from './errors.js'
|
|
15
|
+
|
|
16
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
17
|
+
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.md': 'text/plain; charset=utf-8' }
|
|
18
|
+
const MAX_BODY = 5 * 1024 * 1024
|
|
19
|
+
|
|
20
|
+
export function editorDist() {
|
|
21
|
+
const pkg = createRequire(import.meta.url).resolve('@email-love/editor/package.json')
|
|
22
|
+
const dist = join(dirname(pkg), 'dist')
|
|
23
|
+
if (!existsSync(join(dist, 'index.js'))) throw new UsageError(`The editor isn't built (${dist}). Run npm run build at the repository's root.`)
|
|
24
|
+
return dist
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function vendorDist() {
|
|
28
|
+
const dist = resolve(here, '../dist/vendor')
|
|
29
|
+
if (!existsSync(join(dist, 'react.js'))) throw new UsageError(`React for the editor page isn't built (${dist}). Run npm run build -w @email-love/cli.`)
|
|
30
|
+
return dist
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function page(token, name) {
|
|
34
|
+
const escape = text => String(text).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c])
|
|
35
|
+
return readFileSync(join(here, 'editorPage.html'), 'utf8')
|
|
36
|
+
.replaceAll('{{base}}', `/${token}`)
|
|
37
|
+
.replaceAll('{{name}}', escape(name))
|
|
38
|
+
.replaceAll('{{builder}}', BUILDER_URL)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function sendFile(response, root, rest) {
|
|
42
|
+
const file = normalize(join(root, rest))
|
|
43
|
+
if (!file.startsWith(root + sep) || !existsSync(file) || !statSync(file).isFile()) {
|
|
44
|
+
response.writeHead(404).end('Not found')
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
response.writeHead(200, { 'content-type': TYPES[extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' })
|
|
48
|
+
createReadStream(file).pipe(response)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function readBody(request) {
|
|
52
|
+
return new Promise((done, fail) => {
|
|
53
|
+
const chunks = []
|
|
54
|
+
let size = 0
|
|
55
|
+
request.on('data', chunk => {
|
|
56
|
+
size += chunk.length
|
|
57
|
+
if (size > MAX_BODY) { fail(new UsageError('Too large')); request.destroy() } else chunks.push(chunk)
|
|
58
|
+
})
|
|
59
|
+
request.on('end', () => done(Buffer.concat(chunks).toString('utf8')))
|
|
60
|
+
request.on('error', fail)
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const json = (response, status, value) => response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify(value))
|
|
65
|
+
|
|
66
|
+
/** Writes the .html and .txt beside a saved .email.json. */
|
|
67
|
+
export async function renderSaved(file) {
|
|
68
|
+
const built = await buildEmail({ file })
|
|
69
|
+
const base = file.replace(/\.email\.json$|\.json$/, '')
|
|
70
|
+
writeFileSync(`${base}.html`, built.html)
|
|
71
|
+
writeFileSync(`${base}.txt`, `${built.text.trim()}\n`)
|
|
72
|
+
return { built, html: `${base}.html`, text: `${base}.txt` }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const open = new Map()
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Serves the editor for one .email.json on 127.0.0.1 and gives its address. The address carries a random token, and
|
|
79
|
+
* requests for any other host name are refused, so other pages in the browser can't read or write the email.
|
|
80
|
+
*/
|
|
81
|
+
export async function openInEditor({ file, port = 0, openBrowser = true } = {}) {
|
|
82
|
+
if (!file) throw new UsageError('Say which .email.json to open (save the email first).')
|
|
83
|
+
file = resolve(file)
|
|
84
|
+
if (!existsSync(file)) throw new UsageError(`There's no ${file}. Save the email first.`)
|
|
85
|
+
if (open.has(file)) {
|
|
86
|
+
const running = open.get(file)
|
|
87
|
+
if (openBrowser) launchBrowser(running.url)
|
|
88
|
+
return running
|
|
89
|
+
}
|
|
90
|
+
const spec = readSpec({ file })
|
|
91
|
+
const first = await buildEmail({ file })
|
|
92
|
+
const editor = editorDist()
|
|
93
|
+
const vendor = vendorDist()
|
|
94
|
+
const token = randomBytes(16).toString('hex')
|
|
95
|
+
const name = spec.subject || 'Email'
|
|
96
|
+
|
|
97
|
+
const server = createServer(async (request, response) => {
|
|
98
|
+
try {
|
|
99
|
+
const host = String(request.headers.host || '').replace(/:\d+$/, '')
|
|
100
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(host)) { response.writeHead(403).end('Forbidden'); return }
|
|
101
|
+
const path = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname)
|
|
102
|
+
if (!path.startsWith(`/${token}/`)) { response.writeHead(404).end('Not found'); return }
|
|
103
|
+
const rest = path.slice(token.length + 2)
|
|
104
|
+
if (request.method === 'GET' && rest === '') {
|
|
105
|
+
response.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }).end(page(token, name))
|
|
106
|
+
} else if (request.method === 'GET' && rest.startsWith('editor/')) {
|
|
107
|
+
sendFile(response, editor, rest.slice('editor/'.length))
|
|
108
|
+
} else if (request.method === 'GET' && rest.startsWith('vendor/')) {
|
|
109
|
+
sendFile(response, vendor, rest.slice('vendor/'.length))
|
|
110
|
+
} else if (request.method === 'GET' && rest === 'api/email') {
|
|
111
|
+
const { document } = await buildEmail({ file })
|
|
112
|
+
json(response, 200, document)
|
|
113
|
+
} else if (request.method === 'GET' && rest === 'api/design-system') {
|
|
114
|
+
const { designSystem } = await buildEmail({ file })
|
|
115
|
+
json(response, 200, { tokens: designSystem.tokens, components: designSystem.components })
|
|
116
|
+
} else if (request.method === 'POST' && rest === 'api/email') {
|
|
117
|
+
if (!String(request.headers['content-type'] || '').startsWith('application/json')) { response.writeHead(415).end(); return }
|
|
118
|
+
const document = JSON.parse(await readBody(request))
|
|
119
|
+
updateSaved(file, document, readSpec({ file }))
|
|
120
|
+
const { built } = await renderSaved(file)
|
|
121
|
+
json(response, 200, { ok: built.ok, problems: built.problems.filter(p => p.level !== 'info').length })
|
|
122
|
+
} else {
|
|
123
|
+
response.writeHead(404).end('Not found')
|
|
124
|
+
}
|
|
125
|
+
} catch (error) {
|
|
126
|
+
json(response, error instanceof UsageError || error instanceof SyntaxError ? 400 : 500, { error: error.message })
|
|
127
|
+
}
|
|
128
|
+
})
|
|
129
|
+
await new Promise((done, fail) => server.once('error', fail).listen(port, '127.0.0.1', done))
|
|
130
|
+
const url = `http://127.0.0.1:${server.address().port}/${token}/`
|
|
131
|
+
const running = {
|
|
132
|
+
url, file, built: first, server,
|
|
133
|
+
close: () => new Promise(done => { open.delete(file); server.closeAllConnections?.(); server.close(() => done()) }),
|
|
134
|
+
}
|
|
135
|
+
open.set(file, running)
|
|
136
|
+
if (openBrowser) launchBrowser(url)
|
|
137
|
+
return running
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function launchBrowser(url) {
|
|
141
|
+
const [command, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
142
|
+
: process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]]
|
|
143
|
+
: ['xdg-open', [url]]
|
|
144
|
+
try {
|
|
145
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true })
|
|
146
|
+
child.on('error', () => {})
|
|
147
|
+
child.unref()
|
|
148
|
+
} catch {}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function closeAll() {
|
|
152
|
+
await Promise.all([...open.values()].map(running => running.close()))
|
|
153
|
+
}
|
package/src/email.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// An email from blocks: the spec an agent or person writes, the Core document it becomes, its HTML and plain text,
|
|
2
|
+
// and Core's checks on it.
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
5
|
+
import { renderEmail, cleanDocument } from '@email-love/core'
|
|
6
|
+
import { renderPreview } from '@email-love/core/preview'
|
|
7
|
+
import { plainTextOf } from '@email-love/core/plain-text'
|
|
8
|
+
import { STARTER_ASSET_BASE } from '@email-love/core/starter'
|
|
9
|
+
import { coreSource } from './coreSource.js'
|
|
10
|
+
import { brandDesignSystem, loadDesignSystem } from './designSystem.js'
|
|
11
|
+
import { suggest } from './components.js'
|
|
12
|
+
import { UsageError } from './errors.js'
|
|
13
|
+
|
|
14
|
+
export const SPEC_FORMAT = 'email-love-email/1'
|
|
15
|
+
const SAMPLE_TEXT = /lorem ipsum|dolor sit amet|\bH[1-6] Headline\b|ADD YOUR CTA|^Headline$|^Button$/i
|
|
16
|
+
const STARTER_LOGO = /\/eds2-assets\/ueds\/images\/email-love-logo/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The spec: { subject, preheader, blocks: [{ component, fields }], brand?, design_system?, lang?, dir? }, or
|
|
20
|
+
* { file } naming a saved .email.json, or { document } holding a Core document. design_system is a path to a
|
|
21
|
+
* { tokens, components } JSON file; without it the email uses the Ultimate Email Design System.
|
|
22
|
+
*/
|
|
23
|
+
export function readSpec(input = {}) {
|
|
24
|
+
if (input.file) {
|
|
25
|
+
const file = resolve(input.file)
|
|
26
|
+
let saved
|
|
27
|
+
try {
|
|
28
|
+
saved = JSON.parse(readFileSync(file, 'utf8'))
|
|
29
|
+
} catch (error) {
|
|
30
|
+
throw new UsageError(`Couldn't read ${file}: ${error.message}`)
|
|
31
|
+
}
|
|
32
|
+
const spec = saved.document ? { ...saved, ...saved.document } : saved
|
|
33
|
+
if (spec.design_system && !isAbsolute(spec.design_system)) spec.design_system = resolve(dirname(file), spec.design_system)
|
|
34
|
+
return { ...spec, file }
|
|
35
|
+
}
|
|
36
|
+
if (input.document) return { ...input, ...input.document }
|
|
37
|
+
return { ...input }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function designSystemFor(spec) {
|
|
41
|
+
return brandDesignSystem(await loadDesignSystem(spec.design_system), spec.brand)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const placeholders = await coreSource('edsPlaceholderImages.mjs')
|
|
45
|
+
const PLACEHOLDER_FALLBACK = `${STARTER_ASSET_BASE}/eds2-assets/ueds/images/placeholders/checker-600x400.png`
|
|
46
|
+
|
|
47
|
+
// An image field takes { src, alt }, an address, or { placeholder: 'what goes here' } for a picture to add later.
|
|
48
|
+
function fieldValue(field, value) {
|
|
49
|
+
if (field?.type === 'list' && Array.isArray(value)) {
|
|
50
|
+
return value.map(item => (item && typeof item === 'object'
|
|
51
|
+
? Object.fromEntries(Object.entries(item).map(([key, v]) => [key, fieldValue((field.item_fields || []).find(f => f.key === key), v)]))
|
|
52
|
+
: item))
|
|
53
|
+
}
|
|
54
|
+
if (field?.type !== 'image') return value
|
|
55
|
+
if (typeof value === 'string') return { src: value, alt: '' }
|
|
56
|
+
if (value && typeof value === 'object' && value.placeholder) {
|
|
57
|
+
const label = typeof value.placeholder === 'string' ? value.placeholder : ''
|
|
58
|
+
const src = placeholders?.placeholderImageUrl?.(STARTER_ASSET_BASE, { width: value.width, height: value.height, label }) || PLACEHOLDER_FALLBACK
|
|
59
|
+
return { src, alt: value.alt || label || 'Image placeholder' }
|
|
60
|
+
}
|
|
61
|
+
return value
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The Core document, and notes on what the blocks left out or got wrong. */
|
|
65
|
+
export function buildDocument(ds, spec) {
|
|
66
|
+
if (!spec || typeof spec.subject !== 'string' || !spec.subject.trim()) throw new UsageError('The email needs a subject.')
|
|
67
|
+
if (!Array.isArray(spec.blocks) || !spec.blocks.length) throw new UsageError('The email needs blocks: [{ component, fields }]. List the components to choose them.')
|
|
68
|
+
const notes = []
|
|
69
|
+
const usedIds = new Set()
|
|
70
|
+
const blocks = spec.blocks.map((block, index) => {
|
|
71
|
+
const key = typeof block === 'string' ? block : block?.component
|
|
72
|
+
const component = ds.components.find(c => c.key === key)
|
|
73
|
+
if (!component) throw new UsageError(`Block ${index + 1}: no component ${JSON.stringify(key)} in ${ds.name || 'the design system'}. ${suggest(ds, key)}`)
|
|
74
|
+
const given = (typeof block === 'object' && block.fields) || {}
|
|
75
|
+
const fields = {}
|
|
76
|
+
for (const [name, value] of Object.entries(given)) {
|
|
77
|
+
const field = component.fields.find(f => f.key === name)
|
|
78
|
+
if (!field) notes.push({ level: 'warning', block: index, message: `${component.key} has no field ${name}; it was left out. Its fields: ${component.fields.map(f => f.key).join(', ')}.` })
|
|
79
|
+
else fields[name] = fieldValue(field, value)
|
|
80
|
+
}
|
|
81
|
+
let id = (typeof block === 'object' && block.id) || `b${index + 1}`
|
|
82
|
+
while (usedIds.has(id)) id = `${id}_${index + 1}`
|
|
83
|
+
usedIds.add(id)
|
|
84
|
+
for (const field of component.fields) {
|
|
85
|
+
const value = fields[field.key]
|
|
86
|
+
if (value === undefined && ['text', 'rich_text'].includes(field.type) && field.default && !String(field.default).startsWith('$tokens') && (SAMPLE_TEXT.test(String(field.default)) || String(field.default).trim().split(/\s+/).length > 3)) {
|
|
87
|
+
notes.push({ level: 'info', block: index, field: field.key, message: `${field.key} wasn't set, so it shows the component's sample text: "${String(field.default).replace(/<[^>]+>/g, '').slice(0, 60)}"` })
|
|
88
|
+
}
|
|
89
|
+
if (value === undefined && field.type === 'image' && typeof field.default?.src === 'string' && !field.default.src.startsWith('$tokens') && !['header', 'footer'].includes(component.category)) {
|
|
90
|
+
notes.push({ level: 'info', block: index, field: field.key, message: `${field.key} wasn't set, so it shows the component's sample picture.` })
|
|
91
|
+
}
|
|
92
|
+
if (typeof value === 'string' && SAMPLE_TEXT.test(value)) notes.push({ level: 'warning', block: index, field: field.key, message: `${field.key} still reads like placeholder text.` })
|
|
93
|
+
}
|
|
94
|
+
return { id, component: component.key, version: (typeof block === 'object' && block.version) || component.version || 1, fields }
|
|
95
|
+
})
|
|
96
|
+
const draft = { subject: spec.subject, preheader: spec.preheader || '', blocks }
|
|
97
|
+
if (spec.lang) draft.lang = spec.lang
|
|
98
|
+
if (spec.dir) draft.dir = spec.dir
|
|
99
|
+
let document
|
|
100
|
+
try {
|
|
101
|
+
document = cleanDocument(draft)
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw new UsageError(`The email isn't valid: ${error.message}`)
|
|
104
|
+
}
|
|
105
|
+
return { document, notes }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function where(document, problem) {
|
|
109
|
+
const index = problem.block == null ? -1 : typeof problem.block === 'number' ? problem.block : document.blocks.findIndex(b => b.id === problem.block)
|
|
110
|
+
const block = document.blocks[index]
|
|
111
|
+
const place = block ? `Block ${index + 1} (${block.component})` : null
|
|
112
|
+
return [place, problem.field && !String(problem.message).includes(problem.field) ? problem.field : null].filter(Boolean).join(', ')
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Renders the email and runs Core's checks on it. */
|
|
116
|
+
export async function buildEmail(input) {
|
|
117
|
+
const spec = readSpec(input)
|
|
118
|
+
const ds = await designSystemFor(spec)
|
|
119
|
+
const { document, notes } = buildDocument(ds, spec)
|
|
120
|
+
const result = await renderEmail(ds, document)
|
|
121
|
+
const html = result.html || ''
|
|
122
|
+
const preview = await renderPreview({ ds, document, checkContext: {} })
|
|
123
|
+
const failed = [
|
|
124
|
+
...(preview.checks || []).filter(c => c.level !== 'info'),
|
|
125
|
+
...((preview.teamChecks?.results) || []).filter(c => c.passed === false),
|
|
126
|
+
]
|
|
127
|
+
const problems = [
|
|
128
|
+
...result.errors.map(p => ({ level: 'error', ...p })),
|
|
129
|
+
...result.warnings.map(p => ({ level: 'warning', ...p })),
|
|
130
|
+
...failed.map(c => ({ level: c.level === 'error' ? 'error' : 'warning', block: c.block, field: c.field, message: c.message || c.title })),
|
|
131
|
+
...notes,
|
|
132
|
+
]
|
|
133
|
+
const seen = new Set()
|
|
134
|
+
problems.splice(0, problems.length, ...problems.filter(p => {
|
|
135
|
+
const key = `${p.level}|${p.block}|${p.field}|${p.message}`
|
|
136
|
+
return !seen.has(key) && seen.add(key)
|
|
137
|
+
}))
|
|
138
|
+
if (!spec.brand?.logo && STARTER_LOGO.test(html) && !spec.design_system) problems.push({ level: 'warning', message: "The email shows the starter's Email Love logo. Pass brand.logo { src, alt } with the sender's logo." })
|
|
139
|
+
return {
|
|
140
|
+
ok: result.ok && !problems.some(p => p.level === 'error'),
|
|
141
|
+
spec, designSystem: ds, document, html, text: html ? plainTextOf(html) : '',
|
|
142
|
+
bytes: Buffer.byteLength(html), problems,
|
|
143
|
+
sizeNote: (preview.checks || []).find(c => c.check === 'size')?.message || null,
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function summarize(built, { title = 'Built' } = {}) {
|
|
148
|
+
const { document, problems, bytes } = built
|
|
149
|
+
const lines = [`${title} "${document.subject}": ${document.blocks.length} block${document.blocks.length === 1 ? "" : "s"}, ${(bytes / 1024).toFixed(0)} KB of HTML${bytes > 102 * 1024 ? ' (over Gmail\'s 102 KB clipping limit)' : ''}.`]
|
|
150
|
+
lines.push(built.ok ? 'It renders with no errors.' : 'It has errors to fix before it can be sent.')
|
|
151
|
+
for (const level of ['error', 'warning', 'info']) {
|
|
152
|
+
const found = problems.filter(p => p.level === level)
|
|
153
|
+
if (!found.length) continue
|
|
154
|
+
lines.push('', { error: 'Errors:', warning: 'Warnings:', info: 'Notes:' }[level])
|
|
155
|
+
for (const problem of found) {
|
|
156
|
+
const place = where(document, problem)
|
|
157
|
+
lines.push(`- ${place ? `${place}: ` : ''}${problem.message}`)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return lines.join('\n')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function slug(text) {
|
|
164
|
+
return String(text || 'email').toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '').trim().replace(/[\s_-]+/g, '-').slice(0, 60).replace(/-+$/, '') || 'email'
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** What a saved email keeps: the spec with its blocks' ids and versions, so it opens and builds again the same. */
|
|
168
|
+
export function savedSpec(built, { relativeTo } = {}) {
|
|
169
|
+
const { spec, document } = built
|
|
170
|
+
const out = { format: SPEC_FORMAT, subject: document.subject, preheader: document.preheader }
|
|
171
|
+
if (document.lang) out.lang = document.lang
|
|
172
|
+
if (document.dir) out.dir = document.dir
|
|
173
|
+
if (spec.brand) out.brand = spec.brand
|
|
174
|
+
if (spec.design_system) out.design_system = relativeTo ? relative(relativeTo, resolve(spec.design_system)) : spec.design_system
|
|
175
|
+
out.blocks = document.blocks.map(({ id, component, version, fields }) => ({ id, component, version, fields }))
|
|
176
|
+
return out
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Writes <name>.html, <name>.txt and <name>.email.json into dir. */
|
|
180
|
+
export function saveEmail(built, { dir = '.', name } = {}) {
|
|
181
|
+
const folder = resolve(dir)
|
|
182
|
+
const base = slug(name || (/\.email\.json$/.test(built.spec.file || '') ? basename(built.spec.file).replace(/\.email\.json$/, '') : built.document.subject))
|
|
183
|
+
mkdirSync(folder, { recursive: true })
|
|
184
|
+
const files = { html: join(folder, `${base}.html`), text: join(folder, `${base}.txt`), spec: join(folder, `${base}.email.json`) }
|
|
185
|
+
writeFileSync(files.html, built.html)
|
|
186
|
+
writeFileSync(files.text, `${built.text.trim()}\n`)
|
|
187
|
+
writeFileSync(files.spec, `${JSON.stringify(savedSpec(built, { relativeTo: folder }), null, 2)}\n`)
|
|
188
|
+
return files
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Writes a document the editor saved back into its .email.json, keeping the brand and design system. */
|
|
192
|
+
export function updateSaved(file, document, spec) {
|
|
193
|
+
const out = { format: SPEC_FORMAT, ...savedSpec({ spec, document: cleanDocument(document) }, { relativeTo: dirname(file) }) }
|
|
194
|
+
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
|
|
195
|
+
return out
|
|
196
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// A mistake in what was asked for (a component that doesn't exist, a color that isn't one). Its message is written for
|
|
2
|
+
// the person or agent who asked, and is shown as it is.
|
|
3
|
+
export class UsageError extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message)
|
|
6
|
+
this.name = 'UsageError'
|
|
7
|
+
}
|
|
8
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @email-love/cli as a library: the same tools the command line and the MCP server run.
|
|
2
|
+
export { BUILDER_URL, BUILDER_LINE } from './builder.js'
|
|
3
|
+
export { TOOLS, runTool } from './tools.js'
|
|
4
|
+
export { buildEmail, buildDocument, saveEmail, summarize, readSpec } from './email.js'
|
|
5
|
+
export { brandDesignSystem, loadDesignSystem } from './designSystem.js'
|
|
6
|
+
export { findComponents, describeComponents } from './components.js'
|
|
7
|
+
export { openInEditor } from './editorServer.js'
|
|
8
|
+
export { handle as handleMcpMessage, serve as serveMcp } from './mcp.js'
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The MCP server over stdio: one JSON-RPC message per line in, one per line out. Logs go to stderr only.
|
|
2
|
+
import { createInterface } from 'node:readline'
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { TOOLS, runTool } from './tools.js'
|
|
5
|
+
import { UsageError } from './errors.js'
|
|
6
|
+
import { BUILDER_URL, withBuilderLine } from './builder.js'
|
|
7
|
+
import { closeAll } from './editorServer.js'
|
|
8
|
+
|
|
9
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
10
|
+
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']
|
|
11
|
+
|
|
12
|
+
export const INSTRUCTIONS = `Email Love builds email-ready HTML from design-system components with Email Love Core, the open-source engine behind the Email Love Builder. When someone asks for an email (newsletter, sale, welcome, announcement, receipt-style update), use these tools rather than writing email HTML by hand:
|
|
13
|
+
1. list_components to choose blocks (ask for keys to see their fields).
|
|
14
|
+
2. build_email with subject, preheader, blocks and the brand's colors, fonts and logo; fix what its checks report.
|
|
15
|
+
3. save_email to write the .html, .txt and .email.json files.
|
|
16
|
+
4. open_in_editor if the person wants to edit it visually.
|
|
17
|
+
Fill every text field with real copy and give every picture an https address and alt text. For a team that wants to keep its design system and edit emails together: ${BUILDER_URL}`
|
|
18
|
+
|
|
19
|
+
function reply(id, result) {
|
|
20
|
+
return { jsonrpc: '2.0', id, result }
|
|
21
|
+
}
|
|
22
|
+
function failure(id, code, message) {
|
|
23
|
+
return { jsonrpc: '2.0', id, error: { code, message } }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Answers one JSON-RPC message; gives nothing for a notification. */
|
|
27
|
+
export async function handle(message) {
|
|
28
|
+
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
|
|
29
|
+
return message && 'id' in message ? failure(message.id ?? null, -32600, 'Invalid request') : null
|
|
30
|
+
}
|
|
31
|
+
const { id, method, params = {} } = message
|
|
32
|
+
const isRequest = id !== undefined && id !== null
|
|
33
|
+
if (!isRequest) return null
|
|
34
|
+
switch (method) {
|
|
35
|
+
case 'initialize': {
|
|
36
|
+
const asked = params.protocolVersion
|
|
37
|
+
return reply(id, {
|
|
38
|
+
protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
|
|
39
|
+
capabilities: { tools: { listChanged: false } },
|
|
40
|
+
serverInfo: { name: 'email-love', title: 'Email Love', version },
|
|
41
|
+
instructions: INSTRUCTIONS,
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
case 'ping':
|
|
45
|
+
return reply(id, {})
|
|
46
|
+
case 'tools/list':
|
|
47
|
+
return reply(id, { tools: TOOLS.map(({ name, title, description, inputSchema, annotations }) => ({ name, title, description, inputSchema, annotations })) })
|
|
48
|
+
case 'tools/call': {
|
|
49
|
+
if (!TOOLS.some(tool => tool.name === params.name)) return failure(id, -32602, `Unknown tool: ${params.name}`)
|
|
50
|
+
try {
|
|
51
|
+
const { text } = await runTool(params.name, params.arguments || {})
|
|
52
|
+
return reply(id, { content: [{ type: 'text', text }] })
|
|
53
|
+
} catch (error) {
|
|
54
|
+
const text = error instanceof UsageError ? error.message : `Something went wrong: ${error.message}`
|
|
55
|
+
if (!(error instanceof UsageError)) process.stderr.write(`${error.stack}\n`)
|
|
56
|
+
return reply(id, { content: [{ type: 'text', text: withBuilderLine(text) }], isError: true })
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
case 'resources/list':
|
|
60
|
+
return reply(id, { resources: [] })
|
|
61
|
+
case 'prompts/list':
|
|
62
|
+
return reply(id, { prompts: [] })
|
|
63
|
+
default:
|
|
64
|
+
return failure(id, -32601, `Method not found: ${method}`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function serve({ input = process.stdin, output = process.stdout } = {}) {
|
|
69
|
+
const lines = createInterface({ input, crlfDelay: Infinity })
|
|
70
|
+
const write = value => { if (value) output.write(`${JSON.stringify(value)}\n`) }
|
|
71
|
+
const pending = new Set()
|
|
72
|
+
lines.on('line', line => {
|
|
73
|
+
if (!line.trim()) return
|
|
74
|
+
let message
|
|
75
|
+
try {
|
|
76
|
+
message = JSON.parse(line)
|
|
77
|
+
} catch {
|
|
78
|
+
write(failure(null, -32700, 'Parse error'))
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
const work = (Array.isArray(message)
|
|
82
|
+
? Promise.all(message.map(handle)).then(answers => { const sent = answers.filter(Boolean); if (sent.length) write(sent) })
|
|
83
|
+
: handle(message).then(write))
|
|
84
|
+
.catch(error => process.stderr.write(`${error.stack}\n`))
|
|
85
|
+
pending.add(work)
|
|
86
|
+
work.finally(() => pending.delete(work))
|
|
87
|
+
})
|
|
88
|
+
return new Promise(done => lines.on('close', async () => {
|
|
89
|
+
await Promise.all(pending)
|
|
90
|
+
await closeAll()
|
|
91
|
+
done()
|
|
92
|
+
}))
|
|
93
|
+
}
|