posthog-node 5.60.1 → 5.61.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +34 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +33 -4
- package/dist/client.mjs +33 -4
- package/dist/emails/emails.d.ts +45 -0
- package/dist/emails/emails.d.ts.map +1 -0
- package/dist/emails/emails.js +360 -0
- package/dist/emails/emails.mjs +316 -0
- package/dist/emails/errors.d.ts +37 -0
- package/dist/emails/errors.d.ts.map +1 -0
- package/dist/emails/errors.js +79 -0
- package/dist/emails/errors.mjs +41 -0
- package/dist/emails/types.d.ts +112 -0
- package/dist/emails/types.d.ts.map +1 -0
- package/dist/emails/types.js +18 -0
- package/dist/emails/types.mjs +1 -0
- package/dist/exports.d.ts +3 -0
- package/dist/exports.d.ts.map +1 -1
- package/dist/exports.js +19 -9
- package/dist/exports.mjs +1 -0
- package/dist/extensions/error-tracking/autocapture.d.ts +32 -2
- package/dist/extensions/error-tracking/autocapture.d.ts.map +1 -1
- package/dist/extensions/error-tracking/autocapture.js +337 -35
- package/dist/extensions/error-tracking/autocapture.mjs +324 -28
- package/dist/extensions/error-tracking/index.d.ts +16 -1
- package/dist/extensions/error-tracking/index.d.ts.map +1 -1
- package/dist/extensions/error-tracking/index.js +23 -8
- package/dist/extensions/error-tracking/index.mjs +24 -9
- package/dist/types.d.ts +33 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +2 -2
- package/src/client.ts +76 -3
- package/src/emails/emails.ts +459 -0
- package/src/emails/errors.ts +90 -0
- package/src/emails/types.ts +108 -0
- package/src/exports.ts +12 -0
- package/src/extensions/error-tracking/autocapture.ts +579 -57
- package/src/extensions/error-tracking/index.ts +48 -10
- package/src/types.ts +34 -2
- package/src/version.ts +1 -1
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __webpack_require__ = {};
|
|
3
|
+
(()=>{
|
|
4
|
+
__webpack_require__.d = (exports1, getters, values)=>{
|
|
5
|
+
var define = (defs, kind)=>{
|
|
6
|
+
for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
[kind]: defs[key]
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
define(getters, "get");
|
|
12
|
+
define(values, "value");
|
|
13
|
+
};
|
|
14
|
+
})();
|
|
15
|
+
(()=>{
|
|
16
|
+
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
17
|
+
})();
|
|
18
|
+
(()=>{
|
|
19
|
+
__webpack_require__.r = (exports1)=>{
|
|
20
|
+
if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
|
|
21
|
+
value: 'Module'
|
|
22
|
+
});
|
|
23
|
+
Object.defineProperty(exports1, '__esModule', {
|
|
24
|
+
value: true
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
})();
|
|
28
|
+
var __webpack_exports__ = {};
|
|
29
|
+
__webpack_require__.r(__webpack_exports__);
|
|
30
|
+
__webpack_require__.d(__webpack_exports__, {
|
|
31
|
+
DEFAULT_EMAIL_REQUEST_MAX_RETRIES: ()=>DEFAULT_EMAIL_REQUEST_MAX_RETRIES,
|
|
32
|
+
DEFAULT_EMAIL_REQUEST_TIMEOUT_MS: ()=>DEFAULT_EMAIL_REQUEST_TIMEOUT_MS,
|
|
33
|
+
EmailSender: ()=>EmailSender
|
|
34
|
+
});
|
|
35
|
+
const core_namespaceObject = require("@posthog/core");
|
|
36
|
+
const external_errors_js_namespaceObject = require("./errors.js");
|
|
37
|
+
const SEND_PATH = '/api/projects/@current/messaging/send/email/';
|
|
38
|
+
const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/';
|
|
39
|
+
const US_APP_HOST = 'https://us.posthog.com';
|
|
40
|
+
const EU_APP_HOST = 'https://eu.posthog.com';
|
|
41
|
+
const CLOUD_APP_HOSTS = {
|
|
42
|
+
'https://us.i.posthog.com': US_APP_HOST,
|
|
43
|
+
'https://us.posthog.com': US_APP_HOST,
|
|
44
|
+
'https://app.posthog.com': US_APP_HOST,
|
|
45
|
+
'https://eu.i.posthog.com': EU_APP_HOST,
|
|
46
|
+
'https://eu.posthog.com': EU_APP_HOST
|
|
47
|
+
};
|
|
48
|
+
const MAX_RETRY_DELAY_MS = 30000;
|
|
49
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
50
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{1,255}$/;
|
|
51
|
+
const DEFAULT_EMAIL_REQUEST_TIMEOUT_MS = 15000;
|
|
52
|
+
const DEFAULT_EMAIL_REQUEST_MAX_RETRIES = 2;
|
|
53
|
+
class EmailSender {
|
|
54
|
+
constructor(config, hooks){
|
|
55
|
+
this.inFlight = new Set();
|
|
56
|
+
this.config = config;
|
|
57
|
+
this.hooks = hooks;
|
|
58
|
+
}
|
|
59
|
+
send(options) {
|
|
60
|
+
return this.track(this.sendUntracked(options));
|
|
61
|
+
}
|
|
62
|
+
get(id) {
|
|
63
|
+
return this.track(this.getUntracked(id));
|
|
64
|
+
}
|
|
65
|
+
track(pending) {
|
|
66
|
+
this.inFlight.add(pending);
|
|
67
|
+
pending.finally(()=>this.inFlight.delete(pending));
|
|
68
|
+
return pending;
|
|
69
|
+
}
|
|
70
|
+
async drain() {
|
|
71
|
+
while(this.inFlight.size > 0)await Promise.all(this.inFlight);
|
|
72
|
+
}
|
|
73
|
+
async sendUntracked(options) {
|
|
74
|
+
try {
|
|
75
|
+
const prepared = prepareSend(options, this.config.maxRetries);
|
|
76
|
+
const { appHost, secretKey } = this.connect('no email was sent', 'Sending email needs secretKey, a project secret API key with the hog_flow:write scope.');
|
|
77
|
+
const headers = this.headers(secretKey, {
|
|
78
|
+
'Content-Type': 'application/json',
|
|
79
|
+
'Idempotency-Key': prepared.idempotencyKey
|
|
80
|
+
});
|
|
81
|
+
const result = await this.withRetries(prepared.maxRetries, async ()=>parseSendReply(await this.request(appHost + prepared.path, 'POST', headers, prepared.body)));
|
|
82
|
+
for (const warning of result.warnings)this.hooks.logger.warn(`PostHog email warning ${warning.code}: ${warning.message}`);
|
|
83
|
+
return {
|
|
84
|
+
data: result,
|
|
85
|
+
error: null
|
|
86
|
+
};
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return {
|
|
89
|
+
data: null,
|
|
90
|
+
error: asEmailError(error, 'Sending the email failed unexpectedly.')
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async getUntracked(id) {
|
|
95
|
+
try {
|
|
96
|
+
if ('string' != typeof id || !UUID_PATTERN.test(id)) throw invalid('invalid_message_id', 'id must be the message ID that send() returned.', 'id');
|
|
97
|
+
const { appHost, secretKey } = this.connect('no email status was read', 'Reading an email status needs secretKey, a project secret API key with the hog_flow:read or hog_flow:write scope.');
|
|
98
|
+
const url = appHost + STATUS_PATH.replace('{messageId}', id.toLowerCase());
|
|
99
|
+
const headers = this.headers(secretKey, {});
|
|
100
|
+
const status = await this.withRetries(this.config.maxRetries, async ()=>parseStatusReply(await this.request(url, 'GET', headers)));
|
|
101
|
+
return {
|
|
102
|
+
data: status,
|
|
103
|
+
error: null
|
|
104
|
+
};
|
|
105
|
+
} catch (error) {
|
|
106
|
+
return {
|
|
107
|
+
data: null,
|
|
108
|
+
error: asEmailError(error, 'Reading the email status failed unexpectedly.')
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
connect(nothingDone, missingSecretKey) {
|
|
113
|
+
if (this.hooks.isDisabled()) throw new external_errors_js_namespaceObject.EmailError({
|
|
114
|
+
code: 'client_disabled',
|
|
115
|
+
message: `The PostHog client is disabled, so ${nothingDone}.`
|
|
116
|
+
});
|
|
117
|
+
if (this.hooks.isClosed()) throw new external_errors_js_namespaceObject.EmailError({
|
|
118
|
+
code: 'client_closed',
|
|
119
|
+
message: `The PostHog client is shut down, so ${nothingDone}.`
|
|
120
|
+
});
|
|
121
|
+
const appHost = resolveAppHost(this.config.host, this.config.appHost);
|
|
122
|
+
if (!appHost) throw new external_errors_js_namespaceObject.EmailError({
|
|
123
|
+
code: 'missing_app_host',
|
|
124
|
+
message: "The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."
|
|
125
|
+
});
|
|
126
|
+
const secretKey = this.config.secretKey?.trim();
|
|
127
|
+
if (!secretKey) throw new external_errors_js_namespaceObject.EmailError({
|
|
128
|
+
code: 'missing_secret_key',
|
|
129
|
+
message: missingSecretKey
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
appHost,
|
|
133
|
+
secretKey
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
headers(secretKey, extra) {
|
|
137
|
+
const headers = {
|
|
138
|
+
Authorization: `Bearer ${secretKey}`,
|
|
139
|
+
Accept: 'application/json',
|
|
140
|
+
...extra
|
|
141
|
+
};
|
|
142
|
+
if (this.hooks.userAgent) headers['User-Agent'] = this.hooks.userAgent;
|
|
143
|
+
return headers;
|
|
144
|
+
}
|
|
145
|
+
async withRetries(maxRetries, attemptOnce) {
|
|
146
|
+
for(let attempt = 0;; attempt++){
|
|
147
|
+
let error;
|
|
148
|
+
try {
|
|
149
|
+
return await attemptOnce();
|
|
150
|
+
} catch (caught) {
|
|
151
|
+
error = caught instanceof external_errors_js_namespaceObject.EmailError ? caught : new external_errors_js_namespaceObject.EmailError({
|
|
152
|
+
code: 'network_error',
|
|
153
|
+
message: 'The request to PostHog failed.',
|
|
154
|
+
cause: caught
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const delayMs = retryDelayMs(error, attempt, maxRetries);
|
|
158
|
+
if (void 0 === delayMs) throw error;
|
|
159
|
+
await new Promise((resolve)=>setTimeout(resolve, delayMs));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async request(url, method, headers, body) {
|
|
163
|
+
const controller = new AbortController();
|
|
164
|
+
const timeoutMs = this.config.requestTimeoutMs;
|
|
165
|
+
let timer;
|
|
166
|
+
const deadline = new Promise((_resolve, reject)=>{
|
|
167
|
+
timer = setTimeout(()=>{
|
|
168
|
+
const timeoutError = new Error(`Email request timed out after ${timeoutMs}ms`);
|
|
169
|
+
timeoutError.name = 'AbortError';
|
|
170
|
+
reject(timeoutError);
|
|
171
|
+
controller.abort(timeoutError);
|
|
172
|
+
}, timeoutMs);
|
|
173
|
+
});
|
|
174
|
+
const fetchPromise = Promise.resolve().then(()=>this.hooks.fetch(url, {
|
|
175
|
+
method,
|
|
176
|
+
headers,
|
|
177
|
+
...void 0 === body ? {} : {
|
|
178
|
+
body
|
|
179
|
+
},
|
|
180
|
+
signal: controller.signal
|
|
181
|
+
}));
|
|
182
|
+
fetchPromise.then((lateResponse)=>{
|
|
183
|
+
if (controller.signal.aborted) Promise.resolve(lateResponse.body?.cancel()).catch(()=>{});
|
|
184
|
+
}).catch(()=>{});
|
|
185
|
+
let response;
|
|
186
|
+
try {
|
|
187
|
+
response = await Promise.race([
|
|
188
|
+
fetchPromise,
|
|
189
|
+
deadline
|
|
190
|
+
]);
|
|
191
|
+
let text;
|
|
192
|
+
try {
|
|
193
|
+
text = await Promise.race([
|
|
194
|
+
response.text(),
|
|
195
|
+
deadline
|
|
196
|
+
]);
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (response.status >= 200 && response.status < 300) throw error;
|
|
199
|
+
return {
|
|
200
|
+
status: response.status,
|
|
201
|
+
payload: null,
|
|
202
|
+
retryAfterMs: readRetryAfter(response)
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
status: response.status,
|
|
207
|
+
payload: parseJson(text),
|
|
208
|
+
retryAfterMs: readRetryAfter(response)
|
|
209
|
+
};
|
|
210
|
+
} finally{
|
|
211
|
+
clearTimeout(timer);
|
|
212
|
+
if (controller.signal.aborted && response) Promise.resolve(response.body?.cancel()).catch(()=>{});
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function prepareSend(options, defaultMaxRetries) {
|
|
217
|
+
const fallback = {};
|
|
218
|
+
const { to, templateId, templateData, distinctId, idempotencyKey, maxRetries } = options ?? fallback;
|
|
219
|
+
if ('string' != typeof to || !to.trim()) throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to');
|
|
220
|
+
if ('string' != typeof templateId || !UUID_PATTERN.test(templateId)) throw invalid('invalid_template_id', "templateId must be the template's UUID.", 'templateId');
|
|
221
|
+
if (void 0 !== templateData && ('object' != typeof templateData || null === templateData || Array.isArray(templateData))) throw invalid('invalid_template_data', 'templateData must be an object.', 'templateData');
|
|
222
|
+
if (void 0 !== distinctId && ('string' != typeof distinctId || !distinctId)) throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId');
|
|
223
|
+
if (void 0 !== idempotencyKey && ('string' != typeof idempotencyKey || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))) throw invalid('invalid_idempotency_key', 'idempotencyKey must be 1 to 255 visible ASCII characters without spaces.', 'idempotencyKey');
|
|
224
|
+
if (void 0 !== maxRetries && !(Number.isInteger(maxRetries) && maxRetries >= 0)) throw invalid('invalid_max_retries', 'maxRetries must be a nonnegative integer.', 'maxRetries');
|
|
225
|
+
const payload = {
|
|
226
|
+
template: {
|
|
227
|
+
id: templateId.toLowerCase()
|
|
228
|
+
},
|
|
229
|
+
to,
|
|
230
|
+
message_data: templateData ?? {}
|
|
231
|
+
};
|
|
232
|
+
if (void 0 !== distinctId) payload.identifiers = {
|
|
233
|
+
distinct_id: distinctId
|
|
234
|
+
};
|
|
235
|
+
return {
|
|
236
|
+
path: SEND_PATH,
|
|
237
|
+
body: (0, core_namespaceObject.safeJsonStringify)(payload),
|
|
238
|
+
idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
|
|
239
|
+
maxRetries: maxRetries ?? defaultMaxRetries
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function invalid(code, message, field) {
|
|
243
|
+
return new external_errors_js_namespaceObject.EmailError({
|
|
244
|
+
code,
|
|
245
|
+
message,
|
|
246
|
+
field
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
function resolveAppHost(host, appHost) {
|
|
250
|
+
const explicit = 'string' == typeof appHost ? (0, core_namespaceObject.removeTrailingSlash)(appHost.trim()) : '';
|
|
251
|
+
if (explicit) return CLOUD_APP_HOSTS[explicit] ?? explicit;
|
|
252
|
+
return CLOUD_APP_HOSTS[(0, core_namespaceObject.removeTrailingSlash)(host)];
|
|
253
|
+
}
|
|
254
|
+
function parseJson(text) {
|
|
255
|
+
try {
|
|
256
|
+
return JSON.parse(text);
|
|
257
|
+
} catch {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function readRetryAfter(response) {
|
|
262
|
+
try {
|
|
263
|
+
return (0, core_namespaceObject.parseRetryAfterMs)(response.headers?.get('retry-after'), Date.now(), Number.MAX_SAFE_INTEGER);
|
|
264
|
+
} catch {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function emails_text(value) {
|
|
269
|
+
return 'string' == typeof value && value ? value : void 0;
|
|
270
|
+
}
|
|
271
|
+
function replyFields(payload) {
|
|
272
|
+
return null === payload || 'object' != typeof payload || Array.isArray(payload) ? {} : payload;
|
|
273
|
+
}
|
|
274
|
+
function parseSendReply({ status, payload, retryAfterMs }) {
|
|
275
|
+
const fields = replyFields(payload);
|
|
276
|
+
if (status >= 200 && status < 300) {
|
|
277
|
+
const id = emails_text(fields.message_id);
|
|
278
|
+
if (!id) throw new external_errors_js_namespaceObject.EmailError({
|
|
279
|
+
code: 'api_error',
|
|
280
|
+
message: 'PostHog answered without a message ID.',
|
|
281
|
+
statusCode: status
|
|
282
|
+
});
|
|
283
|
+
const warnings = [];
|
|
284
|
+
if (Array.isArray(fields.warnings)) {
|
|
285
|
+
for (const warning of fields.warnings)if (null !== warning && 'object' == typeof warning) warnings.push({
|
|
286
|
+
code: emails_text(warning.code) ?? 'warning',
|
|
287
|
+
message: emails_text(warning.detail) ?? emails_text(warning.message) ?? '',
|
|
288
|
+
fix: emails_text(warning.fix)
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
return {
|
|
292
|
+
id,
|
|
293
|
+
replayed: true === fields.replayed,
|
|
294
|
+
warnings
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
throw replyError(fields, status, retryAfterMs);
|
|
298
|
+
}
|
|
299
|
+
function parseStatusReply({ status, payload, retryAfterMs }) {
|
|
300
|
+
const fields = replyFields(payload);
|
|
301
|
+
if (status < 200 || status >= 300) throw replyError(fields, status, retryAfterMs);
|
|
302
|
+
const id = emails_text(fields.id);
|
|
303
|
+
const deliveryStatus = emails_text(fields.status);
|
|
304
|
+
const createdAt = emails_text(fields.created_at);
|
|
305
|
+
const statusAt = emails_text(fields.status_at);
|
|
306
|
+
if (!id || !deliveryStatus || !createdAt || !statusAt) throw new external_errors_js_namespaceObject.EmailError({
|
|
307
|
+
code: 'api_error',
|
|
308
|
+
message: 'PostHog answered without an email status.',
|
|
309
|
+
statusCode: status
|
|
310
|
+
});
|
|
311
|
+
return {
|
|
312
|
+
id,
|
|
313
|
+
status: deliveryStatus,
|
|
314
|
+
createdAt,
|
|
315
|
+
statusAt,
|
|
316
|
+
reason: emails_text(fields.reason) ?? null
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
function replyError(fields, status, retryAfterMs) {
|
|
320
|
+
return new external_errors_js_namespaceObject.EmailError({
|
|
321
|
+
code: emails_text(fields.code) ?? 'api_error',
|
|
322
|
+
message: emails_text(fields.detail) ?? `PostHog answered HTTP ${status}.`,
|
|
323
|
+
statusCode: status,
|
|
324
|
+
why: emails_text(fields.why),
|
|
325
|
+
fix: emails_text(fields.fix),
|
|
326
|
+
docsUrl: emails_text(fields.docs_url),
|
|
327
|
+
field: emails_text(fields.attr),
|
|
328
|
+
retryAfterMs
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
function asEmailError(error, message) {
|
|
332
|
+
return error instanceof external_errors_js_namespaceObject.EmailError ? error : new external_errors_js_namespaceObject.EmailError({
|
|
333
|
+
code: 'unexpected_error',
|
|
334
|
+
message,
|
|
335
|
+
cause: error
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
function isRetryable(error) {
|
|
339
|
+
if (void 0 === error.statusCode) return 'network_error' === error.code;
|
|
340
|
+
if (409 === error.statusCode) return 'idempotency_key_in_flight' === error.code;
|
|
341
|
+
if (429 === error.statusCode) return 'quota_limited' !== error.code;
|
|
342
|
+
return 503 === error.statusCode;
|
|
343
|
+
}
|
|
344
|
+
function retryDelayMs(error, attempt, maxRetries) {
|
|
345
|
+
if (attempt >= maxRetries || !isRetryable(error)) return;
|
|
346
|
+
if (void 0 !== error.retryAfterMs && error.retryAfterMs > MAX_RETRY_DELAY_MS) return;
|
|
347
|
+
const backoffMs = Math.min(MAX_RETRY_DELAY_MS, 1000 * 2 ** attempt * (0.8 + 0.4 * Math.random()));
|
|
348
|
+
return Math.max(backoffMs, error.retryAfterMs ?? 0);
|
|
349
|
+
}
|
|
350
|
+
exports.DEFAULT_EMAIL_REQUEST_MAX_RETRIES = __webpack_exports__.DEFAULT_EMAIL_REQUEST_MAX_RETRIES;
|
|
351
|
+
exports.DEFAULT_EMAIL_REQUEST_TIMEOUT_MS = __webpack_exports__.DEFAULT_EMAIL_REQUEST_TIMEOUT_MS;
|
|
352
|
+
exports.EmailSender = __webpack_exports__.EmailSender;
|
|
353
|
+
for(var __rspack_i in __webpack_exports__)if (-1 === [
|
|
354
|
+
"DEFAULT_EMAIL_REQUEST_MAX_RETRIES",
|
|
355
|
+
"DEFAULT_EMAIL_REQUEST_TIMEOUT_MS",
|
|
356
|
+
"EmailSender"
|
|
357
|
+
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
|
|
358
|
+
Object.defineProperty(exports, '__esModule', {
|
|
359
|
+
value: true
|
|
360
|
+
});
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { parseRetryAfterMs, removeTrailingSlash, safeJsonStringify } from "@posthog/core";
|
|
2
|
+
import { EmailError } from "./errors.mjs";
|
|
3
|
+
const SEND_PATH = '/api/projects/@current/messaging/send/email/';
|
|
4
|
+
const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/';
|
|
5
|
+
const US_APP_HOST = 'https://us.posthog.com';
|
|
6
|
+
const EU_APP_HOST = 'https://eu.posthog.com';
|
|
7
|
+
const CLOUD_APP_HOSTS = {
|
|
8
|
+
'https://us.i.posthog.com': US_APP_HOST,
|
|
9
|
+
'https://us.posthog.com': US_APP_HOST,
|
|
10
|
+
'https://app.posthog.com': US_APP_HOST,
|
|
11
|
+
'https://eu.i.posthog.com': EU_APP_HOST,
|
|
12
|
+
'https://eu.posthog.com': EU_APP_HOST
|
|
13
|
+
};
|
|
14
|
+
const MAX_RETRY_DELAY_MS = 30000;
|
|
15
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7e]{1,255}$/;
|
|
17
|
+
const DEFAULT_EMAIL_REQUEST_TIMEOUT_MS = 15000;
|
|
18
|
+
const DEFAULT_EMAIL_REQUEST_MAX_RETRIES = 2;
|
|
19
|
+
class EmailSender {
|
|
20
|
+
constructor(config, hooks){
|
|
21
|
+
this.inFlight = new Set();
|
|
22
|
+
this.config = config;
|
|
23
|
+
this.hooks = hooks;
|
|
24
|
+
}
|
|
25
|
+
send(options) {
|
|
26
|
+
return this.track(this.sendUntracked(options));
|
|
27
|
+
}
|
|
28
|
+
get(id) {
|
|
29
|
+
return this.track(this.getUntracked(id));
|
|
30
|
+
}
|
|
31
|
+
track(pending) {
|
|
32
|
+
this.inFlight.add(pending);
|
|
33
|
+
pending.finally(()=>this.inFlight.delete(pending));
|
|
34
|
+
return pending;
|
|
35
|
+
}
|
|
36
|
+
async drain() {
|
|
37
|
+
while(this.inFlight.size > 0)await Promise.all(this.inFlight);
|
|
38
|
+
}
|
|
39
|
+
async sendUntracked(options) {
|
|
40
|
+
try {
|
|
41
|
+
const prepared = prepareSend(options, this.config.maxRetries);
|
|
42
|
+
const { appHost, secretKey } = this.connect('no email was sent', 'Sending email needs secretKey, a project secret API key with the hog_flow:write scope.');
|
|
43
|
+
const headers = this.headers(secretKey, {
|
|
44
|
+
'Content-Type': 'application/json',
|
|
45
|
+
'Idempotency-Key': prepared.idempotencyKey
|
|
46
|
+
});
|
|
47
|
+
const result = await this.withRetries(prepared.maxRetries, async ()=>parseSendReply(await this.request(appHost + prepared.path, 'POST', headers, prepared.body)));
|
|
48
|
+
for (const warning of result.warnings)this.hooks.logger.warn(`PostHog email warning ${warning.code}: ${warning.message}`);
|
|
49
|
+
return {
|
|
50
|
+
data: result,
|
|
51
|
+
error: null
|
|
52
|
+
};
|
|
53
|
+
} catch (error) {
|
|
54
|
+
return {
|
|
55
|
+
data: null,
|
|
56
|
+
error: asEmailError(error, 'Sending the email failed unexpectedly.')
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async getUntracked(id) {
|
|
61
|
+
try {
|
|
62
|
+
if ('string' != typeof id || !UUID_PATTERN.test(id)) throw invalid('invalid_message_id', 'id must be the message ID that send() returned.', 'id');
|
|
63
|
+
const { appHost, secretKey } = this.connect('no email status was read', 'Reading an email status needs secretKey, a project secret API key with the hog_flow:read or hog_flow:write scope.');
|
|
64
|
+
const url = appHost + STATUS_PATH.replace('{messageId}', id.toLowerCase());
|
|
65
|
+
const headers = this.headers(secretKey, {});
|
|
66
|
+
const status = await this.withRetries(this.config.maxRetries, async ()=>parseStatusReply(await this.request(url, 'GET', headers)));
|
|
67
|
+
return {
|
|
68
|
+
data: status,
|
|
69
|
+
error: null
|
|
70
|
+
};
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return {
|
|
73
|
+
data: null,
|
|
74
|
+
error: asEmailError(error, 'Reading the email status failed unexpectedly.')
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
connect(nothingDone, missingSecretKey) {
|
|
79
|
+
if (this.hooks.isDisabled()) throw new EmailError({
|
|
80
|
+
code: 'client_disabled',
|
|
81
|
+
message: `The PostHog client is disabled, so ${nothingDone}.`
|
|
82
|
+
});
|
|
83
|
+
if (this.hooks.isClosed()) throw new EmailError({
|
|
84
|
+
code: 'client_closed',
|
|
85
|
+
message: `The PostHog client is shut down, so ${nothingDone}.`
|
|
86
|
+
});
|
|
87
|
+
const appHost = resolveAppHost(this.config.host, this.config.appHost);
|
|
88
|
+
if (!appHost) throw new EmailError({
|
|
89
|
+
code: 'missing_app_host',
|
|
90
|
+
message: "The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."
|
|
91
|
+
});
|
|
92
|
+
const secretKey = this.config.secretKey?.trim();
|
|
93
|
+
if (!secretKey) throw new EmailError({
|
|
94
|
+
code: 'missing_secret_key',
|
|
95
|
+
message: missingSecretKey
|
|
96
|
+
});
|
|
97
|
+
return {
|
|
98
|
+
appHost,
|
|
99
|
+
secretKey
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
headers(secretKey, extra) {
|
|
103
|
+
const headers = {
|
|
104
|
+
Authorization: `Bearer ${secretKey}`,
|
|
105
|
+
Accept: 'application/json',
|
|
106
|
+
...extra
|
|
107
|
+
};
|
|
108
|
+
if (this.hooks.userAgent) headers['User-Agent'] = this.hooks.userAgent;
|
|
109
|
+
return headers;
|
|
110
|
+
}
|
|
111
|
+
async withRetries(maxRetries, attemptOnce) {
|
|
112
|
+
for(let attempt = 0;; attempt++){
|
|
113
|
+
let error;
|
|
114
|
+
try {
|
|
115
|
+
return await attemptOnce();
|
|
116
|
+
} catch (caught) {
|
|
117
|
+
error = caught instanceof EmailError ? caught : new EmailError({
|
|
118
|
+
code: 'network_error',
|
|
119
|
+
message: 'The request to PostHog failed.',
|
|
120
|
+
cause: caught
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
const delayMs = retryDelayMs(error, attempt, maxRetries);
|
|
124
|
+
if (void 0 === delayMs) throw error;
|
|
125
|
+
await new Promise((resolve)=>setTimeout(resolve, delayMs));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async request(url, method, headers, body) {
|
|
129
|
+
const controller = new AbortController();
|
|
130
|
+
const timeoutMs = this.config.requestTimeoutMs;
|
|
131
|
+
let timer;
|
|
132
|
+
const deadline = new Promise((_resolve, reject)=>{
|
|
133
|
+
timer = setTimeout(()=>{
|
|
134
|
+
const timeoutError = new Error(`Email request timed out after ${timeoutMs}ms`);
|
|
135
|
+
timeoutError.name = 'AbortError';
|
|
136
|
+
reject(timeoutError);
|
|
137
|
+
controller.abort(timeoutError);
|
|
138
|
+
}, timeoutMs);
|
|
139
|
+
});
|
|
140
|
+
const fetchPromise = Promise.resolve().then(()=>this.hooks.fetch(url, {
|
|
141
|
+
method,
|
|
142
|
+
headers,
|
|
143
|
+
...void 0 === body ? {} : {
|
|
144
|
+
body
|
|
145
|
+
},
|
|
146
|
+
signal: controller.signal
|
|
147
|
+
}));
|
|
148
|
+
fetchPromise.then((lateResponse)=>{
|
|
149
|
+
if (controller.signal.aborted) Promise.resolve(lateResponse.body?.cancel()).catch(()=>{});
|
|
150
|
+
}).catch(()=>{});
|
|
151
|
+
let response;
|
|
152
|
+
try {
|
|
153
|
+
response = await Promise.race([
|
|
154
|
+
fetchPromise,
|
|
155
|
+
deadline
|
|
156
|
+
]);
|
|
157
|
+
let text;
|
|
158
|
+
try {
|
|
159
|
+
text = await Promise.race([
|
|
160
|
+
response.text(),
|
|
161
|
+
deadline
|
|
162
|
+
]);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (response.status >= 200 && response.status < 300) throw error;
|
|
165
|
+
return {
|
|
166
|
+
status: response.status,
|
|
167
|
+
payload: null,
|
|
168
|
+
retryAfterMs: readRetryAfter(response)
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
status: response.status,
|
|
173
|
+
payload: parseJson(text),
|
|
174
|
+
retryAfterMs: readRetryAfter(response)
|
|
175
|
+
};
|
|
176
|
+
} finally{
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
if (controller.signal.aborted && response) Promise.resolve(response.body?.cancel()).catch(()=>{});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
function prepareSend(options, defaultMaxRetries) {
|
|
183
|
+
const fallback = {};
|
|
184
|
+
const { to, templateId, templateData, distinctId, idempotencyKey, maxRetries } = options ?? fallback;
|
|
185
|
+
if ('string' != typeof to || !to.trim()) throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to');
|
|
186
|
+
if ('string' != typeof templateId || !UUID_PATTERN.test(templateId)) throw invalid('invalid_template_id', "templateId must be the template's UUID.", 'templateId');
|
|
187
|
+
if (void 0 !== templateData && ('object' != typeof templateData || null === templateData || Array.isArray(templateData))) throw invalid('invalid_template_data', 'templateData must be an object.', 'templateData');
|
|
188
|
+
if (void 0 !== distinctId && ('string' != typeof distinctId || !distinctId)) throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId');
|
|
189
|
+
if (void 0 !== idempotencyKey && ('string' != typeof idempotencyKey || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))) throw invalid('invalid_idempotency_key', 'idempotencyKey must be 1 to 255 visible ASCII characters without spaces.', 'idempotencyKey');
|
|
190
|
+
if (void 0 !== maxRetries && !(Number.isInteger(maxRetries) && maxRetries >= 0)) throw invalid('invalid_max_retries', 'maxRetries must be a nonnegative integer.', 'maxRetries');
|
|
191
|
+
const payload = {
|
|
192
|
+
template: {
|
|
193
|
+
id: templateId.toLowerCase()
|
|
194
|
+
},
|
|
195
|
+
to,
|
|
196
|
+
message_data: templateData ?? {}
|
|
197
|
+
};
|
|
198
|
+
if (void 0 !== distinctId) payload.identifiers = {
|
|
199
|
+
distinct_id: distinctId
|
|
200
|
+
};
|
|
201
|
+
return {
|
|
202
|
+
path: SEND_PATH,
|
|
203
|
+
body: safeJsonStringify(payload),
|
|
204
|
+
idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
|
|
205
|
+
maxRetries: maxRetries ?? defaultMaxRetries
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function invalid(code, message, field) {
|
|
209
|
+
return new EmailError({
|
|
210
|
+
code,
|
|
211
|
+
message,
|
|
212
|
+
field
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
function resolveAppHost(host, appHost) {
|
|
216
|
+
const explicit = 'string' == typeof appHost ? removeTrailingSlash(appHost.trim()) : '';
|
|
217
|
+
if (explicit) return CLOUD_APP_HOSTS[explicit] ?? explicit;
|
|
218
|
+
return CLOUD_APP_HOSTS[removeTrailingSlash(host)];
|
|
219
|
+
}
|
|
220
|
+
function parseJson(text) {
|
|
221
|
+
try {
|
|
222
|
+
return JSON.parse(text);
|
|
223
|
+
} catch {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function readRetryAfter(response) {
|
|
228
|
+
try {
|
|
229
|
+
return parseRetryAfterMs(response.headers?.get('retry-after'), Date.now(), Number.MAX_SAFE_INTEGER);
|
|
230
|
+
} catch {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
function emails_text(value) {
|
|
235
|
+
return 'string' == typeof value && value ? value : void 0;
|
|
236
|
+
}
|
|
237
|
+
function replyFields(payload) {
|
|
238
|
+
return null === payload || 'object' != typeof payload || Array.isArray(payload) ? {} : payload;
|
|
239
|
+
}
|
|
240
|
+
function parseSendReply({ status, payload, retryAfterMs }) {
|
|
241
|
+
const fields = replyFields(payload);
|
|
242
|
+
if (status >= 200 && status < 300) {
|
|
243
|
+
const id = emails_text(fields.message_id);
|
|
244
|
+
if (!id) throw new EmailError({
|
|
245
|
+
code: 'api_error',
|
|
246
|
+
message: 'PostHog answered without a message ID.',
|
|
247
|
+
statusCode: status
|
|
248
|
+
});
|
|
249
|
+
const warnings = [];
|
|
250
|
+
if (Array.isArray(fields.warnings)) {
|
|
251
|
+
for (const warning of fields.warnings)if (null !== warning && 'object' == typeof warning) warnings.push({
|
|
252
|
+
code: emails_text(warning.code) ?? 'warning',
|
|
253
|
+
message: emails_text(warning.detail) ?? emails_text(warning.message) ?? '',
|
|
254
|
+
fix: emails_text(warning.fix)
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
id,
|
|
259
|
+
replayed: true === fields.replayed,
|
|
260
|
+
warnings
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
throw replyError(fields, status, retryAfterMs);
|
|
264
|
+
}
|
|
265
|
+
function parseStatusReply({ status, payload, retryAfterMs }) {
|
|
266
|
+
const fields = replyFields(payload);
|
|
267
|
+
if (status < 200 || status >= 300) throw replyError(fields, status, retryAfterMs);
|
|
268
|
+
const id = emails_text(fields.id);
|
|
269
|
+
const deliveryStatus = emails_text(fields.status);
|
|
270
|
+
const createdAt = emails_text(fields.created_at);
|
|
271
|
+
const statusAt = emails_text(fields.status_at);
|
|
272
|
+
if (!id || !deliveryStatus || !createdAt || !statusAt) throw new EmailError({
|
|
273
|
+
code: 'api_error',
|
|
274
|
+
message: 'PostHog answered without an email status.',
|
|
275
|
+
statusCode: status
|
|
276
|
+
});
|
|
277
|
+
return {
|
|
278
|
+
id,
|
|
279
|
+
status: deliveryStatus,
|
|
280
|
+
createdAt,
|
|
281
|
+
statusAt,
|
|
282
|
+
reason: emails_text(fields.reason) ?? null
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function replyError(fields, status, retryAfterMs) {
|
|
286
|
+
return new EmailError({
|
|
287
|
+
code: emails_text(fields.code) ?? 'api_error',
|
|
288
|
+
message: emails_text(fields.detail) ?? `PostHog answered HTTP ${status}.`,
|
|
289
|
+
statusCode: status,
|
|
290
|
+
why: emails_text(fields.why),
|
|
291
|
+
fix: emails_text(fields.fix),
|
|
292
|
+
docsUrl: emails_text(fields.docs_url),
|
|
293
|
+
field: emails_text(fields.attr),
|
|
294
|
+
retryAfterMs
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
function asEmailError(error, message) {
|
|
298
|
+
return error instanceof EmailError ? error : new EmailError({
|
|
299
|
+
code: 'unexpected_error',
|
|
300
|
+
message,
|
|
301
|
+
cause: error
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
function isRetryable(error) {
|
|
305
|
+
if (void 0 === error.statusCode) return 'network_error' === error.code;
|
|
306
|
+
if (409 === error.statusCode) return 'idempotency_key_in_flight' === error.code;
|
|
307
|
+
if (429 === error.statusCode) return 'quota_limited' !== error.code;
|
|
308
|
+
return 503 === error.statusCode;
|
|
309
|
+
}
|
|
310
|
+
function retryDelayMs(error, attempt, maxRetries) {
|
|
311
|
+
if (attempt >= maxRetries || !isRetryable(error)) return;
|
|
312
|
+
if (void 0 !== error.retryAfterMs && error.retryAfterMs > MAX_RETRY_DELAY_MS) return;
|
|
313
|
+
const backoffMs = Math.min(MAX_RETRY_DELAY_MS, 1000 * 2 ** attempt * (0.8 + 0.4 * Math.random()));
|
|
314
|
+
return Math.max(backoffMs, error.retryAfterMs ?? 0);
|
|
315
|
+
}
|
|
316
|
+
export { DEFAULT_EMAIL_REQUEST_MAX_RETRIES, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS, EmailSender };
|