@kedge/plugin-resend 0.0.0-stage → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/package.json +29 -3
- package/src/index.ts +210 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Kedge Authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kedge/plugin-resend
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Part of [Kedge](https://www.npmjs.com/package/create-kedge), an open-source headless commerce backend on Cloudflare Workers and D1. Resend as the store's email transport: order confirmations, shipments, payment requests and the rest, each sent once under an idempotency key.
|
|
4
|
+
|
|
5
|
+
Add it to `kedge.config.ts` (`plugins: [resendPlugin()]`, `notifications: { transport: "resend" }`), set `RESEND_API_KEY` with `kedge secret put`, and set the sender with `PUT /admin/settings/notifications` on a domain Resend has verified. Your store's `node_modules/@kedge/docs/reference/notifications.md` has the rest.
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kedge/plugin-resend",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.12.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/chandeldivyam/Kedge.git",
|
|
8
|
+
"directory": "packages/plugin-resend"
|
|
9
|
+
},
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=24"
|
|
12
|
+
},
|
|
13
|
+
"type": "module",
|
|
14
|
+
"description": "Resend as Kedge's email transport: one send per notification under Resend's idempotency key, paced, behind core's email port (docs/proposals/p1.11a-notifications.md).",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./src/index.ts"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@kedge/plugin-sdk": "0.12.1"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/node": "24.19.2",
|
|
26
|
+
"@kedge/core": "0.12.1"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"typecheck": "tsc --noEmit -p .",
|
|
30
|
+
"test": "vitest run"
|
|
31
|
+
}
|
|
6
32
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// @kedge/plugin-resend: Resend as Kedge's email transport (docs/proposals/p1.11a-notifications.md §5.3). Add it to
|
|
2
|
+
// kedge.config.ts, set `notifications: { transport: "resend" }` and the secret RESEND_API_KEY with `kedge secret`.
|
|
3
|
+
// Core builds the K12 port `email.resend` from it: K12's key is passed as Resend's `Idempotency-Key`, which Resend
|
|
4
|
+
// keeps for 24 hours, so a lost result is resent under the same key within the hour and Resend answers with the
|
|
5
|
+
// first send. Every request leaves through core's pacer (`ctx.fetch`), never the global `fetch`.
|
|
6
|
+
//
|
|
7
|
+
// Two credentials of one Resend team get two pacers, whose rates must sum below the team's 10 requests a second
|
|
8
|
+
// (https://resend.com/docs/api-reference/rate-limit); a store normally has one key.
|
|
9
|
+
import {
|
|
10
|
+
type DirectEmail,
|
|
11
|
+
defineEmailTransport,
|
|
12
|
+
definePlugin,
|
|
13
|
+
type EmailTransportDefinition,
|
|
14
|
+
KedgeProviderError,
|
|
15
|
+
type OutboundEmail,
|
|
16
|
+
type PluginInstance,
|
|
17
|
+
type TransportContext,
|
|
18
|
+
} from "@kedge/plugin-sdk";
|
|
19
|
+
|
|
20
|
+
export const RESEND_API = "https://api.resend.com";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Resend's error names (https://resend.com/docs/api-reference/errors). Only `missing_required_field` and
|
|
24
|
+
* `invalid_parameter`, which Resend documents at 422 alone, are decided by the request's bytes (`contentDetermined`,
|
|
25
|
+
* §5.2): every transmission of a key carries the same frozen bytes, so they get the same verdict. `validation_error`
|
|
26
|
+
* isn't (codex code r22): Resend also answers it for an invalid key (400), an inactive one (401) and an unverified
|
|
27
|
+
* or mismatched domain (403), which the account's state decides, so it is a lost result like every other refusal:
|
|
28
|
+
* resent under the same key within the hour, then `unresolved` for staff, never a second key.
|
|
29
|
+
*/
|
|
30
|
+
export const RESEND_FAILURES = [
|
|
31
|
+
"validation_error",
|
|
32
|
+
"missing_required_field",
|
|
33
|
+
"invalid_parameter",
|
|
34
|
+
"invalid_idempotency_key",
|
|
35
|
+
"invalid_idempotent_request",
|
|
36
|
+
"concurrent_idempotent_requests",
|
|
37
|
+
"missing_api_key",
|
|
38
|
+
"invalid_api_key",
|
|
39
|
+
"restricted_api_key",
|
|
40
|
+
"suspended_api_key",
|
|
41
|
+
"missing_required_parameter",
|
|
42
|
+
"dns_lookup_failed",
|
|
43
|
+
"invalid_from_address",
|
|
44
|
+
"invalid_access",
|
|
45
|
+
"not_found",
|
|
46
|
+
"method_not_allowed",
|
|
47
|
+
"rate_limit_exceeded",
|
|
48
|
+
"daily_quota_exceeded",
|
|
49
|
+
"monthly_quota_exceeded",
|
|
50
|
+
"security_error",
|
|
51
|
+
"application_error",
|
|
52
|
+
"internal_server_error",
|
|
53
|
+
"service_unavailable",
|
|
54
|
+
"not_started",
|
|
55
|
+
"http_error",
|
|
56
|
+
] as const;
|
|
57
|
+
export const RESEND_CONTENT_DETERMINED = ["missing_required_field", "invalid_parameter"] as const;
|
|
58
|
+
/** The only status a content-determined name is final at: Resend documents both at 422 alone. */
|
|
59
|
+
const CONTENT_STATUS = 422;
|
|
60
|
+
|
|
61
|
+
export interface ResendOptions {
|
|
62
|
+
/** Lower than the plugin's 5 a second when the team's other traffic needs more room (§5.6). */
|
|
63
|
+
readonly requestsPerSecond?: number;
|
|
64
|
+
/**
|
|
65
|
+
* A gate's test hook only (§11): a send to a recipient starting with this prefix and then a deadline in epoch
|
|
66
|
+
* milliseconds (`delivered+drop-1795064625491-…@resend.dev`) has its response dropped after Resend accepted it,
|
|
67
|
+
* as a network failure would, until that deadline; past it the same key's resend is answered. The deadline rides
|
|
68
|
+
* in the address because nothing else is shared by the isolates a key's transmissions land in: an in-memory
|
|
69
|
+
* "once" dropped every resend on Cloudflare (the P1.11a gate). Never set in a store.
|
|
70
|
+
*/
|
|
71
|
+
readonly dropResponseOnceTo?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A Resend tag value holds only ASCII letters, numbers, underscores or dashes (§5.3): a kind's dots become dashes. */
|
|
75
|
+
export const tagValue = (kind: string) => kind.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 256);
|
|
76
|
+
|
|
77
|
+
/** The JSON Resend's `POST /emails` takes (https://resend.com/docs/api-reference/emails/send-email). */
|
|
78
|
+
export function resendBody(m: OutboundEmail): Record<string, unknown> {
|
|
79
|
+
return {
|
|
80
|
+
from: m.from,
|
|
81
|
+
to: [m.to],
|
|
82
|
+
subject: m.subject,
|
|
83
|
+
html: m.html,
|
|
84
|
+
text: m.text,
|
|
85
|
+
...(m.replyTo ? { reply_to: m.replyTo } : {}),
|
|
86
|
+
tags: [{ name: "kedge_kind", value: tagValue(m.kind) }],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const known = new Set<string>(RESEND_FAILURES);
|
|
91
|
+
const content = new Set<string>(RESEND_CONTENT_DETERMINED);
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* What a Resend answer means (§5.5): a content-determined name at 422 is final; anything else, a lost result. Only the
|
|
95
|
+
* error's `name` is read, a machine token: Resend's `message` can quote an address, and never reaches the journal.
|
|
96
|
+
*/
|
|
97
|
+
async function refusal(res: Response): Promise<KedgeProviderError> {
|
|
98
|
+
let name = "";
|
|
99
|
+
try {
|
|
100
|
+
const body = (await res.json()) as { name?: unknown };
|
|
101
|
+
if (typeof body.name === "string") name = body.name;
|
|
102
|
+
} catch {
|
|
103
|
+
// An unreadable body is the HTTP status alone.
|
|
104
|
+
}
|
|
105
|
+
const code = known.has(name) ? name : "http_error";
|
|
106
|
+
return content.has(code) && res.status === CONTENT_STATUS
|
|
107
|
+
? new KedgeProviderError(code, { final: true })
|
|
108
|
+
: new KedgeProviderError(code);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
112
|
+
|
|
113
|
+
/** Whether the gate's hook drops this send's response (ResendOptions.dropResponseOnceTo): before the address's deadline. */
|
|
114
|
+
export function dropsResponse(prefix: string | undefined, to: string, now: number): boolean {
|
|
115
|
+
if (!prefix || !to.startsWith(prefix)) return false;
|
|
116
|
+
const deadline = /^-?(\d{13})(?:\D|$)/.exec(to.slice(prefix.length))?.[1];
|
|
117
|
+
return deadline !== undefined && now < Number(deadline);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The transport. `drop` is the gate's hook (ResendOptions.dropResponseOnceTo). */
|
|
121
|
+
export function resendTransport(opts: ResendOptions = {}): EmailTransportDefinition {
|
|
122
|
+
const post = async (ctx: TransportContext, body: Record<string, unknown>, idempotencyKey?: string) => {
|
|
123
|
+
const res = await ctx.fetch(
|
|
124
|
+
new Request(`${RESEND_API}/emails`, {
|
|
125
|
+
method: "POST",
|
|
126
|
+
headers: {
|
|
127
|
+
authorization: `Bearer ${ctx.credential}`,
|
|
128
|
+
"content-type": "application/json",
|
|
129
|
+
...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}),
|
|
130
|
+
},
|
|
131
|
+
body: JSON.stringify(body),
|
|
132
|
+
signal: ctx.signal,
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
// The pacer couldn't start it (§5.6): nothing left, and for this key-deduplicating port a lost result.
|
|
136
|
+
if ("notStarted" in res) throw new KedgeProviderError("not_started");
|
|
137
|
+
return res;
|
|
138
|
+
};
|
|
139
|
+
return defineEmailTransport({
|
|
140
|
+
version: 1,
|
|
141
|
+
// "Idempotency keys are kept in the system for 24 hours" (https://resend.com/docs/dashboard/emails/idempotency-keys).
|
|
142
|
+
dedupe: { enforced: true, scope: "team", horizonMs: 86_400_000 },
|
|
143
|
+
credentialSecret: "RESEND_API_KEY",
|
|
144
|
+
requestsPerSecond: Math.min(opts.requestsPerSecond ?? 5, 5),
|
|
145
|
+
failures: [...RESEND_FAILURES],
|
|
146
|
+
contentDetermined: [...RESEND_CONTENT_DETERMINED],
|
|
147
|
+
// Resend's keys carry no test or live mark (§5.3): a preview refuses Resend and captures instead.
|
|
148
|
+
credentialMode: async () => "unknown",
|
|
149
|
+
// No team identity a key can read (§5.3): the binding is the key itself, by digest, so any change of key is a
|
|
150
|
+
// new binding and an uncertain send made under the old one is never resent under the new one.
|
|
151
|
+
account: async (ctx) =>
|
|
152
|
+
`key:${hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(ctx.credential))).slice(0, 32)}`,
|
|
153
|
+
async send(ctx, message, providerKey) {
|
|
154
|
+
const res = await post(ctx, resendBody(message), providerKey);
|
|
155
|
+
if (res.status >= 200 && res.status < 300) {
|
|
156
|
+
const id = ((await res.json()) as { id?: unknown }).id;
|
|
157
|
+
if (typeof id !== "string" || !id) throw new KedgeProviderError("http_error");
|
|
158
|
+
if (dropsResponse(opts.dropResponseOnceTo, message.to, Date.now()))
|
|
159
|
+
throw new Error("gate: response dropped after Resend accepted the send");
|
|
160
|
+
return { messageId: id };
|
|
161
|
+
}
|
|
162
|
+
throw await refusal(res);
|
|
163
|
+
},
|
|
164
|
+
async direct(ctx, message: DirectEmail) {
|
|
165
|
+
const res = await post(ctx, {
|
|
166
|
+
from: message.from,
|
|
167
|
+
to: [message.to],
|
|
168
|
+
subject: message.subject,
|
|
169
|
+
text: message.text,
|
|
170
|
+
...(message.html ? { html: message.html } : {}),
|
|
171
|
+
});
|
|
172
|
+
if (res.status < 200 || res.status >= 300) throw await refusal(res);
|
|
173
|
+
// The gate's hook (P1.11b §11): a test send's response lost after Resend accepted it. Only the id is logged,
|
|
174
|
+
// so the gate can ask Resend for that one email; the attempt must then answer `unknown`.
|
|
175
|
+
if (dropsResponse(opts.dropResponseOnceTo, message.to, Date.now())) {
|
|
176
|
+
const id = String(((await res.json().catch(() => ({}))) as { id?: unknown }).id ?? "");
|
|
177
|
+
console.log(JSON.stringify({ event: "gate_dropped", id }));
|
|
178
|
+
throw new Error("gate: response dropped after Resend accepted the send");
|
|
179
|
+
}
|
|
180
|
+
await res.body?.cancel().catch(() => {});
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const parseOptions = (raw: unknown): ResendOptions => {
|
|
186
|
+
const o = (raw ?? {}) as ResendOptions;
|
|
187
|
+
if (o.requestsPerSecond !== undefined && !(o.requestsPerSecond > 0 && o.requestsPerSecond <= 5))
|
|
188
|
+
// kedge-allow no-dynamic-throw: a fixed configuration message
|
|
189
|
+
throw new Error("resend: requestsPerSecond is above 0 and at most 5");
|
|
190
|
+
return o;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The plugin, ready for `plugins: [...]`, with its transport built from `opts`: a store's lower rate, or a gate's
|
|
195
|
+
* test hook. It returns the instance, not a factory: `definePlugin` gives a factory, and handing that to `plugins`
|
|
196
|
+
* failed the store's typecheck (the P1.11a gate). The port's contract (its name, dedupe and failures) is the same
|
|
197
|
+
* whatever the options, so the lock doesn't move.
|
|
198
|
+
*/
|
|
199
|
+
export function resendPlugin(raw?: unknown): PluginInstance<ResendOptions> {
|
|
200
|
+
const opts = parseOptions(raw);
|
|
201
|
+
return definePlugin<ResendOptions>({
|
|
202
|
+
name: "resend",
|
|
203
|
+
version: "1.0.0",
|
|
204
|
+
parseOptions,
|
|
205
|
+
email: resendTransport(opts),
|
|
206
|
+
})(opts);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** `plugins: [resend()]`, as `@kedge/plugin-stripe`'s default export is used. */
|
|
210
|
+
export default resendPlugin;
|