@lovable.dev/email-js 0.1.0-rc.2 → 0.1.0-rc.4
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/README.md +41 -0
- package/dist/index.cjs +148 -49
- package/dist/index.d.cts +45 -9
- package/dist/index.d.ts +45 -9
- package/dist/index.js +137 -49
- package/package.json +21 -1
package/README.md
CHANGED
|
@@ -153,3 +153,44 @@ registered handler are acknowledged with 200. A handler that throws returns
|
|
|
153
153
|
500 and the delivery is retried (up to 5 attempts in total, with backoff) —
|
|
154
154
|
use `event.event_id` (also sent as the `X-Lovable-Delivery` header) to
|
|
155
155
|
deduplicate redeliveries.
|
|
156
|
+
|
|
157
|
+
### Handling auth email webhooks
|
|
158
|
+
|
|
159
|
+
`createAuthEmailHandler` is the auth counterpart: it verifies the delivery the
|
|
160
|
+
same way, then renders and sends the requested auth email (requires the
|
|
161
|
+
optional `react` and `@react-email/render` peer dependencies). The `emails`
|
|
162
|
+
map is total — all six action types (`signup`, `invite`, `magiclink`,
|
|
163
|
+
`recovery`, `email_change`, `reauthentication`) must be present, so a missing
|
|
164
|
+
handler is a compile error rather than a silently-unsent password reset.
|
|
165
|
+
|
|
166
|
+
```tsx
|
|
167
|
+
import { createAuthEmailHandler } from "@lovable.dev/email-js";
|
|
168
|
+
|
|
169
|
+
const handler = createAuthEmailHandler({
|
|
170
|
+
apiKey: process.env.LOVABLE_API_KEY!,
|
|
171
|
+
from: "My App <noreply@notify.example.com>", // sender domain derived from the address
|
|
172
|
+
sendUrl: process.env.LOVABLE_SEND_URL,
|
|
173
|
+
emails: {
|
|
174
|
+
signup: { subject: "Confirm your email", render: (data) => <SignupEmail confirmationUrl={data.url} /> },
|
|
175
|
+
invite: { subject: "You've been invited", render: (data) => <InviteEmail confirmationUrl={data.url} /> },
|
|
176
|
+
magiclink: { subject: "Your login link", render: (data) => <MagicLinkEmail confirmationUrl={data.url} /> },
|
|
177
|
+
recovery: { subject: "Reset your password", render: (data) => <RecoveryEmail confirmationUrl={data.url} /> },
|
|
178
|
+
email_change: { subject: "Confirm your new email", render: (data) => <EmailChangeEmail confirmationUrl={data.url} /> },
|
|
179
|
+
reauthentication: { subject: "Your verification code", render: (data) => <ReauthenticationEmail token={data.token ?? ""} /> },
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`render` may be async — look up personalization data first, and fall back
|
|
185
|
+
(`?? "friend"`) instead of throwing when it's missing: auth emails are
|
|
186
|
+
load-bearing. A per-type entry can also be a single async function returning
|
|
187
|
+
`{ subject, element }` when subject and body share one lookup.
|
|
188
|
+
|
|
189
|
+
The auth webhook is a work request, not a notification, so its failure
|
|
190
|
+
semantics differ from `createEmailWebhookHandler`: unknown action types and
|
|
191
|
+
payload versions return 400 (a permanent delivery failure recorded on the
|
|
192
|
+
run) instead of being acked, and a render failure or retryable send failure
|
|
193
|
+
returns 500 so the delivery is retried — the payload's `run_id` doubles as
|
|
194
|
+
the send idempotency key, so retries cannot double-send. Permanent send
|
|
195
|
+
rejections (for example an expired run) also return 400 rather than burning
|
|
196
|
+
retries on a deterministic failure.
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,12 +17,21 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
21
31
|
var src_exports = {};
|
|
22
32
|
__export(src_exports, {
|
|
23
33
|
EmailAPIError: () => EmailAPIError,
|
|
34
|
+
createAuthEmailHandler: () => createAuthEmailHandler,
|
|
24
35
|
createEmailWebhookHandler: () => createEmailWebhookHandler,
|
|
25
36
|
getEmailUnsubscribe: () => getEmailUnsubscribe,
|
|
26
37
|
listEmailLogs: () => listEmailLogs,
|
|
@@ -30,6 +41,9 @@ __export(src_exports, {
|
|
|
30
41
|
});
|
|
31
42
|
module.exports = __toCommonJS(src_exports);
|
|
32
43
|
|
|
44
|
+
// src/auth-email-handler.ts
|
|
45
|
+
var import_webhooks_js2 = require("@lovable.dev/webhooks-js");
|
|
46
|
+
|
|
33
47
|
// src/http.ts
|
|
34
48
|
var DEFAULT_AUTH_HEADER = "Authorization";
|
|
35
49
|
var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
|
|
@@ -79,11 +93,16 @@ async function throwIfNotOk(response) {
|
|
|
79
93
|
return;
|
|
80
94
|
const errorText = await response.text();
|
|
81
95
|
const safeErrorText = errorText.length > 500 ? `${errorText.slice(0, 500)}...` : errorText;
|
|
96
|
+
const retryAfterSeconds = parseRetryAfter(response.headers.get("Retry-After"));
|
|
97
|
+
const code = parseErrorCode(errorText);
|
|
98
|
+
if (response.status === 429) {
|
|
99
|
+
console.error("[email-js] rate limited:", { status: response.status, code, retryAfterSeconds });
|
|
100
|
+
}
|
|
82
101
|
throw new EmailAPIError(
|
|
83
102
|
response.status,
|
|
84
103
|
`Email API error: ${response.status} ${safeErrorText}`,
|
|
85
|
-
|
|
86
|
-
|
|
104
|
+
retryAfterSeconds,
|
|
105
|
+
code
|
|
87
106
|
);
|
|
88
107
|
}
|
|
89
108
|
async function emailApiRequest(options, path, init = { method: "GET" }) {
|
|
@@ -132,52 +151,8 @@ async function sendLovableEmail(payload, options) {
|
|
|
132
151
|
return await response.json();
|
|
133
152
|
}
|
|
134
153
|
|
|
135
|
-
// src/
|
|
136
|
-
var
|
|
137
|
-
function buildLogsQuery(filters) {
|
|
138
|
-
const params = new URLSearchParams();
|
|
139
|
-
if (filters.recipient)
|
|
140
|
-
params.set("recipient", filters.recipient);
|
|
141
|
-
if (filters.event_type)
|
|
142
|
-
params.set("event_type", filters.event_type);
|
|
143
|
-
if (filters.status)
|
|
144
|
-
params.set("status", filters.status);
|
|
145
|
-
if (filters.tag)
|
|
146
|
-
params.set("tag", filters.tag);
|
|
147
|
-
if (filters.since)
|
|
148
|
-
params.set("since", filters.since);
|
|
149
|
-
if (filters.until)
|
|
150
|
-
params.set("until", filters.until);
|
|
151
|
-
if (filters.limit !== void 0)
|
|
152
|
-
params.set("limit", String(filters.limit));
|
|
153
|
-
if (filters.cursor)
|
|
154
|
-
params.set("cursor", filters.cursor);
|
|
155
|
-
const query = params.toString();
|
|
156
|
-
return query ? `?${query}` : "";
|
|
157
|
-
}
|
|
158
|
-
async function listEmailLogs(filters, options) {
|
|
159
|
-
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
160
|
-
return { ...body, data: body.data ?? [] };
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// src/unsubscribe.ts
|
|
164
|
-
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
165
|
-
function buildUnsubscribePath(recipient, domain) {
|
|
166
|
-
if (!recipient.includes("@")) {
|
|
167
|
-
throw new Error("Invalid recipient");
|
|
168
|
-
}
|
|
169
|
-
const query = new URLSearchParams({ domain }).toString();
|
|
170
|
-
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
171
|
-
}
|
|
172
|
-
async function getEmailUnsubscribe(request, options) {
|
|
173
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
174
|
-
}
|
|
175
|
-
async function setEmailUnsubscribe(request, options) {
|
|
176
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
177
|
-
method: "PUT",
|
|
178
|
-
body: { subscribed: request.subscribed }
|
|
179
|
-
});
|
|
180
|
-
}
|
|
154
|
+
// src/webhook-handler.ts
|
|
155
|
+
var import_webhooks_js = require("@lovable.dev/webhooks-js");
|
|
181
156
|
|
|
182
157
|
// src/webhook.ts
|
|
183
158
|
function parseEmailWebhookPayload(body) {
|
|
@@ -193,7 +168,6 @@ function parseEmailWebhookPayload(body) {
|
|
|
193
168
|
}
|
|
194
169
|
|
|
195
170
|
// src/webhook-handler.ts
|
|
196
|
-
var import_webhooks_js = require("@lovable.dev/webhooks-js");
|
|
197
171
|
var WEBHOOK_ERROR_STATUS = {
|
|
198
172
|
missing_secret: 401,
|
|
199
173
|
missing_timestamp: 401,
|
|
@@ -241,9 +215,134 @@ function createEmailWebhookHandler(options) {
|
|
|
241
215
|
return Response.json({ received: true });
|
|
242
216
|
};
|
|
243
217
|
}
|
|
218
|
+
|
|
219
|
+
// src/auth-email-handler.ts
|
|
220
|
+
function parseAuthEmailWebhookPayload(body) {
|
|
221
|
+
const parsed = JSON.parse(body);
|
|
222
|
+
const payload = parsed;
|
|
223
|
+
if (!parsed || typeof parsed !== "object" || typeof payload.version !== "string" || payload.type !== "auth" || !payload.data || typeof payload.data !== "object" || typeof payload.data.action_type !== "string" || typeof payload.data.email !== "string") {
|
|
224
|
+
throw new Error("Invalid auth email webhook payload");
|
|
225
|
+
}
|
|
226
|
+
return payload;
|
|
227
|
+
}
|
|
228
|
+
function domainOfAddress(from) {
|
|
229
|
+
const match = /@([^@\s<>]+)>?\s*$/.exec(from.trim());
|
|
230
|
+
return match?.[1];
|
|
231
|
+
}
|
|
232
|
+
function createAuthEmailHandler(options) {
|
|
233
|
+
const { apiKey, from, emails } = options;
|
|
234
|
+
if (!apiKey) {
|
|
235
|
+
throw new Error("Missing Lovable API key");
|
|
236
|
+
}
|
|
237
|
+
const senderDomain = options.senderDomain ?? domainOfAddress(from);
|
|
238
|
+
if (!senderDomain) {
|
|
239
|
+
throw new Error(`Cannot derive a sender domain from "${from}"; pass senderDomain`);
|
|
240
|
+
}
|
|
241
|
+
return async (req) => {
|
|
242
|
+
if (req.method !== "POST") {
|
|
243
|
+
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
|
|
244
|
+
}
|
|
245
|
+
let event;
|
|
246
|
+
try {
|
|
247
|
+
({ payload: event } = await (0, import_webhooks_js2.verifyWebhookRequest)({ req, secret: apiKey, parser: parseAuthEmailWebhookPayload }));
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (error instanceof import_webhooks_js2.WebhookError) {
|
|
250
|
+
return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
|
|
251
|
+
}
|
|
252
|
+
console.error("[email-js] auth webhook verification failed:", error);
|
|
253
|
+
return Response.json({ error: "Webhook verification failed" }, { status: 500 });
|
|
254
|
+
}
|
|
255
|
+
if (!event.run_id) {
|
|
256
|
+
return Response.json({ error: "Missing run_id" }, { status: 400 });
|
|
257
|
+
}
|
|
258
|
+
if (event.version !== "1") {
|
|
259
|
+
return Response.json({ error: `Unsupported payload version: ${event.version}` }, { status: 400 });
|
|
260
|
+
}
|
|
261
|
+
const actionType = event.data.action_type;
|
|
262
|
+
const definition = Object.prototype.hasOwnProperty.call(emails, actionType) ? emails[actionType] : void 0;
|
|
263
|
+
if (!definition) {
|
|
264
|
+
return Response.json({ error: `Unknown auth email action type: ${actionType}` }, { status: 400 });
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
const { render } = await import("@react-email/render");
|
|
268
|
+
const { subject, element } = typeof definition === "function" ? await definition(event.data) : { subject: definition.subject, element: await definition.render(event.data) };
|
|
269
|
+
const html = await render(element);
|
|
270
|
+
const text = await render(element, { plainText: true });
|
|
271
|
+
await sendLovableEmail(
|
|
272
|
+
{
|
|
273
|
+
run_id: event.run_id,
|
|
274
|
+
to: event.data.email,
|
|
275
|
+
from,
|
|
276
|
+
sender_domain: senderDomain,
|
|
277
|
+
subject,
|
|
278
|
+
html,
|
|
279
|
+
text,
|
|
280
|
+
purpose: "transactional",
|
|
281
|
+
label: actionType
|
|
282
|
+
},
|
|
283
|
+
{ apiKey, sendUrl: options.sendUrl }
|
|
284
|
+
);
|
|
285
|
+
} catch (error) {
|
|
286
|
+
console.error("[email-js] auth email send failed:", error);
|
|
287
|
+
if (error instanceof EmailAPIError && !error.retryable) {
|
|
288
|
+
return Response.json({ error: "Email send rejected" }, { status: 400 });
|
|
289
|
+
}
|
|
290
|
+
return Response.json({ error: "Failed to send email" }, { status: 500 });
|
|
291
|
+
}
|
|
292
|
+
return Response.json({ success: true, sent: true });
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// src/logs.ts
|
|
297
|
+
var LOGS_PATH = "/v1/messaging/email/logs";
|
|
298
|
+
function buildLogsQuery(filters) {
|
|
299
|
+
const params = new URLSearchParams();
|
|
300
|
+
if (filters.recipient)
|
|
301
|
+
params.set("recipient", filters.recipient);
|
|
302
|
+
if (filters.event_type)
|
|
303
|
+
params.set("event_type", filters.event_type);
|
|
304
|
+
if (filters.status)
|
|
305
|
+
params.set("status", filters.status);
|
|
306
|
+
if (filters.tag)
|
|
307
|
+
params.set("tag", filters.tag);
|
|
308
|
+
if (filters.since)
|
|
309
|
+
params.set("since", filters.since);
|
|
310
|
+
if (filters.until)
|
|
311
|
+
params.set("until", filters.until);
|
|
312
|
+
if (filters.limit !== void 0)
|
|
313
|
+
params.set("limit", String(filters.limit));
|
|
314
|
+
if (filters.cursor)
|
|
315
|
+
params.set("cursor", filters.cursor);
|
|
316
|
+
const query = params.toString();
|
|
317
|
+
return query ? `?${query}` : "";
|
|
318
|
+
}
|
|
319
|
+
async function listEmailLogs(filters, options) {
|
|
320
|
+
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
321
|
+
return { ...body, data: body.data ?? [] };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/unsubscribe.ts
|
|
325
|
+
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
326
|
+
function buildUnsubscribePath(recipient, domain) {
|
|
327
|
+
if (!recipient.includes("@")) {
|
|
328
|
+
throw new Error("Invalid recipient");
|
|
329
|
+
}
|
|
330
|
+
const query = new URLSearchParams({ domain }).toString();
|
|
331
|
+
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
332
|
+
}
|
|
333
|
+
async function getEmailUnsubscribe(request, options) {
|
|
334
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
335
|
+
}
|
|
336
|
+
async function setEmailUnsubscribe(request, options) {
|
|
337
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
338
|
+
method: "PUT",
|
|
339
|
+
body: { subscribed: request.subscribed }
|
|
340
|
+
});
|
|
341
|
+
}
|
|
244
342
|
// Annotate the CommonJS export names for ESM import in node:
|
|
245
343
|
0 && (module.exports = {
|
|
246
344
|
EmailAPIError,
|
|
345
|
+
createAuthEmailHandler,
|
|
247
346
|
createEmailWebhookHandler,
|
|
248
347
|
getEmailUnsubscribe,
|
|
249
348
|
listEmailLogs,
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ReactElement } from 'react';
|
|
1
2
|
import { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
2
3
|
export { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
3
4
|
|
|
@@ -28,7 +29,7 @@ interface SendEmailOptions {
|
|
|
28
29
|
apiKey: string;
|
|
29
30
|
authHeader?: string;
|
|
30
31
|
apiBaseUrl?: string;
|
|
31
|
-
sendUrl?: string;
|
|
32
|
+
sendUrl?: string | undefined;
|
|
32
33
|
idempotencyKey?: string;
|
|
33
34
|
}
|
|
34
35
|
interface EmailClientOptions {
|
|
@@ -61,6 +62,8 @@ interface EmailLogsPagination {
|
|
|
61
62
|
interface ListEmailLogsResponse {
|
|
62
63
|
data: EmailEvent[];
|
|
63
64
|
pagination: EmailLogsPagination;
|
|
65
|
+
/** Earliest timestamp visible under the workspace plan's retention window; an older `since` is clamped to it. */
|
|
66
|
+
history_starts_at: string;
|
|
64
67
|
}
|
|
65
68
|
interface GetEmailUnsubscribeRequest {
|
|
66
69
|
recipient: string;
|
|
@@ -77,21 +80,22 @@ interface EmailUnsubscribeResponse {
|
|
|
77
80
|
subscribed: boolean;
|
|
78
81
|
}
|
|
79
82
|
type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
|
|
80
|
-
interface
|
|
83
|
+
interface WebhookEnvelope<Type extends string, Data> {
|
|
81
84
|
event_id: string;
|
|
82
85
|
run_id: string;
|
|
83
|
-
type:
|
|
86
|
+
type: Type;
|
|
84
87
|
project_id: string;
|
|
85
88
|
environment: "dev" | "prod";
|
|
86
|
-
data:
|
|
87
|
-
event: T;
|
|
88
|
-
recipient: string;
|
|
89
|
-
message_id: string;
|
|
90
|
-
};
|
|
89
|
+
data: Data;
|
|
91
90
|
timestamp: string;
|
|
92
91
|
version: string;
|
|
93
92
|
replay_id?: string;
|
|
94
93
|
}
|
|
94
|
+
type EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> = WebhookEnvelope<T, {
|
|
95
|
+
event: T;
|
|
96
|
+
recipient: string;
|
|
97
|
+
message_id: string;
|
|
98
|
+
}>;
|
|
95
99
|
type EmailWebhookHandlers = {
|
|
96
100
|
[T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
|
|
97
101
|
};
|
|
@@ -99,6 +103,38 @@ interface EmailWebhookHandlerOptions {
|
|
|
99
103
|
apiKey: string;
|
|
100
104
|
on: EmailWebhookHandlers;
|
|
101
105
|
}
|
|
106
|
+
type AuthEmailActionType = "signup" | "invite" | "magiclink" | "recovery" | "email_change" | "reauthentication";
|
|
107
|
+
interface AuthEmailHookData {
|
|
108
|
+
action_type: AuthEmailActionType;
|
|
109
|
+
url: string;
|
|
110
|
+
email: string;
|
|
111
|
+
old_email: string | null;
|
|
112
|
+
new_email: string | null;
|
|
113
|
+
site_url: string | null;
|
|
114
|
+
token: string | null;
|
|
115
|
+
new_token: string | null;
|
|
116
|
+
callback_url?: string;
|
|
117
|
+
}
|
|
118
|
+
type AuthEmailWebhookPayload = WebhookEnvelope<"auth", AuthEmailHookData>;
|
|
119
|
+
interface AuthEmailContent {
|
|
120
|
+
subject: string;
|
|
121
|
+
element: ReactElement;
|
|
122
|
+
}
|
|
123
|
+
type AuthEmailDefinition = {
|
|
124
|
+
subject: string;
|
|
125
|
+
render: (data: AuthEmailHookData) => ReactElement | Promise<ReactElement>;
|
|
126
|
+
} | ((data: AuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
|
|
127
|
+
type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
|
|
128
|
+
interface AuthEmailHandlerOptions {
|
|
129
|
+
apiKey: string;
|
|
130
|
+
from: string;
|
|
131
|
+
/** Defaults to the domain of `from`. */
|
|
132
|
+
senderDomain?: string;
|
|
133
|
+
sendUrl?: string | undefined;
|
|
134
|
+
emails: AuthEmailDefinitions;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare function createAuthEmailHandler(options: AuthEmailHandlerOptions): (req: Request) => Promise<Response>;
|
|
102
138
|
|
|
103
139
|
declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
|
|
104
140
|
|
|
@@ -119,4 +155,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
|
|
|
119
155
|
|
|
120
156
|
declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
|
|
121
157
|
|
|
122
|
-
export { EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
|
158
|
+
export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ReactElement } from 'react';
|
|
1
2
|
import { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
2
3
|
export { EmailWebhookPayload } from '@lovable.dev/webhooks-js';
|
|
3
4
|
|
|
@@ -28,7 +29,7 @@ interface SendEmailOptions {
|
|
|
28
29
|
apiKey: string;
|
|
29
30
|
authHeader?: string;
|
|
30
31
|
apiBaseUrl?: string;
|
|
31
|
-
sendUrl?: string;
|
|
32
|
+
sendUrl?: string | undefined;
|
|
32
33
|
idempotencyKey?: string;
|
|
33
34
|
}
|
|
34
35
|
interface EmailClientOptions {
|
|
@@ -61,6 +62,8 @@ interface EmailLogsPagination {
|
|
|
61
62
|
interface ListEmailLogsResponse {
|
|
62
63
|
data: EmailEvent[];
|
|
63
64
|
pagination: EmailLogsPagination;
|
|
65
|
+
/** Earliest timestamp visible under the workspace plan's retention window; an older `since` is clamped to it. */
|
|
66
|
+
history_starts_at: string;
|
|
64
67
|
}
|
|
65
68
|
interface GetEmailUnsubscribeRequest {
|
|
66
69
|
recipient: string;
|
|
@@ -77,21 +80,22 @@ interface EmailUnsubscribeResponse {
|
|
|
77
80
|
subscribed: boolean;
|
|
78
81
|
}
|
|
79
82
|
type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
|
|
80
|
-
interface
|
|
83
|
+
interface WebhookEnvelope<Type extends string, Data> {
|
|
81
84
|
event_id: string;
|
|
82
85
|
run_id: string;
|
|
83
|
-
type:
|
|
86
|
+
type: Type;
|
|
84
87
|
project_id: string;
|
|
85
88
|
environment: "dev" | "prod";
|
|
86
|
-
data:
|
|
87
|
-
event: T;
|
|
88
|
-
recipient: string;
|
|
89
|
-
message_id: string;
|
|
90
|
-
};
|
|
89
|
+
data: Data;
|
|
91
90
|
timestamp: string;
|
|
92
91
|
version: string;
|
|
93
92
|
replay_id?: string;
|
|
94
93
|
}
|
|
94
|
+
type EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> = WebhookEnvelope<T, {
|
|
95
|
+
event: T;
|
|
96
|
+
recipient: string;
|
|
97
|
+
message_id: string;
|
|
98
|
+
}>;
|
|
95
99
|
type EmailWebhookHandlers = {
|
|
96
100
|
[T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
|
|
97
101
|
};
|
|
@@ -99,6 +103,38 @@ interface EmailWebhookHandlerOptions {
|
|
|
99
103
|
apiKey: string;
|
|
100
104
|
on: EmailWebhookHandlers;
|
|
101
105
|
}
|
|
106
|
+
type AuthEmailActionType = "signup" | "invite" | "magiclink" | "recovery" | "email_change" | "reauthentication";
|
|
107
|
+
interface AuthEmailHookData {
|
|
108
|
+
action_type: AuthEmailActionType;
|
|
109
|
+
url: string;
|
|
110
|
+
email: string;
|
|
111
|
+
old_email: string | null;
|
|
112
|
+
new_email: string | null;
|
|
113
|
+
site_url: string | null;
|
|
114
|
+
token: string | null;
|
|
115
|
+
new_token: string | null;
|
|
116
|
+
callback_url?: string;
|
|
117
|
+
}
|
|
118
|
+
type AuthEmailWebhookPayload = WebhookEnvelope<"auth", AuthEmailHookData>;
|
|
119
|
+
interface AuthEmailContent {
|
|
120
|
+
subject: string;
|
|
121
|
+
element: ReactElement;
|
|
122
|
+
}
|
|
123
|
+
type AuthEmailDefinition = {
|
|
124
|
+
subject: string;
|
|
125
|
+
render: (data: AuthEmailHookData) => ReactElement | Promise<ReactElement>;
|
|
126
|
+
} | ((data: AuthEmailHookData) => AuthEmailContent | Promise<AuthEmailContent>);
|
|
127
|
+
type AuthEmailDefinitions = Record<AuthEmailActionType, AuthEmailDefinition>;
|
|
128
|
+
interface AuthEmailHandlerOptions {
|
|
129
|
+
apiKey: string;
|
|
130
|
+
from: string;
|
|
131
|
+
/** Defaults to the domain of `from`. */
|
|
132
|
+
senderDomain?: string;
|
|
133
|
+
sendUrl?: string | undefined;
|
|
134
|
+
emails: AuthEmailDefinitions;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare function createAuthEmailHandler(options: AuthEmailHandlerOptions): (req: Request) => Promise<Response>;
|
|
102
138
|
|
|
103
139
|
declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
|
|
104
140
|
|
|
@@ -119,4 +155,4 @@ declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
|
|
|
119
155
|
|
|
120
156
|
declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
|
|
121
157
|
|
|
122
|
-
export { EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
|
158
|
+
export { type AuthEmailActionType, type AuthEmailContent, type AuthEmailDefinition, type AuthEmailDefinitions, type AuthEmailHandlerOptions, type AuthEmailHookData, type AuthEmailWebhookPayload, EmailAPIError, type EmailClientOptions, type EmailEvent, type EmailLogsPagination, type EmailSendRequest, type EmailSendResponse, type EmailUnsubscribeResponse, type EmailWebhookEvent, type EmailWebhookEventType, type EmailWebhookHandlerOptions, type EmailWebhookHandlers, type GetEmailUnsubscribeRequest, type ListEmailLogsFilters, type ListEmailLogsResponse, type SendEmailOptions, type SetEmailUnsubscribeRequest, createAuthEmailHandler, createEmailWebhookHandler, getEmailUnsubscribe, listEmailLogs, parseEmailWebhookPayload, sendLovableEmail, setEmailUnsubscribe };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// src/auth-email-handler.ts
|
|
2
|
+
import { WebhookError as WebhookError2, verifyWebhookRequest as verifyWebhookRequest2 } from "@lovable.dev/webhooks-js";
|
|
3
|
+
|
|
1
4
|
// src/http.ts
|
|
2
5
|
var DEFAULT_AUTH_HEADER = "Authorization";
|
|
3
6
|
var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
|
|
@@ -47,11 +50,16 @@ async function throwIfNotOk(response) {
|
|
|
47
50
|
return;
|
|
48
51
|
const errorText = await response.text();
|
|
49
52
|
const safeErrorText = errorText.length > 500 ? `${errorText.slice(0, 500)}...` : errorText;
|
|
53
|
+
const retryAfterSeconds = parseRetryAfter(response.headers.get("Retry-After"));
|
|
54
|
+
const code = parseErrorCode(errorText);
|
|
55
|
+
if (response.status === 429) {
|
|
56
|
+
console.error("[email-js] rate limited:", { status: response.status, code, retryAfterSeconds });
|
|
57
|
+
}
|
|
50
58
|
throw new EmailAPIError(
|
|
51
59
|
response.status,
|
|
52
60
|
`Email API error: ${response.status} ${safeErrorText}`,
|
|
53
|
-
|
|
54
|
-
|
|
61
|
+
retryAfterSeconds,
|
|
62
|
+
code
|
|
55
63
|
);
|
|
56
64
|
}
|
|
57
65
|
async function emailApiRequest(options, path, init = { method: "GET" }) {
|
|
@@ -100,52 +108,8 @@ async function sendLovableEmail(payload, options) {
|
|
|
100
108
|
return await response.json();
|
|
101
109
|
}
|
|
102
110
|
|
|
103
|
-
// src/
|
|
104
|
-
|
|
105
|
-
function buildLogsQuery(filters) {
|
|
106
|
-
const params = new URLSearchParams();
|
|
107
|
-
if (filters.recipient)
|
|
108
|
-
params.set("recipient", filters.recipient);
|
|
109
|
-
if (filters.event_type)
|
|
110
|
-
params.set("event_type", filters.event_type);
|
|
111
|
-
if (filters.status)
|
|
112
|
-
params.set("status", filters.status);
|
|
113
|
-
if (filters.tag)
|
|
114
|
-
params.set("tag", filters.tag);
|
|
115
|
-
if (filters.since)
|
|
116
|
-
params.set("since", filters.since);
|
|
117
|
-
if (filters.until)
|
|
118
|
-
params.set("until", filters.until);
|
|
119
|
-
if (filters.limit !== void 0)
|
|
120
|
-
params.set("limit", String(filters.limit));
|
|
121
|
-
if (filters.cursor)
|
|
122
|
-
params.set("cursor", filters.cursor);
|
|
123
|
-
const query = params.toString();
|
|
124
|
-
return query ? `?${query}` : "";
|
|
125
|
-
}
|
|
126
|
-
async function listEmailLogs(filters, options) {
|
|
127
|
-
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
128
|
-
return { ...body, data: body.data ?? [] };
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// src/unsubscribe.ts
|
|
132
|
-
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
133
|
-
function buildUnsubscribePath(recipient, domain) {
|
|
134
|
-
if (!recipient.includes("@")) {
|
|
135
|
-
throw new Error("Invalid recipient");
|
|
136
|
-
}
|
|
137
|
-
const query = new URLSearchParams({ domain }).toString();
|
|
138
|
-
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
139
|
-
}
|
|
140
|
-
async function getEmailUnsubscribe(request, options) {
|
|
141
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
142
|
-
}
|
|
143
|
-
async function setEmailUnsubscribe(request, options) {
|
|
144
|
-
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
145
|
-
method: "PUT",
|
|
146
|
-
body: { subscribed: request.subscribed }
|
|
147
|
-
});
|
|
148
|
-
}
|
|
111
|
+
// src/webhook-handler.ts
|
|
112
|
+
import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
|
|
149
113
|
|
|
150
114
|
// src/webhook.ts
|
|
151
115
|
function parseEmailWebhookPayload(body) {
|
|
@@ -161,7 +125,6 @@ function parseEmailWebhookPayload(body) {
|
|
|
161
125
|
}
|
|
162
126
|
|
|
163
127
|
// src/webhook-handler.ts
|
|
164
|
-
import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
|
|
165
128
|
var WEBHOOK_ERROR_STATUS = {
|
|
166
129
|
missing_secret: 401,
|
|
167
130
|
missing_timestamp: 401,
|
|
@@ -209,8 +172,133 @@ function createEmailWebhookHandler(options) {
|
|
|
209
172
|
return Response.json({ received: true });
|
|
210
173
|
};
|
|
211
174
|
}
|
|
175
|
+
|
|
176
|
+
// src/auth-email-handler.ts
|
|
177
|
+
function parseAuthEmailWebhookPayload(body) {
|
|
178
|
+
const parsed = JSON.parse(body);
|
|
179
|
+
const payload = parsed;
|
|
180
|
+
if (!parsed || typeof parsed !== "object" || typeof payload.version !== "string" || payload.type !== "auth" || !payload.data || typeof payload.data !== "object" || typeof payload.data.action_type !== "string" || typeof payload.data.email !== "string") {
|
|
181
|
+
throw new Error("Invalid auth email webhook payload");
|
|
182
|
+
}
|
|
183
|
+
return payload;
|
|
184
|
+
}
|
|
185
|
+
function domainOfAddress(from) {
|
|
186
|
+
const match = /@([^@\s<>]+)>?\s*$/.exec(from.trim());
|
|
187
|
+
return match?.[1];
|
|
188
|
+
}
|
|
189
|
+
function createAuthEmailHandler(options) {
|
|
190
|
+
const { apiKey, from, emails } = options;
|
|
191
|
+
if (!apiKey) {
|
|
192
|
+
throw new Error("Missing Lovable API key");
|
|
193
|
+
}
|
|
194
|
+
const senderDomain = options.senderDomain ?? domainOfAddress(from);
|
|
195
|
+
if (!senderDomain) {
|
|
196
|
+
throw new Error(`Cannot derive a sender domain from "${from}"; pass senderDomain`);
|
|
197
|
+
}
|
|
198
|
+
return async (req) => {
|
|
199
|
+
if (req.method !== "POST") {
|
|
200
|
+
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
|
|
201
|
+
}
|
|
202
|
+
let event;
|
|
203
|
+
try {
|
|
204
|
+
({ payload: event } = await verifyWebhookRequest2({ req, secret: apiKey, parser: parseAuthEmailWebhookPayload }));
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (error instanceof WebhookError2) {
|
|
207
|
+
return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
|
|
208
|
+
}
|
|
209
|
+
console.error("[email-js] auth webhook verification failed:", error);
|
|
210
|
+
return Response.json({ error: "Webhook verification failed" }, { status: 500 });
|
|
211
|
+
}
|
|
212
|
+
if (!event.run_id) {
|
|
213
|
+
return Response.json({ error: "Missing run_id" }, { status: 400 });
|
|
214
|
+
}
|
|
215
|
+
if (event.version !== "1") {
|
|
216
|
+
return Response.json({ error: `Unsupported payload version: ${event.version}` }, { status: 400 });
|
|
217
|
+
}
|
|
218
|
+
const actionType = event.data.action_type;
|
|
219
|
+
const definition = Object.prototype.hasOwnProperty.call(emails, actionType) ? emails[actionType] : void 0;
|
|
220
|
+
if (!definition) {
|
|
221
|
+
return Response.json({ error: `Unknown auth email action type: ${actionType}` }, { status: 400 });
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const { render } = await import("@react-email/render");
|
|
225
|
+
const { subject, element } = typeof definition === "function" ? await definition(event.data) : { subject: definition.subject, element: await definition.render(event.data) };
|
|
226
|
+
const html = await render(element);
|
|
227
|
+
const text = await render(element, { plainText: true });
|
|
228
|
+
await sendLovableEmail(
|
|
229
|
+
{
|
|
230
|
+
run_id: event.run_id,
|
|
231
|
+
to: event.data.email,
|
|
232
|
+
from,
|
|
233
|
+
sender_domain: senderDomain,
|
|
234
|
+
subject,
|
|
235
|
+
html,
|
|
236
|
+
text,
|
|
237
|
+
purpose: "transactional",
|
|
238
|
+
label: actionType
|
|
239
|
+
},
|
|
240
|
+
{ apiKey, sendUrl: options.sendUrl }
|
|
241
|
+
);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
console.error("[email-js] auth email send failed:", error);
|
|
244
|
+
if (error instanceof EmailAPIError && !error.retryable) {
|
|
245
|
+
return Response.json({ error: "Email send rejected" }, { status: 400 });
|
|
246
|
+
}
|
|
247
|
+
return Response.json({ error: "Failed to send email" }, { status: 500 });
|
|
248
|
+
}
|
|
249
|
+
return Response.json({ success: true, sent: true });
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// src/logs.ts
|
|
254
|
+
var LOGS_PATH = "/v1/messaging/email/logs";
|
|
255
|
+
function buildLogsQuery(filters) {
|
|
256
|
+
const params = new URLSearchParams();
|
|
257
|
+
if (filters.recipient)
|
|
258
|
+
params.set("recipient", filters.recipient);
|
|
259
|
+
if (filters.event_type)
|
|
260
|
+
params.set("event_type", filters.event_type);
|
|
261
|
+
if (filters.status)
|
|
262
|
+
params.set("status", filters.status);
|
|
263
|
+
if (filters.tag)
|
|
264
|
+
params.set("tag", filters.tag);
|
|
265
|
+
if (filters.since)
|
|
266
|
+
params.set("since", filters.since);
|
|
267
|
+
if (filters.until)
|
|
268
|
+
params.set("until", filters.until);
|
|
269
|
+
if (filters.limit !== void 0)
|
|
270
|
+
params.set("limit", String(filters.limit));
|
|
271
|
+
if (filters.cursor)
|
|
272
|
+
params.set("cursor", filters.cursor);
|
|
273
|
+
const query = params.toString();
|
|
274
|
+
return query ? `?${query}` : "";
|
|
275
|
+
}
|
|
276
|
+
async function listEmailLogs(filters, options) {
|
|
277
|
+
const body = await emailApiRequest(options, `${LOGS_PATH}${buildLogsQuery(filters)}`);
|
|
278
|
+
return { ...body, data: body.data ?? [] };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// src/unsubscribe.ts
|
|
282
|
+
var UNSUBSCRIBES_PATH = "/v1/messaging/email/unsubscribes";
|
|
283
|
+
function buildUnsubscribePath(recipient, domain) {
|
|
284
|
+
if (!recipient.includes("@")) {
|
|
285
|
+
throw new Error("Invalid recipient");
|
|
286
|
+
}
|
|
287
|
+
const query = new URLSearchParams({ domain }).toString();
|
|
288
|
+
return `${UNSUBSCRIBES_PATH}/${encodeURIComponent(recipient)}?${query}`;
|
|
289
|
+
}
|
|
290
|
+
async function getEmailUnsubscribe(request, options) {
|
|
291
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain));
|
|
292
|
+
}
|
|
293
|
+
async function setEmailUnsubscribe(request, options) {
|
|
294
|
+
return emailApiRequest(options, buildUnsubscribePath(request.recipient, request.domain), {
|
|
295
|
+
method: "PUT",
|
|
296
|
+
body: { subscribed: request.subscribed }
|
|
297
|
+
});
|
|
298
|
+
}
|
|
212
299
|
export {
|
|
213
300
|
EmailAPIError,
|
|
301
|
+
createAuthEmailHandler,
|
|
214
302
|
createEmailWebhookHandler,
|
|
215
303
|
getEmailUnsubscribe,
|
|
216
304
|
listEmailLogs,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lovable.dev/email-js",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.4",
|
|
4
4
|
"description": "Lovable Email JS",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -23,8 +23,28 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@lovable.dev/webhooks-js": "0.0.1"
|
|
25
25
|
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@react-email/render": ">=1.0.0",
|
|
28
|
+
"react": ">=18",
|
|
29
|
+
"react-dom": ">=18"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"@react-email/render": {
|
|
33
|
+
"optional": true
|
|
34
|
+
},
|
|
35
|
+
"react": {
|
|
36
|
+
"optional": true
|
|
37
|
+
},
|
|
38
|
+
"react-dom": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
26
42
|
"devDependencies": {
|
|
43
|
+
"@react-email/render": "^1.0.0",
|
|
27
44
|
"@types/node": "^22",
|
|
45
|
+
"@types/react": "^19",
|
|
46
|
+
"react": "^19.0.0",
|
|
47
|
+
"react-dom": "^19.0.0",
|
|
28
48
|
"rimraf": "^5.0.0",
|
|
29
49
|
"tsup": "^7.2.0",
|
|
30
50
|
"typescript": "^5",
|