posthog-node 5.70.0 → 5.72.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/dist/client.d.ts +3 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/emails/attachments.d.ts +23 -0
- package/dist/emails/attachments.d.ts.map +1 -0
- package/dist/emails/attachments.js +170 -0
- package/dist/emails/attachments.mjs +123 -0
- package/dist/emails/emails.d.ts +7 -2
- package/dist/emails/emails.d.ts.map +1 -1
- package/dist/emails/emails.js +202 -36
- package/dist/emails/emails.mjs +202 -36
- package/dist/emails/errors.d.ts +1 -1
- package/dist/emails/errors.d.ts.map +1 -1
- package/dist/emails/errors.js +6 -1
- package/dist/emails/errors.mjs +6 -1
- package/dist/emails/types.d.ts +66 -0
- package/dist/emails/types.d.ts.map +1 -1
- package/dist/exports.d.ts +1 -1
- package/dist/exports.d.ts.map +1 -1
- package/dist/types.d.ts +2 -1
- 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 +4 -4
- package/src/client.ts +3 -2
- package/src/emails/attachments.ts +209 -0
- package/src/emails/emails.ts +248 -36
- package/src/emails/errors.ts +7 -2
- package/src/emails/types.ts +68 -0
- package/src/exports.ts +2 -0
- package/src/types.ts +2 -1
- package/src/version.ts +1 -1
package/src/emails/emails.ts
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
|
-
type FetchLike,
|
|
3
2
|
type Logger,
|
|
3
|
+
type PostHogFetchOptions,
|
|
4
4
|
type PostHogFetchResponse,
|
|
5
5
|
parseRetryAfterMs,
|
|
6
6
|
removeTrailingSlash,
|
|
7
7
|
safeJsonStringify,
|
|
8
8
|
} from '@posthog/core'
|
|
9
9
|
|
|
10
|
+
import {
|
|
11
|
+
type AttachmentFile,
|
|
12
|
+
type HashedFile,
|
|
13
|
+
attachmentFiles,
|
|
14
|
+
attachmentReference,
|
|
15
|
+
hashedFiles,
|
|
16
|
+
refuseRenderedMessageOverLimit,
|
|
17
|
+
} from './attachments'
|
|
10
18
|
import { EmailError } from './errors'
|
|
11
19
|
import type {
|
|
12
20
|
CodeEmailForm,
|
|
@@ -27,6 +35,7 @@ import type {
|
|
|
27
35
|
} from './types'
|
|
28
36
|
|
|
29
37
|
const SEND_PATH = '/api/projects/@current/messaging/send/email/'
|
|
38
|
+
const UPLOADS_PATH = '/api/projects/@current/messaging/attachments/uploads/'
|
|
30
39
|
const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/'
|
|
31
40
|
const PREFERENCES_PATH = '/api/projects/@current/messaging/preferences/'
|
|
32
41
|
const US_APP_HOST = 'https://us.posthog.com'
|
|
@@ -70,6 +79,11 @@ const CODE_FIELDS: EveryField<CodeEmailForm> = {
|
|
|
70
79
|
from: true,
|
|
71
80
|
replyTo: true,
|
|
72
81
|
captureEngagement: true,
|
|
82
|
+
cc: true,
|
|
83
|
+
bcc: true,
|
|
84
|
+
attachments: true,
|
|
85
|
+
sensitive: true,
|
|
86
|
+
tracking: true,
|
|
73
87
|
html: true,
|
|
74
88
|
text: true,
|
|
75
89
|
react: true,
|
|
@@ -100,8 +114,12 @@ export interface EmailSenderConfig {
|
|
|
100
114
|
migratedFrom?: string
|
|
101
115
|
}
|
|
102
116
|
|
|
117
|
+
export interface EmailFetchOptions extends PostHogFetchOptions {
|
|
118
|
+
redirect?: 'manual'
|
|
119
|
+
}
|
|
120
|
+
|
|
103
121
|
export interface EmailSenderHooks {
|
|
104
|
-
fetch:
|
|
122
|
+
fetch: (url: string, options: EmailFetchOptions) => Promise<PostHogFetchResponse>
|
|
105
123
|
isDisabled: () => boolean
|
|
106
124
|
isClosed: () => boolean
|
|
107
125
|
logger: Logger
|
|
@@ -109,15 +127,23 @@ export interface EmailSenderHooks {
|
|
|
109
127
|
}
|
|
110
128
|
|
|
111
129
|
interface PreparedSend {
|
|
112
|
-
|
|
130
|
+
content: Record<string, unknown>
|
|
131
|
+
files: AttachmentFile[]
|
|
113
132
|
react?: EmailReactElement
|
|
114
133
|
idempotencyKey: string
|
|
115
134
|
maxRetries: number
|
|
116
135
|
}
|
|
117
136
|
|
|
137
|
+
interface Upload {
|
|
138
|
+
url: string
|
|
139
|
+
headers: Record<string, string>
|
|
140
|
+
bytes: Uint8Array<ArrayBuffer>
|
|
141
|
+
field: string
|
|
142
|
+
}
|
|
143
|
+
|
|
118
144
|
interface Reply {
|
|
119
145
|
status: number
|
|
120
|
-
|
|
146
|
+
text: string
|
|
121
147
|
retryAfterMs?: number
|
|
122
148
|
}
|
|
123
149
|
|
|
@@ -172,10 +198,15 @@ export class EmailSender implements Emails {
|
|
|
172
198
|
'no email was sent',
|
|
173
199
|
'Sending email needs secretKey, a project secret API key with the transactional_email:write scope.'
|
|
174
200
|
)
|
|
175
|
-
const
|
|
201
|
+
const content =
|
|
176
202
|
prepared.react === undefined
|
|
177
|
-
? prepared.
|
|
178
|
-
: await withRenderedReact(prepared.
|
|
203
|
+
? prepared.content
|
|
204
|
+
: await withRenderedReact(prepared.content, prepared.react, this.config.requestTimeoutMs)
|
|
205
|
+
if (prepared.react !== undefined) {
|
|
206
|
+
refuseRenderedMessageOverLimit(prepared.files, content)
|
|
207
|
+
}
|
|
208
|
+
const attachments = await this.uploadAttachments(prepared, appHost, secretKey)
|
|
209
|
+
const body = safeJsonStringify({ ...content, ...unlessEmpty('attachments', attachments) })
|
|
179
210
|
const headers = this.headers(secretKey, {
|
|
180
211
|
'Content-Type': 'application/json',
|
|
181
212
|
'Idempotency-Key': prepared.idempotencyKey,
|
|
@@ -212,6 +243,86 @@ export class EmailSender implements Emails {
|
|
|
212
243
|
}
|
|
213
244
|
}
|
|
214
245
|
|
|
246
|
+
private async uploadAttachments(
|
|
247
|
+
{ files, maxRetries }: PreparedSend,
|
|
248
|
+
appHost: string,
|
|
249
|
+
secretKey: string
|
|
250
|
+
): Promise<Record<string, unknown>[]> {
|
|
251
|
+
if (files.length === 0) {
|
|
252
|
+
return []
|
|
253
|
+
}
|
|
254
|
+
const hashed = await hashedFiles(files)
|
|
255
|
+
const distinct = new Map<string, HashedFile>()
|
|
256
|
+
for (const file of hashed) {
|
|
257
|
+
if (!distinct.has(file.sha256)) {
|
|
258
|
+
distinct.set(file.sha256, file)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const requested = [...distinct.values()]
|
|
262
|
+
const body = safeJsonStringify({
|
|
263
|
+
files: requested.map(({ sha256, bytes }) => ({ sha256, size: bytes.byteLength })),
|
|
264
|
+
})
|
|
265
|
+
const headers = this.headers(secretKey, { 'Content-Type': 'application/json' })
|
|
266
|
+
const uploads = await this.withRetries(maxRetries, async () =>
|
|
267
|
+
parseUploadsReply(await this.request(appHost + UPLOADS_PATH, 'POST', headers, body), requested)
|
|
268
|
+
)
|
|
269
|
+
const unencrypted = isPlainHttp(appHost) ? undefined : uploads.find(({ url }) => !isHttps(url))
|
|
270
|
+
if (unencrypted) {
|
|
271
|
+
throw new EmailError({
|
|
272
|
+
code: 'api_error',
|
|
273
|
+
message: `PostHog named an upload URL for ${unencrypted.field} that isn't https, so the file would travel unencrypted. No email was sent.`,
|
|
274
|
+
field: unencrypted.field,
|
|
275
|
+
fix: "Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host.",
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
for (const upload of uploads) {
|
|
279
|
+
await this.withRetries(maxRetries, () => this.uploadFile(upload))
|
|
280
|
+
}
|
|
281
|
+
return hashed.map(attachmentReference)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private async uploadFile({ url, headers, bytes, field }: Upload): Promise<void> {
|
|
285
|
+
let reply: Reply
|
|
286
|
+
try {
|
|
287
|
+
reply = await this.request(url, 'PUT', headers, bytes, 'manual')
|
|
288
|
+
} catch (cause) {
|
|
289
|
+
if (cause instanceof Error && cause.name === 'AbortError') {
|
|
290
|
+
throw new EmailError({
|
|
291
|
+
code: 'network_error',
|
|
292
|
+
message: `The upload of ${field} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,
|
|
293
|
+
fix: 'Raise emailRequestTimeoutMs on the client, or send smaller files.',
|
|
294
|
+
field,
|
|
295
|
+
cause,
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
throw new EmailError({
|
|
299
|
+
code: 'network_error',
|
|
300
|
+
message: `The upload of ${field} didn't reach PostHog's file storage, so no email was sent.`,
|
|
301
|
+
field,
|
|
302
|
+
cause,
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
if (reply.status >= 300 && reply.status < 400) {
|
|
306
|
+
throw new EmailError({
|
|
307
|
+
code: 'attachment_upload_failed',
|
|
308
|
+
message: `PostHog's file storage redirected the upload of ${field} elsewhere. The SDK uploads only to the URL PostHog signed, so no email was sent.`,
|
|
309
|
+
statusCode: reply.status,
|
|
310
|
+
fix: "Make your PostHog's file storage URL point straight at the storage, over https.",
|
|
311
|
+
field,
|
|
312
|
+
})
|
|
313
|
+
}
|
|
314
|
+
if (reply.status < 200 || reply.status >= 300) {
|
|
315
|
+
throw new EmailError({
|
|
316
|
+
code: 'attachment_upload_failed',
|
|
317
|
+
message: `PostHog's file storage refused the upload of ${field}, so no email was sent. ${storageAnswer(reply)}`,
|
|
318
|
+
statusCode: reply.status,
|
|
319
|
+
fix: 'Send the email again. Each send asks for new upload URLs.',
|
|
320
|
+
field,
|
|
321
|
+
retryAfterMs: reply.retryAfterMs,
|
|
322
|
+
})
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
215
326
|
private async setPreferencesUntracked(options: SetEmailPreferencesOptions): Promise<SetEmailPreferencesResponse> {
|
|
216
327
|
try {
|
|
217
328
|
const body = preparePreferences(options)
|
|
@@ -299,9 +410,10 @@ export class EmailSender implements Emails {
|
|
|
299
410
|
|
|
300
411
|
private async request(
|
|
301
412
|
url: string,
|
|
302
|
-
method: 'GET' | 'POST',
|
|
413
|
+
method: 'GET' | 'POST' | 'PUT',
|
|
303
414
|
headers: Record<string, string>,
|
|
304
|
-
body?: string
|
|
415
|
+
body?: string | Uint8Array<ArrayBuffer>,
|
|
416
|
+
redirect?: 'manual'
|
|
305
417
|
): Promise<Reply> {
|
|
306
418
|
const controller = new AbortController()
|
|
307
419
|
const timeoutMs = this.config.requestTimeoutMs
|
|
@@ -322,6 +434,7 @@ export class EmailSender implements Emails {
|
|
|
322
434
|
method,
|
|
323
435
|
headers,
|
|
324
436
|
...(body === undefined ? {} : { body }),
|
|
437
|
+
...(redirect ? { redirect } : {}),
|
|
325
438
|
signal: controller.signal,
|
|
326
439
|
})
|
|
327
440
|
)
|
|
@@ -345,9 +458,9 @@ export class EmailSender implements Emails {
|
|
|
345
458
|
throw error
|
|
346
459
|
}
|
|
347
460
|
// The status and Retry-After still decide the retry when an error body can't be read.
|
|
348
|
-
return { status: response.status,
|
|
461
|
+
return { status: response.status, text: '', retryAfterMs: readRetryAfter(response) }
|
|
349
462
|
}
|
|
350
|
-
return { status: response.status,
|
|
463
|
+
return { status: response.status, text, retryAfterMs: readRetryAfter(response) }
|
|
351
464
|
} finally {
|
|
352
465
|
clearTimeout(timer!)
|
|
353
466
|
if (controller.signal.aborted && response) {
|
|
@@ -376,7 +489,7 @@ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): Prep
|
|
|
376
489
|
if (distinctId !== undefined && (typeof distinctId !== 'string' || !distinctId)) {
|
|
377
490
|
throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId')
|
|
378
491
|
}
|
|
379
|
-
const content = contentOf(send, distinctId)
|
|
492
|
+
const { content, files } = contentOf(send, distinctId)
|
|
380
493
|
if (
|
|
381
494
|
idempotencyKey !== undefined &&
|
|
382
495
|
(typeof idempotencyKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))
|
|
@@ -392,13 +505,18 @@ function prepareSend(options: SendEmailOptions, defaultMaxRetries: number): Prep
|
|
|
392
505
|
}
|
|
393
506
|
|
|
394
507
|
return {
|
|
395
|
-
|
|
508
|
+
content: snapshotOf({ ...content, to }),
|
|
509
|
+
files,
|
|
396
510
|
react: isReactElement(send.react) ? send.react : undefined,
|
|
397
511
|
idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
|
|
398
512
|
maxRetries: isRetryCount(maxRetries) ? maxRetries : defaultMaxRetries,
|
|
399
513
|
}
|
|
400
514
|
}
|
|
401
515
|
|
|
516
|
+
function snapshotOf(content: Record<string, unknown>): Record<string, unknown> {
|
|
517
|
+
return JSON.parse(safeJsonStringify(content))
|
|
518
|
+
}
|
|
519
|
+
|
|
402
520
|
function preparePreferences(options: SetEmailPreferencesOptions): string {
|
|
403
521
|
const fallback: Partial<SetEmailPreferencesOptions> = {}
|
|
404
522
|
const { to, allMarketing, topics } = options ?? fallback
|
|
@@ -432,14 +550,21 @@ function isRetryCount(value: unknown): value is number {
|
|
|
432
550
|
return typeof value === 'number' && Number.isInteger(value) && value >= 0
|
|
433
551
|
}
|
|
434
552
|
|
|
435
|
-
|
|
553
|
+
interface SendContent {
|
|
554
|
+
content: Record<string, unknown>
|
|
555
|
+
files: AttachmentFile[]
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function contentOf(send: UncheckedSend, distinctId: string | undefined): SendContent {
|
|
436
559
|
if ((send.templateId === undefined) === (send.templateKey === undefined)) {
|
|
437
560
|
throw new EmailError({
|
|
438
561
|
code: 'invalid_form',
|
|
439
562
|
message: 'Send either templateId, or templateKey with subject and html, text or react.',
|
|
440
563
|
})
|
|
441
564
|
}
|
|
442
|
-
return send.templateKey === undefined
|
|
565
|
+
return send.templateKey === undefined
|
|
566
|
+
? { content: templateContent(send, distinctId), files: [] }
|
|
567
|
+
: codeContent(send, distinctId)
|
|
443
568
|
}
|
|
444
569
|
|
|
445
570
|
function templateContent(send: UncheckedSend, distinctId: string | undefined): Record<string, unknown> {
|
|
@@ -461,8 +586,8 @@ function templateContent(send: UncheckedSend, distinctId: string | undefined): R
|
|
|
461
586
|
}
|
|
462
587
|
}
|
|
463
588
|
|
|
464
|
-
function codeContent(send: UncheckedSend, distinctId: string | undefined):
|
|
465
|
-
const { templateKey, subject, html, text, react
|
|
589
|
+
function codeContent(send: UncheckedSend, distinctId: string | undefined): SendContent {
|
|
590
|
+
const { templateKey, subject, html, text, react } = send
|
|
466
591
|
if (typeof templateKey !== 'string' || !TEMPLATE_KEY_PATTERN.test(templateKey)) {
|
|
467
592
|
throw invalid(
|
|
468
593
|
'invalid_template_key',
|
|
@@ -485,19 +610,41 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): Recor
|
|
|
485
610
|
} else if (html === undefined && text === undefined) {
|
|
486
611
|
throw invalid('invalid_form', 'A send with templateKey needs html, text or react.', 'html')
|
|
487
612
|
}
|
|
488
|
-
const
|
|
613
|
+
const files = send.attachments === undefined ? [] : attachmentFiles(send.attachments, { html, text, subject })
|
|
614
|
+
return {
|
|
615
|
+
content: {
|
|
616
|
+
template_key: templateKey,
|
|
617
|
+
subject,
|
|
618
|
+
...(html !== undefined && { html }),
|
|
619
|
+
...(text !== undefined && { text }),
|
|
620
|
+
...codeFormFields(send),
|
|
621
|
+
...(distinctId !== undefined && { distinct_id: distinctId }),
|
|
622
|
+
},
|
|
623
|
+
files,
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function codeFormFields(send: UncheckedSend): Record<string, unknown> {
|
|
628
|
+
const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking } = send
|
|
489
629
|
return {
|
|
490
|
-
template_key: templateKey,
|
|
491
|
-
subject,
|
|
492
|
-
...(html !== undefined && { html }),
|
|
493
|
-
...(text !== undefined && { text }),
|
|
494
630
|
...(from !== undefined && { from }),
|
|
495
|
-
...(
|
|
496
|
-
|
|
497
|
-
...(
|
|
631
|
+
...(replyTo !== undefined && unlessEmpty('reply_to', addressList(replyTo))),
|
|
632
|
+
...(cc !== undefined && unlessEmpty('cc', addressList(cc))),
|
|
633
|
+
...(bcc !== undefined && unlessEmpty('bcc', addressList(bcc))),
|
|
634
|
+
...(captureEngagement !== undefined && { capture_engagement: captureEngagement }),
|
|
635
|
+
...(sensitive !== undefined && { sensitive }),
|
|
636
|
+
...(tracking !== undefined && { tracking }),
|
|
498
637
|
}
|
|
499
638
|
}
|
|
500
639
|
|
|
640
|
+
function unlessEmpty(field: string, list: unknown): Record<string, unknown> {
|
|
641
|
+
return Array.isArray(list) && list.length === 0 ? {} : { [field]: list }
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function addressList(addresses: unknown): unknown {
|
|
645
|
+
return typeof addresses === 'string' ? [addresses] : addresses
|
|
646
|
+
}
|
|
647
|
+
|
|
501
648
|
function checkReactContent(react: unknown, html: unknown): void {
|
|
502
649
|
if (!isReactElement(react)) {
|
|
503
650
|
throw invalid('invalid_form', 'react must be a React element, such as <WelcomeEmail />.', 'react')
|
|
@@ -528,12 +675,15 @@ function isReactElement(value: unknown): value is EmailReactElement {
|
|
|
528
675
|
)
|
|
529
676
|
}
|
|
530
677
|
|
|
531
|
-
async function withRenderedReact(
|
|
678
|
+
async function withRenderedReact(
|
|
679
|
+
content: Record<string, unknown>,
|
|
680
|
+
react: EmailReactElement,
|
|
681
|
+
timeoutMs: number
|
|
682
|
+
): Promise<Record<string, unknown>> {
|
|
532
683
|
const { render, toPlainText } = await loadReactRenderer()
|
|
533
|
-
const fields: Record<string, unknown> = JSON.parse(body)
|
|
534
684
|
try {
|
|
535
685
|
const html = await settleWithin(render(react), timeoutMs, 'Rendering the react element')
|
|
536
|
-
return
|
|
686
|
+
return { ...content, html, ...(content.text === undefined && { text: toPlainText(html) }) }
|
|
537
687
|
} catch (cause) {
|
|
538
688
|
throw new EmailError({
|
|
539
689
|
code: 'react_render_failed',
|
|
@@ -595,6 +745,14 @@ function invalid(code: string, message: string, field: string): EmailError {
|
|
|
595
745
|
return new EmailError({ code, message, field })
|
|
596
746
|
}
|
|
597
747
|
|
|
748
|
+
function isHttps(url: string): boolean {
|
|
749
|
+
return url.toLowerCase().startsWith('https://')
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function isPlainHttp(url: string): boolean {
|
|
753
|
+
return url.toLowerCase().startsWith('http://')
|
|
754
|
+
}
|
|
755
|
+
|
|
598
756
|
/**
|
|
599
757
|
* The app host for a send, or undefined when the client can't tell it.
|
|
600
758
|
* PostHog Cloud ingestion hosts don't serve the app API, so they map to their region's app host.
|
|
@@ -636,8 +794,8 @@ function replyFields(payload: unknown): Record<string, unknown> {
|
|
|
636
794
|
>
|
|
637
795
|
}
|
|
638
796
|
|
|
639
|
-
function parseSendReply({ status,
|
|
640
|
-
const fields = replyFields(
|
|
797
|
+
function parseSendReply({ status, text: body, retryAfterMs }: Reply): SendEmailResult {
|
|
798
|
+
const fields = replyFields(parseJson(body))
|
|
641
799
|
if (status >= 200 && status < 300) {
|
|
642
800
|
const id = text(fields.message_id)
|
|
643
801
|
if (!id) {
|
|
@@ -664,8 +822,8 @@ function parseSendReply({ status, payload, retryAfterMs }: Reply): SendEmailResu
|
|
|
664
822
|
throw replyError(fields, status, retryAfterMs)
|
|
665
823
|
}
|
|
666
824
|
|
|
667
|
-
function parseStatusReply({ status,
|
|
668
|
-
const fields = replyFields(
|
|
825
|
+
function parseStatusReply({ status, text: body, retryAfterMs }: Reply): EmailStatus {
|
|
826
|
+
const fields = replyFields(parseJson(body))
|
|
669
827
|
if (status < 200 || status >= 300) {
|
|
670
828
|
throw replyError(fields, status, retryAfterMs)
|
|
671
829
|
}
|
|
@@ -683,8 +841,60 @@ function parseStatusReply({ status, payload, retryAfterMs }: Reply): EmailStatus
|
|
|
683
841
|
return { id, status: deliveryStatus, createdAt, statusAt, reason: text(fields.reason) ?? null }
|
|
684
842
|
}
|
|
685
843
|
|
|
686
|
-
function
|
|
687
|
-
const fields = replyFields(
|
|
844
|
+
function parseUploadsReply({ status, text: body, retryAfterMs }: Reply, requested: HashedFile[]): Upload[] {
|
|
845
|
+
const fields = replyFields(parseJson(body))
|
|
846
|
+
if (status === 404) {
|
|
847
|
+
throw replyError({ code: 'not_found', ...fields, attr: text(fields.attr) ?? 'attachments' }, status, retryAfterMs)
|
|
848
|
+
}
|
|
849
|
+
if (status < 200 || status >= 300) {
|
|
850
|
+
throw replyError({ ...fields, attr: callerField(text(fields.attr), requested) }, status, retryAfterMs)
|
|
851
|
+
}
|
|
852
|
+
const answers = Array.isArray(fields.files) ? fields.files.map(replyFields) : []
|
|
853
|
+
const uploads: Upload[] = []
|
|
854
|
+
for (const { sha256, bytes, field } of requested) {
|
|
855
|
+
const answer = answers.find((file) => file.sha256 === sha256)
|
|
856
|
+
if (answer?.status === 'present') {
|
|
857
|
+
continue
|
|
858
|
+
}
|
|
859
|
+
const url = text(answer?.url)
|
|
860
|
+
if (answer?.status !== 'upload' || !url || !isStringRecord(answer.headers)) {
|
|
861
|
+
throw new EmailError({
|
|
862
|
+
code: 'api_error',
|
|
863
|
+
message: 'PostHog answered without telling where to upload every file.',
|
|
864
|
+
statusCode: status,
|
|
865
|
+
})
|
|
866
|
+
}
|
|
867
|
+
uploads.push({ url, headers: answer.headers, bytes, field })
|
|
868
|
+
}
|
|
869
|
+
return uploads
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function callerField(attr: string | undefined, requested: HashedFile[]): string | undefined {
|
|
873
|
+
const file = attr === undefined ? null : /^files(?:__(\d+))?(?:__|$)/.exec(attr)
|
|
874
|
+
if (!file) {
|
|
875
|
+
return attr
|
|
876
|
+
}
|
|
877
|
+
return file[1] === undefined ? 'attachments' : (requested[Number(file[1])]?.field ?? 'attachments')
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function isStringRecord(value: unknown): value is Record<string, string> {
|
|
881
|
+
return (
|
|
882
|
+
value !== null &&
|
|
883
|
+
typeof value === 'object' &&
|
|
884
|
+
!Array.isArray(value) &&
|
|
885
|
+
Object.values(value).every((item) => typeof item === 'string')
|
|
886
|
+
)
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
function storageAnswer({ status, text: body }: Reply): string {
|
|
890
|
+
const code = /<Code>([^<]{1,100})<\/Code>/.exec(body)?.[1]
|
|
891
|
+
const message = /<Message>([^<]{1,300})<\/Message>/.exec(body)?.[1]
|
|
892
|
+
const answer = `It answered HTTP ${status}${code ? ` ${code}` : ''}${message ? `: ${message}` : ''}`
|
|
893
|
+
return answer.endsWith('.') ? answer : `${answer}.`
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function parsePreferencesReply({ status, text: body, retryAfterMs }: Reply): EmailPreferences {
|
|
897
|
+
const fields = replyFields(parseJson(body))
|
|
688
898
|
if (status < 200 || status >= 300) {
|
|
689
899
|
throw replyError(fields, status, retryAfterMs)
|
|
690
900
|
}
|
|
@@ -731,12 +941,14 @@ function isRetryable(error: EmailError): boolean {
|
|
|
731
941
|
if (error.statusCode === undefined) {
|
|
732
942
|
return error.code === 'network_error'
|
|
733
943
|
}
|
|
944
|
+
if (error.code === 'attachment_upload_failed') {
|
|
945
|
+
return error.statusCode === 429 || error.statusCode >= 500
|
|
946
|
+
}
|
|
734
947
|
if (error.statusCode === 409) {
|
|
735
948
|
return error.code === 'idempotency_key_in_flight'
|
|
736
949
|
}
|
|
737
950
|
if (error.statusCode === 429) {
|
|
738
|
-
|
|
739
|
-
return error.code !== 'quota_limited'
|
|
951
|
+
return error.code !== 'quota_limited' && error.code !== 'upload_quota_exceeded'
|
|
740
952
|
}
|
|
741
953
|
return error.statusCode === 503
|
|
742
954
|
}
|
package/src/emails/errors.ts
CHANGED
|
@@ -35,7 +35,7 @@ export class EmailError extends Error {
|
|
|
35
35
|
override name: EmailErrorName
|
|
36
36
|
/** PostHog's error code, such as `quota_limited`, or an SDK code such as `network_error`. */
|
|
37
37
|
readonly code: string
|
|
38
|
-
/** The HTTP status, when PostHog answered. */
|
|
38
|
+
/** The HTTP status, when PostHog or its file storage answered. */
|
|
39
39
|
readonly statusCode?: number
|
|
40
40
|
readonly why?: string
|
|
41
41
|
readonly fix?: string
|
|
@@ -58,6 +58,8 @@ export class EmailError extends Error {
|
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
const ATTACHMENT_LIMIT_CODES: ReadonlySet<string> = new Set(['too_many_attachments', 'message_too_large'])
|
|
62
|
+
|
|
61
63
|
function emailErrorName(status: number | undefined, code: string): EmailErrorName {
|
|
62
64
|
if (code === 'missing_secret_key' || status === 401) {
|
|
63
65
|
return 'missing_api_key'
|
|
@@ -66,7 +68,10 @@ function emailErrorName(status: number | undefined, code: string): EmailErrorNam
|
|
|
66
68
|
if (code === 'network_error') {
|
|
67
69
|
return 'service_unavailable'
|
|
68
70
|
}
|
|
69
|
-
return code.startsWith('invalid_') ? 'validation_error' : 'application_error'
|
|
71
|
+
return code.startsWith('invalid_') || ATTACHMENT_LIMIT_CODES.has(code) ? 'validation_error' : 'application_error'
|
|
72
|
+
}
|
|
73
|
+
if (code === 'attachment_upload_failed') {
|
|
74
|
+
return status >= 500 ? 'service_unavailable' : 'application_error'
|
|
70
75
|
}
|
|
71
76
|
switch (status) {
|
|
72
77
|
case 400:
|
package/src/emails/types.ts
CHANGED
|
@@ -39,13 +39,81 @@ interface CodeEmailFields {
|
|
|
39
39
|
/** A verified sender, such as `'Acme <security@example.com>'`. Without it, the project's default sender. */
|
|
40
40
|
from?: string
|
|
41
41
|
replyTo?: string | string[]
|
|
42
|
+
/** Bare addresses, such as `'finance@example.com'`, that get a copy. */
|
|
43
|
+
cc?: string | string[]
|
|
44
|
+
/** Bare addresses that get a copy the other recipients never see. */
|
|
45
|
+
bcc?: string | string[]
|
|
46
|
+
/**
|
|
47
|
+
* Files sent with the email: at most 10, and at most 40 MB for the whole email after Base64
|
|
48
|
+
* encoding, about 29 MB of files. The SDK checks both before any request. It uploads each file
|
|
49
|
+
* PostHog doesn't have yet, then sends the email. When an upload fails, it sends nothing.
|
|
50
|
+
*/
|
|
51
|
+
attachments?: EmailAttachment[]
|
|
42
52
|
/**
|
|
43
53
|
* Whether PostHog captures the email's engagement events (sent, delivered, opened, clicked,
|
|
44
54
|
* bounced) as events of the recipient. Defaults to `true`. A project whose admin turned
|
|
45
55
|
* engagement capture off captures nothing, whatever the send asks. A template made in PostHog
|
|
46
56
|
* follows the project's setting.
|
|
57
|
+
*
|
|
58
|
+
* @deprecated Use `tracking: { engagement: false }`. It keeps working, but PostHog refuses a
|
|
59
|
+
* send that sets both `captureEngagement` and `tracking`.
|
|
47
60
|
*/
|
|
48
61
|
captureEngagement?: boolean
|
|
62
|
+
/**
|
|
63
|
+
* Marks the email as sensitive, such as one that carries login links, reset tokens or codes.
|
|
64
|
+
* A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its
|
|
65
|
+
* subject off engagement events, and keeps its content out of PostHog's logs.
|
|
66
|
+
*
|
|
67
|
+
* Without it, a send whose `templateKey` matches a template saved in PostHog follows that
|
|
68
|
+
* template's setting, and any other send is sensitive. PostHog refuses `sensitive: false` when
|
|
69
|
+
* the matching template is sensitive.
|
|
70
|
+
*/
|
|
71
|
+
sensitive?: boolean
|
|
72
|
+
/**
|
|
73
|
+
* What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel,
|
|
74
|
+
* captures engagement events, and counts clicks only when the email isn't sensitive.
|
|
75
|
+
*
|
|
76
|
+
* - `true` turns on opens, clicks and engagement events.
|
|
77
|
+
* - `false` turns off all tracking, including kinds PostHog adds later. PostHog can't count the
|
|
78
|
+
* email's opens or clicks, and captures no engagement events.
|
|
79
|
+
* - An object turns each kind on or off. A key you leave out keeps its default.
|
|
80
|
+
*
|
|
81
|
+
* Turn clicks on for a sensitive email only when its links are safe to send through PostHog's
|
|
82
|
+
* click tracking.
|
|
83
|
+
*/
|
|
84
|
+
tracking?: boolean | EmailTracking
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Which kinds of tracking a send with `templateKey` turns on. */
|
|
88
|
+
export interface EmailTracking {
|
|
89
|
+
/** Counts opens with PostHog's open pixel. Defaults to `true`. */
|
|
90
|
+
opens?: boolean
|
|
91
|
+
/**
|
|
92
|
+
* Counts clicks by sending the email's links through PostHog's click tracking. Defaults to
|
|
93
|
+
* `false` for a sensitive email and `true` for any other. Needs `opens`: PostHog refuses a send
|
|
94
|
+
* with `opens: false` and `clicks: true`.
|
|
95
|
+
*/
|
|
96
|
+
clicks?: boolean
|
|
97
|
+
/**
|
|
98
|
+
* Captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events
|
|
99
|
+
* of the recipient. Defaults to `true`. A project whose admin turned engagement capture off
|
|
100
|
+
* captures nothing, whatever the send asks.
|
|
101
|
+
*/
|
|
102
|
+
engagement?: boolean
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A file sent with the email. */
|
|
106
|
+
export interface EmailAttachment {
|
|
107
|
+
/** The name the recipient sees, such as `'invoice.pdf'`. */
|
|
108
|
+
filename: string
|
|
109
|
+
/** The file's bytes, or its content already Base64 encoded. At least one byte. */
|
|
110
|
+
content: Uint8Array | string
|
|
111
|
+
/** A MIME type, such as `'application/pdf'`. */
|
|
112
|
+
contentType?: string
|
|
113
|
+
/** Shows the file inline where the HTML has `<img src="cid:...">` with this id. */
|
|
114
|
+
contentId?: string
|
|
115
|
+
/** PostHog can't fetch a file from a path or URL: read the file and pass its `content`. */
|
|
116
|
+
path?: never
|
|
49
117
|
}
|
|
50
118
|
|
|
51
119
|
/**
|
package/src/exports.ts
CHANGED
|
@@ -9,11 +9,13 @@ export { EmailError } from './emails/errors'
|
|
|
9
9
|
export type { EmailErrorName } from './emails/errors'
|
|
10
10
|
export type {
|
|
11
11
|
CodeEmailForm,
|
|
12
|
+
EmailAttachment,
|
|
12
13
|
EmailDeliveryStatus,
|
|
13
14
|
EmailPreferences,
|
|
14
15
|
EmailReactElement,
|
|
15
16
|
Emails,
|
|
16
17
|
EmailStatus,
|
|
18
|
+
EmailTracking,
|
|
17
19
|
EmailWarning,
|
|
18
20
|
GetEmailResponse,
|
|
19
21
|
SendCodeEmailOptions,
|
package/src/types.ts
CHANGED
|
@@ -276,7 +276,8 @@ export type PostHogOptions = Omit<PostHogCoreOptions, 'before_send' | 'flushInte
|
|
|
276
276
|
*/
|
|
277
277
|
appHost?: string
|
|
278
278
|
/**
|
|
279
|
-
* Timeout in milliseconds for each `emails.send` request.
|
|
279
|
+
* Timeout in milliseconds for each `emails.send` request. Each attachment upload is one request,
|
|
280
|
+
* so raise it when large files upload slowly.
|
|
280
281
|
*
|
|
281
282
|
* @default 15000
|
|
282
283
|
*/
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const version = "5.
|
|
1
|
+
export const version = "5.72.0"
|