posthog-node 5.71.0 → 5.73.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.
Files changed (49) hide show
  1. package/dist/client.d.ts +53 -7
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +94 -19
  4. package/dist/client.mjs +94 -19
  5. package/dist/emails/attachments.d.ts +23 -0
  6. package/dist/emails/attachments.d.ts.map +1 -0
  7. package/dist/emails/attachments.js +170 -0
  8. package/dist/emails/attachments.mjs +123 -0
  9. package/dist/emails/emails.d.ts +7 -2
  10. package/dist/emails/emails.d.ts.map +1 -1
  11. package/dist/emails/emails.js +193 -37
  12. package/dist/emails/emails.mjs +193 -37
  13. package/dist/emails/errors.d.ts +1 -1
  14. package/dist/emails/errors.d.ts.map +1 -1
  15. package/dist/emails/errors.js +6 -1
  16. package/dist/emails/errors.mjs +6 -1
  17. package/dist/emails/types.d.ts +23 -0
  18. package/dist/emails/types.d.ts.map +1 -1
  19. package/dist/exports.d.ts +1 -1
  20. package/dist/exports.d.ts.map +1 -1
  21. package/dist/feature-flag-evaluations.d.ts +14 -0
  22. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  23. package/dist/feature-flag-evaluations.js +2 -1
  24. package/dist/feature-flag-evaluations.mjs +2 -1
  25. package/dist/flag-events.d.ts +112 -0
  26. package/dist/flag-events.d.ts.map +1 -0
  27. package/dist/flag-events.js +230 -0
  28. package/dist/flag-events.mjs +174 -0
  29. package/dist/flags-response.d.ts +83 -0
  30. package/dist/flags-response.d.ts.map +1 -0
  31. package/dist/flags-response.js +255 -0
  32. package/dist/flags-response.mjs +208 -0
  33. package/dist/types.d.ts +2 -1
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/dist/version.mjs +1 -1
  38. package/package.json +4 -3
  39. package/src/client.ts +238 -45
  40. package/src/emails/attachments.ts +209 -0
  41. package/src/emails/emails.ts +243 -35
  42. package/src/emails/errors.ts +7 -2
  43. package/src/emails/types.ts +24 -0
  44. package/src/exports.ts +1 -0
  45. package/src/feature-flag-evaluations.ts +17 -0
  46. package/src/flag-events.ts +280 -0
  47. package/src/flags-response.ts +340 -0
  48. package/src/types.ts +2 -1
  49. package/src/version.ts +1 -1
@@ -33,8 +33,10 @@ __webpack_require__.d(__webpack_exports__, {
33
33
  EmailSender: ()=>EmailSender
34
34
  });
35
35
  const core_namespaceObject = require("@posthog/core");
36
+ const external_attachments_js_namespaceObject = require("./attachments.js");
36
37
  const external_errors_js_namespaceObject = require("./errors.js");
37
38
  const SEND_PATH = '/api/projects/@current/messaging/send/email/';
39
+ const UPLOADS_PATH = '/api/projects/@current/messaging/attachments/uploads/';
38
40
  const STATUS_PATH = '/api/projects/@current/messaging/emails/{messageId}/';
39
41
  const PREFERENCES_PATH = '/api/projects/@current/messaging/preferences/';
40
42
  const US_APP_HOST = 'https://us.posthog.com';
@@ -66,6 +68,9 @@ const CODE_FIELDS = {
66
68
  from: true,
67
69
  replyTo: true,
68
70
  captureEngagement: true,
71
+ cc: true,
72
+ bcc: true,
73
+ attachments: true,
69
74
  sensitive: true,
70
75
  tracking: true,
71
76
  html: true,
@@ -114,7 +119,13 @@ class EmailSender {
114
119
  refuseSecondArgument(unexpected);
115
120
  const prepared = prepareSend(options, this.config.maxRetries);
116
121
  const { appHost, secretKey } = this.connect('no email was sent', 'Sending email needs secretKey, a project secret API key with the transactional_email:write scope.');
117
- const body = void 0 === prepared.react ? prepared.body : await withRenderedReact(prepared.body, prepared.react, this.config.requestTimeoutMs);
122
+ const content = void 0 === prepared.react ? prepared.content : await withRenderedReact(prepared.content, prepared.react, this.config.requestTimeoutMs);
123
+ if (void 0 !== prepared.react) (0, external_attachments_js_namespaceObject.refuseRenderedMessageOverLimit)(prepared.files, content);
124
+ const attachments = await this.uploadAttachments(prepared, appHost, secretKey);
125
+ const body = (0, core_namespaceObject.safeJsonStringify)({
126
+ ...content,
127
+ ...unlessEmpty('attachments', attachments)
128
+ });
118
129
  const headers = this.headers(secretKey, {
119
130
  'Content-Type': 'application/json',
120
131
  'Idempotency-Key': prepared.idempotencyKey
@@ -150,6 +161,69 @@ class EmailSender {
150
161
  };
151
162
  }
152
163
  }
164
+ async uploadAttachments({ files, maxRetries }, appHost, secretKey) {
165
+ if (0 === files.length) return [];
166
+ const hashed = await (0, external_attachments_js_namespaceObject.hashedFiles)(files);
167
+ const distinct = new Map();
168
+ for (const file of hashed)if (!distinct.has(file.sha256)) distinct.set(file.sha256, file);
169
+ const requested = [
170
+ ...distinct.values()
171
+ ];
172
+ const body = (0, core_namespaceObject.safeJsonStringify)({
173
+ files: requested.map(({ sha256, bytes })=>({
174
+ sha256,
175
+ size: bytes.byteLength
176
+ }))
177
+ });
178
+ const headers = this.headers(secretKey, {
179
+ 'Content-Type': 'application/json'
180
+ });
181
+ const uploads = await this.withRetries(maxRetries, async ()=>parseUploadsReply(await this.request(appHost + UPLOADS_PATH, 'POST', headers, body), requested));
182
+ const unencrypted = isPlainHttp(appHost) ? void 0 : uploads.find(({ url })=>!isHttps(url));
183
+ if (unencrypted) throw new external_errors_js_namespaceObject.EmailError({
184
+ code: 'api_error',
185
+ message: `PostHog named an upload URL for ${unencrypted.field} that isn't https, so the file would travel unencrypted. No email was sent.`,
186
+ field: unencrypted.field,
187
+ fix: "Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host."
188
+ });
189
+ for (const upload of uploads)await this.withRetries(maxRetries, ()=>this.uploadFile(upload));
190
+ return hashed.map(external_attachments_js_namespaceObject.attachmentReference);
191
+ }
192
+ async uploadFile({ url, headers, bytes, field }) {
193
+ let reply;
194
+ try {
195
+ reply = await this.request(url, 'PUT', headers, bytes, 'manual');
196
+ } catch (cause) {
197
+ if (cause instanceof Error && 'AbortError' === cause.name) throw new external_errors_js_namespaceObject.EmailError({
198
+ code: 'network_error',
199
+ message: `The upload of ${field} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,
200
+ fix: 'Raise emailRequestTimeoutMs on the client, or send smaller files.',
201
+ field,
202
+ cause
203
+ });
204
+ throw new external_errors_js_namespaceObject.EmailError({
205
+ code: 'network_error',
206
+ message: `The upload of ${field} didn't reach PostHog's file storage, so no email was sent.`,
207
+ field,
208
+ cause
209
+ });
210
+ }
211
+ if (reply.status >= 300 && reply.status < 400) throw new external_errors_js_namespaceObject.EmailError({
212
+ code: 'attachment_upload_failed',
213
+ 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.`,
214
+ statusCode: reply.status,
215
+ fix: "Make your PostHog's file storage URL point straight at the storage, over https.",
216
+ field
217
+ });
218
+ if (reply.status < 200 || reply.status >= 300) throw new external_errors_js_namespaceObject.EmailError({
219
+ code: 'attachment_upload_failed',
220
+ message: `PostHog's file storage refused the upload of ${field}, so no email was sent. ${storageAnswer(reply)}`,
221
+ statusCode: reply.status,
222
+ fix: 'Send the email again. Each send asks for new upload URLs.',
223
+ field,
224
+ retryAfterMs: reply.retryAfterMs
225
+ });
226
+ }
153
227
  async setPreferencesUntracked(options) {
154
228
  try {
155
229
  const body = preparePreferences(options);
@@ -220,7 +294,7 @@ class EmailSender {
220
294
  await new Promise((resolve)=>setTimeout(resolve, delayMs));
221
295
  }
222
296
  }
223
- async request(url, method, headers, body) {
297
+ async request(url, method, headers, body, redirect) {
224
298
  const controller = new AbortController();
225
299
  const timeoutMs = this.config.requestTimeoutMs;
226
300
  let timer;
@@ -238,6 +312,9 @@ class EmailSender {
238
312
  ...void 0 === body ? {} : {
239
313
  body
240
314
  },
315
+ ...redirect ? {
316
+ redirect
317
+ } : {},
241
318
  signal: controller.signal
242
319
  }));
243
320
  fetchPromise.then((lateResponse)=>{
@@ -259,13 +336,13 @@ class EmailSender {
259
336
  if (response.status >= 200 && response.status < 300) throw error;
260
337
  return {
261
338
  status: response.status,
262
- payload: null,
339
+ text: '',
263
340
  retryAfterMs: readRetryAfter(response)
264
341
  };
265
342
  }
266
343
  return {
267
344
  status: response.status,
268
- payload: parseJson(text),
345
+ text,
269
346
  retryAfterMs: readRetryAfter(response)
270
347
  };
271
348
  } finally{
@@ -285,19 +362,23 @@ function prepareSend(options, defaultMaxRetries) {
285
362
  const { to, distinctId, idempotencyKey, maxRetries } = send;
286
363
  if ('string' != typeof to || !to.trim()) throw invalid('invalid_recipient', 'to must be one email address as a nonempty string.', 'to');
287
364
  if (void 0 !== distinctId && ('string' != typeof distinctId || !distinctId)) throw invalid('invalid_distinct_id', 'distinctId must be a nonempty string.', 'distinctId');
288
- const content = contentOf(send, distinctId);
365
+ const { content, files } = contentOf(send, distinctId);
289
366
  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');
290
367
  if (void 0 !== maxRetries && !isRetryCount(maxRetries)) throw invalid('invalid_max_retries', 'maxRetries must be a nonnegative integer.', 'maxRetries');
291
368
  return {
292
- body: (0, core_namespaceObject.safeJsonStringify)({
369
+ content: snapshotOf({
293
370
  ...content,
294
371
  to
295
372
  }),
373
+ files,
296
374
  react: isReactElement(send.react) ? send.react : void 0,
297
375
  idempotencyKey: idempotencyKey ?? globalThis.crypto.randomUUID(),
298
376
  maxRetries: isRetryCount(maxRetries) ? maxRetries : defaultMaxRetries
299
377
  };
300
378
  }
379
+ function snapshotOf(content) {
380
+ return JSON.parse((0, core_namespaceObject.safeJsonStringify)(content));
381
+ }
301
382
  function preparePreferences(options) {
302
383
  const fallback = {};
303
384
  const { to, allMarketing, topics } = options ?? fallback;
@@ -324,7 +405,10 @@ function contentOf(send, distinctId) {
324
405
  code: 'invalid_form',
325
406
  message: 'Send either templateId, or templateKey with subject and html, text or react.'
326
407
  });
327
- return void 0 === send.templateKey ? templateContent(send, distinctId) : codeContent(send, distinctId);
408
+ return void 0 === send.templateKey ? {
409
+ content: templateContent(send, distinctId),
410
+ files: []
411
+ } : codeContent(send, distinctId);
328
412
  }
329
413
  function templateContent(send, distinctId) {
330
414
  const { templateId, templateData } = send;
@@ -340,7 +424,7 @@ function templateContent(send, distinctId) {
340
424
  };
341
425
  }
342
426
  function codeContent(send, distinctId) {
343
- const { templateKey, subject, html, text, react, from, replyTo, captureEngagement, sensitive, tracking } = send;
427
+ const { templateKey, subject, html, text, react } = send;
344
428
  if ('string' != typeof templateKey || !TEMPLATE_KEY_PATTERN.test(templateKey)) throw invalid('invalid_template_key', 'templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.', 'templateKey');
345
429
  refuseFieldsOutside(send, CODE_FORM, TEMPLATE_FORM);
346
430
  if ('string' != typeof subject) throw invalid('invalid_form', 'A send with templateKey needs a subject.', 'subject');
@@ -348,24 +432,38 @@ function codeContent(send, distinctId) {
348
432
  if (void 0 !== text && 'string' != typeof text) throw invalid('invalid_form', 'text must be a string.', 'text');
349
433
  if (void 0 !== react) checkReactContent(react, html);
350
434
  else if (void 0 === html && void 0 === text) throw invalid('invalid_form', 'A send with templateKey needs html, text or react.', 'html');
351
- const sendsReplyTo = void 0 !== replyTo && !(Array.isArray(replyTo) && 0 === replyTo.length);
435
+ const files = void 0 === send.attachments ? [] : (0, external_attachments_js_namespaceObject.attachmentFiles)(send.attachments, {
436
+ html,
437
+ text,
438
+ subject
439
+ });
352
440
  return {
353
- template_key: templateKey,
354
- subject,
355
- ...void 0 !== html && {
356
- html
357
- },
358
- ...void 0 !== text && {
359
- text
441
+ content: {
442
+ template_key: templateKey,
443
+ subject,
444
+ ...void 0 !== html && {
445
+ html
446
+ },
447
+ ...void 0 !== text && {
448
+ text
449
+ },
450
+ ...codeFormFields(send),
451
+ ...void 0 !== distinctId && {
452
+ distinct_id: distinctId
453
+ }
360
454
  },
455
+ files
456
+ };
457
+ }
458
+ function codeFormFields(send) {
459
+ const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking } = send;
460
+ return {
361
461
  ...void 0 !== from && {
362
462
  from
363
463
  },
364
- ...sendsReplyTo && {
365
- reply_to: 'string' == typeof replyTo ? [
366
- replyTo
367
- ] : replyTo
368
- },
464
+ ...void 0 !== replyTo && unlessEmpty('reply_to', addressList(replyTo)),
465
+ ...void 0 !== cc && unlessEmpty('cc', addressList(cc)),
466
+ ...void 0 !== bcc && unlessEmpty('bcc', addressList(bcc)),
369
467
  ...void 0 !== captureEngagement && {
370
468
  capture_engagement: captureEngagement
371
469
  },
@@ -374,12 +472,19 @@ function codeContent(send, distinctId) {
374
472
  },
375
473
  ...void 0 !== tracking && {
376
474
  tracking
377
- },
378
- ...void 0 !== distinctId && {
379
- distinct_id: distinctId
380
475
  }
381
476
  };
382
477
  }
478
+ function unlessEmpty(field, list) {
479
+ return Array.isArray(list) && 0 === list.length ? {} : {
480
+ [field]: list
481
+ };
482
+ }
483
+ function addressList(addresses) {
484
+ return 'string' == typeof addresses ? [
485
+ addresses
486
+ ] : addresses;
487
+ }
383
488
  function checkReactContent(react, html) {
384
489
  if (!isReactElement(react)) throw invalid('invalid_form', 'react must be a React element, such as <WelcomeEmail />.', 'react');
385
490
  if (void 0 !== html) throw new external_errors_js_namespaceObject.EmailError({
@@ -396,18 +501,17 @@ const REACT_18_AND_19_ELEMENT_MARKERS = [
396
501
  function isReactElement(value) {
397
502
  return 'object' == typeof value && null !== value && '$$typeof' in value && REACT_18_AND_19_ELEMENT_MARKERS.includes(value.$$typeof) && 'type' in value && 'props' in value;
398
503
  }
399
- async function withRenderedReact(body, react, timeoutMs) {
504
+ async function withRenderedReact(content, react, timeoutMs) {
400
505
  const { render, toPlainText } = await loadReactRenderer();
401
- const fields = JSON.parse(body);
402
506
  try {
403
507
  const html = await settleWithin(render(react), timeoutMs, 'Rendering the react element');
404
- return (0, core_namespaceObject.safeJsonStringify)({
405
- ...fields,
508
+ return {
509
+ ...content,
406
510
  html,
407
- ...void 0 === fields.text && {
511
+ ...void 0 === content.text && {
408
512
  text: toPlainText(html)
409
513
  }
410
- });
514
+ };
411
515
  } catch (cause) {
412
516
  throw new external_errors_js_namespaceObject.EmailError({
413
517
  code: 'react_render_failed',
@@ -470,6 +574,12 @@ function invalid(code, message, field) {
470
574
  field
471
575
  });
472
576
  }
577
+ function isHttps(url) {
578
+ return url.toLowerCase().startsWith('https://');
579
+ }
580
+ function isPlainHttp(url) {
581
+ return url.toLowerCase().startsWith('http://');
582
+ }
473
583
  function resolveAppHost(host, appHost) {
474
584
  const explicit = 'string' == typeof appHost ? (0, core_namespaceObject.removeTrailingSlash)(appHost.trim()) : '';
475
585
  if (explicit) return CLOUD_APP_HOSTS[explicit] ?? explicit;
@@ -495,8 +605,8 @@ function emails_text(value) {
495
605
  function replyFields(payload) {
496
606
  return null === payload || 'object' != typeof payload || Array.isArray(payload) ? {} : payload;
497
607
  }
498
- function parseSendReply({ status, payload, retryAfterMs }) {
499
- const fields = replyFields(payload);
608
+ function parseSendReply({ status, text: body, retryAfterMs }) {
609
+ const fields = replyFields(parseJson(body));
500
610
  if (status >= 200 && status < 300) {
501
611
  const id = emails_text(fields.message_id);
502
612
  if (!id) throw new external_errors_js_namespaceObject.EmailError({
@@ -520,8 +630,8 @@ function parseSendReply({ status, payload, retryAfterMs }) {
520
630
  }
521
631
  throw replyError(fields, status, retryAfterMs);
522
632
  }
523
- function parseStatusReply({ status, payload, retryAfterMs }) {
524
- const fields = replyFields(payload);
633
+ function parseStatusReply({ status, text: body, retryAfterMs }) {
634
+ const fields = replyFields(parseJson(body));
525
635
  if (status < 200 || status >= 300) throw replyError(fields, status, retryAfterMs);
526
636
  const id = emails_text(fields.id);
527
637
  const deliveryStatus = emails_text(fields.status);
@@ -540,8 +650,53 @@ function parseStatusReply({ status, payload, retryAfterMs }) {
540
650
  reason: emails_text(fields.reason) ?? null
541
651
  };
542
652
  }
543
- function parsePreferencesReply({ status, payload, retryAfterMs }) {
544
- const fields = replyFields(payload);
653
+ function parseUploadsReply({ status, text: body, retryAfterMs }, requested) {
654
+ const fields = replyFields(parseJson(body));
655
+ if (404 === status) throw replyError({
656
+ code: 'not_found',
657
+ ...fields,
658
+ attr: emails_text(fields.attr) ?? 'attachments'
659
+ }, status, retryAfterMs);
660
+ if (status < 200 || status >= 300) throw replyError({
661
+ ...fields,
662
+ attr: callerField(emails_text(fields.attr), requested)
663
+ }, status, retryAfterMs);
664
+ const answers = Array.isArray(fields.files) ? fields.files.map(replyFields) : [];
665
+ const uploads = [];
666
+ for (const { sha256, bytes, field } of requested){
667
+ const answer = answers.find((file)=>file.sha256 === sha256);
668
+ if (answer?.status === 'present') continue;
669
+ const url = emails_text(answer?.url);
670
+ if (answer?.status !== 'upload' || !url || !isStringRecord(answer.headers)) throw new external_errors_js_namespaceObject.EmailError({
671
+ code: 'api_error',
672
+ message: 'PostHog answered without telling where to upload every file.',
673
+ statusCode: status
674
+ });
675
+ uploads.push({
676
+ url,
677
+ headers: answer.headers,
678
+ bytes,
679
+ field
680
+ });
681
+ }
682
+ return uploads;
683
+ }
684
+ function callerField(attr, requested) {
685
+ const file = void 0 === attr ? null : /^files(?:__(\d+))?(?:__|$)/.exec(attr);
686
+ if (!file) return attr;
687
+ return void 0 === file[1] ? 'attachments' : requested[Number(file[1])]?.field ?? 'attachments';
688
+ }
689
+ function isStringRecord(value) {
690
+ return null !== value && 'object' == typeof value && !Array.isArray(value) && Object.values(value).every((item)=>'string' == typeof item);
691
+ }
692
+ function storageAnswer({ status, text: body }) {
693
+ const code = /<Code>([^<]{1,100})<\/Code>/.exec(body)?.[1];
694
+ const message = /<Message>([^<]{1,300})<\/Message>/.exec(body)?.[1];
695
+ const answer = `It answered HTTP ${status}${code ? ` ${code}` : ''}${message ? `: ${message}` : ''}`;
696
+ return answer.endsWith('.') ? answer : `${answer}.`;
697
+ }
698
+ function parsePreferencesReply({ status, text: body, retryAfterMs }) {
699
+ const fields = replyFields(parseJson(body));
545
700
  if (status < 200 || status >= 300) throw replyError(fields, status, retryAfterMs);
546
701
  const to = emails_text(fields.identifier);
547
702
  const allMarketing = fields.all_marketing;
@@ -578,8 +733,9 @@ function asEmailError(error, message) {
578
733
  }
579
734
  function isRetryable(error) {
580
735
  if (void 0 === error.statusCode) return 'network_error' === error.code;
736
+ if ('attachment_upload_failed' === error.code) return 429 === error.statusCode || error.statusCode >= 500;
581
737
  if (409 === error.statusCode) return 'idempotency_key_in_flight' === error.code;
582
- if (429 === error.statusCode) return 'quota_limited' !== error.code;
738
+ if (429 === error.statusCode) return 'quota_limited' !== error.code && 'upload_quota_exceeded' !== error.code;
583
739
  return 503 === error.statusCode;
584
740
  }
585
741
  function retryDelayMs(error, attempt, maxRetries) {