@mailoo/forms 0.0.0-stage → 1.33.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 +16 -0
- package/README.md +208 -2
- package/dist/chunk-4B377BWO.js +147 -0
- package/dist/chunk-4B377BWO.js.map +1 -0
- package/dist/chunk-LD246ORB.js +86 -0
- package/dist/chunk-LD246ORB.js.map +1 -0
- package/dist/chunk-QBZAYHBD.js +36 -0
- package/dist/chunk-QBZAYHBD.js.map +1 -0
- package/dist/events/index.cjs +176 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +107 -0
- package/dist/events/index.d.ts +107 -0
- package/dist/events/index.js +17 -0
- package/dist/events/index.js.map +1 -0
- package/dist/hooks/index.cjs +301 -0
- package/dist/hooks/index.cjs.map +1 -0
- package/dist/hooks/index.d.cts +130 -0
- package/dist/hooks/index.d.ts +130 -0
- package/dist/hooks/index.js +221 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/index.cjs +66 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +35 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/routes/index.cjs +544 -0
- package/dist/routes/index.cjs.map +1 -0
- package/dist/routes/index.d.cts +59 -0
- package/dist/routes/index.d.ts +59 -0
- package/dist/routes/index.js +351 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/server/index.cjs +270 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +44 -0
- package/dist/server/index.d.ts +44 -0
- package/dist/server/index.js +112 -0
- package/dist/server/index.js.map +1 -0
- package/dist/webhooks/index.cjs +111 -0
- package/dist/webhooks/index.cjs.map +1 -0
- package/dist/webhooks/index.d.cts +37 -0
- package/dist/webhooks/index.d.ts +37 -0
- package/dist/webhooks/index.js +9 -0
- package/dist/webhooks/index.js.map +1 -0
- package/package.json +77 -3
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/server/index.ts
|
|
21
|
+
var server_exports = {};
|
|
22
|
+
__export(server_exports, {
|
|
23
|
+
MAILOO_LIFECYCLE_INTEGRATION_PREFIX: () => MAILOO_LIFECYCLE_INTEGRATION_PREFIX,
|
|
24
|
+
getMailooLifecycleIntegrationConfig: () => getMailooLifecycleIntegrationConfig,
|
|
25
|
+
ingestMailooLifecycleEvent: () => ingestMailooLifecycleEvent,
|
|
26
|
+
retryMailooLifecycleEvent: () => retryMailooLifecycleEvent
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(server_exports);
|
|
29
|
+
var import_next_core = require("@mailoo/next-core");
|
|
30
|
+
|
|
31
|
+
// src/events/index.ts
|
|
32
|
+
var MAILOO_LIFECYCLE_EVENTS = {
|
|
33
|
+
USER_REGISTERED: "user.registered",
|
|
34
|
+
USER_ACTIVATED: "user.activated"
|
|
35
|
+
};
|
|
36
|
+
var MAILOO_LIFECYCLE_EVENT_NAMES = [
|
|
37
|
+
MAILOO_LIFECYCLE_EVENTS.USER_REGISTERED,
|
|
38
|
+
MAILOO_LIFECYCLE_EVENTS.USER_ACTIVATED
|
|
39
|
+
];
|
|
40
|
+
var EVENT_NAME_SET = new Set(MAILOO_LIFECYCLE_EVENT_NAMES);
|
|
41
|
+
var MAILOO_LIFECYCLE_ATTRIBUTE_KEYS = [
|
|
42
|
+
"plan",
|
|
43
|
+
"tier",
|
|
44
|
+
"country",
|
|
45
|
+
"signupChannel",
|
|
46
|
+
"referrer"
|
|
47
|
+
];
|
|
48
|
+
var ATTRIBUTE_KEY_SET = new Set(MAILOO_LIFECYCLE_ATTRIBUTE_KEYS);
|
|
49
|
+
var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
50
|
+
function isPlainObject(v) {
|
|
51
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
52
|
+
}
|
|
53
|
+
function validateMailooLifecycleEvent(body) {
|
|
54
|
+
if (!isPlainObject(body)) {
|
|
55
|
+
return { ok: false, message: "JSON body object is required" };
|
|
56
|
+
}
|
|
57
|
+
const idempotencyKey = typeof body.idempotencyKey === "string" ? body.idempotencyKey.trim() : "";
|
|
58
|
+
if (!idempotencyKey || idempotencyKey.length > 256) {
|
|
59
|
+
return {
|
|
60
|
+
ok: false,
|
|
61
|
+
message: "idempotencyKey is required (max 256 characters)"
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const eventName = typeof body.eventName === "string" ? body.eventName.trim() : "";
|
|
65
|
+
if (!eventName) {
|
|
66
|
+
return { ok: false, message: "eventName is required" };
|
|
67
|
+
}
|
|
68
|
+
if (!EVENT_NAME_SET.has(eventName)) {
|
|
69
|
+
return {
|
|
70
|
+
ok: false,
|
|
71
|
+
message: `Unknown eventName: ${eventName}. Allowed: ${MAILOO_LIFECYCLE_EVENT_NAMES.join(", ")}`
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const externalUserId = typeof body.externalUserId === "string" ? body.externalUserId.trim() : "";
|
|
75
|
+
if (!externalUserId) {
|
|
76
|
+
return { ok: false, message: "externalUserId is required" };
|
|
77
|
+
}
|
|
78
|
+
const emailRaw = typeof body.email === "string" ? body.email.trim() : "";
|
|
79
|
+
if (!emailRaw || !EMAIL_RE.test(emailRaw)) {
|
|
80
|
+
return { ok: false, message: "Valid email is required" };
|
|
81
|
+
}
|
|
82
|
+
const locale = typeof body.locale === "string" && body.locale.trim() ? body.locale.trim() : void 0;
|
|
83
|
+
const name = typeof body.name === "string" && body.name.trim() ? body.name.trim() : void 0;
|
|
84
|
+
let marketingConsent;
|
|
85
|
+
const rawConsent = body.marketingConsent;
|
|
86
|
+
if (rawConsent === true || rawConsent === false) {
|
|
87
|
+
marketingConsent = rawConsent;
|
|
88
|
+
} else if (isPlainObject(rawConsent) && typeof rawConsent.granted === "boolean") {
|
|
89
|
+
const at = typeof rawConsent.at === "string" && rawConsent.at.trim() ? rawConsent.at.trim() : void 0;
|
|
90
|
+
if (at !== void 0) {
|
|
91
|
+
const parsed = new Date(at);
|
|
92
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
93
|
+
return {
|
|
94
|
+
ok: false,
|
|
95
|
+
message: "marketingConsent.at must be a valid ISO timestamp"
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
marketingConsent = {
|
|
100
|
+
granted: rawConsent.granted,
|
|
101
|
+
...at ? { at } : {},
|
|
102
|
+
...typeof rawConsent.source === "string" ? { source: rawConsent.source } : {}
|
|
103
|
+
};
|
|
104
|
+
} else {
|
|
105
|
+
return {
|
|
106
|
+
ok: false,
|
|
107
|
+
message: "marketingConsent is required (boolean or { granted })"
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
let attributes;
|
|
111
|
+
if (body.attributes !== void 0) {
|
|
112
|
+
if (!isPlainObject(body.attributes)) {
|
|
113
|
+
return { ok: false, message: "attributes must be an object" };
|
|
114
|
+
}
|
|
115
|
+
attributes = {};
|
|
116
|
+
for (const [key, value] of Object.entries(body.attributes)) {
|
|
117
|
+
if (!ATTRIBUTE_KEY_SET.has(key)) {
|
|
118
|
+
return { ok: false, message: `Unknown attribute key: ${key}` };
|
|
119
|
+
}
|
|
120
|
+
attributes[key] = value;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
ok: true,
|
|
125
|
+
value: {
|
|
126
|
+
eventName,
|
|
127
|
+
idempotencyKey,
|
|
128
|
+
externalUserId,
|
|
129
|
+
email: emailRaw,
|
|
130
|
+
marketingConsent,
|
|
131
|
+
...locale ? { locale } : {},
|
|
132
|
+
...name ? { name } : {},
|
|
133
|
+
...attributes ? { attributes } : {}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function parseMailooLifecycleIngestData(data) {
|
|
138
|
+
if (!isPlainObject(data)) return null;
|
|
139
|
+
if (typeof data.eventId !== "string" || typeof data.contactId !== "string") {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
let send = null;
|
|
143
|
+
if (data.send === null) {
|
|
144
|
+
send = null;
|
|
145
|
+
} else if (isPlainObject(data.send) && typeof data.send.sendId === "string") {
|
|
146
|
+
send = {
|
|
147
|
+
sendId: data.send.sendId,
|
|
148
|
+
status: String(data.send.status ?? ""),
|
|
149
|
+
messageId: data.send.messageId === null || typeof data.send.messageId === "string" ? data.send.messageId : null,
|
|
150
|
+
trackingToken: String(data.send.trackingToken ?? ""),
|
|
151
|
+
campaignId: data.send.campaignId === null || typeof data.send.campaignId === "string" ? data.send.campaignId : null
|
|
152
|
+
};
|
|
153
|
+
} else {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
eventId: data.eventId,
|
|
158
|
+
contactId: data.contactId,
|
|
159
|
+
idempotentReplay: data.idempotentReplay === true,
|
|
160
|
+
processingStatus: String(data.processingStatus ?? ""),
|
|
161
|
+
skipReason: data.skipReason === null || typeof data.skipReason === "string" ? data.skipReason : null,
|
|
162
|
+
send
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/server/index.ts
|
|
167
|
+
var MAILOO_LIFECYCLE_INTEGRATION_PREFIX = "MAILOO_LIFECYCLE";
|
|
168
|
+
function resolveLifecycleConfig(options) {
|
|
169
|
+
if (options?.getConfig) {
|
|
170
|
+
return options.getConfig();
|
|
171
|
+
}
|
|
172
|
+
const prefix = options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX;
|
|
173
|
+
return (0, import_next_core.readMailooIntegrationConfig)({ prefix });
|
|
174
|
+
}
|
|
175
|
+
function parseIngestResponse(status, data) {
|
|
176
|
+
if (status < 200 || status >= 300) {
|
|
177
|
+
const message = typeof data.message === "string" ? data.message : typeof data.error === "string" ? data.error : "Lifecycle ingest failed";
|
|
178
|
+
return { ok: false, status, message, data };
|
|
179
|
+
}
|
|
180
|
+
const inner = data && typeof data === "object" && !Array.isArray(data) && "data" in data ? data.data : data;
|
|
181
|
+
const parsed = parseMailooLifecycleIngestData(inner);
|
|
182
|
+
if (!parsed) {
|
|
183
|
+
return {
|
|
184
|
+
ok: false,
|
|
185
|
+
status,
|
|
186
|
+
message: "Unexpected lifecycle ingest response shape",
|
|
187
|
+
data
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
return { ok: true, status, data: parsed };
|
|
191
|
+
}
|
|
192
|
+
async function ingestMailooLifecycleEvent(input, options) {
|
|
193
|
+
const validated = validateMailooLifecycleEvent(input);
|
|
194
|
+
if (!validated.ok) {
|
|
195
|
+
return { ok: false, status: 400, message: validated.message };
|
|
196
|
+
}
|
|
197
|
+
const config = resolveLifecycleConfig(options);
|
|
198
|
+
if (!config) {
|
|
199
|
+
return {
|
|
200
|
+
ok: false,
|
|
201
|
+
status: 503,
|
|
202
|
+
message: "Lifecycle integration is not configured"
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events`;
|
|
207
|
+
const response = await fetch(url, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: {
|
|
210
|
+
"Content-Type": "application/json",
|
|
211
|
+
"X-API-Key": config.apiKey
|
|
212
|
+
},
|
|
213
|
+
body: JSON.stringify(validated.value)
|
|
214
|
+
});
|
|
215
|
+
const data = await response.json().catch(() => ({}));
|
|
216
|
+
return parseIngestResponse(response.status, data);
|
|
217
|
+
} catch {
|
|
218
|
+
return {
|
|
219
|
+
ok: false,
|
|
220
|
+
status: 502,
|
|
221
|
+
message: "Upstream request failed"
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async function retryMailooLifecycleEvent(eventId, options) {
|
|
226
|
+
const id = typeof eventId === "string" ? eventId.trim() : "";
|
|
227
|
+
if (!id) {
|
|
228
|
+
return { ok: false, status: 400, message: "eventId is required" };
|
|
229
|
+
}
|
|
230
|
+
const config = resolveLifecycleConfig(options);
|
|
231
|
+
if (!config) {
|
|
232
|
+
return {
|
|
233
|
+
ok: false,
|
|
234
|
+
status: 503,
|
|
235
|
+
message: "Lifecycle integration is not configured"
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events/${encodeURIComponent(id)}/retry`;
|
|
240
|
+
const response = await fetch(url, {
|
|
241
|
+
method: "POST",
|
|
242
|
+
headers: {
|
|
243
|
+
"Content-Type": "application/json",
|
|
244
|
+
"X-API-Key": config.apiKey
|
|
245
|
+
},
|
|
246
|
+
body: "{}"
|
|
247
|
+
});
|
|
248
|
+
const data = await response.json().catch(() => ({}));
|
|
249
|
+
return parseIngestResponse(response.status, data);
|
|
250
|
+
} catch {
|
|
251
|
+
return {
|
|
252
|
+
ok: false,
|
|
253
|
+
status: 502,
|
|
254
|
+
message: "Upstream request failed"
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
function getMailooLifecycleIntegrationConfig(options) {
|
|
259
|
+
return (0, import_next_core.readMailooIntegrationConfig)({
|
|
260
|
+
prefix: options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
264
|
+
0 && (module.exports = {
|
|
265
|
+
MAILOO_LIFECYCLE_INTEGRATION_PREFIX,
|
|
266
|
+
getMailooLifecycleIntegrationConfig,
|
|
267
|
+
ingestMailooLifecycleEvent,
|
|
268
|
+
retryMailooLifecycleEvent
|
|
269
|
+
});
|
|
270
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts","../../src/events/index.ts"],"sourcesContent":["import {\n readMailooIntegrationConfig,\n type MailooIntegrationConfig,\n} from '@mailoo/next-core'\nimport {\n validateMailooLifecycleEvent,\n parseMailooLifecycleIngestData,\n type MailooLifecycleEventInput,\n type MailooLifecycleIngestData,\n} from '../events/index.js'\n\n/** Default env prefix for lifecycle ingest (needs `lifecycle.ingest` scope). */\nexport const MAILOO_LIFECYCLE_INTEGRATION_PREFIX = 'MAILOO_LIFECYCLE' as const\n\nexport type IngestMailooLifecycleEventOptions = {\n /** Env prefix; default `MAILOO_LIFECYCLE`. */\n prefix?: string\n /** Explicit config; wins over prefix/env when provided. */\n getConfig?: () => MailooIntegrationConfig | null\n}\n\nexport type MailooLifecycleIngestResult =\n | {\n ok: true\n status: number\n data: MailooLifecycleIngestData\n }\n | {\n ok: false\n status: number\n message: string\n data?: unknown\n }\n\nfunction resolveLifecycleConfig(\n options?: IngestMailooLifecycleEventOptions\n): MailooIntegrationConfig | null {\n if (options?.getConfig) {\n return options.getConfig()\n }\n const prefix = options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX\n return readMailooIntegrationConfig({ prefix })\n}\n\nfunction parseIngestResponse(\n status: number,\n data: unknown\n): MailooLifecycleIngestResult {\n if (status < 200 || status >= 300) {\n const message =\n typeof (data as { message?: string }).message === 'string'\n ? (data as { message: string }).message\n : typeof (data as { error?: string }).error === 'string'\n ? (data as { error: string }).error\n : 'Lifecycle ingest failed'\n return { ok: false, status, message, data }\n }\n const inner =\n data &&\n typeof data === 'object' &&\n !Array.isArray(data) &&\n 'data' in data\n ? (data as { data: unknown }).data\n : data\n const parsed = parseMailooLifecycleIngestData(inner)\n if (!parsed) {\n return {\n ok: false,\n status,\n message: 'Unexpected lifecycle ingest response shape',\n data,\n }\n }\n return { ok: true, status, data: parsed }\n}\n\n/**\n * Server-side lifecycle ingest (Server Action / Route Handler / Node).\n * Posts a validated event to Mailoo with the server-held API key.\n * The host chooses *when* to call; the package owns the contract.\n *\n * Never throws on missing config or network failure — returns\n * `{ ok: false, status, message }` so hosts can isolate the feature.\n *\n * Identity: pass your app user id as `externalUserId` (e.g. Firebase UID)\n * and the user's email. Mailoo merges by UID then email. Do not persist\n * returned `contactId` as your user key — it is Mailoo's internal cuid.\n */\nexport async function ingestMailooLifecycleEvent(\n input: MailooLifecycleEventInput | Record<string, unknown>,\n options?: IngestMailooLifecycleEventOptions\n): Promise<MailooLifecycleIngestResult> {\n const validated = validateMailooLifecycleEvent(input)\n if (!validated.ok) {\n return { ok: false, status: 400, message: validated.message }\n }\n\n const config = resolveLifecycleConfig(options)\n if (!config) {\n return {\n ok: false,\n status: 503,\n message: 'Lifecycle integration is not configured',\n }\n }\n\n try {\n const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events`\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': config.apiKey,\n },\n body: JSON.stringify(validated.value),\n })\n const data = await response.json().catch(() => ({}))\n return parseIngestResponse(response.status, data)\n } catch {\n return {\n ok: false,\n status: 502,\n message: 'Upstream request failed',\n }\n }\n}\n\n/**\n * Server-side retry of a stored lifecycle event (same typed result as ingest).\n * Never throws on missing config or network failure.\n */\nexport async function retryMailooLifecycleEvent(\n eventId: string,\n options?: IngestMailooLifecycleEventOptions\n): Promise<MailooLifecycleIngestResult> {\n const id = typeof eventId === 'string' ? eventId.trim() : ''\n if (!id) {\n return { ok: false, status: 400, message: 'eventId is required' }\n }\n const config = resolveLifecycleConfig(options)\n if (!config) {\n return {\n ok: false,\n status: 503,\n message: 'Lifecycle integration is not configured',\n }\n }\n\n try {\n const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events/${encodeURIComponent(id)}/retry`\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': config.apiKey,\n },\n body: '{}',\n })\n const data = await response.json().catch(() => ({}))\n return parseIngestResponse(response.status, data)\n } catch {\n return {\n ok: false,\n status: 502,\n message: 'Upstream request failed',\n }\n }\n}\n\nexport function getMailooLifecycleIntegrationConfig(options?: {\n prefix?: string\n}): MailooIntegrationConfig | null {\n return readMailooIntegrationConfig({\n prefix: options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX,\n })\n}\n","/**\n * Closed lifecycle event catalog for FORM / CONTACT_FORM integrations.\n * Integrators choose *when* to emit; they must not invent event names or\n * attribute keys.\n */\n\nexport const MAILOO_LIFECYCLE_EVENTS = {\n USER_REGISTERED: 'user.registered',\n USER_ACTIVATED: 'user.activated',\n} as const\n\nexport type MailooLifecycleEventName =\n (typeof MAILOO_LIFECYCLE_EVENTS)[keyof typeof MAILOO_LIFECYCLE_EVENTS]\n\nexport const MAILOO_LIFECYCLE_EVENT_NAMES = [\n MAILOO_LIFECYCLE_EVENTS.USER_REGISTERED,\n MAILOO_LIFECYCLE_EVENTS.USER_ACTIVATED,\n] as const\n\nconst EVENT_NAME_SET = new Set<string>(MAILOO_LIFECYCLE_EVENT_NAMES)\n\nexport const MAILOO_LIFECYCLE_ATTRIBUTE_KEYS = [\n 'plan',\n 'tier',\n 'country',\n 'signupChannel',\n 'referrer',\n] as const\n\nexport type MailooLifecycleAttributeKey =\n (typeof MAILOO_LIFECYCLE_ATTRIBUTE_KEYS)[number]\n\nconst ATTRIBUTE_KEY_SET = new Set<string>(MAILOO_LIFECYCLE_ATTRIBUTE_KEYS)\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nexport type MailooMarketingConsent =\n | boolean\n | {\n granted: boolean\n at?: string\n source?: string\n }\n\nexport type MailooLifecycleEventInput = {\n eventName: MailooLifecycleEventName\n idempotencyKey: string\n externalUserId: string\n email: string\n marketingConsent: MailooMarketingConsent\n locale?: string\n name?: string\n attributes?: Partial<Record<MailooLifecycleAttributeKey, unknown>>\n}\n\nexport type MailooLifecycleEventValidation =\n | { ok: true; value: MailooLifecycleEventInput }\n | { ok: false; message: string }\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\n/**\n * Parse and validate a lifecycle ingest body. Fail-fast — no default\n * `eventName`. Used by BFF handlers and server ingest.\n */\nexport function validateMailooLifecycleEvent(\n body: unknown\n): MailooLifecycleEventValidation {\n if (!isPlainObject(body)) {\n return { ok: false, message: 'JSON body object is required' }\n }\n\n const idempotencyKey =\n typeof body.idempotencyKey === 'string' ? body.idempotencyKey.trim() : ''\n if (!idempotencyKey || idempotencyKey.length > 256) {\n return {\n ok: false,\n message: 'idempotencyKey is required (max 256 characters)',\n }\n }\n\n const eventName =\n typeof body.eventName === 'string' ? body.eventName.trim() : ''\n if (!eventName) {\n return { ok: false, message: 'eventName is required' }\n }\n if (!EVENT_NAME_SET.has(eventName)) {\n return {\n ok: false,\n message: `Unknown eventName: ${eventName}. Allowed: ${MAILOO_LIFECYCLE_EVENT_NAMES.join(', ')}`,\n }\n }\n\n const externalUserId =\n typeof body.externalUserId === 'string' ? body.externalUserId.trim() : ''\n if (!externalUserId) {\n return { ok: false, message: 'externalUserId is required' }\n }\n\n const emailRaw = typeof body.email === 'string' ? body.email.trim() : ''\n if (!emailRaw || !EMAIL_RE.test(emailRaw)) {\n return { ok: false, message: 'Valid email is required' }\n }\n\n const locale =\n typeof body.locale === 'string' && body.locale.trim()\n ? body.locale.trim()\n : undefined\n const name =\n typeof body.name === 'string' && body.name.trim()\n ? body.name.trim()\n : undefined\n\n let marketingConsent: MailooMarketingConsent\n const rawConsent = body.marketingConsent\n if (rawConsent === true || rawConsent === false) {\n marketingConsent = rawConsent\n } else if (isPlainObject(rawConsent) && typeof rawConsent.granted === 'boolean') {\n const at =\n typeof rawConsent.at === 'string' && rawConsent.at.trim()\n ? rawConsent.at.trim()\n : undefined\n if (at !== undefined) {\n const parsed = new Date(at)\n if (Number.isNaN(parsed.getTime())) {\n return {\n ok: false,\n message: 'marketingConsent.at must be a valid ISO timestamp',\n }\n }\n }\n marketingConsent = {\n granted: rawConsent.granted,\n ...(at ? { at } : {}),\n ...(typeof rawConsent.source === 'string'\n ? { source: rawConsent.source }\n : {}),\n }\n } else {\n return {\n ok: false,\n message: 'marketingConsent is required (boolean or { granted })',\n }\n }\n\n let attributes:\n | Partial<Record<MailooLifecycleAttributeKey, unknown>>\n | undefined\n if (body.attributes !== undefined) {\n if (!isPlainObject(body.attributes)) {\n return { ok: false, message: 'attributes must be an object' }\n }\n attributes = {}\n for (const [key, value] of Object.entries(body.attributes)) {\n if (!ATTRIBUTE_KEY_SET.has(key)) {\n return { ok: false, message: `Unknown attribute key: ${key}` }\n }\n attributes[key as MailooLifecycleAttributeKey] = value\n }\n }\n\n return {\n ok: true,\n value: {\n eventName: eventName as MailooLifecycleEventName,\n idempotencyKey,\n externalUserId,\n email: emailRaw,\n marketingConsent,\n ...(locale ? { locale } : {}),\n ...(name ? { name } : {}),\n ...(attributes ? { attributes } : {}),\n },\n }\n}\n\nexport function isMailooLifecycleEventName(\n value: string\n): value is MailooLifecycleEventName {\n return EVENT_NAME_SET.has(value)\n}\n\n/** Send row returned by lifecycle ingest / retry. */\nexport type MailooLifecycleSendResult = {\n sendId: string\n status: string\n messageId: string | null\n trackingToken: string\n campaignId: string | null\n}\n\n/**\n * Typed `data` from lifecycle ingest / retry success JSON.\n * `contactId` is Mailoo's Subscriber cuid — not the host user id.\n * Host identity key is `externalUserId` (e.g. Firebase UID).\n */\nexport type MailooLifecycleIngestData = {\n eventId: string\n contactId: string\n idempotentReplay: boolean\n processingStatus: string\n skipReason: string | null\n send: MailooLifecycleSendResult | null\n}\n\nexport type MailooLifecycleIngestSuccess = {\n success: true\n data: MailooLifecycleIngestData\n}\n\nexport type MailooLifecycleContactSummary = {\n requestedExternalUserId: string | null\n requestedEmail: string | null\n matchedBy: 'externalUserId' | 'email' | null\n contactId: string | null\n externalUserId: string | null\n email: string | null\n marketingConsentGranted: boolean | null\n unsubscribedAt: string | null\n lastEvent: {\n eventId: string\n eventName: string\n processingStatus: string\n skipReason: string | null\n createdAt: string\n } | null\n lastSend: {\n sendId: string\n status: string\n messageId: string | null\n openedAt: string | null\n clickedAt: string | null\n } | null\n}\n\nexport type MailooLifecycleStatusData = {\n success: true\n configured: true\n contacts: number\n contact: Record<string, unknown> | null\n events: Array<Record<string, unknown>>\n sends: Array<Record<string, unknown>>\n segments: Array<{\n id: string\n name: string\n systemKey: string | null\n }>\n summaries?: MailooLifecycleContactSummary[]\n}\n\nexport function parseMailooLifecycleIngestData(\n data: unknown\n): MailooLifecycleIngestData | null {\n if (!isPlainObject(data)) return null\n if (typeof data.eventId !== 'string' || typeof data.contactId !== 'string') {\n return null\n }\n let send: MailooLifecycleSendResult | null = null\n if (data.send === null) {\n send = null\n } else if (isPlainObject(data.send) && typeof data.send.sendId === 'string') {\n send = {\n sendId: data.send.sendId,\n status: String(data.send.status ?? ''),\n messageId:\n data.send.messageId === null || typeof data.send.messageId === 'string'\n ? (data.send.messageId as string | null)\n : null,\n trackingToken: String(data.send.trackingToken ?? ''),\n campaignId:\n data.send.campaignId === null ||\n typeof data.send.campaignId === 'string'\n ? (data.send.campaignId as string | null)\n : null,\n }\n } else {\n return null\n }\n return {\n eventId: data.eventId,\n contactId: data.contactId,\n idempotentReplay: data.idempotentReplay === true,\n processingStatus: String(data.processingStatus ?? ''),\n skipReason:\n data.skipReason === null || typeof data.skipReason === 'string'\n ? (data.skipReason as string | null)\n : null,\n send,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAGO;;;ACGA,IAAM,0BAA0B;AAAA,EACrC,iBAAiB;AAAA,EACjB,gBAAgB;AAClB;AAKO,IAAM,+BAA+B;AAAA,EAC1C,wBAAwB;AAAA,EACxB,wBAAwB;AAC1B;AAEA,IAAM,iBAAiB,IAAI,IAAY,4BAA4B;AAE5D,IAAM,kCAAkC;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKA,IAAM,oBAAoB,IAAI,IAAY,+BAA+B;AAEzE,IAAM,WAAW;AAyBjB,SAAS,cAAc,GAA0C;AAC/D,SAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;AAMO,SAAS,6BACd,MACgC;AAChC,MAAI,CAAC,cAAc,IAAI,GAAG;AACxB,WAAO,EAAE,IAAI,OAAO,SAAS,+BAA+B;AAAA,EAC9D;AAEA,QAAM,iBACJ,OAAO,KAAK,mBAAmB,WAAW,KAAK,eAAe,KAAK,IAAI;AACzE,MAAI,CAAC,kBAAkB,eAAe,SAAS,KAAK;AAClD,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,SAAS;AAAA,IACX;AAAA,EACF;AAEA,QAAM,YACJ,OAAO,KAAK,cAAc,WAAW,KAAK,UAAU,KAAK,IAAI;AAC/D,MAAI,CAAC,WAAW;AACd,WAAO,EAAE,IAAI,OAAO,SAAS,wBAAwB;AAAA,EACvD;AACA,MAAI,CAAC,eAAe,IAAI,SAAS,GAA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;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AACD,UAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACnD,WAAO,oBAAoB,SAAS,QAAQ,IAAI;AAAA,EAClD,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AACF;AAEO,SAAS,oCAAoC,SAEjB;AACjC,aAAO,8CAA4B;AAAA,IACjC,QAAQ,SAAS,UAAU;AAAA,EAC7B,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { MailooIntegrationConfig } from '@mailoo/next-core';
|
|
2
|
+
import { MailooLifecycleIngestData, MailooLifecycleEventInput } from '../events/index.cjs';
|
|
3
|
+
|
|
4
|
+
/** Default env prefix for lifecycle ingest (needs `lifecycle.ingest` scope). */
|
|
5
|
+
declare const MAILOO_LIFECYCLE_INTEGRATION_PREFIX: "MAILOO_LIFECYCLE";
|
|
6
|
+
type IngestMailooLifecycleEventOptions = {
|
|
7
|
+
/** Env prefix; default `MAILOO_LIFECYCLE`. */
|
|
8
|
+
prefix?: string;
|
|
9
|
+
/** Explicit config; wins over prefix/env when provided. */
|
|
10
|
+
getConfig?: () => MailooIntegrationConfig | null;
|
|
11
|
+
};
|
|
12
|
+
type MailooLifecycleIngestResult = {
|
|
13
|
+
ok: true;
|
|
14
|
+
status: number;
|
|
15
|
+
data: MailooLifecycleIngestData;
|
|
16
|
+
} | {
|
|
17
|
+
ok: false;
|
|
18
|
+
status: number;
|
|
19
|
+
message: string;
|
|
20
|
+
data?: unknown;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Server-side lifecycle ingest (Server Action / Route Handler / Node).
|
|
24
|
+
* Posts a validated event to Mailoo with the server-held API key.
|
|
25
|
+
* The host chooses *when* to call; the package owns the contract.
|
|
26
|
+
*
|
|
27
|
+
* Never throws on missing config or network failure — returns
|
|
28
|
+
* `{ ok: false, status, message }` so hosts can isolate the feature.
|
|
29
|
+
*
|
|
30
|
+
* Identity: pass your app user id as `externalUserId` (e.g. Firebase UID)
|
|
31
|
+
* and the user's email. Mailoo merges by UID then email. Do not persist
|
|
32
|
+
* returned `contactId` as your user key — it is Mailoo's internal cuid.
|
|
33
|
+
*/
|
|
34
|
+
declare function ingestMailooLifecycleEvent(input: MailooLifecycleEventInput | Record<string, unknown>, options?: IngestMailooLifecycleEventOptions): Promise<MailooLifecycleIngestResult>;
|
|
35
|
+
/**
|
|
36
|
+
* Server-side retry of a stored lifecycle event (same typed result as ingest).
|
|
37
|
+
* Never throws on missing config or network failure.
|
|
38
|
+
*/
|
|
39
|
+
declare function retryMailooLifecycleEvent(eventId: string, options?: IngestMailooLifecycleEventOptions): Promise<MailooLifecycleIngestResult>;
|
|
40
|
+
declare function getMailooLifecycleIntegrationConfig(options?: {
|
|
41
|
+
prefix?: string;
|
|
42
|
+
}): MailooIntegrationConfig | null;
|
|
43
|
+
|
|
44
|
+
export { type IngestMailooLifecycleEventOptions, MAILOO_LIFECYCLE_INTEGRATION_PREFIX, type MailooLifecycleIngestResult, getMailooLifecycleIntegrationConfig, ingestMailooLifecycleEvent, retryMailooLifecycleEvent };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { MailooIntegrationConfig } from '@mailoo/next-core';
|
|
2
|
+
import { MailooLifecycleIngestData, MailooLifecycleEventInput } from '../events/index.js';
|
|
3
|
+
|
|
4
|
+
/** Default env prefix for lifecycle ingest (needs `lifecycle.ingest` scope). */
|
|
5
|
+
declare const MAILOO_LIFECYCLE_INTEGRATION_PREFIX: "MAILOO_LIFECYCLE";
|
|
6
|
+
type IngestMailooLifecycleEventOptions = {
|
|
7
|
+
/** Env prefix; default `MAILOO_LIFECYCLE`. */
|
|
8
|
+
prefix?: string;
|
|
9
|
+
/** Explicit config; wins over prefix/env when provided. */
|
|
10
|
+
getConfig?: () => MailooIntegrationConfig | null;
|
|
11
|
+
};
|
|
12
|
+
type MailooLifecycleIngestResult = {
|
|
13
|
+
ok: true;
|
|
14
|
+
status: number;
|
|
15
|
+
data: MailooLifecycleIngestData;
|
|
16
|
+
} | {
|
|
17
|
+
ok: false;
|
|
18
|
+
status: number;
|
|
19
|
+
message: string;
|
|
20
|
+
data?: unknown;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Server-side lifecycle ingest (Server Action / Route Handler / Node).
|
|
24
|
+
* Posts a validated event to Mailoo with the server-held API key.
|
|
25
|
+
* The host chooses *when* to call; the package owns the contract.
|
|
26
|
+
*
|
|
27
|
+
* Never throws on missing config or network failure — returns
|
|
28
|
+
* `{ ok: false, status, message }` so hosts can isolate the feature.
|
|
29
|
+
*
|
|
30
|
+
* Identity: pass your app user id as `externalUserId` (e.g. Firebase UID)
|
|
31
|
+
* and the user's email. Mailoo merges by UID then email. Do not persist
|
|
32
|
+
* returned `contactId` as your user key — it is Mailoo's internal cuid.
|
|
33
|
+
*/
|
|
34
|
+
declare function ingestMailooLifecycleEvent(input: MailooLifecycleEventInput | Record<string, unknown>, options?: IngestMailooLifecycleEventOptions): Promise<MailooLifecycleIngestResult>;
|
|
35
|
+
/**
|
|
36
|
+
* Server-side retry of a stored lifecycle event (same typed result as ingest).
|
|
37
|
+
* Never throws on missing config or network failure.
|
|
38
|
+
*/
|
|
39
|
+
declare function retryMailooLifecycleEvent(eventId: string, options?: IngestMailooLifecycleEventOptions): Promise<MailooLifecycleIngestResult>;
|
|
40
|
+
declare function getMailooLifecycleIntegrationConfig(options?: {
|
|
41
|
+
prefix?: string;
|
|
42
|
+
}): MailooIntegrationConfig | null;
|
|
43
|
+
|
|
44
|
+
export { type IngestMailooLifecycleEventOptions, MAILOO_LIFECYCLE_INTEGRATION_PREFIX, type MailooLifecycleIngestResult, getMailooLifecycleIntegrationConfig, ingestMailooLifecycleEvent, retryMailooLifecycleEvent };
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseMailooLifecycleIngestData,
|
|
3
|
+
validateMailooLifecycleEvent
|
|
4
|
+
} from "../chunk-4B377BWO.js";
|
|
5
|
+
|
|
6
|
+
// src/server/index.ts
|
|
7
|
+
import {
|
|
8
|
+
readMailooIntegrationConfig
|
|
9
|
+
} from "@mailoo/next-core";
|
|
10
|
+
var MAILOO_LIFECYCLE_INTEGRATION_PREFIX = "MAILOO_LIFECYCLE";
|
|
11
|
+
function resolveLifecycleConfig(options) {
|
|
12
|
+
if (options?.getConfig) {
|
|
13
|
+
return options.getConfig();
|
|
14
|
+
}
|
|
15
|
+
const prefix = options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX;
|
|
16
|
+
return readMailooIntegrationConfig({ prefix });
|
|
17
|
+
}
|
|
18
|
+
function parseIngestResponse(status, data) {
|
|
19
|
+
if (status < 200 || status >= 300) {
|
|
20
|
+
const message = typeof data.message === "string" ? data.message : typeof data.error === "string" ? data.error : "Lifecycle ingest failed";
|
|
21
|
+
return { ok: false, status, message, data };
|
|
22
|
+
}
|
|
23
|
+
const inner = data && typeof data === "object" && !Array.isArray(data) && "data" in data ? data.data : data;
|
|
24
|
+
const parsed = parseMailooLifecycleIngestData(inner);
|
|
25
|
+
if (!parsed) {
|
|
26
|
+
return {
|
|
27
|
+
ok: false,
|
|
28
|
+
status,
|
|
29
|
+
message: "Unexpected lifecycle ingest response shape",
|
|
30
|
+
data
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return { ok: true, status, data: parsed };
|
|
34
|
+
}
|
|
35
|
+
async function ingestMailooLifecycleEvent(input, options) {
|
|
36
|
+
const validated = validateMailooLifecycleEvent(input);
|
|
37
|
+
if (!validated.ok) {
|
|
38
|
+
return { ok: false, status: 400, message: validated.message };
|
|
39
|
+
}
|
|
40
|
+
const config = resolveLifecycleConfig(options);
|
|
41
|
+
if (!config) {
|
|
42
|
+
return {
|
|
43
|
+
ok: false,
|
|
44
|
+
status: 503,
|
|
45
|
+
message: "Lifecycle integration is not configured"
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events`;
|
|
50
|
+
const response = await fetch(url, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: {
|
|
53
|
+
"Content-Type": "application/json",
|
|
54
|
+
"X-API-Key": config.apiKey
|
|
55
|
+
},
|
|
56
|
+
body: JSON.stringify(validated.value)
|
|
57
|
+
});
|
|
58
|
+
const data = await response.json().catch(() => ({}));
|
|
59
|
+
return parseIngestResponse(response.status, data);
|
|
60
|
+
} catch {
|
|
61
|
+
return {
|
|
62
|
+
ok: false,
|
|
63
|
+
status: 502,
|
|
64
|
+
message: "Upstream request failed"
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function retryMailooLifecycleEvent(eventId, options) {
|
|
69
|
+
const id = typeof eventId === "string" ? eventId.trim() : "";
|
|
70
|
+
if (!id) {
|
|
71
|
+
return { ok: false, status: 400, message: "eventId is required" };
|
|
72
|
+
}
|
|
73
|
+
const config = resolveLifecycleConfig(options);
|
|
74
|
+
if (!config) {
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
status: 503,
|
|
78
|
+
message: "Lifecycle integration is not configured"
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events/${encodeURIComponent(id)}/retry`;
|
|
83
|
+
const response = await fetch(url, {
|
|
84
|
+
method: "POST",
|
|
85
|
+
headers: {
|
|
86
|
+
"Content-Type": "application/json",
|
|
87
|
+
"X-API-Key": config.apiKey
|
|
88
|
+
},
|
|
89
|
+
body: "{}"
|
|
90
|
+
});
|
|
91
|
+
const data = await response.json().catch(() => ({}));
|
|
92
|
+
return parseIngestResponse(response.status, data);
|
|
93
|
+
} catch {
|
|
94
|
+
return {
|
|
95
|
+
ok: false,
|
|
96
|
+
status: 502,
|
|
97
|
+
message: "Upstream request failed"
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function getMailooLifecycleIntegrationConfig(options) {
|
|
102
|
+
return readMailooIntegrationConfig({
|
|
103
|
+
prefix: options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
export {
|
|
107
|
+
MAILOO_LIFECYCLE_INTEGRATION_PREFIX,
|
|
108
|
+
getMailooLifecycleIntegrationConfig,
|
|
109
|
+
ingestMailooLifecycleEvent,
|
|
110
|
+
retryMailooLifecycleEvent
|
|
111
|
+
};
|
|
112
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts"],"sourcesContent":["import {\n readMailooIntegrationConfig,\n type MailooIntegrationConfig,\n} from '@mailoo/next-core'\nimport {\n validateMailooLifecycleEvent,\n parseMailooLifecycleIngestData,\n type MailooLifecycleEventInput,\n type MailooLifecycleIngestData,\n} from '../events/index.js'\n\n/** Default env prefix for lifecycle ingest (needs `lifecycle.ingest` scope). */\nexport const MAILOO_LIFECYCLE_INTEGRATION_PREFIX = 'MAILOO_LIFECYCLE' as const\n\nexport type IngestMailooLifecycleEventOptions = {\n /** Env prefix; default `MAILOO_LIFECYCLE`. */\n prefix?: string\n /** Explicit config; wins over prefix/env when provided. */\n getConfig?: () => MailooIntegrationConfig | null\n}\n\nexport type MailooLifecycleIngestResult =\n | {\n ok: true\n status: number\n data: MailooLifecycleIngestData\n }\n | {\n ok: false\n status: number\n message: string\n data?: unknown\n }\n\nfunction resolveLifecycleConfig(\n options?: IngestMailooLifecycleEventOptions\n): MailooIntegrationConfig | null {\n if (options?.getConfig) {\n return options.getConfig()\n }\n const prefix = options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX\n return readMailooIntegrationConfig({ prefix })\n}\n\nfunction parseIngestResponse(\n status: number,\n data: unknown\n): MailooLifecycleIngestResult {\n if (status < 200 || status >= 300) {\n const message =\n typeof (data as { message?: string }).message === 'string'\n ? (data as { message: string }).message\n : typeof (data as { error?: string }).error === 'string'\n ? (data as { error: string }).error\n : 'Lifecycle ingest failed'\n return { ok: false, status, message, data }\n }\n const inner =\n data &&\n typeof data === 'object' &&\n !Array.isArray(data) &&\n 'data' in data\n ? (data as { data: unknown }).data\n : data\n const parsed = parseMailooLifecycleIngestData(inner)\n if (!parsed) {\n return {\n ok: false,\n status,\n message: 'Unexpected lifecycle ingest response shape',\n data,\n }\n }\n return { ok: true, status, data: parsed }\n}\n\n/**\n * Server-side lifecycle ingest (Server Action / Route Handler / Node).\n * Posts a validated event to Mailoo with the server-held API key.\n * The host chooses *when* to call; the package owns the contract.\n *\n * Never throws on missing config or network failure — returns\n * `{ ok: false, status, message }` so hosts can isolate the feature.\n *\n * Identity: pass your app user id as `externalUserId` (e.g. Firebase UID)\n * and the user's email. Mailoo merges by UID then email. Do not persist\n * returned `contactId` as your user key — it is Mailoo's internal cuid.\n */\nexport async function ingestMailooLifecycleEvent(\n input: MailooLifecycleEventInput | Record<string, unknown>,\n options?: IngestMailooLifecycleEventOptions\n): Promise<MailooLifecycleIngestResult> {\n const validated = validateMailooLifecycleEvent(input)\n if (!validated.ok) {\n return { ok: false, status: 400, message: validated.message }\n }\n\n const config = resolveLifecycleConfig(options)\n if (!config) {\n return {\n ok: false,\n status: 503,\n message: 'Lifecycle integration is not configured',\n }\n }\n\n try {\n const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events`\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': config.apiKey,\n },\n body: JSON.stringify(validated.value),\n })\n const data = await response.json().catch(() => ({}))\n return parseIngestResponse(response.status, data)\n } catch {\n return {\n ok: false,\n status: 502,\n message: 'Upstream request failed',\n }\n }\n}\n\n/**\n * Server-side retry of a stored lifecycle event (same typed result as ingest).\n * Never throws on missing config or network failure.\n */\nexport async function retryMailooLifecycleEvent(\n eventId: string,\n options?: IngestMailooLifecycleEventOptions\n): Promise<MailooLifecycleIngestResult> {\n const id = typeof eventId === 'string' ? eventId.trim() : ''\n if (!id) {\n return { ok: false, status: 400, message: 'eventId is required' }\n }\n const config = resolveLifecycleConfig(options)\n if (!config) {\n return {\n ok: false,\n status: 503,\n message: 'Lifecycle integration is not configured',\n }\n }\n\n try {\n const url = `${config.apiBaseUrl}/api/v1/webhooks/lifecycle/${config.projectUid}/${config.integrationId}/events/${encodeURIComponent(id)}/retry`\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': config.apiKey,\n },\n body: '{}',\n })\n const data = await response.json().catch(() => ({}))\n return parseIngestResponse(response.status, data)\n } catch {\n return {\n ok: false,\n status: 502,\n message: 'Upstream request failed',\n }\n }\n}\n\nexport function getMailooLifecycleIntegrationConfig(options?: {\n prefix?: string\n}): MailooIntegrationConfig | null {\n return readMailooIntegrationConfig({\n prefix: options?.prefix ?? MAILOO_LIFECYCLE_INTEGRATION_PREFIX,\n })\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,OAEK;AASA,IAAM,sCAAsC;AAsBnD,SAAS,uBACP,SACgC;AAChC,MAAI,SAAS,WAAW;AACtB,WAAO,QAAQ,UAAU;AAAA,EAC3B;AACA,QAAM,SAAS,SAAS,UAAU;AAClC,SAAO,4BAA4B,EAAE,OAAO,CAAC;AAC/C;AAEA,SAAS,oBACP,QACA,MAC6B;AAC7B,MAAI,SAAS,OAAO,UAAU,KAAK;AACjC,UAAM,UACJ,OAAQ,KAA8B,YAAY,WAC7C,KAA6B,UAC9B,OAAQ,KAA4B,UAAU,WAC3C,KAA2B,QAC5B;AACR,WAAO,EAAE,IAAI,OAAO,QAAQ,SAAS,KAAK;AAAA,E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IAAI,OAAO,QAAQ,KAAK,SAAS,sBAAsB;AAAA,EAClE;AACA,QAAM,SAAS,uBAAuB,OAAO;AAC7C,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI;AACF,UAAM,MAAM,GAAG,OAAO,UAAU,8BAA8B,OAAO,UAAU,IAAI,OAAO,aAAa,WAAW,mBAAmB,EAAE,CAAC;AACxI,UAAM,WAAW,MAAM,MAAM,KAAK;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AACD,UAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AACnD,WAAO,oBAAoB,SAAS,QAAQ,IAAI;AAAA,EAClD,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AACF;AAEO,SAAS,oCAAoC,SAEjB;AACjC,SAAO,4BAA4B;AAAA,IACjC,QAAQ,SAAS,UAAU;AAAA,EAC7B,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/webhooks/index.ts
|
|
21
|
+
var webhooks_exports = {};
|
|
22
|
+
__export(webhooks_exports, {
|
|
23
|
+
asMailooConsentChanged: () => asMailooConsentChanged,
|
|
24
|
+
verifyMailooDeliveryWebhook: () => verifyMailooDeliveryWebhook
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(webhooks_exports);
|
|
27
|
+
var import_node_crypto = require("crypto");
|
|
28
|
+
function isPlainObject(v) {
|
|
29
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
30
|
+
}
|
|
31
|
+
function verifyMailooDeliveryWebhook(rawBody, headers, secret) {
|
|
32
|
+
const get = (name) => {
|
|
33
|
+
if (headers instanceof Headers) {
|
|
34
|
+
return headers.get(name);
|
|
35
|
+
}
|
|
36
|
+
const lower = name.toLowerCase();
|
|
37
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
38
|
+
if (k.toLowerCase() === lower) {
|
|
39
|
+
return typeof v === "string" ? v : v ?? null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
};
|
|
44
|
+
const signatureHeader = get("x-mailoo-signature");
|
|
45
|
+
if (!signatureHeader || !signatureHeader.trim()) {
|
|
46
|
+
return { ok: false, message: "Missing X-Mailoo-Signature" };
|
|
47
|
+
}
|
|
48
|
+
if (!secret.trim()) {
|
|
49
|
+
return { ok: false, message: "Webhook secret is empty" };
|
|
50
|
+
}
|
|
51
|
+
let timestamp = 0;
|
|
52
|
+
let v1 = "";
|
|
53
|
+
for (const part of signatureHeader.split(",")) {
|
|
54
|
+
const [k, v] = part.trim().split("=", 2);
|
|
55
|
+
if (k === "t" && v) timestamp = Number(v);
|
|
56
|
+
if (k === "v1" && v) v1 = v;
|
|
57
|
+
}
|
|
58
|
+
if (!Number.isFinite(timestamp) || timestamp <= 0 || !v1) {
|
|
59
|
+
return { ok: false, message: "Invalid X-Mailoo-Signature format" };
|
|
60
|
+
}
|
|
61
|
+
const expected = (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
|
|
62
|
+
const a = Buffer.from(expected, "utf8");
|
|
63
|
+
const b = Buffer.from(v1, "utf8");
|
|
64
|
+
if (a.length !== b.length || !(0, import_node_crypto.timingSafeEqual)(a, b)) {
|
|
65
|
+
return { ok: false, message: "Invalid delivery webhook signature" };
|
|
66
|
+
}
|
|
67
|
+
let parsed;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(rawBody);
|
|
70
|
+
} catch {
|
|
71
|
+
return { ok: false, message: "Invalid JSON body" };
|
|
72
|
+
}
|
|
73
|
+
if (!isPlainObject(parsed) || typeof parsed.event !== "string") {
|
|
74
|
+
return { ok: false, message: "Invalid delivery webhook payload" };
|
|
75
|
+
}
|
|
76
|
+
if (typeof parsed.integrationId !== "string") {
|
|
77
|
+
return { ok: false, message: "integrationId is required" };
|
|
78
|
+
}
|
|
79
|
+
if (typeof parsed.timestamp !== "string") {
|
|
80
|
+
return { ok: false, message: "timestamp is required" };
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
ok: true,
|
|
84
|
+
timestamp,
|
|
85
|
+
payload: parsed
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function asMailooConsentChanged(payload) {
|
|
89
|
+
if (payload.event !== "consent.changed") return null;
|
|
90
|
+
if (typeof payload.recipientEmail !== "string" || !payload.recipientEmail) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
if (typeof payload.marketingConsentGranted !== "boolean") {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
event: "consent.changed",
|
|
98
|
+
integrationId: payload.integrationId,
|
|
99
|
+
externalUserId: typeof payload.externalUserId === "string" ? payload.externalUserId : payload.externalUserId === null ? null : null,
|
|
100
|
+
recipientEmail: payload.recipientEmail,
|
|
101
|
+
marketingConsentGranted: payload.marketingConsentGranted,
|
|
102
|
+
unsubscribedAt: typeof payload.unsubscribedAt === "string" ? payload.unsubscribedAt : null,
|
|
103
|
+
timestamp: payload.timestamp
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
107
|
+
0 && (module.exports = {
|
|
108
|
+
asMailooConsentChanged,
|
|
109
|
+
verifyMailooDeliveryWebhook
|
|
110
|
+
});
|
|
111
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/webhooks/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto'\n\nexport type MailooDeliveryWebhookEventName =\n | 'accepted'\n | 'deferred'\n | 'delivered'\n | 'opened'\n | 'clicked'\n | 'unsubscribed'\n | 'bounced'\n | 'consent.changed'\n\nexport type MailooDeliveryWebhookPayload = {\n event: MailooDeliveryWebhookEventName | string\n integrationId: string\n messageId?: string\n idempotencyKey?: string\n recipientEmail?: string\n externalUserId?: string | null\n marketingConsentGranted?: boolean\n unsubscribedAt?: string | null\n timestamp: string\n metadata?: Record<string, unknown>\n}\n\nexport type MailooConsentChangedPayload = {\n event: 'consent.changed'\n integrationId: string\n externalUserId: string | null\n recipientEmail: string\n marketingConsentGranted: boolean\n unsubscribedAt: string | null\n timestamp: string\n}\n\nexport type VerifyMailooDeliveryWebhookResult =\n | { ok: true; timestamp: number; payload: MailooDeliveryWebhookPayload }\n | { ok: false; message: string }\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\n/**\n * Verify `X-Mailoo-Signature: t={unix},v1={hex}` over `\"{timestamp}.{rawBody}\"`.\n */\nexport function verifyMailooDeliveryWebhook(\n rawBody: string,\n headers: Headers | Record<string, string | null | undefined>,\n secret: string\n): VerifyMailooDeliveryWebhookResult {\n const get = (name: string): string | null => {\n if (headers instanceof Headers) {\n return headers.get(name)\n }\n const lower = name.toLowerCase()\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === lower) {\n return typeof v === 'string' ? v : v ?? null\n }\n }\n return null\n }\n\n const signatureHeader = get('x-mailoo-signature')\n if (!signatureHeader || !signatureHeader.trim()) {\n return { ok: false, message: 'Missing X-Mailoo-Signature' }\n }\n if (!secret.trim()) {\n return { ok: false, message: 'Webhook secret is empty' }\n }\n\n let timestamp = 0\n let v1 = ''\n for (const part of signatureHeader.split(',')) {\n const [k, v] = part.trim().split('=', 2)\n if (k === 't' && v) timestamp = Number(v)\n if (k === 'v1' && v) v1 = v\n }\n if (!Number.isFinite(timestamp) || timestamp <= 0 || !v1) {\n return { ok: false, message: 'Invalid X-Mailoo-Signature format' }\n }\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${rawBody}`)\n .digest('hex')\n const a = Buffer.from(expected, 'utf8')\n const b = Buffer.from(v1, 'utf8')\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n return { ok: false, message: 'Invalid delivery webhook signature' }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(rawBody)\n } catch {\n return { ok: false, message: 'Invalid JSON body' }\n }\n if (!isPlainObject(parsed) || typeof parsed.event !== 'string') {\n return { ok: false, message: 'Invalid delivery webhook payload' }\n }\n if (typeof parsed.integrationId !== 'string') {\n return { ok: false, message: 'integrationId is required' }\n }\n if (typeof parsed.timestamp !== 'string') {\n return { ok: false, message: 'timestamp is required' }\n }\n\n return {\n ok: true,\n timestamp,\n payload: parsed as MailooDeliveryWebhookPayload,\n }\n}\n\nexport function asMailooConsentChanged(\n payload: MailooDeliveryWebhookPayload\n): MailooConsentChangedPayload | null {\n if (payload.event !== 'consent.changed') return null\n if (typeof payload.recipientEmail !== 'string' || !payload.recipientEmail) {\n return null\n }\n if (typeof payload.marketingConsentGranted !== 'boolean') {\n return null\n }\n return {\n event: 'consent.changed',\n integrationId: payload.integrationId,\n externalUserId:\n typeof payload.externalUserId === 'string'\n ? payload.externalUserId\n : payload.externalUserId === null\n ? null\n : null,\n recipientEmail: payload.recipientEmail,\n marketingConsentGranted: payload.marketingConsentGranted,\n unsubscribedAt:\n typeof payload.unsubscribedAt === 'string'\n ? payload.unsubscribedAt\n : null,\n timestamp: payload.timestamp,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA4C;AAuC5C,SAAS,cAAc,GAA0C;AAC/D,SAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;AAKO,SAAS,4BACd,SACA,SACA,QACmC;AACnC,QAAM,MAAM,CAAC,SAAgC;AAC3C,QAAI,mBAAmB,SAAS;AAC9B,aAAO,QAAQ,IAAI,IAAI;AAAA,IACzB;AACA,UAAM,QAAQ,KAAK,YAAY;AAC/B,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,OAAO,GAAG;AAC5C,UAAI,EAAE,YAAY,MAAM,OAAO;AAC7B,eAAO,OAAO,MAAM,WAAW,IAAI,KAAK;AAAA,MAC1C;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,QAAM,kBAAkB,IAAI,oBAAoB;AAChD,MAAI,CAAC,mBAAmB,CAAC,gBAAgB,KAAK,GAAG;AAC/C,WAAO,EAAE,IAAI,OAAO,SAAS,6BAA6B;AAAA,EAC5D;AACA,MAAI,CAAC,OAAO,KAAK,GAAG;AAClB,WAAO,EAAE,IAAI,OAAO,SAAS,0BAA0B;AAAA,EACzD;AAEA,MAAI,YAAY;AAChB,MAAI,KAAK;AACT,aAAW,QAAQ,gBAAgB,MAAM,GAAG,GAAG;AAC7C,UAAM,CAAC,G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