@emulators/resend 0.4.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. Please also get an informed
186
+ understanding of your current status in the "Work made for hire"
187
+ or other employer IP clauses in your jurisdiction and contracts
188
+ before applying.
189
+
190
+ Copyright 2025 Chris Tate
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
Binary file
@@ -0,0 +1,80 @@
1
+ import { Entity, Collection, Store, ServicePlugin } from '@emulators/core';
2
+
3
+ interface ResendEmail extends Entity {
4
+ uuid: string;
5
+ from: string;
6
+ to: string[];
7
+ subject: string;
8
+ html: string | null;
9
+ text: string | null;
10
+ cc: string[];
11
+ bcc: string[];
12
+ reply_to: string[];
13
+ headers: Record<string, string>;
14
+ tags: Array<{
15
+ name: string;
16
+ value: string;
17
+ }>;
18
+ status: "sent" | "delivered" | "bounced" | "canceled" | "scheduled";
19
+ scheduled_at: string | null;
20
+ last_event: string;
21
+ }
22
+ interface ResendDomain extends Entity {
23
+ uuid: string;
24
+ name: string;
25
+ status: "pending" | "verified";
26
+ region: string;
27
+ records: Array<{
28
+ record: string;
29
+ name: string;
30
+ type: string;
31
+ ttl: string;
32
+ status: "pending" | "verified";
33
+ value: string;
34
+ priority?: number;
35
+ }>;
36
+ }
37
+ interface ResendApiKey extends Entity {
38
+ uuid: string;
39
+ name: string;
40
+ token: string;
41
+ }
42
+ interface ResendAudience extends Entity {
43
+ uuid: string;
44
+ name: string;
45
+ }
46
+ interface ResendContact extends Entity {
47
+ uuid: string;
48
+ audience_id: string;
49
+ email: string;
50
+ first_name: string | null;
51
+ last_name: string | null;
52
+ unsubscribed: boolean;
53
+ }
54
+
55
+ interface ResendStore {
56
+ emails: Collection<ResendEmail>;
57
+ domains: Collection<ResendDomain>;
58
+ apiKeys: Collection<ResendApiKey>;
59
+ audiences: Collection<ResendAudience>;
60
+ contacts: Collection<ResendContact>;
61
+ }
62
+ declare function getResendStore(store: Store): ResendStore;
63
+
64
+ interface ResendSeedConfig {
65
+ port?: number;
66
+ domains?: Array<{
67
+ name: string;
68
+ region?: string;
69
+ }>;
70
+ contacts?: Array<{
71
+ email: string;
72
+ first_name?: string;
73
+ last_name?: string;
74
+ audience?: string;
75
+ }>;
76
+ }
77
+ declare function seedFromConfig(store: Store, _baseUrl: string, config: ResendSeedConfig): void;
78
+ declare const resendPlugin: ServicePlugin;
79
+
80
+ export { type ResendApiKey, type ResendAudience, type ResendContact, type ResendDomain, type ResendEmail, type ResendSeedConfig, type ResendStore, resendPlugin as default, getResendStore, resendPlugin, seedFromConfig };
package/dist/index.js ADDED
@@ -0,0 +1,790 @@
1
+ // src/store.ts
2
+ function getResendStore(store) {
3
+ return {
4
+ emails: store.collection("resend.emails", ["uuid"]),
5
+ domains: store.collection("resend.domains", ["uuid", "name"]),
6
+ apiKeys: store.collection("resend.api_keys", ["uuid"]),
7
+ audiences: store.collection("resend.audiences", ["uuid"]),
8
+ contacts: store.collection("resend.contacts", ["uuid", "audience_id"])
9
+ };
10
+ }
11
+
12
+ // src/helpers.ts
13
+ import { randomUUID } from "crypto";
14
+ function generateUuid() {
15
+ return randomUUID();
16
+ }
17
+ function resendError(c, statusCode, name, message) {
18
+ return c.json({ statusCode, name, message }, statusCode);
19
+ }
20
+ function resendList(data) {
21
+ return { object: "list", data };
22
+ }
23
+ async function parseResendBody(c) {
24
+ const contentType = c.req.header("content-type") ?? "";
25
+ if (contentType.includes("application/x-www-form-urlencoded")) {
26
+ const text = await c.req.text();
27
+ const params = new URLSearchParams(text);
28
+ const result = {};
29
+ for (const [key, value] of params.entries()) {
30
+ result[key] = value;
31
+ }
32
+ return result;
33
+ }
34
+ try {
35
+ const body = await c.req.json();
36
+ if (body && typeof body === "object" && !Array.isArray(body)) {
37
+ return body;
38
+ }
39
+ return {};
40
+ } catch {
41
+ return {};
42
+ }
43
+ }
44
+
45
+ // src/routes/emails.ts
46
+ function emailRoutes(ctx) {
47
+ const { app, store, webhooks } = ctx;
48
+ const rs = () => getResendStore(store);
49
+ app.post("/emails/batch", async (c) => {
50
+ let emails;
51
+ try {
52
+ const raw = await c.req.json();
53
+ if (!Array.isArray(raw)) {
54
+ return resendError(c, 422, "validation_error", "Request body must be an array");
55
+ }
56
+ emails = raw;
57
+ } catch {
58
+ return resendError(c, 422, "validation_error", "Request body must be an array");
59
+ }
60
+ if (emails.length > 100) {
61
+ return resendError(c, 422, "validation_error", "Batch size cannot exceed 100 emails");
62
+ }
63
+ for (const emailData of emails) {
64
+ if (!emailData.from) return resendError(c, 422, "validation_error", "Missing required field: from");
65
+ if (!emailData.to) return resendError(c, 422, "validation_error", "Missing required field: to");
66
+ if (!emailData.subject) return resendError(c, 422, "validation_error", "Missing required field: subject");
67
+ }
68
+ const results = [];
69
+ for (const emailData of emails) {
70
+ const from = emailData.from;
71
+ const to = emailData.to;
72
+ const subject = emailData.subject;
73
+ const toArray = Array.isArray(to) ? to : [to];
74
+ const uuid = generateUuid();
75
+ const scheduledAt = emailData.scheduled_at;
76
+ const status = scheduledAt ? "scheduled" : "delivered";
77
+ rs().emails.insert({
78
+ uuid,
79
+ from,
80
+ to: toArray,
81
+ subject,
82
+ html: emailData.html ?? null,
83
+ text: emailData.text ?? null,
84
+ cc: normalizeStringArray(emailData.cc),
85
+ bcc: normalizeStringArray(emailData.bcc),
86
+ reply_to: normalizeStringArray(emailData.reply_to),
87
+ headers: emailData.headers ?? {},
88
+ tags: emailData.tags ?? [],
89
+ status,
90
+ scheduled_at: scheduledAt ?? null,
91
+ last_event: status === "scheduled" ? "email.scheduled" : "email.delivered"
92
+ });
93
+ if (!scheduledAt) {
94
+ await webhooks.dispatch("email.sent", void 0, { type: "email.sent", data: { email_id: uuid, to: toArray, from, subject } }, "resend");
95
+ await webhooks.dispatch("email.delivered", void 0, { type: "email.delivered", data: { email_id: uuid, to: toArray, from, subject } }, "resend");
96
+ }
97
+ results.push({ id: uuid });
98
+ }
99
+ return c.json({ data: results }, 200);
100
+ });
101
+ app.post("/emails", async (c) => {
102
+ const body = await parseResendBody(c);
103
+ const from = body.from;
104
+ const to = body.to;
105
+ const subject = body.subject;
106
+ if (!from) return resendError(c, 422, "validation_error", "Missing required field: from");
107
+ if (!to) return resendError(c, 422, "validation_error", "Missing required field: to");
108
+ if (!subject) return resendError(c, 422, "validation_error", "Missing required field: subject");
109
+ const toArray = Array.isArray(to) ? to : [to];
110
+ const uuid = generateUuid();
111
+ const scheduledAt = body.scheduled_at;
112
+ const status = scheduledAt ? "scheduled" : "delivered";
113
+ rs().emails.insert({
114
+ uuid,
115
+ from,
116
+ to: toArray,
117
+ subject,
118
+ html: body.html ?? null,
119
+ text: body.text ?? null,
120
+ cc: normalizeStringArray(body.cc),
121
+ bcc: normalizeStringArray(body.bcc),
122
+ reply_to: normalizeStringArray(body.reply_to),
123
+ headers: body.headers ?? {},
124
+ tags: body.tags ?? [],
125
+ status,
126
+ scheduled_at: scheduledAt ?? null,
127
+ last_event: status === "scheduled" ? "email.scheduled" : "email.delivered"
128
+ });
129
+ if (!scheduledAt) {
130
+ await webhooks.dispatch("email.sent", void 0, { type: "email.sent", data: { email_id: uuid, to: toArray, from, subject } }, "resend");
131
+ await webhooks.dispatch("email.delivered", void 0, { type: "email.delivered", data: { email_id: uuid, to: toArray, from, subject } }, "resend");
132
+ }
133
+ return c.json({ id: uuid }, 200);
134
+ });
135
+ app.get("/emails", (c) => {
136
+ const allEmails = rs().emails.all();
137
+ return c.json(resendList(allEmails.map(formatEmail)));
138
+ });
139
+ app.get("/emails/:id", (c) => {
140
+ const id = c.req.param("id");
141
+ const email = rs().emails.findOneBy("uuid", id);
142
+ if (!email) return resendError(c, 404, "not_found", "Email not found");
143
+ return c.json(formatEmail(email));
144
+ });
145
+ app.post("/emails/:id/cancel", (c) => {
146
+ const id = c.req.param("id");
147
+ const email = rs().emails.findOneBy("uuid", id);
148
+ if (!email) return resendError(c, 404, "not_found", "Email not found");
149
+ if (email.status !== "scheduled") {
150
+ return resendError(c, 422, "validation_error", "Only scheduled emails can be canceled");
151
+ }
152
+ rs().emails.update(email.id, {
153
+ status: "canceled",
154
+ last_event: "email.canceled"
155
+ });
156
+ return c.json({ id: email.uuid, object: "email", canceled: true });
157
+ });
158
+ }
159
+ function normalizeStringArray(value) {
160
+ if (!value) return [];
161
+ if (Array.isArray(value)) return value.map(String);
162
+ if (typeof value === "string") return [value];
163
+ return [];
164
+ }
165
+ function formatEmail(email) {
166
+ return {
167
+ id: email.uuid,
168
+ object: "email",
169
+ from: email.from,
170
+ to: email.to,
171
+ subject: email.subject,
172
+ html: email.html,
173
+ text: email.text,
174
+ cc: email.cc,
175
+ bcc: email.bcc,
176
+ reply_to: email.reply_to,
177
+ headers: email.headers,
178
+ tags: email.tags,
179
+ status: email.status,
180
+ scheduled_at: email.scheduled_at,
181
+ last_event: email.last_event,
182
+ created_at: email.created_at
183
+ };
184
+ }
185
+
186
+ // src/routes/domains.ts
187
+ function domainRoutes(ctx) {
188
+ const { app, store, webhooks } = ctx;
189
+ const rs = () => getResendStore(store);
190
+ app.post("/domains", async (c) => {
191
+ const body = await parseResendBody(c);
192
+ const name = body.name;
193
+ if (!name) return resendError(c, 422, "validation_error", "Missing required field: name");
194
+ const region = body.region ?? "us-east-1";
195
+ const uuid = generateUuid();
196
+ const records = [
197
+ {
198
+ record: "SPF",
199
+ name,
200
+ type: "MX",
201
+ ttl: "Auto",
202
+ status: "pending",
203
+ value: `feedback-smtp.${region}.amazonses.com`,
204
+ priority: 10
205
+ },
206
+ {
207
+ record: "SPF",
208
+ name,
209
+ type: "TXT",
210
+ ttl: "Auto",
211
+ status: "pending",
212
+ value: "v=spf1 include:amazonses.com ~all"
213
+ },
214
+ {
215
+ record: "DKIM",
216
+ name: `resend._domainkey.${name}`,
217
+ type: "CNAME",
218
+ ttl: "Auto",
219
+ status: "pending",
220
+ value: `resend.domainkey.${region}.amazonses.com`
221
+ }
222
+ ];
223
+ const domain = rs().domains.insert({
224
+ uuid,
225
+ name,
226
+ status: "pending",
227
+ region,
228
+ records
229
+ });
230
+ await webhooks.dispatch("domain.created", void 0, { type: "domain.created", data: { id: uuid, name } }, "resend");
231
+ return c.json(formatDomain(domain), 200);
232
+ });
233
+ app.get("/domains", (c) => {
234
+ const allDomains = rs().domains.all();
235
+ return c.json(resendList(allDomains.map(formatDomain)));
236
+ });
237
+ app.get("/domains/:id", (c) => {
238
+ const id = c.req.param("id");
239
+ const domain = rs().domains.findOneBy("uuid", id);
240
+ if (!domain) return resendError(c, 404, "not_found", "Domain not found");
241
+ return c.json(formatDomain(domain));
242
+ });
243
+ app.delete("/domains/:id", async (c) => {
244
+ const id = c.req.param("id");
245
+ const domain = rs().domains.findOneBy("uuid", id);
246
+ if (!domain) return resendError(c, 404, "not_found", "Domain not found");
247
+ rs().domains.delete(domain.id);
248
+ await webhooks.dispatch("domain.deleted", void 0, { type: "domain.deleted", data: { id: domain.uuid, name: domain.name } }, "resend");
249
+ return c.json({ object: "domain", id: domain.uuid, deleted: true });
250
+ });
251
+ app.post("/domains/:id/verify", (c) => {
252
+ const id = c.req.param("id");
253
+ const domain = rs().domains.findOneBy("uuid", id);
254
+ if (!domain) return resendError(c, 404, "not_found", "Domain not found");
255
+ const verifiedRecords = domain.records.map((r) => ({ ...r, status: "verified" }));
256
+ rs().domains.update(domain.id, {
257
+ status: "verified",
258
+ records: verifiedRecords
259
+ });
260
+ return c.json({ object: "domain", id: domain.uuid, status: "verified" });
261
+ });
262
+ }
263
+ function formatDomain(domain) {
264
+ return {
265
+ id: domain.uuid,
266
+ object: "domain",
267
+ name: domain.name,
268
+ status: domain.status,
269
+ region: domain.region,
270
+ records: domain.records,
271
+ created_at: domain.created_at
272
+ };
273
+ }
274
+
275
+ // src/routes/api-keys.ts
276
+ import { randomBytes } from "crypto";
277
+ function apiKeyRoutes(ctx) {
278
+ const { app, store } = ctx;
279
+ const rs = () => getResendStore(store);
280
+ app.post("/api-keys", async (c) => {
281
+ const body = await parseResendBody(c);
282
+ const name = body.name;
283
+ if (!name) return resendError(c, 422, "validation_error", "Missing required field: name");
284
+ const uuid = generateUuid();
285
+ const token = `re_${randomBytes(16).toString("hex")}`;
286
+ const apiKey = rs().apiKeys.insert({
287
+ uuid,
288
+ name,
289
+ token
290
+ });
291
+ return c.json({
292
+ id: apiKey.uuid,
293
+ token: apiKey.token
294
+ }, 200);
295
+ });
296
+ app.get("/api-keys", (c) => {
297
+ const allKeys = rs().apiKeys.all();
298
+ return c.json(resendList(allKeys.map((key) => ({
299
+ id: key.uuid,
300
+ name: key.name,
301
+ created_at: key.created_at
302
+ }))));
303
+ });
304
+ app.delete("/api-keys/:id", (c) => {
305
+ const id = c.req.param("id");
306
+ const apiKey = rs().apiKeys.findOneBy("uuid", id);
307
+ if (!apiKey) return resendError(c, 404, "not_found", "API key not found");
308
+ rs().apiKeys.delete(apiKey.id);
309
+ return c.json({ deleted: true });
310
+ });
311
+ }
312
+
313
+ // src/routes/contacts.ts
314
+ function contactRoutes(ctx) {
315
+ const { app, store, webhooks } = ctx;
316
+ const rs = () => getResendStore(store);
317
+ app.post("/audiences", async (c) => {
318
+ const body = await parseResendBody(c);
319
+ const name = body.name;
320
+ if (!name) return resendError(c, 422, "validation_error", "Missing required field: name");
321
+ const uuid = generateUuid();
322
+ const audience = rs().audiences.insert({ uuid, name });
323
+ return c.json({
324
+ id: audience.uuid,
325
+ object: "audience",
326
+ name: audience.name,
327
+ created_at: audience.created_at
328
+ }, 200);
329
+ });
330
+ app.get("/audiences", (c) => {
331
+ const allAudiences = rs().audiences.all();
332
+ return c.json(resendList(allAudiences.map((a) => ({
333
+ id: a.uuid,
334
+ object: "audience",
335
+ name: a.name,
336
+ created_at: a.created_at
337
+ }))));
338
+ });
339
+ app.delete("/audiences/:id", (c) => {
340
+ const id = c.req.param("id");
341
+ const audience = rs().audiences.findOneBy("uuid", id);
342
+ if (!audience) return resendError(c, 404, "not_found", "Audience not found");
343
+ rs().audiences.delete(audience.id);
344
+ return c.json({ object: "audience", id: audience.uuid, deleted: true });
345
+ });
346
+ app.post("/audiences/:audience_id/contacts", async (c) => {
347
+ const audienceId = c.req.param("audience_id");
348
+ const audience = rs().audiences.findOneBy("uuid", audienceId);
349
+ if (!audience) return resendError(c, 404, "not_found", "Audience not found");
350
+ const body = await parseResendBody(c);
351
+ const email = body.email;
352
+ if (!email) return resendError(c, 422, "validation_error", "Missing required field: email");
353
+ const uuid = generateUuid();
354
+ const contact = rs().contacts.insert({
355
+ uuid,
356
+ audience_id: audienceId,
357
+ email,
358
+ first_name: body.first_name ?? null,
359
+ last_name: body.last_name ?? null,
360
+ unsubscribed: body.unsubscribed ?? false
361
+ });
362
+ await webhooks.dispatch("contact.created", void 0, { type: "contact.created", data: { id: uuid, email, audience_id: audienceId } }, "resend");
363
+ return c.json({
364
+ id: contact.uuid,
365
+ object: "contact",
366
+ email: contact.email
367
+ }, 200);
368
+ });
369
+ app.get("/audiences/:audience_id/contacts", (c) => {
370
+ const audienceId = c.req.param("audience_id");
371
+ const audience = rs().audiences.findOneBy("uuid", audienceId);
372
+ if (!audience) return resendError(c, 404, "not_found", "Audience not found");
373
+ const contacts = rs().contacts.findBy("audience_id", audienceId);
374
+ return c.json(resendList(contacts.map((ct) => ({
375
+ id: ct.uuid,
376
+ object: "contact",
377
+ email: ct.email,
378
+ first_name: ct.first_name,
379
+ last_name: ct.last_name,
380
+ unsubscribed: ct.unsubscribed,
381
+ created_at: ct.created_at
382
+ }))));
383
+ });
384
+ app.delete("/audiences/:audience_id/contacts/:id", async (c) => {
385
+ const audienceId = c.req.param("audience_id");
386
+ const contactId = c.req.param("id");
387
+ const contact = rs().contacts.findOneBy("uuid", contactId);
388
+ if (!contact || contact.audience_id !== audienceId) {
389
+ return resendError(c, 404, "not_found", "Contact not found");
390
+ }
391
+ rs().contacts.delete(contact.id);
392
+ await webhooks.dispatch("contact.deleted", void 0, { type: "contact.deleted", data: { id: contact.uuid, email: contact.email, audience_id: audienceId } }, "resend");
393
+ return c.json({ object: "contact", id: contact.uuid, deleted: true });
394
+ });
395
+ }
396
+
397
+ // ../core/dist/index.js
398
+ import { Hono } from "hono";
399
+ import { cors } from "hono/cors";
400
+ import { readFileSync } from "fs";
401
+ import { fileURLToPath } from "url";
402
+ import { dirname, join } from "path";
403
+ function createErrorHandler(documentationUrl) {
404
+ return async (c, next) => {
405
+ if (documentationUrl) {
406
+ c.set("docsUrl", documentationUrl);
407
+ }
408
+ await next();
409
+ };
410
+ }
411
+ var errorHandler = createErrorHandler();
412
+ var isDebug = typeof process !== "undefined" && (process.env.DEBUG === "1" || process.env.DEBUG === "true" || process.env.EMULATE_DEBUG === "1");
413
+ var __dirname = dirname(fileURLToPath(import.meta.url));
414
+ var FONTS = {
415
+ "geist-sans.woff2": readFileSync(join(__dirname, "fonts", "geist-sans.woff2")),
416
+ "GeistPixel-Square.woff2": readFileSync(join(__dirname, "fonts", "GeistPixel-Square.woff2"))
417
+ };
418
+ function escapeHtml(s) {
419
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
420
+ }
421
+ function escapeAttr(s) {
422
+ return escapeHtml(s).replace(/'/g, "&#39;");
423
+ }
424
+ var CSS = `
425
+ @font-face{
426
+ font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;
427
+ src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');
428
+ }
429
+ @font-face{
430
+ font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;
431
+ src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');
432
+ }
433
+ *{box-sizing:border-box;margin:0;padding:0}
434
+ body{
435
+ font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;
436
+ background:#000;color:#33ff00;min-height:100vh;
437
+ -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
438
+ }
439
+ .emu-bar{
440
+ border-bottom:1px solid #0a3300;padding:10px 20px;
441
+ display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;
442
+ }
443
+ .emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}
444
+ .emu-bar-links{margin-left:auto;display:flex;gap:16px;}
445
+ .emu-bar-links a{
446
+ color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;
447
+ }
448
+ .emu-bar-links a:hover{color:#33ff00;}
449
+ .emu-bar-links a .full{display:inline;}
450
+ .emu-bar-links a .short{display:none;}
451
+ @media(max-width:600px){
452
+ .emu-bar-links a .full{display:none;}
453
+ .emu-bar-links a .short{display:inline;}
454
+ }
455
+
456
+ .content{
457
+ display:flex;align-items:center;justify-content:center;
458
+ min-height:calc(100vh - 42px);padding:24px 16px;
459
+ }
460
+ .content-inner{width:100%;max-width:420px;}
461
+ .card-title{
462
+ font-family:'Geist Pixel',monospace;
463
+ font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;
464
+ }
465
+ .card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}
466
+ .powered-by{
467
+ position:fixed;bottom:0;left:0;right:0;
468
+ text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;
469
+ font-family:'Geist Pixel',monospace;
470
+ }
471
+ .powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}
472
+ .powered-by a:hover{color:#33ff00;}
473
+
474
+ .error-title{
475
+ font-family:'Geist Pixel',monospace;
476
+ color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;
477
+ }
478
+ .error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}
479
+ .error-card{text-align:center;}
480
+
481
+ .user-form{margin-bottom:8px;}
482
+ .user-form:last-of-type{margin-bottom:0;}
483
+ .user-btn{
484
+ width:100%;display:flex;align-items:center;gap:12px;
485
+ padding:10px 12px;border:1px solid #0a3300;border-radius:8px;
486
+ background:#000;color:inherit;cursor:pointer;text-align:left;
487
+ font:inherit;transition:border-color .15s;
488
+ }
489
+ .user-btn:hover{border-color:#33ff00;}
490
+ .avatar{
491
+ width:36px;height:36px;border-radius:50%;
492
+ background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;
493
+ display:flex;align-items:center;justify-content:center;flex-shrink:0;
494
+ font-family:'Geist Pixel',monospace;
495
+ }
496
+ .user-text{min-width:0;}
497
+ .user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}
498
+ .user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}
499
+ .user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}
500
+
501
+ .settings-layout{
502
+ max-width:920px;margin:0 auto;padding:28px 20px;
503
+ display:flex;gap:28px;
504
+ }
505
+ .settings-sidebar{width:200px;flex-shrink:0;}
506
+ .settings-sidebar a{
507
+ display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;
508
+ text-decoration:none;font-size:.8125rem;transition:color .15s;
509
+ }
510
+ .settings-sidebar a:hover{color:#33ff00;}
511
+ .settings-sidebar a.active{color:#33ff00;font-weight:600;}
512
+ .settings-main{flex:1;min-width:0;}
513
+
514
+ .s-card{
515
+ padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;
516
+ }
517
+ .s-card:last-child{border-bottom:none;}
518
+ .s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}
519
+ .s-icon{
520
+ width:42px;height:42px;border-radius:8px;
521
+ background:#0a3300;display:flex;align-items:center;justify-content:center;
522
+ font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;
523
+ font-family:'Geist Pixel',monospace;
524
+ }
525
+ .s-title{
526
+ font-family:'Geist Pixel',monospace;
527
+ font-size:1.25rem;font-weight:600;color:#33ff00;
528
+ }
529
+ .s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}
530
+ .section-heading{
531
+ font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;
532
+ display:flex;align-items:center;justify-content:space-between;
533
+ }
534
+ .perm-list{list-style:none;}
535
+ .perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}
536
+ .check{color:#33ff00;}
537
+ .org-row{
538
+ display:flex;align-items:center;gap:8px;padding:7px 0;
539
+ border-bottom:1px solid #0a3300;font-size:.8125rem;
540
+ }
541
+ .org-row:last-child{border-bottom:none;}
542
+ .org-icon{
543
+ width:22px;height:22px;border-radius:4px;background:#0a3300;
544
+ display:flex;align-items:center;justify-content:center;
545
+ font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;
546
+ font-family:'Geist Pixel',monospace;
547
+ }
548
+ .org-name{font-weight:600;color:#33ff00;}
549
+ .badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}
550
+ .badge-granted{background:#0a3300;color:#33ff00;}
551
+ .badge-denied{background:#1a0a0a;color:#ff4444;}
552
+ .badge-requested{background:#0a3300;color:#1a8c00;}
553
+ .btn-revoke{
554
+ display:inline-block;padding:5px 14px;border-radius:6px;
555
+ border:1px solid #0a3300;background:transparent;color:#ff4444;
556
+ font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;
557
+ }
558
+ .btn-revoke:hover{border-color:#ff4444;}
559
+ .info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}
560
+ .app-link{
561
+ display:flex;align-items:center;gap:12px;padding:12px;
562
+ border:1px solid #0a3300;border-radius:8px;background:#000;
563
+ text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;
564
+ }
565
+ .app-link:hover{border-color:#33ff00;}
566
+ .app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}
567
+ .app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}
568
+ .empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}
569
+ `;
570
+ var POWERED_BY = `<div class="powered-by">Powered by <a href="https://emulate.dev" target="_blank" rel="noopener">emulate</a></div>`;
571
+ function emuBar(service) {
572
+ const title = service ? `${escapeHtml(service)} Emulator` : "Emulator";
573
+ return `<div class="emu-bar">
574
+ <span class="emu-bar-title">${title}</span>
575
+ <nav class="emu-bar-links">
576
+ <a href="https://github.com/vercel-labs/emulate/issues" target="_blank" rel="noopener"><span class="full">Report Issue</span><span class="short">Report</span></a>
577
+ <a href="https://github.com/vercel-labs/emulate" target="_blank" rel="noopener"><span class="full">Source Code</span><span class="short">Source</span></a>
578
+ <a href="https://emulate.dev" target="_blank" rel="noopener"><span class="full">Learn More</span><span class="short">Learn</span></a>
579
+ </nav>
580
+ </div>`;
581
+ }
582
+ function head(title) {
583
+ return `<!DOCTYPE html>
584
+ <html lang="en">
585
+ <head>
586
+ <meta charset="utf-8"/>
587
+ <meta name="viewport" content="width=device-width,initial-scale=1"/>
588
+ <title>${escapeHtml(title)} | emulate</title>
589
+ <style>${CSS}</style>
590
+ </head>`;
591
+ }
592
+ function renderCardPage(title, subtitle, body, service) {
593
+ return `${head(title)}
594
+ <body>
595
+ ${emuBar(service)}
596
+ <div class="content">
597
+ <div class="content-inner">
598
+ <div class="card-title">${escapeHtml(title)}</div>
599
+ <div class="card-subtitle">${subtitle}</div>
600
+ ${body}
601
+ </div>
602
+ </div>
603
+ ${POWERED_BY}
604
+ </body></html>`;
605
+ }
606
+
607
+ // src/routes/inbox.ts
608
+ var SERVICE_LABEL = "Resend";
609
+ function inboxRoutes(ctx) {
610
+ const { app, store } = ctx;
611
+ const rs = () => getResendStore(store);
612
+ app.get("/inbox", (c) => {
613
+ const emails = rs().emails.all().reverse();
614
+ let body = "";
615
+ if (emails.length === 0) {
616
+ body = `<div class="empty">No emails sent yet. Use POST /emails to send one.</div>`;
617
+ } else {
618
+ for (const email of emails) {
619
+ const letter = (email.from?.[0] ?? "?").toUpperCase();
620
+ const statusClass = email.status === "delivered" ? "badge-granted" : email.status === "bounced" ? "badge-denied" : "badge-requested";
621
+ body += `<a href="/inbox/${escapeAttr(email.uuid)}" class="app-link">
622
+ <span class="org-icon">${escapeHtml(letter)}</span>
623
+ <span class="user-text">
624
+ <span class="org-name">${escapeHtml(email.subject)}</span>
625
+ <span class="user-meta">${escapeHtml(email.from)} &rarr; ${escapeHtml(email.to.join(", "))}</span>
626
+ </span>
627
+ <span class="badge ${statusClass}">${escapeHtml(email.status)}</span>
628
+ </a>`;
629
+ }
630
+ }
631
+ const html = renderCardPage(
632
+ "Inbox",
633
+ `${emails.length} email${emails.length !== 1 ? "s" : ""} sent`,
634
+ body,
635
+ SERVICE_LABEL
636
+ );
637
+ return c.html(html);
638
+ });
639
+ app.get("/inbox/:id", (c) => {
640
+ const id = c.req.param("id");
641
+ const email = rs().emails.findOneBy("uuid", id);
642
+ if (!email) {
643
+ const html2 = renderCardPage(
644
+ "Not Found",
645
+ "The requested email was not found.",
646
+ `<div class="empty">Email not found</div>`,
647
+ SERVICE_LABEL
648
+ );
649
+ return c.html(html2, 404);
650
+ }
651
+ const statusClass = email.status === "delivered" ? "badge-granted" : email.status === "bounced" ? "badge-denied" : "badge-requested";
652
+ let tagsHtml = "";
653
+ if (email.tags.length > 0) {
654
+ tagsHtml = `<div class="info-text">`;
655
+ for (const tag of email.tags) {
656
+ tagsHtml += `<span class="badge badge-requested">${escapeHtml(tag.name)}: ${escapeHtml(tag.value)}</span> `;
657
+ }
658
+ tagsHtml += `</div>`;
659
+ }
660
+ const recipientLines = [];
661
+ recipientLines.push(`<strong>To:</strong> ${escapeHtml(email.to.join(", "))}`);
662
+ if (email.cc.length > 0) {
663
+ recipientLines.push(`<strong>Cc:</strong> ${escapeHtml(email.cc.join(", "))}`);
664
+ }
665
+ if (email.bcc.length > 0) {
666
+ recipientLines.push(`<strong>Bcc:</strong> ${escapeHtml(email.bcc.join(", "))}`);
667
+ }
668
+ const previewContent = email.html ? `<iframe
669
+ sandbox=""
670
+ srcdoc="${escapeAttr(email.html)}"
671
+ class="s-card"
672
+ style="width:100%;min-height:300px;border:1px solid #0a3300;border-radius:8px;background:#fff;"
673
+ ></iframe>` : email.text ? `<div class="s-card"><pre class="info-text">${escapeHtml(email.text)}</pre></div>` : `<div class="empty">No content</div>`;
674
+ const body = `
675
+ <div class="org-row">
676
+ <span class="badge ${statusClass}">${escapeHtml(email.status)}</span>
677
+ <span class="user-meta">${escapeHtml(email.created_at)}</span>
678
+ </div>
679
+ <div class="s-card">
680
+ <div class="perm-list">
681
+ <li><strong>From:</strong> ${escapeHtml(email.from)}</li>
682
+ ${recipientLines.map((line) => `<li>${line}</li>`).join("\n ")}
683
+ </div>
684
+ </div>
685
+ ${tagsHtml}
686
+ <div class="section-heading">Preview</div>
687
+ ${previewContent}
688
+ <div class="info-text">
689
+ <strong>Last event:</strong> ${escapeHtml(email.last_event)}
690
+ ${email.scheduled_at ? ` | <strong>Scheduled:</strong> ${escapeHtml(email.scheduled_at)}` : ""}
691
+ </div>`;
692
+ const html = renderCardPage(
693
+ email.subject,
694
+ `Email ${escapeHtml(email.uuid)}`,
695
+ body,
696
+ SERVICE_LABEL
697
+ );
698
+ return c.html(html);
699
+ });
700
+ }
701
+
702
+ // src/index.ts
703
+ function seedFromConfig(store, _baseUrl, config) {
704
+ const rs = getResendStore(store);
705
+ if (config.domains) {
706
+ for (const d of config.domains) {
707
+ const existing = rs.domains.findOneBy("name", d.name);
708
+ if (existing) continue;
709
+ const region = d.region ?? "us-east-1";
710
+ rs.domains.insert({
711
+ uuid: generateUuid(),
712
+ name: d.name,
713
+ status: "verified",
714
+ region,
715
+ records: [
716
+ {
717
+ record: "SPF",
718
+ name: d.name,
719
+ type: "MX",
720
+ ttl: "Auto",
721
+ status: "verified",
722
+ value: `feedback-smtp.${region}.amazonses.com`,
723
+ priority: 10
724
+ },
725
+ {
726
+ record: "SPF",
727
+ name: d.name,
728
+ type: "TXT",
729
+ ttl: "Auto",
730
+ status: "verified",
731
+ value: "v=spf1 include:amazonses.com ~all"
732
+ },
733
+ {
734
+ record: "DKIM",
735
+ name: `resend._domainkey.${d.name}`,
736
+ type: "CNAME",
737
+ ttl: "Auto",
738
+ status: "verified",
739
+ value: `resend.domainkey.${region}.amazonses.com`
740
+ }
741
+ ]
742
+ });
743
+ }
744
+ }
745
+ if (config.contacts) {
746
+ let defaultAudience = rs.audiences.findOneBy("name", "Default");
747
+ if (!defaultAudience) {
748
+ defaultAudience = rs.audiences.insert({ uuid: generateUuid(), name: "Default" });
749
+ }
750
+ for (const ct of config.contacts) {
751
+ let audienceId = defaultAudience.uuid;
752
+ if (ct.audience) {
753
+ let audience = rs.audiences.findOneBy("name", ct.audience);
754
+ if (!audience) {
755
+ audience = rs.audiences.insert({ uuid: generateUuid(), name: ct.audience });
756
+ }
757
+ audienceId = audience.uuid;
758
+ }
759
+ rs.contacts.insert({
760
+ uuid: generateUuid(),
761
+ audience_id: audienceId,
762
+ email: ct.email,
763
+ first_name: ct.first_name ?? null,
764
+ last_name: ct.last_name ?? null,
765
+ unsubscribed: false
766
+ });
767
+ }
768
+ }
769
+ }
770
+ var resendPlugin = {
771
+ name: "resend",
772
+ register(app, store, webhooks, baseUrl, tokenMap) {
773
+ const ctx = { app, store, webhooks, baseUrl, tokenMap };
774
+ emailRoutes(ctx);
775
+ domainRoutes(ctx);
776
+ apiKeyRoutes(ctx);
777
+ contactRoutes(ctx);
778
+ inboxRoutes(ctx);
779
+ },
780
+ seed(_store, _baseUrl) {
781
+ }
782
+ };
783
+ var index_default = resendPlugin;
784
+ export {
785
+ index_default as default,
786
+ getResendStore,
787
+ resendPlugin,
788
+ seedFromConfig
789
+ };
790
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/store.ts","../src/helpers.ts","../src/routes/emails.ts","../src/routes/domains.ts","../src/routes/api-keys.ts","../src/routes/contacts.ts","../../core/src/store.ts","../../core/src/server.ts","../../core/src/webhooks.ts","../../core/src/middleware/error-handler.ts","../../core/src/middleware/auth.ts","../../core/src/debug.ts","../../core/src/fonts.ts","../../core/src/middleware/pagination.ts","../../core/src/ui.ts","../../core/src/oauth-helpers.ts","../../core/src/persistence.ts","../src/routes/inbox.ts","../src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type { ResendEmail, ResendDomain, ResendApiKey, ResendAudience, ResendContact } from \"./entities.js\";\n\nexport interface ResendStore {\n emails: Collection<ResendEmail>;\n domains: Collection<ResendDomain>;\n apiKeys: Collection<ResendApiKey>;\n audiences: Collection<ResendAudience>;\n contacts: Collection<ResendContact>;\n}\n\nexport function getResendStore(store: Store): ResendStore {\n return {\n emails: store.collection<ResendEmail>(\"resend.emails\", [\"uuid\"]),\n domains: store.collection<ResendDomain>(\"resend.domains\", [\"uuid\", \"name\"]),\n apiKeys: store.collection<ResendApiKey>(\"resend.api_keys\", [\"uuid\"]),\n audiences: store.collection<ResendAudience>(\"resend.audiences\", [\"uuid\"]),\n contacts: store.collection<ResendContact>(\"resend.contacts\", [\"uuid\", \"audience_id\"]),\n };\n}\n","import { randomUUID } from \"crypto\";\nimport type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\n\nexport function generateUuid(): string {\n return randomUUID();\n}\n\nexport function resendError(\n c: Context,\n statusCode: number,\n name: string,\n message: string,\n) {\n return c.json({ statusCode, name, message }, statusCode as ContentfulStatusCode);\n}\n\nexport function resendList(data: unknown[]) {\n return { object: \"list\" as const, data };\n}\n\nexport async function parseResendBody(c: Context): Promise<Record<string, unknown>> {\n const contentType = c.req.header(\"content-type\") ?? \"\";\n\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const text = await c.req.text();\n const params = new URLSearchParams(text);\n const result: Record<string, unknown> = {};\n for (const [key, value] of params.entries()) {\n result[key] = value;\n }\n return result;\n }\n\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n return {};\n }\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getResendStore } from \"../store.js\";\nimport { generateUuid, resendError, resendList, parseResendBody } from \"../helpers.js\";\nimport type { ResendEmail } from \"../entities.js\";\n\nexport function emailRoutes(ctx: RouteContext): void {\n const { app, store, webhooks } = ctx;\n const rs = () => getResendStore(store);\n\n app.post(\"/emails/batch\", async (c) => {\n let emails: Array<Record<string, unknown>>;\n try {\n const raw = await c.req.json();\n if (!Array.isArray(raw)) {\n return resendError(c, 422, \"validation_error\", \"Request body must be an array\");\n }\n emails = raw;\n } catch {\n return resendError(c, 422, \"validation_error\", \"Request body must be an array\");\n }\n\n if (emails.length > 100) {\n return resendError(c, 422, \"validation_error\", \"Batch size cannot exceed 100 emails\");\n }\n\n // Validate all emails before inserting any to prevent phantom records\n for (const emailData of emails) {\n if (!emailData.from) return resendError(c, 422, \"validation_error\", \"Missing required field: from\");\n if (!emailData.to) return resendError(c, 422, \"validation_error\", \"Missing required field: to\");\n if (!emailData.subject) return resendError(c, 422, \"validation_error\", \"Missing required field: subject\");\n }\n\n const results: Array<{ id: string }> = [];\n\n for (const emailData of emails) {\n const from = emailData.from as string;\n const to = emailData.to as string | string[];\n const subject = emailData.subject as string;\n const toArray = Array.isArray(to) ? to : [to];\n const uuid = generateUuid();\n\n const scheduledAt = emailData.scheduled_at as string | undefined;\n const status = scheduledAt ? \"scheduled\" as const : \"delivered\" as const;\n\n rs().emails.insert({\n uuid,\n from,\n to: toArray,\n subject,\n html: (emailData.html as string) ?? null,\n text: (emailData.text as string) ?? null,\n cc: normalizeStringArray(emailData.cc),\n bcc: normalizeStringArray(emailData.bcc),\n reply_to: normalizeStringArray(emailData.reply_to),\n headers: (emailData.headers as Record<string, string>) ?? {},\n tags: (emailData.tags as Array<{ name: string; value: string }>) ?? [],\n status,\n scheduled_at: scheduledAt ?? null,\n last_event: status === \"scheduled\" ? \"email.scheduled\" : \"email.delivered\",\n });\n\n if (!scheduledAt) {\n await webhooks.dispatch(\"email.sent\", undefined, { type: \"email.sent\", data: { email_id: uuid, to: toArray, from, subject } }, \"resend\");\n await webhooks.dispatch(\"email.delivered\", undefined, { type: \"email.delivered\", data: { email_id: uuid, to: toArray, from, subject } }, \"resend\");\n }\n\n results.push({ id: uuid });\n }\n\n return c.json({ data: results }, 200);\n });\n\n app.post(\"/emails\", async (c) => {\n const body = await parseResendBody(c);\n const from = body.from as string | undefined;\n const to = body.to as string | string[] | undefined;\n const subject = body.subject as string | undefined;\n\n if (!from) return resendError(c, 422, \"validation_error\", \"Missing required field: from\");\n if (!to) return resendError(c, 422, \"validation_error\", \"Missing required field: to\");\n if (!subject) return resendError(c, 422, \"validation_error\", \"Missing required field: subject\");\n\n const toArray = Array.isArray(to) ? to : [to];\n const uuid = generateUuid();\n\n const scheduledAt = body.scheduled_at as string | undefined;\n const status = scheduledAt ? \"scheduled\" as const : \"delivered\" as const;\n\n rs().emails.insert({\n uuid,\n from,\n to: toArray,\n subject,\n html: (body.html as string) ?? null,\n text: (body.text as string) ?? null,\n cc: normalizeStringArray(body.cc),\n bcc: normalizeStringArray(body.bcc),\n reply_to: normalizeStringArray(body.reply_to),\n headers: (body.headers as Record<string, string>) ?? {},\n tags: (body.tags as Array<{ name: string; value: string }>) ?? [],\n status,\n scheduled_at: scheduledAt ?? null,\n last_event: status === \"scheduled\" ? \"email.scheduled\" : \"email.delivered\",\n });\n\n if (!scheduledAt) {\n await webhooks.dispatch(\"email.sent\", undefined, { type: \"email.sent\", data: { email_id: uuid, to: toArray, from, subject } }, \"resend\");\n await webhooks.dispatch(\"email.delivered\", undefined, { type: \"email.delivered\", data: { email_id: uuid, to: toArray, from, subject } }, \"resend\");\n }\n\n return c.json({ id: uuid }, 200);\n });\n\n app.get(\"/emails\", (c) => {\n const allEmails = rs().emails.all();\n return c.json(resendList(allEmails.map(formatEmail)));\n });\n\n app.get(\"/emails/:id\", (c) => {\n const id = c.req.param(\"id\");\n const email = rs().emails.findOneBy(\"uuid\", id);\n if (!email) return resendError(c, 404, \"not_found\", \"Email not found\");\n return c.json(formatEmail(email));\n });\n\n app.post(\"/emails/:id/cancel\", (c) => {\n const id = c.req.param(\"id\");\n const email = rs().emails.findOneBy(\"uuid\", id);\n if (!email) return resendError(c, 404, \"not_found\", \"Email not found\");\n\n if (email.status !== \"scheduled\") {\n return resendError(c, 422, \"validation_error\", \"Only scheduled emails can be canceled\");\n }\n\n rs().emails.update(email.id, {\n status: \"canceled\",\n last_event: \"email.canceled\",\n });\n\n return c.json({ id: email.uuid, object: \"email\", canceled: true });\n });\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n if (!value) return [];\n if (Array.isArray(value)) return value.map(String);\n if (typeof value === \"string\") return [value];\n return [];\n}\n\nfunction formatEmail(email: ResendEmail) {\n return {\n id: email.uuid,\n object: \"email\",\n from: email.from,\n to: email.to,\n subject: email.subject,\n html: email.html,\n text: email.text,\n cc: email.cc,\n bcc: email.bcc,\n reply_to: email.reply_to,\n headers: email.headers,\n tags: email.tags,\n status: email.status,\n scheduled_at: email.scheduled_at,\n last_event: email.last_event,\n created_at: email.created_at,\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getResendStore } from \"../store.js\";\nimport { generateUuid, resendError, resendList, parseResendBody } from \"../helpers.js\";\nimport type { ResendDomain } from \"../entities.js\";\n\nexport function domainRoutes(ctx: RouteContext): void {\n const { app, store, webhooks } = ctx;\n const rs = () => getResendStore(store);\n\n app.post(\"/domains\", async (c) => {\n const body = await parseResendBody(c);\n const name = body.name as string | undefined;\n\n if (!name) return resendError(c, 422, \"validation_error\", \"Missing required field: name\");\n\n const region = (body.region as string) ?? \"us-east-1\";\n const uuid = generateUuid();\n\n const records = [\n {\n record: \"SPF\",\n name,\n type: \"MX\",\n ttl: \"Auto\",\n status: \"pending\" as const,\n value: `feedback-smtp.${region}.amazonses.com`,\n priority: 10,\n },\n {\n record: \"SPF\",\n name,\n type: \"TXT\",\n ttl: \"Auto\",\n status: \"pending\" as const,\n value: \"v=spf1 include:amazonses.com ~all\",\n },\n {\n record: \"DKIM\",\n name: `resend._domainkey.${name}`,\n type: \"CNAME\",\n ttl: \"Auto\",\n status: \"pending\" as const,\n value: `resend.domainkey.${region}.amazonses.com`,\n },\n ];\n\n const domain = rs().domains.insert({\n uuid,\n name,\n status: \"pending\",\n region,\n records,\n });\n\n await webhooks.dispatch(\"domain.created\", undefined, { type: \"domain.created\", data: { id: uuid, name } }, \"resend\");\n\n return c.json(formatDomain(domain), 200);\n });\n\n app.get(\"/domains\", (c) => {\n const allDomains = rs().domains.all();\n return c.json(resendList(allDomains.map(formatDomain)));\n });\n\n app.get(\"/domains/:id\", (c) => {\n const id = c.req.param(\"id\");\n const domain = rs().domains.findOneBy(\"uuid\", id);\n if (!domain) return resendError(c, 404, \"not_found\", \"Domain not found\");\n return c.json(formatDomain(domain));\n });\n\n app.delete(\"/domains/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const domain = rs().domains.findOneBy(\"uuid\", id);\n if (!domain) return resendError(c, 404, \"not_found\", \"Domain not found\");\n\n rs().domains.delete(domain.id);\n\n await webhooks.dispatch(\"domain.deleted\", undefined, { type: \"domain.deleted\", data: { id: domain.uuid, name: domain.name } }, \"resend\");\n\n return c.json({ object: \"domain\", id: domain.uuid, deleted: true });\n });\n\n app.post(\"/domains/:id/verify\", (c) => {\n const id = c.req.param(\"id\");\n const domain = rs().domains.findOneBy(\"uuid\", id);\n if (!domain) return resendError(c, 404, \"not_found\", \"Domain not found\");\n\n const verifiedRecords = domain.records.map((r) => ({ ...r, status: \"verified\" as const }));\n\n rs().domains.update(domain.id, {\n status: \"verified\",\n records: verifiedRecords,\n });\n\n return c.json({ object: \"domain\", id: domain.uuid, status: \"verified\" });\n });\n}\n\nfunction formatDomain(domain: ResendDomain) {\n return {\n id: domain.uuid,\n object: \"domain\",\n name: domain.name,\n status: domain.status,\n region: domain.region,\n records: domain.records,\n created_at: domain.created_at,\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getResendStore } from \"../store.js\";\nimport { generateUuid, resendError, resendList, parseResendBody } from \"../helpers.js\";\nimport { randomBytes } from \"crypto\";\n\nexport function apiKeyRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const rs = () => getResendStore(store);\n\n app.post(\"/api-keys\", async (c) => {\n const body = await parseResendBody(c);\n const name = body.name as string | undefined;\n\n if (!name) return resendError(c, 422, \"validation_error\", \"Missing required field: name\");\n\n const uuid = generateUuid();\n const token = `re_${randomBytes(16).toString(\"hex\")}`;\n\n const apiKey = rs().apiKeys.insert({\n uuid,\n name,\n token,\n });\n\n return c.json({\n id: apiKey.uuid,\n token: apiKey.token,\n }, 200);\n });\n\n app.get(\"/api-keys\", (c) => {\n const allKeys = rs().apiKeys.all();\n return c.json(resendList(allKeys.map((key) => ({\n id: key.uuid,\n name: key.name,\n created_at: key.created_at,\n }))));\n });\n\n app.delete(\"/api-keys/:id\", (c) => {\n const id = c.req.param(\"id\");\n const apiKey = rs().apiKeys.findOneBy(\"uuid\", id);\n if (!apiKey) return resendError(c, 404, \"not_found\", \"API key not found\");\n\n rs().apiKeys.delete(apiKey.id);\n\n return c.json({ deleted: true });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getResendStore } from \"../store.js\";\nimport { generateUuid, resendError, resendList, parseResendBody } from \"../helpers.js\";\n\nexport function contactRoutes(ctx: RouteContext): void {\n const { app, store, webhooks } = ctx;\n const rs = () => getResendStore(store);\n\n // Audiences\n app.post(\"/audiences\", async (c) => {\n const body = await parseResendBody(c);\n const name = body.name as string | undefined;\n\n if (!name) return resendError(c, 422, \"validation_error\", \"Missing required field: name\");\n\n const uuid = generateUuid();\n const audience = rs().audiences.insert({ uuid, name });\n\n return c.json({\n id: audience.uuid,\n object: \"audience\",\n name: audience.name,\n created_at: audience.created_at,\n }, 200);\n });\n\n app.get(\"/audiences\", (c) => {\n const allAudiences = rs().audiences.all();\n return c.json(resendList(allAudiences.map((a) => ({\n id: a.uuid,\n object: \"audience\",\n name: a.name,\n created_at: a.created_at,\n }))));\n });\n\n app.delete(\"/audiences/:id\", (c) => {\n const id = c.req.param(\"id\");\n const audience = rs().audiences.findOneBy(\"uuid\", id);\n if (!audience) return resendError(c, 404, \"not_found\", \"Audience not found\");\n\n rs().audiences.delete(audience.id);\n\n return c.json({ object: \"audience\", id: audience.uuid, deleted: true });\n });\n\n // Contacts\n app.post(\"/audiences/:audience_id/contacts\", async (c) => {\n const audienceId = c.req.param(\"audience_id\");\n const audience = rs().audiences.findOneBy(\"uuid\", audienceId);\n if (!audience) return resendError(c, 404, \"not_found\", \"Audience not found\");\n\n const body = await parseResendBody(c);\n const email = body.email as string | undefined;\n\n if (!email) return resendError(c, 422, \"validation_error\", \"Missing required field: email\");\n\n const uuid = generateUuid();\n const contact = rs().contacts.insert({\n uuid,\n audience_id: audienceId,\n email,\n first_name: (body.first_name as string) ?? null,\n last_name: (body.last_name as string) ?? null,\n unsubscribed: (body.unsubscribed as boolean) ?? false,\n });\n\n await webhooks.dispatch(\"contact.created\", undefined, { type: \"contact.created\", data: { id: uuid, email, audience_id: audienceId } }, \"resend\");\n\n return c.json({\n id: contact.uuid,\n object: \"contact\",\n email: contact.email,\n }, 200);\n });\n\n app.get(\"/audiences/:audience_id/contacts\", (c) => {\n const audienceId = c.req.param(\"audience_id\");\n const audience = rs().audiences.findOneBy(\"uuid\", audienceId);\n if (!audience) return resendError(c, 404, \"not_found\", \"Audience not found\");\n\n const contacts = rs().contacts.findBy(\"audience_id\", audienceId);\n return c.json(resendList(contacts.map((ct) => ({\n id: ct.uuid,\n object: \"contact\",\n email: ct.email,\n first_name: ct.first_name,\n last_name: ct.last_name,\n unsubscribed: ct.unsubscribed,\n created_at: ct.created_at,\n }))));\n });\n\n app.delete(\"/audiences/:audience_id/contacts/:id\", async (c) => {\n const audienceId = c.req.param(\"audience_id\");\n const contactId = c.req.param(\"id\");\n\n const contact = rs().contacts.findOneBy(\"uuid\", contactId);\n if (!contact || contact.audience_id !== audienceId) {\n return resendError(c, 404, \"not_found\", \"Contact not found\");\n }\n\n rs().contacts.delete(contact.id);\n\n await webhooks.dispatch(\"contact.deleted\", undefined, { type: \"contact.deleted\", data: { id: contact.uuid, email: contact.email, audience_id: audienceId } }, \"resend\");\n\n return c.json({ object: \"contact\", id: contact.uuid, deleted: true });\n });\n}\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport interface CollectionSnapshot<T extends Entity = Entity> {\n items: T[];\n autoId: number;\n indexFields: string[];\n}\n\nexport interface StoreSnapshot {\n collections: Record<string, CollectionSnapshot>;\n data: Record<string, unknown>;\n}\n\nexport function serializeValue(value: unknown): unknown {\n if (value instanceof Map) {\n return { __type: \"Map\" as const, entries: [...value.entries()].map(([k, v]) => [k, serializeValue(v)]) };\n }\n if (value instanceof Set) {\n return { __type: \"Set\" as const, values: [...value.values()] };\n }\n return value;\n}\n\nexport function deserializeValue(value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && \"__type\" in value) {\n const tagged = value as Record<string, unknown>;\n if (tagged.__type === \"Map\") {\n const entries = tagged.entries as [unknown, unknown][];\n return new Map(entries.map(([k, v]) => [k, deserializeValue(v)]));\n }\n if (tagged.__type === \"Set\") {\n return new Set(tagged.values as unknown[]);\n }\n }\n return value;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids).map((id) => this.items.get(id)!).filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n\n snapshot(): CollectionSnapshot<T> {\n return {\n items: this.all(),\n autoId: this.autoId,\n indexFields: this.fieldNames,\n };\n }\n\n restore(snap: CollectionSnapshot<T>): void {\n this.clear();\n this.autoId = snap.autoId;\n for (const item of snap.items) {\n this.items.set(item.id, item);\n this.addToIndex(item);\n }\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n\n snapshot(): StoreSnapshot {\n const collections: Record<string, CollectionSnapshot> = {};\n for (const [name, col] of this.collections) {\n collections[name] = col.snapshot();\n }\n const data: Record<string, unknown> = {};\n for (const [key, value] of this._data) {\n data[key] = serializeValue(value);\n }\n return { collections, data };\n }\n\n restore(snap: StoreSnapshot): void {\n const snapshotNames = new Set(Object.keys(snap.collections));\n for (const name of this.collections.keys()) {\n if (!snapshotNames.has(name)) {\n this.collections.delete(name);\n }\n }\n for (const [name, colSnap] of Object.entries(snap.collections)) {\n const indexFields = colSnap.indexFields as (keyof Entity)[];\n const col = this.collection(name, indexFields);\n col.restore(colSnap as CollectionSnapshot<any>);\n }\n this._data.clear();\n for (const [key, value] of Object.entries(snap.data)) {\n this._data.set(key, deserializeValue(value));\n }\n }\n}\n","import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport { authMiddleware, type AuthFallback, type TokenMap, type AppKeyResolver, type AppEnv } from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://emulate.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404\n )\n );\n\n return { app, store, webhooks, port, baseUrl, tokenMap };\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(event: string, action: string | undefined, payload: unknown, owner: string, repo?: string): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return (\n event === \"ping\" ||\n s.events.includes(\"*\") ||\n s.events.includes(event)\n );\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ErrorHandler, MiddlewareHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Hono routes handler throws to the app error handler, not to outer middleware try/catch.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"hono\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport interface TokenEntry {\n token: string;\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function serializeTokenMap(tokenMap: TokenMap): TokenEntry[] {\n return [...tokenMap.entries()].map(([token, user]) => ({\n token,\n login: user.login,\n id: user.id,\n scopes: user.scopes,\n }));\n}\n\nexport function restoreTokenMap(tokenMap: TokenMap, tokens: TokenEntry[]): void {\n tokenMap.clear();\n for (const t of tokens) {\n tokenMap.set(t.token, { login: t.login, id: t.id, scopes: t.scopes });\n }\n}\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(\n Buffer.from(payloadB64, \"base64url\").toString()\n );\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401\n );\n }\n await next();\n };\n}\n","const isDebug = typeof process !== \"undefined\" && (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"hono\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst FONTS: Record<string, Buffer> = {\n \"geist-sans.woff2\": readFileSync(join(__dirname, \"fonts\", \"geist-sans.woff2\")),\n \"GeistPixel-Square.woff2\": readFileSync(join(__dirname, \"fonts\", \"GeistPixel-Square.woff2\")),\n};\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n const buf = FONTS[name];\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n}\n","import type { Context } from \"hono\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(\n c: Context,\n totalCount: number,\n page: number,\n perPage: number\n): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","export function escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"&#39;\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(\n title: string,\n subtitle: string,\n body: string,\n service?: string\n): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(\n title: string,\n sidebarHtml: string,\n bodyHtml: string,\n service?: string\n): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name\n ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>`\n : \"\";\n const emailLine = opts.email\n ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>`\n : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nexport interface PersistenceAdapter {\n load(): Promise<string | null>;\n save(data: string): Promise<void>;\n}\n\nexport function filePersistence(path: string): PersistenceAdapter {\n return {\n async load() {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n },\n async save(data: string) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, data, \"utf-8\");\n },\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { renderCardPage, escapeHtml, escapeAttr } from \"@emulators/core\";\nimport { getResendStore } from \"../store.js\";\n\nconst SERVICE_LABEL = \"Resend\";\n\nexport function inboxRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const rs = () => getResendStore(store);\n\n app.get(\"/inbox\", (c) => {\n const emails = rs().emails.all().reverse();\n\n let body = \"\";\n\n if (emails.length === 0) {\n body = `<div class=\"empty\">No emails sent yet. Use POST /emails to send one.</div>`;\n } else {\n for (const email of emails) {\n const letter = (email.from?.[0] ?? \"?\").toUpperCase();\n const statusClass = email.status === \"delivered\"\n ? \"badge-granted\"\n : email.status === \"bounced\"\n ? \"badge-denied\"\n : \"badge-requested\";\n\n body += `<a href=\"/inbox/${escapeAttr(email.uuid)}\" class=\"app-link\">\n <span class=\"org-icon\">${escapeHtml(letter)}</span>\n <span class=\"user-text\">\n <span class=\"org-name\">${escapeHtml(email.subject)}</span>\n <span class=\"user-meta\">${escapeHtml(email.from)} &rarr; ${escapeHtml(email.to.join(\", \"))}</span>\n </span>\n <span class=\"badge ${statusClass}\">${escapeHtml(email.status)}</span>\n</a>`;\n }\n }\n\n const html = renderCardPage(\n \"Inbox\",\n `${emails.length} email${emails.length !== 1 ? \"s\" : \"\"} sent`,\n body,\n SERVICE_LABEL,\n );\n\n return c.html(html);\n });\n\n app.get(\"/inbox/:id\", (c) => {\n const id = c.req.param(\"id\");\n const email = rs().emails.findOneBy(\"uuid\", id);\n\n if (!email) {\n const html = renderCardPage(\n \"Not Found\",\n \"The requested email was not found.\",\n `<div class=\"empty\">Email not found</div>`,\n SERVICE_LABEL,\n );\n return c.html(html, 404);\n }\n\n const statusClass = email.status === \"delivered\"\n ? \"badge-granted\"\n : email.status === \"bounced\"\n ? \"badge-denied\"\n : \"badge-requested\";\n\n let tagsHtml = \"\";\n if (email.tags.length > 0) {\n tagsHtml = `<div class=\"info-text\">`;\n for (const tag of email.tags) {\n tagsHtml += `<span class=\"badge badge-requested\">${escapeHtml(tag.name)}: ${escapeHtml(tag.value)}</span> `;\n }\n tagsHtml += `</div>`;\n }\n\n const recipientLines: string[] = [];\n recipientLines.push(`<strong>To:</strong> ${escapeHtml(email.to.join(\", \"))}`);\n if (email.cc.length > 0) {\n recipientLines.push(`<strong>Cc:</strong> ${escapeHtml(email.cc.join(\", \"))}`);\n }\n if (email.bcc.length > 0) {\n recipientLines.push(`<strong>Bcc:</strong> ${escapeHtml(email.bcc.join(\", \"))}`);\n }\n\n const previewContent = email.html\n ? `<iframe\n sandbox=\"\"\n srcdoc=\"${escapeAttr(email.html)}\"\n class=\"s-card\"\n style=\"width:100%;min-height:300px;border:1px solid #0a3300;border-radius:8px;background:#fff;\"\n></iframe>`\n : email.text\n ? `<div class=\"s-card\"><pre class=\"info-text\">${escapeHtml(email.text)}</pre></div>`\n : `<div class=\"empty\">No content</div>`;\n\n const body = `\n<div class=\"org-row\">\n <span class=\"badge ${statusClass}\">${escapeHtml(email.status)}</span>\n <span class=\"user-meta\">${escapeHtml(email.created_at)}</span>\n</div>\n<div class=\"s-card\">\n <div class=\"perm-list\">\n <li><strong>From:</strong> ${escapeHtml(email.from)}</li>\n ${recipientLines.map((line) => `<li>${line}</li>`).join(\"\\n \")}\n </div>\n</div>\n${tagsHtml}\n<div class=\"section-heading\">Preview</div>\n${previewContent}\n<div class=\"info-text\">\n <strong>Last event:</strong> ${escapeHtml(email.last_event)}\n ${email.scheduled_at ? ` | <strong>Scheduled:</strong> ${escapeHtml(email.scheduled_at)}` : \"\"}\n</div>`;\n\n const html = renderCardPage(\n email.subject,\n `Email ${escapeHtml(email.uuid)}`,\n body,\n SERVICE_LABEL,\n );\n\n return c.html(html);\n });\n}\n","import type { Hono } from \"hono\";\nimport type { ServicePlugin, Store, WebhookDispatcher, TokenMap, AppEnv, RouteContext } from \"@emulators/core\";\nimport { getResendStore } from \"./store.js\";\nimport { generateUuid } from \"./helpers.js\";\nimport { emailRoutes } from \"./routes/emails.js\";\nimport { domainRoutes } from \"./routes/domains.js\";\nimport { apiKeyRoutes } from \"./routes/api-keys.js\";\nimport { contactRoutes } from \"./routes/contacts.js\";\nimport { inboxRoutes } from \"./routes/inbox.js\";\n\nexport { getResendStore, type ResendStore } from \"./store.js\";\nexport * from \"./entities.js\";\n\nexport interface ResendSeedConfig {\n port?: number;\n domains?: Array<{\n name: string;\n region?: string;\n }>;\n contacts?: Array<{\n email: string;\n first_name?: string;\n last_name?: string;\n audience?: string;\n }>;\n}\n\nexport function seedFromConfig(store: Store, _baseUrl: string, config: ResendSeedConfig): void {\n const rs = getResendStore(store);\n\n if (config.domains) {\n for (const d of config.domains) {\n const existing = rs.domains.findOneBy(\"name\", d.name);\n if (existing) continue;\n\n const region = d.region ?? \"us-east-1\";\n rs.domains.insert({\n uuid: generateUuid(),\n name: d.name,\n status: \"verified\",\n region,\n records: [\n {\n record: \"SPF\",\n name: d.name,\n type: \"MX\",\n ttl: \"Auto\",\n status: \"verified\" as const,\n value: `feedback-smtp.${region}.amazonses.com`,\n priority: 10,\n },\n {\n record: \"SPF\",\n name: d.name,\n type: \"TXT\",\n ttl: \"Auto\",\n status: \"verified\" as const,\n value: \"v=spf1 include:amazonses.com ~all\",\n },\n {\n record: \"DKIM\",\n name: `resend._domainkey.${d.name}`,\n type: \"CNAME\",\n ttl: \"Auto\",\n status: \"verified\" as const,\n value: `resend.domainkey.${region}.amazonses.com`,\n },\n ],\n });\n }\n }\n\n if (config.contacts) {\n // Ensure default audience exists\n let defaultAudience = rs.audiences.findOneBy(\"name\", \"Default\");\n if (!defaultAudience) {\n defaultAudience = rs.audiences.insert({ uuid: generateUuid(), name: \"Default\" });\n }\n\n for (const ct of config.contacts) {\n let audienceId = defaultAudience.uuid;\n\n if (ct.audience) {\n let audience = rs.audiences.findOneBy(\"name\", ct.audience);\n if (!audience) {\n audience = rs.audiences.insert({ uuid: generateUuid(), name: ct.audience });\n }\n audienceId = audience.uuid;\n }\n\n rs.contacts.insert({\n uuid: generateUuid(),\n audience_id: audienceId,\n email: ct.email,\n first_name: ct.first_name ?? null,\n last_name: ct.last_name ?? null,\n unsubscribed: false,\n });\n }\n }\n}\n\nexport const resendPlugin: ServicePlugin = {\n name: \"resend\",\n register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void {\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n emailRoutes(ctx);\n domainRoutes(ctx);\n apiKeyRoutes(ctx);\n contactRoutes(ctx);\n inboxRoutes(ctx);\n },\n seed(_store: Store, _baseUrl: string): void {\n // No default seed data - inbox starts empty\n },\n};\n\nexport default resendPlugin;\n"],"mappings":";AAWO,SAAS,eAAe,OAA2B;AACxD,SAAO;AAAA,IACL,QAAQ,MAAM,WAAwB,iBAAiB,CAAC,MAAM,CAAC;AAAA,IAC/D,SAAS,MAAM,WAAyB,kBAAkB,CAAC,QAAQ,MAAM,CAAC;AAAA,IAC1E,SAAS,MAAM,WAAyB,mBAAmB,CAAC,MAAM,CAAC;AAAA,IACnE,WAAW,MAAM,WAA2B,oBAAoB,CAAC,MAAM,CAAC;AAAA,IACxE,UAAU,MAAM,WAA0B,mBAAmB,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AS;AAC9D,QAAI,CAAC,iBAAiB;AACpB,wBAAkB,GAAG,UAAU,OAAO,EAAE,MAAM,aAAa,GAAG,MAAM,UAAU,CAAC;AAAA,IACjF;AAEA,eAAW,MAAM,OAAO,UAAU;AAChC,UAAI,aAAa,gBAAgB;AAEjC,UAAI,GAAG,UAAU;AACf,YAAI,WAAW,GAAG,UAAU,UAAU,QAAQ,GAAG,QAAQ;AACzD,YAAI,CAAC,UAAU;AACb,qBAAW,GAAG,UAAU,OAAO,EAAE,MAAM,aAAa,GAAG,MAAM,GAAG,SAAS,CAAC;AAAA,QAC5E;AACA,qBAAa,SAAS;AAAA,MACxB;AAEA,SAAG,SAAS,OAAO;AAAA,QACjB,MAAM,aAAa;AAAA,QACnB,aAAa;AAAA,QACb,OAAO,GAAG;AAAA,QACV,YAAY,GAAG,cAAc;AAAA,QAC7B,WAAW,GAAG,aAAa;AAAA,QAC3B,cAAc;AAAA,MAChB,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,IAAM,eAA8B;AAAA,EACzC,MAAM;AAAA,EACN,SAAS,KAAmB,OAAc,UAA6B,SAAiB,UAA2B;AACjH,UAAM,MAAoB,EAAE,KAAK,OAAO,UAAU,SAAS,SAAS;AACpE,gBAAY,GAAG;AACf,iBAAa,GAAG;AAChB,iBAAa,GAAG;AAChB,kBAAc,GAAG;AACjB,gBAAY,GAAG;AAAA,EACjB;AAAA,EACA,KAAK,QAAe,UAAwB;AAAA,EAE5C;AACF;AAEA,IAAO,gBAAQ;","names":["html"]}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@emulators/resend",
3
+ "version": "0.4.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "homepage": "https://emulate.dev",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/vercel-labs/emulate.git",
18
+ "directory": "packages/@emulators/resend"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/vercel-labs/emulate/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "dependencies": {
30
+ "hono": "^4",
31
+ "@emulators/core": "0.4.0"
32
+ },
33
+ "devDependencies": {
34
+ "tsup": "^8",
35
+ "typescript": "^5.7",
36
+ "vitest": "^4.1.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup --clean",
40
+ "dev": "tsup --watch",
41
+ "test": "vitest run",
42
+ "clean": "rm -rf dist .turbo"
43
+ }
44
+ }