@hogsend/email 0.0.1

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 ADDED
@@ -0,0 +1,93 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ Copyright 2025 Doug Silkstone and Hogsend contributors
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor's trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising out
70
+ of these terms or the use or nature of the software, under any kind of legal
71
+ claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that organization.
84
+ **control** means ownership of substantially all the assets of an entity, or the
85
+ power to direct its management and policies by vote, contract, or otherwise.
86
+ Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # @hogsend/email
2
+
3
+ Email **machinery** for Hogsend, built on [React Email](https://react.email):
4
+ template rendering, a typed template registry, and unsubscribe token/URL helpers.
5
+
6
+ > **No concrete business templates live here.** As of the boundary revision,
7
+ > your `.tsx` templates are content you own in your app's `src/emails/`. And
8
+ > **sending isn't here either** — that moved to the engine. This package is just
9
+ > the typed plumbing both of those build on.
10
+
11
+ ## Where the rest went
12
+
13
+ | You want to… | Use | Lives in |
14
+ | --- | --- | --- |
15
+ | Render a template to HTML/text | `renderToHtml` / `renderToPlainText` | `@hogsend/email` (here) |
16
+ | Resolve a template by key | `getTemplate(..., { registry })` | `@hogsend/email` (here) |
17
+ | Build / merge a template registry | `createRegistry` | `@hogsend/email` (here) |
18
+ | Generate unsubscribe links/tokens | `generateUnsubscribeUrl`, `generateUnsubscribeToken`, … | `@hogsend/email` (here) |
19
+ | **Send** a tracked email | `createTrackedMailer` / `sendEmail()` | `@hogsend/engine` |
20
+ | Talk to the email provider | `createResendProvider` (the `EmailProvider` contract) | `@hogsend/plugin-resend` |
21
+ | **Own** your email designs | `welcome.tsx`, `registry.ts`, `templates.d.ts` | **your app** `src/emails/` |
22
+
23
+ Link rewriting, the open pixel, preference/suppression checks, the `email_sends`
24
+ write, and webhook status updates all live in the engine's `createTrackedMailer`,
25
+ so they come along regardless of which `EmailProvider` you supply.
26
+
27
+ ## Public API
28
+
29
+ ```ts
30
+ import {
31
+ // rendering
32
+ renderToHtml,
33
+ renderToPlainText,
34
+ // registry
35
+ createRegistry,
36
+ getTemplate,
37
+ getTemplateDefinition,
38
+ getPreviewText,
39
+ getTemplateNames,
40
+ // unsubscribe
41
+ generateUnsubscribeUrl,
42
+ generatePreferenceCenterUrl,
43
+ generateUnsubscribeToken,
44
+ validateUnsubscribeToken,
45
+ // errors
46
+ EmailSendError,
47
+ EmailSuppressionError,
48
+ WebhookVerificationError,
49
+ InvalidTokenError,
50
+ } from "@hogsend/email";
51
+
52
+ import type {
53
+ TemplateRegistry,
54
+ TemplateRegistryMap,
55
+ TemplateDefinition,
56
+ TemplateName,
57
+ } from "@hogsend/email";
58
+ ```
59
+
60
+ ## Owning your templates (Option B — module augmentation)
61
+
62
+ Templates are your content. Put the `.tsx` files in your app's `src/emails/`,
63
+ build a registry, and augment `TemplateRegistryMap` so the engine's `sendEmail`
64
+ is fully type-checked against *your* templates.
65
+
66
+ **`src/emails/welcome.tsx`** — a normal React Email component you design freely.
67
+
68
+ **`src/emails/registry.ts`** — map each key to its component, subject, category:
69
+
70
+ ```ts
71
+ import { createRegistry } from "@hogsend/email";
72
+ import { WelcomeEmail } from "./welcome.js";
73
+
74
+ export const templates = createRegistry({
75
+ welcome: {
76
+ component: WelcomeEmail,
77
+ defaultSubject: "Welcome to Acme",
78
+ category: "transactional",
79
+ preview: (props) => `Welcome, ${props.name}!`,
80
+ },
81
+ });
82
+ ```
83
+
84
+ **`src/emails/templates.d.ts`** — the augmentation that gives you type safety:
85
+
86
+ ```ts
87
+ import type { WelcomeEmailProps } from "./welcome.js";
88
+
89
+ declare module "@hogsend/email" {
90
+ interface TemplateRegistryMap {
91
+ welcome: WelcomeEmailProps;
92
+ // add a line per template; key ↔ props are enforced everywhere
93
+ }
94
+ }
95
+ ```
96
+
97
+ Pass the registry to the client: `createHogsendClient({ journeys, email: { templates } })`.
98
+ Now `sendEmail({ template: "welcome", props: { name: "Doug" } })` is checked —
99
+ an unknown key or wrong props is a compile error.
100
+
101
+ > `create-hogsend` scaffolds a starter `src/emails/` (a couple of templates +
102
+ > `registry.ts` + `templates.d.ts`) so this is wired from the first commit.
103
+
104
+ ## Rendering directly
105
+
106
+ ```ts
107
+ import { getTemplate, renderToHtml } from "@hogsend/email";
108
+
109
+ const { element, subject, category } = getTemplate({
110
+ key: "welcome",
111
+ props: { name: "Jane" },
112
+ registry, // your TemplateRegistry
113
+ });
114
+ const html = await renderToHtml(element);
115
+ ```
116
+
117
+ ## Scripts
118
+
119
+ ```bash
120
+ pnpm build # tsup build to dist/
121
+ pnpm test # vitest run
122
+ pnpm check-types # tsc --noEmit
123
+ ```
124
+
125
+ Preview your designs from your **app** (where the `.tsx` files live) with the
126
+ React Email dev server, not from this package.
127
+
128
+ ## Peer dependencies
129
+
130
+ `react` / `react-dom` (peer). This package no longer depends on `@hogsend/db`
131
+ or a mail provider — it's pure rendering + typing machinery.
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@hogsend/email",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/dougwithseismic/hogsend.git",
9
+ "directory": "packages/email"
10
+ },
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "exports": {
14
+ ".": "./src/index.ts"
15
+ },
16
+ "files": [
17
+ "src",
18
+ "README.md"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "peerDependencies": {
24
+ "react": "^19.0.0",
25
+ "react-dom": "^19.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@react-email/ui": "^6.3.2",
29
+ "@types/node": "^22.0.0",
30
+ "@types/react": "^19.0.0",
31
+ "@types/react-dom": "^19.0.0",
32
+ "react": "^19.0.0",
33
+ "react-dom": "^19.0.0",
34
+ "react-email": "^6.3.2",
35
+ "tsup": "^8.0.0",
36
+ "typescript": "^5.7.0",
37
+ "vitest": "^4.1.7",
38
+ "@repo/typescript-config": "^0.0.0"
39
+ },
40
+ "scripts": {
41
+ "dev": "email dev --port 3003",
42
+ "build": "tsup",
43
+ "preview": "email export --outDir out --pretty",
44
+ "check-types": "tsc --noEmit",
45
+ "test": "vitest run",
46
+ "test:watch": "vitest watch"
47
+ }
48
+ }
@@ -0,0 +1,81 @@
1
+ import { createElement } from "react";
2
+ import { describe, expect, it } from "vitest";
3
+ import {
4
+ createRegistry,
5
+ getPreviewText,
6
+ getTemplate,
7
+ getTemplateDefinition,
8
+ getTemplateNames,
9
+ } from "../registry.js";
10
+ import type { TemplateRegistry } from "../types.js";
11
+
12
+ // The package ships no business templates; these tests exercise the registry
13
+ // machinery against a tiny self-contained fixture registry (the same shape a
14
+ // client app builds in `src/emails/registry.ts`).
15
+ function Hello(props: { name: string }) {
16
+ return createElement("div", null, `Hello ${props.name}`);
17
+ }
18
+
19
+ const fixture = {
20
+ hello: {
21
+ component: Hello,
22
+ defaultSubject: "Hello there",
23
+ category: "transactional",
24
+ preview: (props: { name: string }) => `Hi ${props.name}!`,
25
+ },
26
+ } as unknown as TemplateRegistry;
27
+
28
+ describe("template registry", () => {
29
+ it("returns the registered template names", () => {
30
+ const names = getTemplateNames(fixture);
31
+ expect(names).toEqual(["hello"]);
32
+ });
33
+
34
+ it("gets a template definition by key", () => {
35
+ const def = getTemplateDefinition({
36
+ key: "hello" as never,
37
+ registry: fixture,
38
+ });
39
+ expect(def.component).toBeTypeOf("function");
40
+ expect(def.defaultSubject).toBe("Hello there");
41
+ expect(def.category).toBe("transactional");
42
+ });
43
+
44
+ it("resolves a template with props", () => {
45
+ const result = getTemplate({
46
+ key: "hello" as never,
47
+ props: { name: "Doug" } as never,
48
+ registry: fixture,
49
+ });
50
+ expect(result.element).toBeDefined();
51
+ expect(result.subject).toBe("Hello there");
52
+ expect(result.category).toBe("transactional");
53
+ });
54
+
55
+ it("generates preview text", () => {
56
+ const preview = getPreviewText({
57
+ key: "hello" as never,
58
+ props: { name: "Doug" } as never,
59
+ registry: fixture,
60
+ });
61
+ expect(preview).toBe("Hi Doug!");
62
+ });
63
+
64
+ it("merges overrides over a base registry", () => {
65
+ const override = {
66
+ hello: {
67
+ component: Hello,
68
+ defaultSubject: "Hey!",
69
+ category: "transactional",
70
+ },
71
+ } as unknown as Partial<TemplateRegistry>;
72
+ const custom = createRegistry(fixture, override);
73
+
74
+ const result = getTemplate({
75
+ key: "hello" as never,
76
+ props: { name: "Doug" } as never,
77
+ registry: custom,
78
+ });
79
+ expect(result.subject).toBe("Hey!");
80
+ });
81
+ });
@@ -0,0 +1,32 @@
1
+ import { createElement } from "react";
2
+ import { Body, Html, Text } from "react-email";
3
+ import { describe, expect, it } from "vitest";
4
+ import { renderToHtml, renderToPlainText } from "../render.js";
5
+
6
+ // Render is template-agnostic machinery: it turns any react-email element into
7
+ // HTML / plain text. Use a minimal inline element rather than a baked template.
8
+ function fixtureElement(name: string) {
9
+ return createElement(
10
+ Html,
11
+ null,
12
+ createElement(Body, null, createElement(Text, null, `Welcome ${name}`)),
13
+ );
14
+ }
15
+
16
+ describe("renderToHtml", () => {
17
+ it("renders a react-email element to HTML", async () => {
18
+ const html = await renderToHtml(fixtureElement("Doug"));
19
+ expect(html).toContain("Welcome");
20
+ expect(html).toContain("Doug");
21
+ expect(html).toContain("<html");
22
+ });
23
+ });
24
+
25
+ describe("renderToPlainText", () => {
26
+ it("renders a react-email element to plain text", async () => {
27
+ const text = await renderToPlainText(fixtureElement("Doug"));
28
+ expect(text).toContain("Welcome");
29
+ expect(text).toContain("Doug");
30
+ expect(text).not.toContain("<html");
31
+ });
32
+ });
@@ -0,0 +1,54 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ EmailSendError,
4
+ EmailSuppressionError,
5
+ WebhookVerificationError,
6
+ } from "../types.js";
7
+
8
+ describe("EmailSendError", () => {
9
+ it("has retryable flag", () => {
10
+ const err = new EmailSendError("rate limited", {
11
+ retryable: true,
12
+ statusCode: 429,
13
+ });
14
+ expect(err.retryable).toBe(true);
15
+ expect(err.statusCode).toBe(429);
16
+ expect(err.name).toBe("EmailSendError");
17
+ expect(err.message).toBe("rate limited");
18
+ });
19
+
20
+ it("supports non-retryable errors", () => {
21
+ const err = new EmailSendError("bad address", {
22
+ retryable: false,
23
+ statusCode: 422,
24
+ });
25
+ expect(err.retryable).toBe(false);
26
+ });
27
+
28
+ it("preserves cause", () => {
29
+ const cause = new Error("original");
30
+ const err = new EmailSendError("wrapped", {
31
+ retryable: false,
32
+ cause,
33
+ });
34
+ expect(err.cause).toBe(cause);
35
+ });
36
+ });
37
+
38
+ describe("EmailSuppressionError", () => {
39
+ it("formats message with reason and email", () => {
40
+ const err = new EmailSuppressionError("unsubscribed", "user@example.com");
41
+ expect(err.message).toContain("unsubscribed");
42
+ expect(err.message).toContain("user@example.com");
43
+ expect(err.reason).toBe("unsubscribed");
44
+ expect(err.name).toBe("EmailSuppressionError");
45
+ });
46
+ });
47
+
48
+ describe("WebhookVerificationError", () => {
49
+ it("sets name and message", () => {
50
+ const err = new WebhookVerificationError("bad sig");
51
+ expect(err.name).toBe("WebhookVerificationError");
52
+ expect(err.message).toBe("bad sig");
53
+ });
54
+ });
@@ -0,0 +1,226 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ generateUnsubscribeToken,
4
+ InvalidTokenError,
5
+ validateUnsubscribeToken,
6
+ } from "../unsubscribe-tokens.js";
7
+ import {
8
+ generatePreferenceCenterUrl,
9
+ generateUnsubscribeUrl,
10
+ } from "../unsubscribe-url.js";
11
+
12
+ const SECRET = "test-secret-minimum-32-characters-long-ok";
13
+
14
+ describe("unsubscribe tokens", () => {
15
+ it("round-trips a global unsubscribe token", () => {
16
+ const token = generateUnsubscribeToken({
17
+ secret: SECRET,
18
+ externalId: "user-123",
19
+ email: "user@example.com",
20
+ action: "unsubscribe",
21
+ });
22
+
23
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
24
+ expect(payload.externalId).toBe("user-123");
25
+ expect(payload.email).toBe("user@example.com");
26
+ expect(payload.action).toBe("unsubscribe");
27
+ expect(payload.category).toBeUndefined();
28
+ expect(payload.exp).toBeGreaterThan(Math.floor(Date.now() / 1000));
29
+ });
30
+
31
+ it("round-trips a category unsubscribe token", () => {
32
+ const token = generateUnsubscribeToken({
33
+ secret: SECRET,
34
+ externalId: "user-456",
35
+ email: "user@example.com",
36
+ category: "journey",
37
+ action: "unsubscribe",
38
+ });
39
+
40
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
41
+ expect(payload.category).toBe("journey");
42
+ expect(payload.action).toBe("unsubscribe");
43
+ });
44
+
45
+ it("round-trips a resubscribe token", () => {
46
+ const token = generateUnsubscribeToken({
47
+ secret: SECRET,
48
+ externalId: "user-789",
49
+ email: "user@example.com",
50
+ category: "journey",
51
+ action: "resubscribe",
52
+ });
53
+
54
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
55
+ expect(payload.action).toBe("resubscribe");
56
+ expect(payload.category).toBe("journey");
57
+ });
58
+
59
+ it("round-trips a manage token", () => {
60
+ const token = generateUnsubscribeToken({
61
+ secret: SECRET,
62
+ externalId: "user-abc",
63
+ email: "user@example.com",
64
+ action: "manage",
65
+ });
66
+
67
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
68
+ expect(payload.action).toBe("manage");
69
+ });
70
+
71
+ it("rejects an expired token", () => {
72
+ const token = generateUnsubscribeToken({
73
+ secret: SECRET,
74
+ externalId: "user-123",
75
+ email: "user@example.com",
76
+ action: "unsubscribe",
77
+ expiresInSeconds: -1,
78
+ });
79
+
80
+ expect(() => validateUnsubscribeToken({ token, secret: SECRET })).toThrow(
81
+ InvalidTokenError,
82
+ );
83
+ expect(() => validateUnsubscribeToken({ token, secret: SECRET })).toThrow(
84
+ "Token has expired",
85
+ );
86
+ });
87
+
88
+ it("rejects a tampered payload", () => {
89
+ const token = generateUnsubscribeToken({
90
+ secret: SECRET,
91
+ externalId: "user-123",
92
+ email: "user@example.com",
93
+ action: "unsubscribe",
94
+ });
95
+
96
+ const [, signature] = token.split(".");
97
+ const tamperedPayload = Buffer.from(
98
+ JSON.stringify({
99
+ externalId: "hacker",
100
+ email: "hacker@evil.com",
101
+ action: "unsubscribe",
102
+ exp: Math.floor(Date.now() / 1000) + 99999,
103
+ }),
104
+ ).toString("base64url");
105
+
106
+ expect(() =>
107
+ validateUnsubscribeToken({
108
+ token: `${tamperedPayload}.${signature}`,
109
+ secret: SECRET,
110
+ }),
111
+ ).toThrow(InvalidTokenError);
112
+ });
113
+
114
+ it("rejects a tampered signature", () => {
115
+ const token = generateUnsubscribeToken({
116
+ secret: SECRET,
117
+ externalId: "user-123",
118
+ email: "user@example.com",
119
+ action: "unsubscribe",
120
+ });
121
+
122
+ const [payload] = token.split(".");
123
+ const badSig = Buffer.from("not-a-valid-signature").toString("base64url");
124
+
125
+ expect(() =>
126
+ validateUnsubscribeToken({
127
+ token: `${payload}.${badSig}`,
128
+ secret: SECRET,
129
+ }),
130
+ ).toThrow(InvalidTokenError);
131
+ });
132
+
133
+ it("rejects a wrong secret", () => {
134
+ const token = generateUnsubscribeToken({
135
+ secret: SECRET,
136
+ externalId: "user-123",
137
+ email: "user@example.com",
138
+ action: "unsubscribe",
139
+ });
140
+
141
+ expect(() =>
142
+ validateUnsubscribeToken({
143
+ token,
144
+ secret: "wrong-secret-also-32-characters-long",
145
+ }),
146
+ ).toThrow(InvalidTokenError);
147
+ });
148
+
149
+ it("rejects a malformed token without a dot", () => {
150
+ expect(() =>
151
+ validateUnsubscribeToken({ token: "nodot", secret: SECRET }),
152
+ ).toThrow(InvalidTokenError);
153
+ expect(() =>
154
+ validateUnsubscribeToken({ token: "nodot", secret: SECRET }),
155
+ ).toThrow("Malformed token");
156
+ });
157
+
158
+ it("uses 30-day default expiry", () => {
159
+ const token = generateUnsubscribeToken({
160
+ secret: SECRET,
161
+ externalId: "user-123",
162
+ email: "user@example.com",
163
+ action: "unsubscribe",
164
+ });
165
+
166
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
167
+ const expectedExp = Math.floor(Date.now() / 1000) + 30 * 24 * 3600;
168
+ expect(Math.abs(payload.exp - expectedExp)).toBeLessThan(5);
169
+ });
170
+ });
171
+
172
+ describe("unsubscribe URLs", () => {
173
+ const baseUrl = "https://api.hogsend.com";
174
+
175
+ it("generates a global unsubscribe URL", () => {
176
+ const url = generateUnsubscribeUrl({
177
+ baseUrl,
178
+ secret: SECRET,
179
+ externalId: "user-123",
180
+ email: "user@example.com",
181
+ });
182
+
183
+ expect(url).toMatch(
184
+ /^https:\/\/api\.hogsend\.com\/v1\/email\/unsubscribe\?token=.+/,
185
+ );
186
+
187
+ const parsed = new URL(url);
188
+ const token = parsed.searchParams.get("token") as string;
189
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
190
+ expect(payload.action).toBe("unsubscribe");
191
+ expect(payload.externalId).toBe("user-123");
192
+ });
193
+
194
+ it("generates a category unsubscribe URL", () => {
195
+ const url = generateUnsubscribeUrl({
196
+ baseUrl,
197
+ secret: SECRET,
198
+ externalId: "user-123",
199
+ email: "user@example.com",
200
+ category: "journey",
201
+ });
202
+
203
+ const parsed = new URL(url);
204
+ const token = parsed.searchParams.get("token") as string;
205
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
206
+ expect(payload.category).toBe("journey");
207
+ });
208
+
209
+ it("generates a preference center URL", () => {
210
+ const url = generatePreferenceCenterUrl({
211
+ baseUrl,
212
+ secret: SECRET,
213
+ externalId: "user-123",
214
+ email: "user@example.com",
215
+ });
216
+
217
+ expect(url).toMatch(
218
+ /^https:\/\/api\.hogsend\.com\/v1\/email\/preferences\?token=.+/,
219
+ );
220
+
221
+ const parsed = new URL(url);
222
+ const token = parsed.searchParams.get("token") as string;
223
+ const payload = validateUnsubscribeToken({ token, secret: SECRET });
224
+ expect(payload.action).toBe("manage");
225
+ });
226
+ });
package/src/index.ts ADDED
@@ -0,0 +1,53 @@
1
+ // @hogsend/email — email machinery only. No concrete business templates are
2
+ // baked in here; clients own their `.tsx` templates + registry and augment the
3
+ // open `TemplateRegistryMap` interface (Option B).
4
+
5
+ // Template registry
6
+ export {
7
+ createRegistry,
8
+ getPreviewText,
9
+ getTemplate,
10
+ getTemplateDefinition,
11
+ getTemplateNames,
12
+ } from "./registry.js";
13
+
14
+ // Rendering
15
+ export { renderToHtml, renderToPlainText } from "./render.js";
16
+
17
+ // Types
18
+ export type {
19
+ EmailServiceRenderOptions,
20
+ EmailServiceRenderResult,
21
+ RetryOptions,
22
+ TemplateDefinition,
23
+ TemplateName,
24
+ TemplateRegistry,
25
+ TemplateRegistryMap,
26
+ } from "./types.js";
27
+
28
+ // Runtime values & error classes
29
+ export {
30
+ DEFAULT_RETRY_OPTIONS,
31
+ EmailSendError,
32
+ EmailSuppressionError,
33
+ WebhookVerificationError,
34
+ } from "./types.js";
35
+
36
+ // Unsubscribe tokens
37
+ export type {
38
+ TokenAction,
39
+ TokenOptions,
40
+ UnsubscribeTokenPayload,
41
+ } from "./unsubscribe-tokens.js";
42
+ export {
43
+ generateUnsubscribeToken,
44
+ InvalidTokenError,
45
+ validateUnsubscribeToken,
46
+ } from "./unsubscribe-tokens.js";
47
+
48
+ // Unsubscribe URLs
49
+ export type { UnsubscribeUrlOptions } from "./unsubscribe-url.js";
50
+ export {
51
+ generatePreferenceCenterUrl,
52
+ generateUnsubscribeUrl,
53
+ } from "./unsubscribe-url.js";
@@ -0,0 +1,65 @@
1
+ import type { ReactElement } from "react";
2
+ import type {
3
+ TemplateDefinition,
4
+ TemplateName,
5
+ TemplateRegistry,
6
+ TemplateRegistryMap,
7
+ } from "./types.js";
8
+
9
+ // The registry holds no baked-in business templates. Client apps build their
10
+ // own `TemplateRegistry` (key → component + subject + category) and pass it to
11
+ // these helpers — see the engine `TrackedMailer`, which threads the
12
+ // container-provided registry through at send + render time.
13
+
14
+ export function getTemplate<K extends TemplateName>(opts: {
15
+ key: K;
16
+ props: TemplateRegistryMap[K];
17
+ registry: TemplateRegistry;
18
+ }): { element: ReactElement; subject: string; category?: string } {
19
+ const { key, props, registry } = opts;
20
+ const definition = registry[key] as TemplateDefinition<
21
+ TemplateRegistryMap[K]
22
+ >;
23
+
24
+ return {
25
+ element: definition.component(props) as ReactElement,
26
+ subject: definition.defaultSubject,
27
+ category: definition.category,
28
+ };
29
+ }
30
+
31
+ export function getTemplateDefinition<K extends TemplateName>(opts: {
32
+ key: K;
33
+ registry: TemplateRegistry;
34
+ }): TemplateDefinition<TemplateRegistryMap[K]> {
35
+ const { key, registry } = opts;
36
+ return registry[key] as TemplateDefinition<TemplateRegistryMap[K]>;
37
+ }
38
+
39
+ export function getPreviewText<K extends TemplateName>(opts: {
40
+ key: K;
41
+ props: TemplateRegistryMap[K];
42
+ registry: TemplateRegistry;
43
+ }): string | undefined {
44
+ const { key, props, registry } = opts;
45
+ const definition = registry[key] as TemplateDefinition<
46
+ TemplateRegistryMap[K]
47
+ >;
48
+ return definition.preview?.(props);
49
+ }
50
+
51
+ /**
52
+ * Merge partial registry overrides over a base registry. Useful for clients
53
+ * that want to tweak a few templates while inheriting the rest of a starter
54
+ * set.
55
+ */
56
+ export function createRegistry(
57
+ base: TemplateRegistry,
58
+ overrides: Partial<TemplateRegistry> = {},
59
+ ): TemplateRegistry {
60
+ return { ...base, ...overrides };
61
+ }
62
+
63
+ export function getTemplateNames(registry: TemplateRegistry): TemplateName[] {
64
+ return Object.keys(registry) as TemplateName[];
65
+ }
package/src/render.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { ReactElement } from "react";
2
+ import { render } from "react-email";
3
+
4
+ export async function renderToHtml(element: ReactElement): Promise<string> {
5
+ return render(element);
6
+ }
7
+
8
+ export async function renderToPlainText(
9
+ element: ReactElement,
10
+ ): Promise<string> {
11
+ return render(element, { plainText: true });
12
+ }
package/src/types.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { ReactElement } from "react";
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Template registry (open, augmentable — Option B "module augmentation")
5
+ // ---------------------------------------------------------------------------
6
+
7
+ /**
8
+ * The set of template keys known to the type system, and the props each key
9
+ * expects. This interface ships EMPTY: `@hogsend/email` bakes in no concrete
10
+ * business templates. Client apps declare their templates by augmenting it:
11
+ *
12
+ * ```ts
13
+ * declare module "@hogsend/email" {
14
+ * interface TemplateRegistryMap {
15
+ * welcome: { name: string; dashboardUrl?: string };
16
+ * }
17
+ * }
18
+ * ```
19
+ *
20
+ * After augmentation, `TemplateName` resolves to the client's keys and
21
+ * `emailService.send({ template, props })` is fully type-checked.
22
+ */
23
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally open for client augmentation
24
+ export interface TemplateRegistryMap {}
25
+
26
+ export type TemplateName = keyof TemplateRegistryMap;
27
+
28
+ export interface TemplateDefinition<P = Record<string, unknown>> {
29
+ component: (props: P) => ReactElement;
30
+ defaultSubject: string;
31
+ category?: string;
32
+ preview?: (props: P) => string;
33
+ }
34
+
35
+ export type TemplateRegistry = {
36
+ [K in TemplateName]: TemplateDefinition<TemplateRegistryMap[K]>;
37
+ };
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // Render options
41
+ // ---------------------------------------------------------------------------
42
+
43
+ export interface EmailServiceRenderOptions<
44
+ K extends TemplateName = TemplateName,
45
+ > {
46
+ template: K;
47
+ props: TemplateRegistryMap[K];
48
+ }
49
+
50
+ export interface EmailServiceRenderResult {
51
+ html: string;
52
+ text: string;
53
+ subject: string;
54
+ category?: string;
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Retry configuration
59
+ // ---------------------------------------------------------------------------
60
+
61
+ export interface RetryOptions {
62
+ maxRetries?: number;
63
+ baseDelayMs?: number;
64
+ maxDelayMs?: number;
65
+ }
66
+
67
+ export const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
68
+ maxRetries: 3,
69
+ baseDelayMs: 500,
70
+ maxDelayMs: 30_000,
71
+ };
72
+
73
+ // ---------------------------------------------------------------------------
74
+ // Errors
75
+ // ---------------------------------------------------------------------------
76
+
77
+ export class EmailSendError extends Error {
78
+ readonly retryable: boolean;
79
+ readonly statusCode?: number;
80
+
81
+ constructor(
82
+ message: string,
83
+ options: { retryable: boolean; statusCode?: number; cause?: unknown },
84
+ ) {
85
+ super(message, { cause: options.cause });
86
+ this.name = "EmailSendError";
87
+ this.retryable = options.retryable;
88
+ this.statusCode = options.statusCode;
89
+ }
90
+ }
91
+
92
+ export class EmailSuppressionError extends Error {
93
+ readonly reason: "unsubscribed" | "suppressed" | "category_unsubscribed";
94
+
95
+ constructor(reason: EmailSuppressionError["reason"], email: string) {
96
+ super(`Email to ${email} suppressed: ${reason}`);
97
+ this.name = "EmailSuppressionError";
98
+ this.reason = reason;
99
+ }
100
+ }
101
+
102
+ export class WebhookVerificationError extends Error {
103
+ constructor(message: string) {
104
+ super(message);
105
+ this.name = "WebhookVerificationError";
106
+ }
107
+ }
@@ -0,0 +1,116 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ export type TokenAction = "unsubscribe" | "resubscribe" | "manage";
4
+
5
+ export interface UnsubscribeTokenPayload {
6
+ externalId: string;
7
+ email: string;
8
+ category?: string;
9
+ action: TokenAction;
10
+ exp: number;
11
+ }
12
+
13
+ export interface TokenOptions {
14
+ secret: string;
15
+ externalId: string;
16
+ email: string;
17
+ category?: string;
18
+ action: TokenAction;
19
+ expiresInSeconds?: number;
20
+ }
21
+
22
+ export class InvalidTokenError extends Error {
23
+ constructor(message: string) {
24
+ super(message);
25
+ this.name = "InvalidTokenError";
26
+ }
27
+ }
28
+
29
+ const DEFAULT_EXPIRY_SECONDS = 30 * 24 * 3600; // 30 days
30
+
31
+ function toBase64Url(data: string): string {
32
+ return Buffer.from(data).toString("base64url");
33
+ }
34
+
35
+ function fromBase64Url(data: string): string {
36
+ return Buffer.from(data, "base64url").toString("utf-8");
37
+ }
38
+
39
+ function sign(payload: string, secret: string): string {
40
+ return createHmac("sha256", secret).update(payload).digest("base64url");
41
+ }
42
+
43
+ export function generateUnsubscribeToken(options: TokenOptions): string {
44
+ const {
45
+ secret,
46
+ externalId,
47
+ email,
48
+ category,
49
+ action,
50
+ expiresInSeconds = DEFAULT_EXPIRY_SECONDS,
51
+ } = options;
52
+
53
+ const payload: UnsubscribeTokenPayload = {
54
+ externalId,
55
+ email,
56
+ action,
57
+ exp: Math.floor(Date.now() / 1000) + expiresInSeconds,
58
+ };
59
+
60
+ if (category) {
61
+ payload.category = category;
62
+ }
63
+
64
+ const encodedPayload = toBase64Url(JSON.stringify(payload));
65
+ const signature = sign(encodedPayload, secret);
66
+
67
+ return `${encodedPayload}.${signature}`;
68
+ }
69
+
70
+ export function validateUnsubscribeToken(opts: {
71
+ token: string;
72
+ secret: string;
73
+ }): UnsubscribeTokenPayload {
74
+ const { token, secret } = opts;
75
+ const parts = token.split(".");
76
+ if (parts.length !== 2) {
77
+ throw new InvalidTokenError("Malformed token");
78
+ }
79
+
80
+ const [encodedPayload, signature] = parts as [string, string];
81
+
82
+ const expectedSignature = sign(encodedPayload, secret);
83
+
84
+ const sigBuffer = Buffer.from(signature, "base64url");
85
+ const expectedBuffer = Buffer.from(expectedSignature, "base64url");
86
+
87
+ if (
88
+ sigBuffer.length !== expectedBuffer.length ||
89
+ !timingSafeEqual(sigBuffer, expectedBuffer)
90
+ ) {
91
+ throw new InvalidTokenError("Invalid token signature");
92
+ }
93
+
94
+ let payload: UnsubscribeTokenPayload;
95
+ try {
96
+ payload = JSON.parse(fromBase64Url(encodedPayload));
97
+ } catch {
98
+ throw new InvalidTokenError("Malformed token payload");
99
+ }
100
+
101
+ if (
102
+ !payload.externalId ||
103
+ !payload.email ||
104
+ !payload.action ||
105
+ !payload.exp
106
+ ) {
107
+ throw new InvalidTokenError("Incomplete token payload");
108
+ }
109
+
110
+ const now = Math.floor(Date.now() / 1000);
111
+ if (payload.exp < now) {
112
+ throw new InvalidTokenError("Token has expired");
113
+ }
114
+
115
+ return payload;
116
+ }
@@ -0,0 +1,38 @@
1
+ import { generateUnsubscribeToken } from "./unsubscribe-tokens.js";
2
+
3
+ export interface UnsubscribeUrlOptions {
4
+ baseUrl: string;
5
+ secret: string;
6
+ externalId: string;
7
+ email: string;
8
+ category?: string;
9
+ }
10
+
11
+ export function generateUnsubscribeUrl(options: UnsubscribeUrlOptions): string {
12
+ const { baseUrl, secret, externalId, email, category } = options;
13
+
14
+ const token = generateUnsubscribeToken({
15
+ secret,
16
+ externalId,
17
+ email,
18
+ category,
19
+ action: "unsubscribe",
20
+ });
21
+
22
+ return `${baseUrl}/v1/email/unsubscribe?token=${encodeURIComponent(token)}`;
23
+ }
24
+
25
+ export function generatePreferenceCenterUrl(
26
+ options: Omit<UnsubscribeUrlOptions, "category">,
27
+ ): string {
28
+ const { baseUrl, secret, externalId, email } = options;
29
+
30
+ const token = generateUnsubscribeToken({
31
+ secret,
32
+ externalId,
33
+ email,
34
+ action: "manage",
35
+ });
36
+
37
+ return `${baseUrl}/v1/email/preferences?token=${encodeURIComponent(token)}`;
38
+ }