@lovable.dev/email-js 0.0.4 → 0.1.0-rc.2

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 CHANGED
@@ -78,3 +78,78 @@ await sendLovableEmail(
78
78
  { apiKey },
79
79
  );
80
80
  ```
81
+
82
+ All clients take the client options (`{ apiKey, apiBaseUrl?, authHeader? }`)
83
+ as their last argument.
84
+
85
+ ### Listing email logs
86
+
87
+ `listEmailLogs` returns recent delivery events for the calling project.
88
+ `since`/`until` are RFC3339 timestamps, clamped server-side to the workspace
89
+ plan's retention window. Results are cursor-paginated (max 100 per page).
90
+
91
+ ```ts
92
+ import { listEmailLogs } from "@lovable.dev/email-js";
93
+
94
+ const { data, pagination } = await listEmailLogs(
95
+ { recipient: "user@example.com", event_type: "delivered", since: "2026-06-01T00:00:00Z", limit: 50 },
96
+ { apiKey },
97
+ );
98
+
99
+ if (pagination.next_cursor) {
100
+ const nextPage = await listEmailLogs({ cursor: pagination.next_cursor }, { apiKey });
101
+ }
102
+ ```
103
+
104
+ ### Managing unsubscribes
105
+
106
+ Unsubscribe state is scoped to the recipient and the sender domain's apex.
107
+ Setting `subscribed: true` lifts a sender-driven unsubscribe; recipients who
108
+ filed a spam complaint cannot be resubscribed — the API responds 409 and the
109
+ thrown `EmailAPIError` has `code === "complaint_not_liftable"`.
110
+
111
+ ```ts
112
+ import { getEmailUnsubscribe, setEmailUnsubscribe } from "@lovable.dev/email-js";
113
+
114
+ const state = await getEmailUnsubscribe(
115
+ { recipient: "user@example.com", domain: "notify.example.com" },
116
+ { apiKey },
117
+ );
118
+
119
+ await setEmailUnsubscribe(
120
+ { recipient: "user@example.com", domain: "notify.example.com", subscribed: false },
121
+ { apiKey },
122
+ );
123
+ ```
124
+
125
+ ### Handling email webhooks
126
+
127
+ `createEmailWebhookHandler` verifies the `X-Lovable-Signature` on each delivery
128
+ (signed with the project's `LOVABLE_API_KEY`) and dispatches to the handler
129
+ registered for the event type. Write only handler bodies — verification stays
130
+ inside the package.
131
+
132
+ ```ts
133
+ import { createEmailWebhookHandler } from "@lovable.dev/email-js";
134
+
135
+ const handler = createEmailWebhookHandler({
136
+ apiKey: Deno.env.get("LOVABLE_API_KEY")!,
137
+ on: {
138
+ "email.bounced": async (event) => {
139
+ await markEmailUndeliverable(event.data.recipient);
140
+ },
141
+ "email.unsubscribed": async (event) => {
142
+ await recordOptOut(event.data.recipient);
143
+ },
144
+ },
145
+ });
146
+
147
+ Deno.serve(handler);
148
+ ```
149
+
150
+ Event types: `email.bounced`, `email.complaint`, `email.unsubscribed`,
151
+ `email.resubscribed` (defined but not yet emitted). Events without a
152
+ registered handler are acknowledged with 200. A handler that throws returns
153
+ 500 and the delivery is retried (up to 5 attempts in total, with backoff) —
154
+ use `event.event_id` (also sent as the `X-Lovable-Delivery` header) to
155
+ deduplicate redeliveries.
package/dist/index.cjs CHANGED
@@ -21,21 +21,28 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  EmailAPIError: () => EmailAPIError,
24
+ createEmailWebhookHandler: () => createEmailWebhookHandler,
25
+ getEmailUnsubscribe: () => getEmailUnsubscribe,
26
+ listEmailLogs: () => listEmailLogs,
24
27
  parseEmailWebhookPayload: () => parseEmailWebhookPayload,
25
- sendLovableEmail: () => sendLovableEmail
28
+ sendLovableEmail: () => sendLovableEmail,
29
+ setEmailUnsubscribe: () => setEmailUnsubscribe
26
30
  });
27
31
  module.exports = __toCommonJS(src_exports);
28
32
 
29
- // src/email.ts
33
+ // src/http.ts
30
34
  var DEFAULT_AUTH_HEADER = "Authorization";
31
35
  var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
32
- var DEFAULT_SEND_PATH = "/v1/messaging/email/send";
36
+ function resolveApiBaseUrl(apiBaseUrl) {
37
+ return (apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
38
+ }
33
39
  var EmailAPIError = class extends Error {
34
- constructor(status, message, retryAfterSeconds) {
40
+ constructor(status, message, retryAfterSeconds, code = null) {
35
41
  super(message);
36
42
  this.name = "EmailAPIError";
37
43
  this.status = status;
38
44
  this.retryAfterSeconds = retryAfterSeconds;
45
+ this.code = code;
39
46
  }
40
47
  get retryable() {
41
48
  return this.status === 429 || this.status >= 500 && this.status < 600;
@@ -56,6 +63,50 @@ function parseRetryAfter(header) {
56
63
  function buildAuthHeaderValue(apiKey) {
57
64
  return `Bearer ${apiKey}`;
58
65
  }
66
+ function parseErrorCode(body) {
67
+ try {
68
+ const parsed = JSON.parse(body);
69
+ if (parsed && typeof parsed === "object" && "type" in parsed && typeof parsed.type === "string") {
70
+ return parsed.type;
71
+ }
72
+ } catch {
73
+ return null;
74
+ }
75
+ return null;
76
+ }
77
+ async function throwIfNotOk(response) {
78
+ if (response.ok)
79
+ return;
80
+ const errorText = await response.text();
81
+ const safeErrorText = errorText.length > 500 ? `${errorText.slice(0, 500)}...` : errorText;
82
+ throw new EmailAPIError(
83
+ response.status,
84
+ `Email API error: ${response.status} ${safeErrorText}`,
85
+ parseRetryAfter(response.headers.get("Retry-After")),
86
+ parseErrorCode(errorText)
87
+ );
88
+ }
89
+ async function emailApiRequest(options, path, init = { method: "GET" }) {
90
+ if (!options.apiKey) {
91
+ throw new Error("Missing Lovable API key");
92
+ }
93
+ const headers = {
94
+ [options.authHeader ?? DEFAULT_AUTH_HEADER]: buildAuthHeaderValue(options.apiKey)
95
+ };
96
+ if (init.body !== void 0) {
97
+ headers["Content-Type"] = "application/json";
98
+ }
99
+ const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
100
+ method: init.method,
101
+ headers,
102
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
103
+ });
104
+ await throwIfNotOk(response);
105
+ return await response.json();
106
+ }
107
+
108
+ // src/email.ts
109
+ var DEFAULT_SEND_PATH = "/v1/messaging/email/send";
59
110
  async function sendLovableEmail(payload, options) {
60
111
  const apiKey = options.apiKey;
61
112
  if (!apiKey) {
@@ -63,8 +114,7 @@ async function sendLovableEmail(payload, options) {
63
114
  }
64
115
  const authHeader = options.authHeader ?? DEFAULT_AUTH_HEADER;
65
116
  const sendUrl = options.sendUrl;
66
- const apiBaseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;
67
- const url = sendUrl || `${apiBaseUrl.replace(/\/$/, "")}${DEFAULT_SEND_PATH}`;
117
+ const url = sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
68
118
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
69
119
  const headers = {
70
120
  [authHeader]: buildAuthHeaderValue(apiKey),
@@ -78,18 +128,57 @@ async function sendLovableEmail(payload, options) {
78
128
  headers,
79
129
  body: JSON.stringify(payload)
80
130
  });
81
- if (!response.ok) {
82
- const errorText = await response.text();
83
- const safeErrorText = errorText.length > 500 ? `${errorText.slice(0, 500)}...` : errorText;
84
- throw new EmailAPIError(
85
- response.status,
86
- `Email API error: ${response.status} ${safeErrorText}`,
87
- parseRetryAfter(response.headers.get("Retry-After"))
88
- );
89
- }
131
+ await throwIfNotOk(response);
90
132
  return await response.json();
91
133
  }
92
134
 
135
+ // src/logs.ts
136
+ var LOGS_PATH = "/v1/messaging/email/logs";
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
+ }
181
+
93
182
  // src/webhook.ts
94
183
  function parseEmailWebhookPayload(body) {
95
184
  const parsed = JSON.parse(body);
@@ -102,9 +191,63 @@ function parseEmailWebhookPayload(body) {
102
191
  }
103
192
  return payload;
104
193
  }
194
+
195
+ // src/webhook-handler.ts
196
+ var import_webhooks_js = require("@lovable.dev/webhooks-js");
197
+ var WEBHOOK_ERROR_STATUS = {
198
+ missing_secret: 401,
199
+ missing_timestamp: 401,
200
+ invalid_timestamp: 401,
201
+ stale_timestamp: 401,
202
+ invalid_signature: 401,
203
+ body_too_large: 400,
204
+ invalid_json: 400,
205
+ invalid_payload: 400
206
+ };
207
+ function parseEmailWebhookEvent(body) {
208
+ return parseEmailWebhookPayload(body);
209
+ }
210
+ function createEmailWebhookHandler(options) {
211
+ const { apiKey, on } = options;
212
+ if (!apiKey) {
213
+ throw new Error("Missing Lovable API key");
214
+ }
215
+ return async (req) => {
216
+ if (req.method !== "POST") {
217
+ return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
218
+ }
219
+ let event;
220
+ try {
221
+ ({ payload: event } = await (0, import_webhooks_js.verifyWebhookRequest)({ req, secret: apiKey, parser: parseEmailWebhookEvent }));
222
+ } catch (error) {
223
+ if (error instanceof import_webhooks_js.WebhookError) {
224
+ return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
225
+ }
226
+ console.error("[email-js] webhook verification failed:", error);
227
+ return Response.json({ error: "Webhook verification failed" }, { status: 500 });
228
+ }
229
+ if (event.version !== "1") {
230
+ return Response.json({ received: true });
231
+ }
232
+ const handler = on[event.type];
233
+ if (handler) {
234
+ try {
235
+ await handler(event);
236
+ } catch (error) {
237
+ console.error("[email-js] webhook handler failed:", error);
238
+ return Response.json({ error: "Handler failed" }, { status: 500 });
239
+ }
240
+ }
241
+ return Response.json({ received: true });
242
+ };
243
+ }
105
244
  // Annotate the CommonJS export names for ESM import in node:
106
245
  0 && (module.exports = {
107
246
  EmailAPIError,
247
+ createEmailWebhookHandler,
248
+ getEmailUnsubscribe,
249
+ listEmailLogs,
108
250
  parseEmailWebhookPayload,
109
- sendLovableEmail
251
+ sendLovableEmail,
252
+ setEmailUnsubscribe
110
253
  });
package/dist/index.d.cts CHANGED
@@ -31,15 +31,92 @@ interface SendEmailOptions {
31
31
  sendUrl?: string;
32
32
  idempotencyKey?: string;
33
33
  }
34
+ interface EmailClientOptions {
35
+ apiKey: string;
36
+ authHeader?: string;
37
+ apiBaseUrl?: string;
38
+ }
39
+ interface ListEmailLogsFilters {
40
+ recipient?: string;
41
+ event_type?: string;
42
+ status?: string;
43
+ tag?: string;
44
+ since?: string;
45
+ until?: string;
46
+ limit?: number;
47
+ cursor?: string;
48
+ }
49
+ interface EmailEvent {
50
+ timestamp: string;
51
+ recipient: string;
52
+ event_type: string;
53
+ status?: string;
54
+ message_id?: string;
55
+ tags?: string[] | null;
56
+ }
57
+ interface EmailLogsPagination {
58
+ next_cursor: string | null;
59
+ has_more: boolean;
60
+ }
61
+ interface ListEmailLogsResponse {
62
+ data: EmailEvent[];
63
+ pagination: EmailLogsPagination;
64
+ }
65
+ interface GetEmailUnsubscribeRequest {
66
+ recipient: string;
67
+ domain: string;
68
+ }
69
+ interface SetEmailUnsubscribeRequest {
70
+ recipient: string;
71
+ domain: string;
72
+ subscribed: boolean;
73
+ }
74
+ interface EmailUnsubscribeResponse {
75
+ recipient: string;
76
+ domain: string;
77
+ subscribed: boolean;
78
+ }
79
+ type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
80
+ interface EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> {
81
+ event_id: string;
82
+ run_id: string;
83
+ type: T;
84
+ project_id: string;
85
+ environment: "dev" | "prod";
86
+ data: {
87
+ event: T;
88
+ recipient: string;
89
+ message_id: string;
90
+ };
91
+ timestamp: string;
92
+ version: string;
93
+ replay_id?: string;
94
+ }
95
+ type EmailWebhookHandlers = {
96
+ [T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
97
+ };
98
+ interface EmailWebhookHandlerOptions {
99
+ apiKey: string;
100
+ on: EmailWebhookHandlers;
101
+ }
102
+
103
+ declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
34
104
 
35
105
  declare class EmailAPIError extends Error {
36
106
  readonly status: number;
37
107
  readonly retryAfterSeconds: number | null;
38
- constructor(status: number, message: string, retryAfterSeconds: number | null);
108
+ readonly code: string | null;
109
+ constructor(status: number, message: string, retryAfterSeconds: number | null, code?: string | null);
39
110
  get retryable(): boolean;
40
111
  }
41
- declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
112
+
113
+ declare function listEmailLogs(filters: ListEmailLogsFilters, options: EmailClientOptions): Promise<ListEmailLogsResponse>;
114
+
115
+ declare function getEmailUnsubscribe(request: GetEmailUnsubscribeRequest, options: EmailClientOptions): Promise<EmailUnsubscribeResponse>;
116
+ declare function setEmailUnsubscribe(request: SetEmailUnsubscribeRequest, options: EmailClientOptions): Promise<EmailUnsubscribeResponse>;
42
117
 
43
118
  declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
44
119
 
45
- export { EmailAPIError, EmailSendRequest, EmailSendResponse, SendEmailOptions, parseEmailWebhookPayload, sendLovableEmail };
120
+ declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
121
+
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 };
package/dist/index.d.ts CHANGED
@@ -31,15 +31,92 @@ interface SendEmailOptions {
31
31
  sendUrl?: string;
32
32
  idempotencyKey?: string;
33
33
  }
34
+ interface EmailClientOptions {
35
+ apiKey: string;
36
+ authHeader?: string;
37
+ apiBaseUrl?: string;
38
+ }
39
+ interface ListEmailLogsFilters {
40
+ recipient?: string;
41
+ event_type?: string;
42
+ status?: string;
43
+ tag?: string;
44
+ since?: string;
45
+ until?: string;
46
+ limit?: number;
47
+ cursor?: string;
48
+ }
49
+ interface EmailEvent {
50
+ timestamp: string;
51
+ recipient: string;
52
+ event_type: string;
53
+ status?: string;
54
+ message_id?: string;
55
+ tags?: string[] | null;
56
+ }
57
+ interface EmailLogsPagination {
58
+ next_cursor: string | null;
59
+ has_more: boolean;
60
+ }
61
+ interface ListEmailLogsResponse {
62
+ data: EmailEvent[];
63
+ pagination: EmailLogsPagination;
64
+ }
65
+ interface GetEmailUnsubscribeRequest {
66
+ recipient: string;
67
+ domain: string;
68
+ }
69
+ interface SetEmailUnsubscribeRequest {
70
+ recipient: string;
71
+ domain: string;
72
+ subscribed: boolean;
73
+ }
74
+ interface EmailUnsubscribeResponse {
75
+ recipient: string;
76
+ domain: string;
77
+ subscribed: boolean;
78
+ }
79
+ type EmailWebhookEventType = "email.bounced" | "email.complaint" | "email.unsubscribed" | "email.resubscribed";
80
+ interface EmailWebhookEvent<T extends EmailWebhookEventType = EmailWebhookEventType> {
81
+ event_id: string;
82
+ run_id: string;
83
+ type: T;
84
+ project_id: string;
85
+ environment: "dev" | "prod";
86
+ data: {
87
+ event: T;
88
+ recipient: string;
89
+ message_id: string;
90
+ };
91
+ timestamp: string;
92
+ version: string;
93
+ replay_id?: string;
94
+ }
95
+ type EmailWebhookHandlers = {
96
+ [T in EmailWebhookEventType]?: (event: EmailWebhookEvent<T>) => void | Promise<void>;
97
+ };
98
+ interface EmailWebhookHandlerOptions {
99
+ apiKey: string;
100
+ on: EmailWebhookHandlers;
101
+ }
102
+
103
+ declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
34
104
 
35
105
  declare class EmailAPIError extends Error {
36
106
  readonly status: number;
37
107
  readonly retryAfterSeconds: number | null;
38
- constructor(status: number, message: string, retryAfterSeconds: number | null);
108
+ readonly code: string | null;
109
+ constructor(status: number, message: string, retryAfterSeconds: number | null, code?: string | null);
39
110
  get retryable(): boolean;
40
111
  }
41
- declare function sendLovableEmail(payload: EmailSendRequest, options: SendEmailOptions): Promise<EmailSendResponse>;
112
+
113
+ declare function listEmailLogs(filters: ListEmailLogsFilters, options: EmailClientOptions): Promise<ListEmailLogsResponse>;
114
+
115
+ declare function getEmailUnsubscribe(request: GetEmailUnsubscribeRequest, options: EmailClientOptions): Promise<EmailUnsubscribeResponse>;
116
+ declare function setEmailUnsubscribe(request: SetEmailUnsubscribeRequest, options: EmailClientOptions): Promise<EmailUnsubscribeResponse>;
42
117
 
43
118
  declare function parseEmailWebhookPayload(body: string): EmailWebhookPayload;
44
119
 
45
- export { EmailAPIError, EmailSendRequest, EmailSendResponse, SendEmailOptions, parseEmailWebhookPayload, sendLovableEmail };
120
+ declare function createEmailWebhookHandler(options: EmailWebhookHandlerOptions): (req: Request) => Promise<Response>;
121
+
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 };
package/dist/index.js CHANGED
@@ -1,13 +1,16 @@
1
- // src/email.ts
1
+ // src/http.ts
2
2
  var DEFAULT_AUTH_HEADER = "Authorization";
3
3
  var DEFAULT_API_BASE_URL = "https://api.lovable.dev";
4
- var DEFAULT_SEND_PATH = "/v1/messaging/email/send";
4
+ function resolveApiBaseUrl(apiBaseUrl) {
5
+ return (apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\/$/, "");
6
+ }
5
7
  var EmailAPIError = class extends Error {
6
- constructor(status, message, retryAfterSeconds) {
8
+ constructor(status, message, retryAfterSeconds, code = null) {
7
9
  super(message);
8
10
  this.name = "EmailAPIError";
9
11
  this.status = status;
10
12
  this.retryAfterSeconds = retryAfterSeconds;
13
+ this.code = code;
11
14
  }
12
15
  get retryable() {
13
16
  return this.status === 429 || this.status >= 500 && this.status < 600;
@@ -28,6 +31,50 @@ function parseRetryAfter(header) {
28
31
  function buildAuthHeaderValue(apiKey) {
29
32
  return `Bearer ${apiKey}`;
30
33
  }
34
+ function parseErrorCode(body) {
35
+ try {
36
+ const parsed = JSON.parse(body);
37
+ if (parsed && typeof parsed === "object" && "type" in parsed && typeof parsed.type === "string") {
38
+ return parsed.type;
39
+ }
40
+ } catch {
41
+ return null;
42
+ }
43
+ return null;
44
+ }
45
+ async function throwIfNotOk(response) {
46
+ if (response.ok)
47
+ return;
48
+ const errorText = await response.text();
49
+ const safeErrorText = errorText.length > 500 ? `${errorText.slice(0, 500)}...` : errorText;
50
+ throw new EmailAPIError(
51
+ response.status,
52
+ `Email API error: ${response.status} ${safeErrorText}`,
53
+ parseRetryAfter(response.headers.get("Retry-After")),
54
+ parseErrorCode(errorText)
55
+ );
56
+ }
57
+ async function emailApiRequest(options, path, init = { method: "GET" }) {
58
+ if (!options.apiKey) {
59
+ throw new Error("Missing Lovable API key");
60
+ }
61
+ const headers = {
62
+ [options.authHeader ?? DEFAULT_AUTH_HEADER]: buildAuthHeaderValue(options.apiKey)
63
+ };
64
+ if (init.body !== void 0) {
65
+ headers["Content-Type"] = "application/json";
66
+ }
67
+ const response = await fetch(`${resolveApiBaseUrl(options.apiBaseUrl)}${path}`, {
68
+ method: init.method,
69
+ headers,
70
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
71
+ });
72
+ await throwIfNotOk(response);
73
+ return await response.json();
74
+ }
75
+
76
+ // src/email.ts
77
+ var DEFAULT_SEND_PATH = "/v1/messaging/email/send";
31
78
  async function sendLovableEmail(payload, options) {
32
79
  const apiKey = options.apiKey;
33
80
  if (!apiKey) {
@@ -35,8 +82,7 @@ async function sendLovableEmail(payload, options) {
35
82
  }
36
83
  const authHeader = options.authHeader ?? DEFAULT_AUTH_HEADER;
37
84
  const sendUrl = options.sendUrl;
38
- const apiBaseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;
39
- const url = sendUrl || `${apiBaseUrl.replace(/\/$/, "")}${DEFAULT_SEND_PATH}`;
85
+ const url = sendUrl || `${resolveApiBaseUrl(options.apiBaseUrl)}${DEFAULT_SEND_PATH}`;
40
86
  const idempotencyKey = options.idempotencyKey ?? payload.idempotency_key ?? payload.run_id;
41
87
  const headers = {
42
88
  [authHeader]: buildAuthHeaderValue(apiKey),
@@ -50,18 +96,57 @@ async function sendLovableEmail(payload, options) {
50
96
  headers,
51
97
  body: JSON.stringify(payload)
52
98
  });
53
- if (!response.ok) {
54
- const errorText = await response.text();
55
- const safeErrorText = errorText.length > 500 ? `${errorText.slice(0, 500)}...` : errorText;
56
- throw new EmailAPIError(
57
- response.status,
58
- `Email API error: ${response.status} ${safeErrorText}`,
59
- parseRetryAfter(response.headers.get("Retry-After"))
60
- );
61
- }
99
+ await throwIfNotOk(response);
62
100
  return await response.json();
63
101
  }
64
102
 
103
+ // src/logs.ts
104
+ var LOGS_PATH = "/v1/messaging/email/logs";
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
+ }
149
+
65
150
  // src/webhook.ts
66
151
  function parseEmailWebhookPayload(body) {
67
152
  const parsed = JSON.parse(body);
@@ -74,8 +159,62 @@ function parseEmailWebhookPayload(body) {
74
159
  }
75
160
  return payload;
76
161
  }
162
+
163
+ // src/webhook-handler.ts
164
+ import { WebhookError, verifyWebhookRequest } from "@lovable.dev/webhooks-js";
165
+ var WEBHOOK_ERROR_STATUS = {
166
+ missing_secret: 401,
167
+ missing_timestamp: 401,
168
+ invalid_timestamp: 401,
169
+ stale_timestamp: 401,
170
+ invalid_signature: 401,
171
+ body_too_large: 400,
172
+ invalid_json: 400,
173
+ invalid_payload: 400
174
+ };
175
+ function parseEmailWebhookEvent(body) {
176
+ return parseEmailWebhookPayload(body);
177
+ }
178
+ function createEmailWebhookHandler(options) {
179
+ const { apiKey, on } = options;
180
+ if (!apiKey) {
181
+ throw new Error("Missing Lovable API key");
182
+ }
183
+ return async (req) => {
184
+ if (req.method !== "POST") {
185
+ return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: "POST" } });
186
+ }
187
+ let event;
188
+ try {
189
+ ({ payload: event } = await verifyWebhookRequest({ req, secret: apiKey, parser: parseEmailWebhookEvent }));
190
+ } catch (error) {
191
+ if (error instanceof WebhookError) {
192
+ return Response.json({ error: error.message }, { status: WEBHOOK_ERROR_STATUS[error.code] });
193
+ }
194
+ console.error("[email-js] webhook verification failed:", error);
195
+ return Response.json({ error: "Webhook verification failed" }, { status: 500 });
196
+ }
197
+ if (event.version !== "1") {
198
+ return Response.json({ received: true });
199
+ }
200
+ const handler = on[event.type];
201
+ if (handler) {
202
+ try {
203
+ await handler(event);
204
+ } catch (error) {
205
+ console.error("[email-js] webhook handler failed:", error);
206
+ return Response.json({ error: "Handler failed" }, { status: 500 });
207
+ }
208
+ }
209
+ return Response.json({ received: true });
210
+ };
211
+ }
77
212
  export {
78
213
  EmailAPIError,
214
+ createEmailWebhookHandler,
215
+ getEmailUnsubscribe,
216
+ listEmailLogs,
79
217
  parseEmailWebhookPayload,
80
- sendLovableEmail
218
+ sendLovableEmail,
219
+ setEmailUnsubscribe
81
220
  };
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@lovable.dev/email-js",
3
- "version": "0.0.4",
3
+ "version": "0.1.0-rc.2",
4
4
  "description": "Lovable Email JS",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/lovablelabs/lovable.git",
8
+ "directory": "npm-packages/email-js"
9
+ },
5
10
  "main": "./dist/index.cjs",
6
11
  "module": "./dist/index.js",
7
12
  "types": "./dist/index.d.ts",
@@ -9,14 +14,6 @@
9
14
  "files": [
10
15
  "dist"
11
16
  ],
12
- "scripts": {
13
- "build": "tsup src/index.ts --format cjs,esm --dts --outDir dist",
14
- "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
15
- "test": "vitest run",
16
- "prepublishOnly": "npm run clean && npm run build",
17
- "clean": "rimraf dist",
18
- "typecheck": "tsgo --noEmit"
19
- },
20
17
  "keywords": [
21
18
  "lovable",
22
19
  "email",
@@ -31,6 +28,14 @@
31
28
  "rimraf": "^5.0.0",
32
29
  "tsup": "^7.2.0",
33
30
  "typescript": "^5",
34
- "vitest": "^3"
31
+ "vitest": "^4.1.5",
32
+ "@lovable/api-utils": "1.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsup src/index.ts --format cjs,esm --dts --outDir dist",
36
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
37
+ "test": "vitest run",
38
+ "clean": "rimraf dist",
39
+ "typecheck": "tsgo --noEmit"
35
40
  }
36
- }
41
+ }