Skip to content

feat: i18n for emails #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
65 changes: 61 additions & 4 deletions cli/actions/email/compile.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import config from '@/config.js'
import type { GlobalOptions, Installer } from '@/types.js'
import { action, supabaseProjectRef } from '@/utils.js'
import interpose from '@/utils/interpose.js'
import { Option } from 'commander'
import { log } from 'console'
import { getProperty } from 'dot-prop'
import { compile } from 'ejs'
import { readFile, writeFile } from 'fs/promises'
import { glob } from 'glob'
import type { Root } from 'hast'
Expand All @@ -14,6 +18,7 @@ import rehypeMinify from 'rehype-preset-minify'
import rehypeStringify from 'rehype-stringify'

const directory = resolve('supabase/emails')
const i18n = resolve('supabase/i18n')

const supabaseConfigMap: Record<string, string> = {
'confirmation': 'mailer_templates_confirmation_content',
Expand All @@ -25,19 +30,63 @@ const supabaseConfigMap: Record<string, string> = {
}

type Options = GlobalOptions & {
minify: boolean
deploy: boolean
}

type Translations = Record<string, Record<string, unknown>>

function ejsTranslate(translations: Translations) {
return (key: string) => {
const languages = Object.keys(translations)
const branches = languages.map((lang, index) => {
if (index === 0) {
return `{{ if eq .Data.${config.i18n.attribute} "${lang}" }}`
} else {
return `{{ else if eq .Data.${config.i18n.attribute} "${lang}" }}`
}
}).concat('{{ else }}', '{{ end }}')

const result = interpose(branches, ({ cursor, last }) => {
const _default = getProperty(
translations[config.i18n.default],
key,
'!!MISSING TRANSLATION KEY!!',
)

if (last) {
return _default
}

return getProperty(
translations[languages[cursor - 1]],
key,
_default,
)
})

return result.join('\n')
}
}

const installer: Installer = program => {
program.command('email:compile')
.description('Compile and optionally deploy email templates')
.option('--no-minify', 'Disable minifying of the result files.')
.addOption(
new Option('--deploy', 'Enable deployment to linked Supabase project. (Implies --linked)')
.implies({ linked: true }),
)
.action(action<Options>(async ({ opts }) => {
const projectRef = opts.deploy ? await supabaseProjectRef() : null

const languages = await glob('*.js', { cwd: i18n })
const languageMap: Translations = {}
for await (const language of languages) {
const { default: data } = await import(`${i18n}/${language}`)
languageMap[basename(language, '.js')] = data
}

const files = await glob('*.mjml', { cwd: directory })
files.sort()

Expand All @@ -50,8 +99,16 @@ const installer: Installer = program => {
log(`Processing file ${file} (${++i}/${files.length}) …`)

const abs = join(directory, file)
const template = await readFile(abs)
const converted = convert(template.toString('utf8'), {
const contents = await readFile(abs)
const template = compile(contents.toString('utf8'), {
async: true,
beautify: false,
cache: true,
})
const compiled = await template({
__: ejsTranslate(languageMap),
})
const converted = convertMjml(compiled, {
filePath: abs,
})

Expand All @@ -69,7 +126,7 @@ const installer: Installer = program => {

const result = await rehype()
.use(inlineImages)
.use(rehypeMinify)
.use(opts.minify ? rehypeMinify : null)
.use(rehypeStringify)
.process(html)

Expand Down Expand Up @@ -113,7 +170,7 @@ type ConvertResults = {
error: null
} & MJMLParseResults

function convert(input: string, options?: MJMLParsingOptions): ConvertResults {
function convertMjml(input: string, options?: MJMLParsingOptions): ConvertResults {
try {
const results = mjml2html(input, options)
return {
Expand Down
6 changes: 5 additions & 1 deletion cli/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,14 @@ async function load<T>(file?: string): Promise<T> {
}
}

const defaults: Config = {
export const defaults: Config = {
typeFiles: [
'db.ts',
],
i18n: {
attribute: 'language',
default: 'en',
},
}

const configFile = await selectFile()
Expand Down
4 changes: 4 additions & 0 deletions cli/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { z } from 'zod'

export type Config = {
typeFiles: string[]
i18n: {
attribute: string
default: string
}
}

export const globalOptionsSchema = z.object({
Expand Down
48 changes: 48 additions & 0 deletions cli/utils/interpose.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
type Args = {
/**
* The current index of the overall iteration.
*/
index: number

/**
* The current index of the interpose iteration.
*/
cursor: number

/**
* Whether this is the first interpose.
*/
first: boolean

/**
* Whether this is the last interpose.
*/
last: boolean
}

/**
* Interpose items to an array.
*
* @param arr The source array to modify.
* @param producer A function that returns the items to interpose.
* @returns The interposed array.
*/
export default function interpose<T>(arr: T[], producer: (args: Args) => T) {
let cursor = 0

const result = []
const max = arr.length * 2 - 1

for (let index = 0; index < max; index++) {
const first = index == 1
const last = index === max - 2

if (index % 2 === 0) {
result.push(arr[cursor++])
} else {
result.push(producer({index, cursor, first, last}))
}
}

return result
}
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const config = [
{
ignores: [
'*.d.ts',
'supabase/',
'supabase/functions',
'.venv',
],
},
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"@inquirer/select": "^2.4.7",
"commander": "^12.1.0",
"dayjs": "^1.11.12",
"dot-prop": "^9.0.0",
"dotenv": "^16.4.5",
"glob": "^11.0.0",
"hast-util-select": "^6.0.2",
Expand Down
12 changes: 7 additions & 5 deletions supabase/emails/confirmation.mjml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@

<mj-section background-color="#ffffff">
<mj-column>
<mj-text font-size="20px" color="#3ECF8E" font-weight="bold">Hello World</mj-text>
<mj-text>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
<mj-text font-size="20px" color="#3ECF8E" font-weight="bold">
<%- __("confirmation.title") %>
</mj-text>

<mj-text>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
<%- __("confirmation.text1") %>
</mj-text>
<mj-text>
<%- __("confirmation.text2") %>
</mj-text>
</mj-column>
</mj-section>
Expand All @@ -38,7 +40,7 @@
<mj-column>

<mj-text align="center" font-size="11px">
Copyright (c) [NAME] [YEAR]
Copyright (c) act coding GbR {{ now.UTC.Year }}
</mj-text>

</mj-column>
Expand Down
9 changes: 9 additions & 0 deletions supabase/i18n/de.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default {
confirmation: {
title: 'Konto aktivieren',
text1: `Es wurde ein neues Konto mit dieser E-Mail-Adresse erstellt.
Verwende den unten stehenden Link, um die Erstellung des Kontos zu bestätigen.`,
text2: `Wenn du kein Konto bei uns registriert haben, kannst du diese E-Mail einfach ignorieren.
Prüfe aber zur Sicherheit die Integrität deiner E-Mail-Adresse.`,
},
}
9 changes: 9 additions & 0 deletions supabase/i18n/en.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default {
confirmation: {
title: 'Active account',
text1: `A new account has been created using this email address.
Use the link below to confirm the account creation.`,
text2: `If you did not register an account with us, you can simply ignore
this email. Be sure to verify your email's account integrity.`,
},
}